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

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

see #8465 - Use of new Java 7 zip constructors allowing to specify a charset for entries names

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