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

Last change on this file since 4908 was 4812, checked in by bastiK, 12 years ago

use cache folder for MirroredInputStream as well

  • Property svn:eol-style set to native
File size: 12.5 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
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.net.HttpURLConnection;
14import java.net.MalformedURLException;
15import java.net.URL;
16import java.net.URLConnection;
17import java.util.ArrayList;
18import java.util.Arrays;
19import java.util.Collection;
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.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 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 URLConnection conn = url.openConnection();
74 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
75 conn.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
76 fs = new BufferedInputStream(conn.getInputStream());
77 file = new File(url.getFile());
78 } else {
79 file = checkLocal(url, destDir, maxTime);
80 }
81 }
82 } catch (java.net.MalformedURLException e) {
83 if (name.startsWith("resource://")) {
84 fs = getClass().getResourceAsStream(
85 name.substring("resource:/".length()));
86 if (fs == null)
87 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
88 return;
89 }
90 file = new File(name);
91 }
92 if (file == null)
93 throw new IOException();
94 fs = new FileInputStream(file);
95 }
96
97 /**
98 * Replies an input stream for a file in a ZIP-file. Replies a file in the top
99 * level directory of the ZIP file which has an extension <code>extension</code>. If more
100 * than one files have this extension, the last file whose name includes <code>namepart</code>
101 * is opened.
102 *
103 * @param extension the extension of the file we're looking for
104 * @param namepart the name part
105 * @return an input stream. Null if this mirrored input stream doesn't represent a zip file or if
106 * there was no matching file in the ZIP file
107 */
108 public InputStream getZipEntry(String extension, String namepart) {
109 if (file == null)
110 return null;
111 InputStream res = null;
112 try {
113 ZipFile zipFile = new ZipFile(file);
114 ZipEntry resentry = null;
115 Enumeration<? extends ZipEntry> entries = zipFile.entries();
116 while (entries.hasMoreElements()) {
117 ZipEntry entry = entries.nextElement();
118 if (entry.getName().endsWith("." + extension)) {
119 /* choose any file with correct extension. When more than
120 one file, prefer the one which matches namepart */
121 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
122 resentry = entry;
123 }
124 }
125 }
126 if (resentry != null) {
127 res = zipFile.getInputStream(resentry);
128 } else {
129 zipFile.close();
130 }
131 } catch (Exception e) {
132 if(file.getName().endsWith(".zip")) {
133 System.err.println(tr("Warning: failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
134 file.getName(), e.toString(), extension, namepart));
135 }
136 }
137 return res;
138 }
139
140 public File getFile()
141 {
142 return file;
143 }
144
145 static public void cleanup(String name)
146 {
147 cleanup(name, null);
148 }
149 static public void cleanup(String name, String destDir)
150 {
151 URL url;
152 try {
153 url = new URL(name);
154 if (!url.getProtocol().equals("file"))
155 {
156 String prefKey = getPrefKey(url, destDir);
157 List<String> localPath = new ArrayList<String>(Main.pref.getCollection(prefKey));
158 if (localPath.size() == 2) {
159 File lfile = new File(localPath.get(1));
160 if(lfile.exists()) {
161 lfile.delete();
162 }
163 }
164 Main.pref.putCollection(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 prefKey.append(destDir);
178 prefKey.append(".");
179 }
180 prefKey.append(url.toString());
181 return prefKey.toString().replaceAll("=","_");
182 }
183
184 private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
185 String prefKey = getPrefKey(url, destDir);
186 long age = 0L;
187 File localFile = null;
188 List<String> localPathEntry = new ArrayList<String>(Main.pref.getCollection(prefKey));
189 if (localPathEntry.size() == 2) {
190 localFile = new File(localPathEntry.get(1));
191 if(!localFile.exists())
192 localFile = null;
193 else {
194 if ( maxTime == DEFAULT_MAXTIME
195 || maxTime <= 0 // arbitrary value <= 0 is deprecated
196 ) {
197 maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60); // one week
198 }
199 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
200 if (age < maxTime*1000) {
201 return localFile;
202 }
203 }
204 }
205 if (destDir == null) {
206 destDir = Main.pref.getCacheDirectory().getPath();
207 }
208
209 File destDirFile = new File(destDir);
210 if (!destDirFile.exists()) {
211 destDirFile.mkdirs();
212 }
213
214 String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
215 String localPath = "mirror_" + a;
216 destDirFile = new File(destDir, localPath + ".tmp");
217 BufferedOutputStream bos = null;
218 BufferedInputStream bis = null;
219 try {
220 HttpURLConnection con = connectFollowingRedirect(url);
221 bis = new BufferedInputStream(con.getInputStream());
222 FileOutputStream fos = new FileOutputStream(destDirFile);
223 bos = new BufferedOutputStream(fos);
224 byte[] buffer = new byte[4096];
225 int length;
226 while ((length = bis.read(buffer)) > -1) {
227 bos.write(buffer, 0, length);
228 }
229 bos.close();
230 bos = null;
231 /* close fos as well to be sure! */
232 fos.close();
233 fos = null;
234 localFile = new File(destDir, localPath);
235 if(Main.platform.rename(destDirFile, localFile)) {
236 Main.pref.putCollection(prefKey, Arrays.asList(new String[]
237 {Long.toString(System.currentTimeMillis()), localFile.toString()}));
238 } else {
239 System.out.println(tr("Failed to rename file {0} to {1}.",
240 destDirFile.getPath(), localFile.getPath()));
241 }
242 } catch (IOException e) {
243 if (age >= maxTime*1000 && age < maxTime*1000*2) {
244 System.out.println(tr("Failed to load {0}, use cached file and retry next time: {1}",
245 url, e));
246 return localFile;
247 } else {
248 throw e;
249 }
250 } finally {
251 Utils.close(bis);
252 Utils.close(bos);
253 }
254
255 return localFile;
256 }
257
258 /**
259 * Opens a connection for downloading a resource.
260 * <p>
261 * Manually follows redirects because
262 * {@link HttpURLConnection#setFollowRedirects(boolean)} fails if the redirect
263 * 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>.
264 * <p>
265 * This can causes problems when downloading from certain GitHub URLs.
266 */
267 protected HttpURLConnection connectFollowingRedirect(URL downloadUrl) throws MalformedURLException, IOException {
268 HttpURLConnection con = null;
269 int numRedirects = 0;
270 while(true) {
271 con = (HttpURLConnection)downloadUrl.openConnection();
272 con.setInstanceFollowRedirects(false);
273 con.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
274 con.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
275 con.connect();
276 switch(con.getResponseCode()) {
277 case HttpURLConnection.HTTP_OK:
278 return con;
279 case HttpURLConnection.HTTP_MOVED_PERM:
280 case HttpURLConnection.HTTP_MOVED_TEMP:
281 case HttpURLConnection.HTTP_SEE_OTHER:
282 String redirectLocation = con.getHeaderField("Location");
283 if (downloadUrl == null) {
284 /* 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());
285 throw new IOException(msg);
286 }
287 downloadUrl = new URL(redirectLocation);
288 // keep track of redirect attempts to break a redirect loops if it happens
289 // to occur for whatever reason
290 numRedirects++;
291 if (numRedirects >= Main.pref.getInteger("socket.maxredirects", 5)) {
292 String msg = tr("Too many redirects to the download URL detected. Aborting.");
293 throw new IOException(msg);
294 }
295 System.out.println(tr("Download redirected to ''{0}''", downloadUrl));
296 break;
297 default:
298 String msg = tr("Failed to read from ''{0}''. Server responded with status code {1}.", downloadUrl, con.getResponseCode());
299 throw new IOException(msg);
300 }
301 }
302 }
303
304 @Override
305 public int available() throws IOException
306 { return fs.available(); }
307 @Override
308 public void close() throws IOException
309 { fs.close(); }
310 @Override
311 public int read() throws IOException
312 { return fs.read(); }
313 @Override
314 public int read(byte[] b) throws IOException
315 { return fs.read(b); }
316 @Override
317 public int read(byte[] b, int off, int len) throws IOException
318 { return fs.read(b,off, len); }
319 @Override
320 public long skip(long n) throws IOException
321 { return fs.skip(n); }
322}
Note: See TracBrowser for help on using the repository browser.