1 | // License: GPL. Copyright 2007 by Immanuel Scholz and others
|
---|
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.net.URLConnection;
|
---|
17 | import java.util.ArrayList;
|
---|
18 | import java.util.Arrays;
|
---|
19 | import java.util.Collection;
|
---|
20 | import java.util.Enumeration;
|
---|
21 | import java.util.List;
|
---|
22 | import java.util.zip.ZipEntry;
|
---|
23 | import java.util.zip.ZipFile;
|
---|
24 |
|
---|
25 | import org.openstreetmap.josm.Main;
|
---|
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 | public MirroredInputStream(String name) throws IOException {
|
---|
39 | this(name, null, DEFAULT_MAXTIME);
|
---|
40 | }
|
---|
41 |
|
---|
42 | public MirroredInputStream(String name, long maxTime) throws IOException {
|
---|
43 | this(name, null, maxTime);
|
---|
44 | }
|
---|
45 |
|
---|
46 | public MirroredInputStream(String name, String destDir) throws IOException {
|
---|
47 | this(name, destDir, DEFAULT_MAXTIME);
|
---|
48 | }
|
---|
49 |
|
---|
50 | /**
|
---|
51 | * Get an inputstream from a given filename, url or internal resource.
|
---|
52 | * @param name can be
|
---|
53 | * - relative or absolute file name
|
---|
54 | * - file:///SOME/FILE the same as above
|
---|
55 | * - resource://SOME/FILE file from the classpath (usually in the current *.jar)
|
---|
56 | * - http://... a url. It will be cached on disk.
|
---|
57 | * @param destDir the destination directory for the cache file. only applies for urls.
|
---|
58 | * @param maxTime the maximum age of the cache file (in seconds)
|
---|
59 | * @throws IOException when the resource with the given name could not be retrieved
|
---|
60 | */
|
---|
61 | public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
|
---|
62 | URL url;
|
---|
63 | try {
|
---|
64 | url = new URL(name);
|
---|
65 | if (url.getProtocol().equals("file")) {
|
---|
66 | file = new File(name.substring("file:/".length()));
|
---|
67 | if (!file.exists()) {
|
---|
68 | file = new File(name.substring("file://".length()));
|
---|
69 | }
|
---|
70 | } else {
|
---|
71 | if(Main.applet) {
|
---|
72 | URLConnection conn = url.openConnection();
|
---|
73 | conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
|
---|
74 | conn.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
|
---|
75 | fs = new BufferedInputStream(conn.getInputStream());
|
---|
76 | file = new File(url.getFile());
|
---|
77 | } else {
|
---|
78 | file = checkLocal(url, destDir, maxTime);
|
---|
79 | }
|
---|
80 | }
|
---|
81 | } catch (java.net.MalformedURLException e) {
|
---|
82 | if(name.startsWith("resource://")) {
|
---|
83 | fs = getClass().getResourceAsStream(
|
---|
84 | name.substring("resource:/".length()));
|
---|
85 | if (fs == null)
|
---|
86 | throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
|
---|
87 | return;
|
---|
88 | }
|
---|
89 | file = new File(name);
|
---|
90 | }
|
---|
91 | if (file == null)
|
---|
92 | throw new IOException();
|
---|
93 | fs = new FileInputStream(file);
|
---|
94 | }
|
---|
95 |
|
---|
96 | /**
|
---|
97 | * Replies an input stream for a file in a ZIP-file. Replies a file in the top
|
---|
98 | * level directory of the ZIP file which has an extension <code>extension</code>. If more
|
---|
99 | * than one files have this extension, the last file whose name includes <code>namepart</code>
|
---|
100 | * is opened.
|
---|
101 | *
|
---|
102 | * @param extension the extension of the file we're looking for
|
---|
103 | * @param namepart the name part
|
---|
104 | * @return an input stream. Null if this mirrored input stream doesn't represent a zip file or if
|
---|
105 | * there was no matching file in the ZIP file
|
---|
106 | */
|
---|
107 | public InputStream getZipEntry(String extension, String namepart) {
|
---|
108 | if (file == null)
|
---|
109 | return null;
|
---|
110 | InputStream res = null;
|
---|
111 | try {
|
---|
112 | ZipFile zipFile = new ZipFile(file);
|
---|
113 | ZipEntry resentry = null;
|
---|
114 | Enumeration<? extends ZipEntry> entries = zipFile.entries();
|
---|
115 | while (entries.hasMoreElements()) {
|
---|
116 | ZipEntry entry = entries.nextElement();
|
---|
117 | if (entry.getName().endsWith("." + extension)) {
|
---|
118 | /* choose any file with correct extension. When more than
|
---|
119 | one file, prefer the one which matches namepart */
|
---|
120 | if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
|
---|
121 | resentry = entry;
|
---|
122 | }
|
---|
123 | }
|
---|
124 | }
|
---|
125 | if (resentry != null) {
|
---|
126 | res = zipFile.getInputStream(resentry);
|
---|
127 | } else {
|
---|
128 | zipFile.close();
|
---|
129 | }
|
---|
130 | } catch (Exception e) {
|
---|
131 | if(file.getName().endsWith(".zip")) {
|
---|
132 | System.err.println(tr("Warning: failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
|
---|
133 | file.getName(), e.toString(), extension, namepart));
|
---|
134 | }
|
---|
135 | }
|
---|
136 | return res;
|
---|
137 | }
|
---|
138 |
|
---|
139 | public File getFile()
|
---|
140 | {
|
---|
141 | return file;
|
---|
142 | }
|
---|
143 |
|
---|
144 | static public void cleanup(String name)
|
---|
145 | {
|
---|
146 | cleanup(name, null);
|
---|
147 | }
|
---|
148 | static public void cleanup(String name, String destDir)
|
---|
149 | {
|
---|
150 | URL url;
|
---|
151 | try {
|
---|
152 | url = new URL(name);
|
---|
153 | if (!url.getProtocol().equals("file"))
|
---|
154 | {
|
---|
155 | String prefKey = getPrefKey(url, destDir);
|
---|
156 | Collection<String> localPath = Main.pref.getCollection(prefKey);
|
---|
157 | if(localPath.size() == 2) {
|
---|
158 | String[] lp = (String[]) localPath.toArray();
|
---|
159 | File lfile = new File(lp[1]);
|
---|
160 | if(lfile.exists()) {
|
---|
161 | lfile.delete();
|
---|
162 | }
|
---|
163 | }
|
---|
164 | Main.pref.put(prefKey, null);
|
---|
165 | }
|
---|
166 | } catch (java.net.MalformedURLException e) {}
|
---|
167 | }
|
---|
168 |
|
---|
169 | /**
|
---|
170 | * get preference key to store the location and age of the cached file.
|
---|
171 | * 2 resources that point to the same url, but that are to be stored in different
|
---|
172 | * directories will not share a cache file.
|
---|
173 | */
|
---|
174 | private static String getPrefKey(URL url, String destDir) {
|
---|
175 | StringBuilder prefKey = new StringBuilder("mirror.");
|
---|
176 | if (destDir != null) {
|
---|
177 | String prefDir = Main.pref.getPreferencesDir();
|
---|
178 | if (destDir.startsWith(prefDir)) {
|
---|
179 | destDir = destDir.substring(prefDir.length());
|
---|
180 | }
|
---|
181 | prefKey.append(destDir);
|
---|
182 | prefKey.append(".");
|
---|
183 | }
|
---|
184 | prefKey.append(url.toString());
|
---|
185 | return prefKey.toString().replaceAll("=","_");
|
---|
186 | }
|
---|
187 |
|
---|
188 | private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
|
---|
189 | String prefKey = getPrefKey(url, destDir);
|
---|
190 | long age = 0L;
|
---|
191 | File localFile = null;
|
---|
192 | List<String> localPathEntry = new ArrayList<String>(Main.pref.getCollection(prefKey));
|
---|
193 | if (localPathEntry.size() == 2) {
|
---|
194 | localFile = new File(localPathEntry.get(1));
|
---|
195 | if(!localFile.exists())
|
---|
196 | localFile = null;
|
---|
197 | else {
|
---|
198 | if ( maxTime == DEFAULT_MAXTIME
|
---|
199 | || maxTime <= 0 // arbitrary value <= 0 is deprecated
|
---|
200 | ) {
|
---|
201 | maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60);
|
---|
202 | }
|
---|
203 | age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
|
---|
204 | if (age < maxTime*1000) {
|
---|
205 | return localFile;
|
---|
206 | }
|
---|
207 | }
|
---|
208 | }
|
---|
209 | if(destDir == null) {
|
---|
210 | destDir = Main.pref.getPreferencesDir();
|
---|
211 | }
|
---|
212 |
|
---|
213 | File destDirFile = new File(destDir);
|
---|
214 | if (!destDirFile.exists()) {
|
---|
215 | destDirFile.mkdirs();
|
---|
216 | }
|
---|
217 |
|
---|
218 | String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
|
---|
219 | String localPath = "mirror_" + a;
|
---|
220 | destDirFile = new File(destDir, localPath + ".tmp");
|
---|
221 | BufferedOutputStream bos = null;
|
---|
222 | BufferedInputStream bis = null;
|
---|
223 | try {
|
---|
224 | HttpURLConnection con = connectFollowingRedirect(url);
|
---|
225 | bis = new BufferedInputStream(con.getInputStream());
|
---|
226 | FileOutputStream fos = new FileOutputStream(destDirFile);
|
---|
227 | bos = new BufferedOutputStream(fos);
|
---|
228 | byte[] buffer = new byte[4096];
|
---|
229 | int length;
|
---|
230 | while ((length = bis.read(buffer)) > -1) {
|
---|
231 | bos.write(buffer, 0, length);
|
---|
232 | }
|
---|
233 | bos.close();
|
---|
234 | bos = null;
|
---|
235 | /* close fos as well to be sure! */
|
---|
236 | fos.close();
|
---|
237 | fos = null;
|
---|
238 | localFile = new File(destDir, localPath);
|
---|
239 | if(Main.platform.rename(destDirFile, localFile)) {
|
---|
240 | Main.pref.putCollection(prefKey, Arrays.asList(new String[]
|
---|
241 | {Long.toString(System.currentTimeMillis()), localFile.toString()}));
|
---|
242 | } else {
|
---|
243 | System.out.println(tr("Failed to rename file {0} to {1}.",
|
---|
244 | destDirFile.getPath(), localFile.getPath()));
|
---|
245 | }
|
---|
246 | } catch (IOException e) {
|
---|
247 | if (age >= maxTime*1000 && age < maxTime*1000*2) {
|
---|
248 | System.out.println(tr("Failed to load {0}, use cached file and retry next time: {1}",
|
---|
249 | url, e));
|
---|
250 | return localFile;
|
---|
251 | } else {
|
---|
252 | throw e;
|
---|
253 | }
|
---|
254 | } finally {
|
---|
255 | if (bis != null) {
|
---|
256 | try {
|
---|
257 | bis.close();
|
---|
258 | } catch (IOException e) {
|
---|
259 | e.printStackTrace();
|
---|
260 | }
|
---|
261 | }
|
---|
262 | if (bos != null) {
|
---|
263 | try {
|
---|
264 | bos.close();
|
---|
265 | } catch (IOException e) {
|
---|
266 | e.printStackTrace();
|
---|
267 | }
|
---|
268 | }
|
---|
269 | }
|
---|
270 |
|
---|
271 | return localFile;
|
---|
272 | }
|
---|
273 |
|
---|
274 | /**
|
---|
275 | * Opens a connection for downloading a resource.
|
---|
276 | * <p>
|
---|
277 | * Manually follows redirects because
|
---|
278 | * {@link HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
|
---|
279 | * is going from a http to a https URL, see <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4620571">bug report</a>.
|
---|
280 | * <p>
|
---|
281 | * This can causes problems when downloading from certain GitHub URLs.
|
---|
282 | */
|
---|
283 | protected HttpURLConnection connectFollowingRedirect(URL downloadUrl) throws MalformedURLException, IOException {
|
---|
284 | HttpURLConnection con = null;
|
---|
285 | int numRedirects = 0;
|
---|
286 | while(true) {
|
---|
287 | con = (HttpURLConnection)downloadUrl.openConnection();
|
---|
288 | con.setInstanceFollowRedirects(false);
|
---|
289 | con.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
|
---|
290 | con.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
|
---|
291 | con.connect();
|
---|
292 | switch(con.getResponseCode()) {
|
---|
293 | case HttpURLConnection.HTTP_OK:
|
---|
294 | return con;
|
---|
295 | case HttpURLConnection.HTTP_MOVED_PERM:
|
---|
296 | case HttpURLConnection.HTTP_MOVED_TEMP:
|
---|
297 | case HttpURLConnection.HTTP_SEE_OTHER:
|
---|
298 | String redirectLocation = con.getHeaderField("Location");
|
---|
299 | if (downloadUrl == null) {
|
---|
300 | /* 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());
|
---|
301 | throw new IOException(msg);
|
---|
302 | }
|
---|
303 | downloadUrl = new URL(redirectLocation);
|
---|
304 | // keep track of redirect attempts to break a redirect loops if it happens
|
---|
305 | // to occur for whatever reason
|
---|
306 | numRedirects++;
|
---|
307 | if (numRedirects >= Main.pref.getInteger("socket.maxredirects", 5)) {
|
---|
308 | String msg = tr("Too many redirects to the download URL detected. Aborting.");
|
---|
309 | throw new IOException(msg);
|
---|
310 | }
|
---|
311 | System.out.println(tr("Download redirected to ''{0}''", downloadUrl));
|
---|
312 | break;
|
---|
313 | default:
|
---|
314 | String msg = tr("Failed to read from ''{0}''. Server responded with status code {1}.", downloadUrl, con.getResponseCode());
|
---|
315 | throw new IOException(msg);
|
---|
316 | }
|
---|
317 | }
|
---|
318 | }
|
---|
319 |
|
---|
320 | @Override
|
---|
321 | public int available() throws IOException
|
---|
322 | { return fs.available(); }
|
---|
323 | @Override
|
---|
324 | public void close() throws IOException
|
---|
325 | { fs.close(); }
|
---|
326 | @Override
|
---|
327 | public int read() throws IOException
|
---|
328 | { return fs.read(); }
|
---|
329 | @Override
|
---|
330 | public int read(byte[] b) throws IOException
|
---|
331 | { return fs.read(b); }
|
---|
332 | @Override
|
---|
333 | public int read(byte[] b, int off, int len) throws IOException
|
---|
334 | { return fs.read(b,off, len); }
|
---|
335 | @Override
|
---|
336 | public long skip(long n) throws IOException
|
---|
337 | { return fs.skip(n); }
|
---|
338 | }
|
---|