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

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

see #8465 - global use of try-with-resources, according to

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