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