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

Last change on this file since 7026 was 7026, checked in by stoecker, 10 years ago

fix #3142 - drop applet code finally

  • Property svn:eol-style set to native
File size: 17.1 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 file = checkLocal(url, destDir, maxTime, httpAccept);
140 }
141 } catch (java.net.MalformedURLException e) {
142 if (name.startsWith("resource://")) {
143 fs = getClass().getResourceAsStream(
144 name.substring("resource:/".length()));
145 if (fs == null)
146 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
147 return;
148 }
149 file = new File(name);
150 }
151 if (file == null)
152 throw new IOException();
153 fs = new FileInputStream(file);
154 }
155
156 /**
157 * Looks for a certain entry inside a zip file and returns the entry path.
158 *
159 * Replies a file in the top level directory of the ZIP file which has an
160 * extension <code>extension</code>. If more than one files have this
161 * extension, the last file whose name includes <code>namepart</code>
162 * is opened.
163 *
164 * @param extension the extension of the file we're looking for
165 * @param namepart the name part
166 * @return The zip entry path of the matching file. Null if this mirrored
167 * input stream doesn't represent a zip file or if there was no matching
168 * file in the ZIP file.
169 */
170 public String findZipEntryPath(String extension, String namepart) {
171 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
172 if (ze == null) return null;
173 return ze.a;
174 }
175
176 /**
177 * Like {@link #findZipEntryPath}, but returns the corresponding InputStream.
178 * @since 6148
179 */
180 public InputStream findZipEntryInputStream(String extension, String namepart) {
181 Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
182 if (ze == null) return null;
183 return ze.b;
184 }
185
186 private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
187 if (file == null)
188 return null;
189 Pair<String, InputStream> res = null;
190 try {
191 ZipFile zipFile = new ZipFile(file);
192 ZipEntry resentry = null;
193 Enumeration<? extends ZipEntry> entries = zipFile.entries();
194 while (entries.hasMoreElements()) {
195 ZipEntry entry = entries.nextElement();
196 if (entry.getName().endsWith("." + extension)) {
197 /* choose any file with correct extension. When more than
198 one file, prefer the one which matches namepart */
199 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
200 resentry = entry;
201 }
202 }
203 }
204 if (resentry != null) {
205 InputStream is = zipFile.getInputStream(resentry);
206 res = Pair.create(resentry.getName(), is);
207 } else {
208 Utils.close(zipFile);
209 }
210 } catch (Exception e) {
211 if (file.getName().endsWith(".zip")) {
212 Main.warn(tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
213 file.getName(), e.toString(), extension, namepart));
214 }
215 }
216 return res;
217 }
218
219 public File getFile() {
220 return file;
221 }
222
223 public static void cleanup(String name) {
224 cleanup(name, null);
225 }
226
227 public static void cleanup(String name, String destDir) {
228 URL url;
229 try {
230 url = new URL(name);
231 if (!"file".equals(url.getProtocol())) {
232 String prefKey = getPrefKey(url, destDir);
233 List<String> localPath = new ArrayList<>(Main.pref.getCollection(prefKey));
234 if (localPath.size() == 2) {
235 File lfile = new File(localPath.get(1));
236 if(lfile.exists()) {
237 lfile.delete();
238 }
239 }
240 Main.pref.putCollection(prefKey, null);
241 }
242 } catch (MalformedURLException e) {
243 Main.warn(e);
244 }
245 }
246
247 /**
248 * get preference key to store the location and age of the cached file.
249 * 2 resources that point to the same url, but that are to be stored in different
250 * directories will not share a cache file.
251 */
252 private static String getPrefKey(URL url, String destDir) {
253 StringBuilder prefKey = new StringBuilder("mirror.");
254 if (destDir != null) {
255 prefKey.append(destDir);
256 prefKey.append(".");
257 }
258 prefKey.append(url.toString());
259 return prefKey.toString().replaceAll("=","_");
260 }
261
262 private File checkLocal(URL url, String destDir, long maxTime, String httpAccept) throws IOException {
263 String prefKey = getPrefKey(url, destDir);
264 long age = 0L;
265 File localFile = null;
266 List<String> localPathEntry = new ArrayList<>(Main.pref.getCollection(prefKey));
267 if (localPathEntry.size() == 2) {
268 localFile = new File(localPathEntry.get(1));
269 if(!localFile.exists())
270 localFile = null;
271 else {
272 if ( maxTime == DEFAULT_MAXTIME
273 || maxTime <= 0 // arbitrary value <= 0 is deprecated
274 ) {
275 maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
276 }
277 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
278 if (age < maxTime*1000) {
279 return localFile;
280 }
281 }
282 }
283 if (destDir == null) {
284 destDir = Main.pref.getCacheDirectory().getPath();
285 }
286
287 File destDirFile = new File(destDir);
288 if (!destDirFile.exists()) {
289 destDirFile.mkdirs();
290 }
291
292 String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
293 String localPath = "mirror_" + a;
294 destDirFile = new File(destDir, localPath + ".tmp");
295 BufferedOutputStream bos = null;
296 BufferedInputStream bis = null;
297 try {
298 HttpURLConnection con = connectFollowingRedirect(url, httpAccept);
299 bis = new BufferedInputStream(con.getInputStream());
300 FileOutputStream fos = new FileOutputStream(destDirFile);
301 bos = new BufferedOutputStream(fos);
302 byte[] buffer = new byte[4096];
303 int length;
304 while ((length = bis.read(buffer)) > -1) {
305 bos.write(buffer, 0, length);
306 }
307 Utils.close(bos);
308 bos = null;
309 /* close fos as well to be sure! */
310 Utils.close(fos);
311 fos = null;
312 localFile = new File(destDir, localPath);
313 if(Main.platform.rename(destDirFile, localFile)) {
314 Main.pref.putCollection(prefKey, Arrays.asList(new String[]
315 {Long.toString(System.currentTimeMillis()), localFile.toString()}));
316 } else {
317 Main.warn(tr("Failed to rename file {0} to {1}.",
318 destDirFile.getPath(), localFile.getPath()));
319 }
320 } catch (IOException e) {
321 if (age >= maxTime*1000 && age < maxTime*1000*2) {
322 Main.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", url, e));
323 return localFile;
324 } else {
325 throw e;
326 }
327 } finally {
328 Utils.close(bis);
329 Utils.close(bos);
330 }
331
332 return localFile;
333 }
334
335 /**
336 * Opens a connection for downloading a resource.
337 * <p>
338 * Manually follows redirects because
339 * {@link HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
340 * is going from a http to a https URL, see <a href="https://bugs.openjdk.java.net/browse/JDK-4620571">bug report</a>.
341 * <p>
342 * This can causes problems when downloading from certain GitHub URLs.
343 *
344 * @param downloadUrl The resource URL to download
345 * @param httpAccept The accepted MIME types sent in the HTTP Accept header. Can be {@code null}
346 * @return The HTTP connection effectively linked to the resource, after all potential redirections
347 * @throws MalformedURLException If a redirected URL is wrong
348 * @throws IOException If any I/O operation goes wrong
349 * @since 6867
350 */
351 public static HttpURLConnection connectFollowingRedirect(URL downloadUrl, String httpAccept) throws MalformedURLException, IOException {
352 HttpURLConnection con = null;
353 int numRedirects = 0;
354 while(true) {
355 con = Utils.openHttpConnection(downloadUrl);
356 con.setInstanceFollowRedirects(false);
357 con.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
358 con.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
359 Main.debug("GET "+downloadUrl);
360 if (httpAccept != null) {
361 Main.debug("Accept: "+httpAccept);
362 con.setRequestProperty("Accept", httpAccept);
363 }
364 try {
365 con.connect();
366 } catch (IOException e) {
367 Main.addNetworkError(downloadUrl, Utils.getRootCause(e));
368 throw e;
369 }
370 switch(con.getResponseCode()) {
371 case HttpURLConnection.HTTP_OK:
372 return con;
373 case HttpURLConnection.HTTP_MOVED_PERM:
374 case HttpURLConnection.HTTP_MOVED_TEMP:
375 case HttpURLConnection.HTTP_SEE_OTHER:
376 String redirectLocation = con.getHeaderField("Location");
377 if (downloadUrl == null) {
378 /* 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());
379 throw new IOException(msg);
380 }
381 downloadUrl = new URL(redirectLocation);
382 // keep track of redirect attempts to break a redirect loops if it happens
383 // to occur for whatever reason
384 numRedirects++;
385 if (numRedirects >= Main.pref.getInteger("socket.maxredirects", 5)) {
386 String msg = tr("Too many redirects to the download URL detected. Aborting.");
387 throw new IOException(msg);
388 }
389 Main.info(tr("Download redirected to ''{0}''", downloadUrl));
390 break;
391 default:
392 String msg = tr("Failed to read from ''{0}''. Server responded with status code {1}.", downloadUrl, con.getResponseCode());
393 throw new IOException(msg);
394 }
395 }
396 }
397
398 @Override
399 public int available() throws IOException
400 { return fs.available(); }
401 @Override
402 public void close() throws IOException
403 { Utils.close(fs); }
404 @Override
405 public int read() throws IOException
406 { return fs.read(); }
407 @Override
408 public int read(byte[] b) throws IOException
409 { return fs.read(b); }
410 @Override
411 public int read(byte[] b, int off, int len) throws IOException
412 { return fs.read(b,off, len); }
413 @Override
414 public long skip(long n) throws IOException
415 { return fs.skip(n); }
416}
Note: See TracBrowser for help on using the repository browser.