source: josm/trunk/src/org/openstreetmap/josm/io/MirroredInputStream.java@ 7013

Last change on this file since 7013 was 7012, checked in by Don-vip, 10 years ago

see #8465 - use String switch/case where applicable

  • Property svn:eol-style set to native
File size: 17.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.io.BufferedInputStream;
7import java.io.BufferedOutputStream;
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.FileOutputStream;
11import java.io.IOException;
12import java.io.InputStream;
13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.util.ArrayList;
17import java.util.Arrays;
18import java.util.Enumeration;
19import java.util.List;
20import java.util.zip.ZipEntry;
21import java.util.zip.ZipFile;
22
23import org.openstreetmap.josm.Main;
24import org.openstreetmap.josm.tools.Pair;
25import org.openstreetmap.josm.tools.Utils;
26
27/**
28 * Mirrors a file to a local file.
29 * <p>
30 * The file mirrored is only downloaded if it has been more than 7 days since last download
31 */
32public class MirroredInputStream extends InputStream {
33 InputStream fs = null;
34 File file = null;
35
36 public static final long DEFAULT_MAXTIME = -1L;
37
38 /**
39 * Constructs an input stream from a given filename, URL or internal resource.
40 *
41 * @param name can be:<ul>
42 * <li>relative or absolute file name</li>
43 * <li>{@code file:///SOME/FILE} the same as above</li>
44 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
45 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
46 * @throws IOException when the resource with the given name could not be retrieved
47 */
48 public MirroredInputStream(String name) throws IOException {
49 this(name, null, DEFAULT_MAXTIME, null);
50 }
51
52 /**
53 * Constructs an input stream from a given filename, URL or internal resource.
54 *
55 * @param name can be:<ul>
56 * <li>relative or absolute file name</li>
57 * <li>{@code file:///SOME/FILE} the same as above</li>
58 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
59 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
60 * @param maxTime the maximum age of the cache file (in seconds)
61 * @throws IOException when the resource with the given name could not be retrieved
62 */
63 public MirroredInputStream(String name, long maxTime) throws IOException {
64 this(name, null, maxTime, null);
65 }
66
67 /**
68 * Constructs an input stream from a given filename, URL or internal resource.
69 *
70 * @param name can be:<ul>
71 * <li>relative or absolute file name</li>
72 * <li>{@code file:///SOME/FILE} the same as above</li>
73 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
74 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
75 * @param destDir the destination directory for the cache file. Only applies for URLs.
76 * @throws IOException when the resource with the given name could not be retrieved
77 */
78 public MirroredInputStream(String name, String destDir) throws IOException {
79 this(name, destDir, DEFAULT_MAXTIME, null);
80 }
81
82 /**
83 * Constructs an input stream from a given filename, URL or internal resource.
84 *
85 * @param name can be:<ul>
86 * <li>relative or absolute file name</li>
87 * <li>{@code file:///SOME/FILE} the same as above</li>
88 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
89 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
90 * @param destDir the destination directory for the cache file. Only applies for URLs.
91 * @param maxTime the maximum age of the cache file (in seconds)
92 * @throws IOException when the resource with the given name could not be retrieved
93 */
94 public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
95 this(name, destDir, maxTime, null);
96 }
97
98 /**
99 * Constructs an input stream from a given filename, URL or internal resource.
100 *
101 * @param name can be:<ul>
102 * <li>relative or absolute file name</li>
103 * <li>{@code file:///SOME/FILE} the same as above</li>
104 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
105 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
106 * @param destDir the destination directory for the cache file. Only applies for URLs.
107 * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Only applies for URLs.
108 * @throws IOException when the resource with the given name could not be retrieved
109 * @since 6867
110 */
111 public MirroredInputStream(String name, String destDir, String httpAccept) throws IOException {
112 this(name, destDir, DEFAULT_MAXTIME, httpAccept);
113 }
114
115 /**
116 * Constructs an input stream from a given filename, URL or internal resource.
117 *
118 * @param name can be:<ul>
119 * <li>relative or absolute file name</li>
120 * <li>{@code file:///SOME/FILE} the same as above</li>
121 * <li>{@code resource://SOME/FILE} file from the classpath (usually in the current *.jar)</li>
122 * <li>{@code http://...} a URL. It will be cached on disk.</li></ul>
123 * @param destDir the destination directory for the cache file. Only applies for URLs.
124 * @param maxTime the maximum age of the cache file (in seconds)
125 * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Only applies for URLs.
126 * @throws IOException when the resource with the given name could not be retrieved
127 * @since 6867
128 */
129 public MirroredInputStream(String name, String destDir, long maxTime, String httpAccept) throws IOException {
130 URL url;
131 try {
132 url = new URL(name);
133 if ("file".equals(url.getProtocol())) {
134 file = new File(name.substring("file:/".length()));
135 if (!file.exists()) {
136 file = new File(name.substring("file://".length()));
137 }
138 } else {
139 if (Main.applet) {
140 fs = new BufferedInputStream(Utils.openURL(url));
141 file = new File(url.getFile());
142 } else {
143 file = checkLocal(url, destDir, maxTime, httpAccept);
144 }
145 }
146 } catch (java.net.MalformedURLException e) {
147 if (name.startsWith("resource://")) {
148 fs = getClass().getResourceAsStream(
149 name.substring("resource:/".length()));
150 if (fs == null)
151 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
152 return;
153 }
154 file = new File(name);
155 }
156 if (file == null)
157 throw new IOException();
158 fs = new FileInputStream(file);
159 }
160
161 /**
162 * Looks for a certain entry inside a zip file and returns the entry path.
163 *
164 * Replies a file in the top level directory of the ZIP file which has an
165 * extension <code>extension</code>. If more than one files have this
166 * extension, the last file whose name includes <code>namepart</code>
167 * is opened.
168 *
169 * @param extension the extension of the file we're looking for
170 * @param namepart the name part
171 * @return The zip entry path of the matching file. Null if this mirrored
172 * input stream doesn't represent a zip file or if there was no matching
173 * file in the ZIP file.
174 */
175 public String findZipEntryPath(String extension, String namepart) {
176 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
177 if (ze == null) return null;
178 return ze.a;
179 }
180
181 /**
182 * Like {@link #findZipEntryPath}, but returns the corresponding InputStream.
183 * @since 6148
184 */
185 public InputStream findZipEntryInputStream(String extension, String namepart) {
186 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
187 if (ze == null) return null;
188 return ze.b;
189 }
190
191 private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
192 if (file == null)
193 return null;
194 Pair<String, InputStream> res = null;
195 try {
196 ZipFile zipFile = new ZipFile(file);
197 ZipEntry resentry = null;
198 Enumeration<? extends ZipEntry> entries = zipFile.entries();
199 while (entries.hasMoreElements()) {
200 ZipEntry entry = entries.nextElement();
201 if (entry.getName().endsWith("." + extension)) {
202 /* choose any file with correct extension. When more than
203 one file, prefer the one which matches namepart */
204 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
205 resentry = entry;
206 }
207 }
208 }
209 if (resentry != null) {
210 InputStream is = zipFile.getInputStream(resentry);
211 res = Pair.create(resentry.getName(), is);
212 } else {
213 Utils.close(zipFile);
214 }
215 } catch (Exception e) {
216 if (file.getName().endsWith(".zip")) {
217 Main.warn(tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
218 file.getName(), e.toString(), extension, namepart));
219 }
220 }
221 return res;
222 }
223
224 public File getFile() {
225 return file;
226 }
227
228 public static void cleanup(String name) {
229 cleanup(name, null);
230 }
231
232 public static void cleanup(String name, String destDir) {
233 URL url;
234 try {
235 url = new URL(name);
236 if (!"file".equals(url.getProtocol())) {
237 String prefKey = getPrefKey(url, destDir);
238 List<String> localPath = new ArrayList<>(Main.pref.getCollection(prefKey));
239 if (localPath.size() == 2) {
240 File lfile = new File(localPath.get(1));
241 if(lfile.exists()) {
242 lfile.delete();
243 }
244 }
245 Main.pref.putCollection(prefKey, null);
246 }
247 } catch (MalformedURLException e) {
248 Main.warn(e);
249 }
250 }
251
252 /**
253 * get preference key to store the location and age of the cached file.
254 * 2 resources that point to the same url, but that are to be stored in different
255 * directories will not share a cache file.
256 */
257 private static String getPrefKey(URL url, String destDir) {
258 StringBuilder prefKey = new StringBuilder("mirror.");
259 if (destDir != null) {
260 prefKey.append(destDir);
261 prefKey.append(".");
262 }
263 prefKey.append(url.toString());
264 return prefKey.toString().replaceAll("=","_");
265 }
266
267 private File checkLocal(URL url, String destDir, long maxTime, String httpAccept) throws IOException {
268 String prefKey = getPrefKey(url, destDir);
269 long age = 0L;
270 File localFile = null;
271 List<String> localPathEntry = new ArrayList<>(Main.pref.getCollection(prefKey));
272 if (localPathEntry.size() == 2) {
273 localFile = new File(localPathEntry.get(1));
274 if(!localFile.exists())
275 localFile = null;
276 else {
277 if ( maxTime == DEFAULT_MAXTIME
278 || maxTime <= 0 // arbitrary value <= 0 is deprecated
279 ) {
280 maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
281 }
282 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
283 if (age < maxTime*1000) {
284 return localFile;
285 }
286 }
287 }
288 if (destDir == null) {
289 destDir = Main.pref.getCacheDirectory().getPath();
290 }
291
292 File destDirFile = new File(destDir);
293 if (!destDirFile.exists()) {
294 destDirFile.mkdirs();
295 }
296
297 String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
298 String localPath = "mirror_" + a;
299 destDirFile = new File(destDir, localPath + ".tmp");
300 BufferedOutputStream bos = null;
301 BufferedInputStream bis = null;
302 try {
303 HttpURLConnection con = connectFollowingRedirect(url, httpAccept);
304 bis = new BufferedInputStream(con.getInputStream());
305 FileOutputStream fos = new FileOutputStream(destDirFile);
306 bos = new BufferedOutputStream(fos);
307 byte[] buffer = new byte[4096];
308 int length;
309 while ((length = bis.read(buffer)) > -1) {
310 bos.write(buffer, 0, length);
311 }
312 Utils.close(bos);
313 bos = null;
314 /* close fos as well to be sure! */
315 Utils.close(fos);
316 fos = null;
317 localFile = new File(destDir, localPath);
318 if(Main.platform.rename(destDirFile, localFile)) {
319 Main.pref.putCollection(prefKey, Arrays.asList(new String[]
320 {Long.toString(System.currentTimeMillis()), localFile.toString()}));
321 } else {
322 Main.warn(tr("Failed to rename file {0} to {1}.",
323 destDirFile.getPath(), localFile.getPath()));
324 }
325 } catch (IOException e) {
326 if (age >= maxTime*1000 && age < maxTime*1000*2) {
327 Main.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", url, e));
328 return localFile;
329 } else {
330 throw e;
331 }
332 } finally {
333 Utils.close(bis);
334 Utils.close(bos);
335 }
336
337 return localFile;
338 }
339
340 /**
341 * Opens a connection for downloading a resource.
342 * <p>
343 * Manually follows redirects because
344 * {@link HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
345 * is going from a http to a https URL, see <a href="https://bugs.openjdk.java.net/browse/JDK-4620571">bug report</a>.
346 * <p>
347 * This can causes problems when downloading from certain GitHub URLs.
348 *
349 * @param downloadUrl The resource URL to download
350 * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Can be {@code null}
351 * @return The HTTP connection effectively linked to the resource, after all potential redirections
352 * @throws MalformedURLException If a redirected URL is wrong
353 * @throws IOException If any I/O operation goes wrong
354 * @since 6867
355 */
356 public static HttpURLConnection connectFollowingRedirect(URL downloadUrl, String httpAccept) throws MalformedURLException, IOException {
357 HttpURLConnection con = null;
358 int numRedirects = 0;
359 while(true) {
360 con = Utils.openHttpConnection(downloadUrl);
361 con.setInstanceFollowRedirects(false);
362 con.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
363 con.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
364 Main.debug("GET "+downloadUrl);
365 if (httpAccept != null) {
366 Main.debug("Accept: "+httpAccept);
367 con.setRequestProperty("Accept", httpAccept);
368 }
369 try {
370 con.connect();
371 } catch (IOException e) {
372 Main.addNetworkError(downloadUrl, Utils.getRootCause(e));
373 throw e;
374 }
375 switch(con.getResponseCode()) {
376 case HttpURLConnection.HTTP_OK:
377 return con;
378 case HttpURLConnection.HTTP_MOVED_PERM:
379 case HttpURLConnection.HTTP_MOVED_TEMP:
380 case HttpURLConnection.HTTP_SEE_OTHER:
381 String redirectLocation = con.getHeaderField("Location");
382 if (downloadUrl == null) {
383 /* I18n: argument is HTTP response code */ String msg = tr("Unexpected response from HTTP server. Got {0} response without ''Location'' header. Can''t redirect. Aborting.", con.getResponseCode());
384 throw new IOException(msg);
385 }
386 downloadUrl = new URL(redirectLocation);
387 // keep track of redirect attempts to break a redirect loops if it happens
388 // to occur for whatever reason
389 numRedirects++;
390 if (numRedirects >= Main.pref.getInteger("socket.maxredirects", 5)) {
391 String msg = tr("Too many redirects to the download URL detected. Aborting.");
392 throw new IOException(msg);
393 }
394 Main.info(tr("Download redirected to ''{0}''", downloadUrl));
395 break;
396 default:
397 String msg = tr("Failed to read from ''{0}''. Server responded with status code {1}.", downloadUrl, con.getResponseCode());
398 throw new IOException(msg);
399 }
400 }
401 }
402
403 @Override
404 public int available() throws IOException
405 { return fs.available(); }
406 @Override
407 public void close() throws IOException
408 { Utils.close(fs); }
409 @Override
410 public int read() throws IOException
411 { return fs.read(); }
412 @Override
413 public int read(byte[] b) throws IOException
414 { return fs.read(b); }
415 @Override
416 public int read(byte[] b, int off, int len) throws IOException
417 { return fs.read(b,off, len); }
418 @Override
419 public long skip(long n) throws IOException
420 { return fs.skip(n); }
421}
Note: See TracBrowser for help on using the repository browser.