1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.BufferedInputStream;
|
---|
7 | import java.io.BufferedOutputStream;
|
---|
8 | import java.io.File;
|
---|
9 | import java.io.FileInputStream;
|
---|
10 | import java.io.FileOutputStream;
|
---|
11 | import java.io.IOException;
|
---|
12 | import java.io.InputStream;
|
---|
13 | import java.net.HttpURLConnection;
|
---|
14 | import java.net.MalformedURLException;
|
---|
15 | import java.net.URL;
|
---|
16 | import java.util.ArrayList;
|
---|
17 | import java.util.Arrays;
|
---|
18 | import java.util.Enumeration;
|
---|
19 | import java.util.List;
|
---|
20 | import java.util.zip.ZipEntry;
|
---|
21 | import java.util.zip.ZipFile;
|
---|
22 |
|
---|
23 | import org.openstreetmap.josm.Main;
|
---|
24 | import org.openstreetmap.josm.tools.Pair;
|
---|
25 | import 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 | */
|
---|
32 | public class MirroredInputStream extends InputStream {
|
---|
33 | InputStream fs = null;
|
---|
34 | File file = null;
|
---|
35 |
|
---|
36 | public final static 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 (url.getProtocol().equals("file")) {
|
---|
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 | */
|
---|
184 | public InputStream findZipEntryInputStream(String extension, String namepart) {
|
---|
185 | Pair<String, InputStream> ze = findZipEntryImpl(extension, namepart);
|
---|
186 | if (ze == null) return null;
|
---|
187 | return ze.b;
|
---|
188 | }
|
---|
189 |
|
---|
190 | @Deprecated // use findZipEntryInputStream
|
---|
191 | public InputStream getZipEntry(String extension, String namepart) {
|
---|
192 | return findZipEntryInputStream(extension, namepart);
|
---|
193 | }
|
---|
194 |
|
---|
195 | private Pair<String, InputStream> findZipEntryImpl(String extension, String namepart) {
|
---|
196 | if (file == null)
|
---|
197 | return null;
|
---|
198 | Pair<String, InputStream> res = null;
|
---|
199 | try {
|
---|
200 | ZipFile zipFile = new ZipFile(file);
|
---|
201 | ZipEntry resentry = null;
|
---|
202 | Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
---|
203 | while (entries.hasMoreElements()) {
|
---|
204 | ZipEntry entry = entries.nextElement();
|
---|
205 | if (entry.getName().endsWith("." + extension)) {
|
---|
206 | /* choose any file with correct extension. When more than
|
---|
207 | one file, prefer the one which matches namepart */
|
---|
208 | if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
|
---|
209 | resentry = entry;
|
---|
210 | }
|
---|
211 | }
|
---|
212 | }
|
---|
213 | if (resentry != null) {
|
---|
214 | InputStream is = zipFile.getInputStream(resentry);
|
---|
215 | res = Pair.create(resentry.getName(), is);
|
---|
216 | } else {
|
---|
217 | Utils.close(zipFile);
|
---|
218 | }
|
---|
219 | } catch (Exception e) {
|
---|
220 | if (file.getName().endsWith(".zip")) {
|
---|
221 | Main.warn(tr("Failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
|
---|
222 | file.getName(), e.toString(), extension, namepart));
|
---|
223 | }
|
---|
224 | }
|
---|
225 | return res;
|
---|
226 | }
|
---|
227 |
|
---|
228 | public File getFile() {
|
---|
229 | return file;
|
---|
230 | }
|
---|
231 |
|
---|
232 | public static void cleanup(String name) {
|
---|
233 | cleanup(name, null);
|
---|
234 | }
|
---|
235 |
|
---|
236 | public static void cleanup(String name, String destDir) {
|
---|
237 | URL url;
|
---|
238 | try {
|
---|
239 | url = new URL(name);
|
---|
240 | if (!url.getProtocol().equals("file")) {
|
---|
241 | String prefKey = getPrefKey(url, destDir);
|
---|
242 | List<String> localPath = new ArrayList<String>(Main.pref.getCollection(prefKey));
|
---|
243 | if (localPath.size() == 2) {
|
---|
244 | File lfile = new File(localPath.get(1));
|
---|
245 | if(lfile.exists()) {
|
---|
246 | lfile.delete();
|
---|
247 | }
|
---|
248 | }
|
---|
249 | Main.pref.putCollection(prefKey, null);
|
---|
250 | }
|
---|
251 | } catch (MalformedURLException e) {
|
---|
252 | Main.warn(e);
|
---|
253 | }
|
---|
254 | }
|
---|
255 |
|
---|
256 | /**
|
---|
257 | * get preference key to store the location and age of the cached file.
|
---|
258 | * 2 resources that point to the same url, but that are to be stored in different
|
---|
259 | * directories will not share a cache file.
|
---|
260 | */
|
---|
261 | private static String getPrefKey(URL url, String destDir) {
|
---|
262 | StringBuilder prefKey = new StringBuilder("mirror.");
|
---|
263 | if (destDir != null) {
|
---|
264 | prefKey.append(destDir);
|
---|
265 | prefKey.append(".");
|
---|
266 | }
|
---|
267 | prefKey.append(url.toString());
|
---|
268 | return prefKey.toString().replaceAll("=","_");
|
---|
269 | }
|
---|
270 |
|
---|
271 | private File checkLocal(URL url, String destDir, long maxTime, String httpAccept) throws IOException {
|
---|
272 | String prefKey = getPrefKey(url, destDir);
|
---|
273 | long age = 0L;
|
---|
274 | File localFile = null;
|
---|
275 | List<String> localPathEntry = new ArrayList<String>(Main.pref.getCollection(prefKey));
|
---|
276 | if (localPathEntry.size() == 2) {
|
---|
277 | localFile = new File(localPathEntry.get(1));
|
---|
278 | if(!localFile.exists())
|
---|
279 | localFile = null;
|
---|
280 | else {
|
---|
281 | if ( maxTime == DEFAULT_MAXTIME
|
---|
282 | || maxTime <= 0 // arbitrary value <= 0 is deprecated
|
---|
283 | ) {
|
---|
284 | maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
|
---|
285 | }
|
---|
286 | age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
|
---|
287 | if (age < maxTime*1000) {
|
---|
288 | return localFile;
|
---|
289 | }
|
---|
290 | }
|
---|
291 | }
|
---|
292 | if (destDir == null) {
|
---|
293 | destDir = Main.pref.getCacheDirectory().getPath();
|
---|
294 | }
|
---|
295 |
|
---|
296 | File destDirFile = new File(destDir);
|
---|
297 | if (!destDirFile.exists()) {
|
---|
298 | destDirFile.mkdirs();
|
---|
299 | }
|
---|
300 |
|
---|
301 | String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
|
---|
302 | String localPath = "mirror_" + a;
|
---|
303 | destDirFile = new File(destDir, localPath + ".tmp");
|
---|
304 | BufferedOutputStream bos = null;
|
---|
305 | BufferedInputStream bis = null;
|
---|
306 | try {
|
---|
307 | HttpURLConnection con = connectFollowingRedirect(url, httpAccept);
|
---|
308 | bis = new BufferedInputStream(con.getInputStream());
|
---|
309 | FileOutputStream fos = new FileOutputStream(destDirFile);
|
---|
310 | bos = new BufferedOutputStream(fos);
|
---|
311 | byte[] buffer = new byte[4096];
|
---|
312 | int length;
|
---|
313 | while ((length = bis.read(buffer)) > -1) {
|
---|
314 | bos.write(buffer, 0, length);
|
---|
315 | }
|
---|
316 | Utils.close(bos);
|
---|
317 | bos = null;
|
---|
318 | /* close fos as well to be sure! */
|
---|
319 | Utils.close(fos);
|
---|
320 | fos = null;
|
---|
321 | localFile = new File(destDir, localPath);
|
---|
322 | if(Main.platform.rename(destDirFile, localFile)) {
|
---|
323 | Main.pref.putCollection(prefKey, Arrays.asList(new String[]
|
---|
324 | {Long.toString(System.currentTimeMillis()), localFile.toString()}));
|
---|
325 | } else {
|
---|
326 | Main.warn(tr("Failed to rename file {0} to {1}.",
|
---|
327 | destDirFile.getPath(), localFile.getPath()));
|
---|
328 | }
|
---|
329 | } catch (IOException e) {
|
---|
330 | if (age >= maxTime*1000 && age < maxTime*1000*2) {
|
---|
331 | Main.warn(tr("Failed to load {0}, use cached file and retry next time: {1}", url, e));
|
---|
332 | return localFile;
|
---|
333 | } else {
|
---|
334 | throw e;
|
---|
335 | }
|
---|
336 | } finally {
|
---|
337 | Utils.close(bis);
|
---|
338 | Utils.close(bos);
|
---|
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 | }
|
---|