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

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

see #7027 - internal structures for preferences (expect some problems next few days)

  • Property svn:eol-style set to native
File size: 13.0 KB
RevLine 
[906]1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm.io;
3
[2832]4import static org.openstreetmap.josm.tools.I18n.tr;
5
[906]6import java.io.BufferedInputStream;
7import java.io.BufferedOutputStream;
8import java.io.File;
9import java.io.FileInputStream;
10import java.io.FileOutputStream;
[2017]11import java.io.IOException;
[906]12import java.io.InputStream;
[4262]13import java.net.HttpURLConnection;
14import java.net.MalformedURLException;
[906]15import java.net.URL;
16import java.net.URLConnection;
[4612]17import java.util.ArrayList;
[4022]18import java.util.Arrays;
19import java.util.Collection;
[2889]20import java.util.Enumeration;
[4612]21import java.util.List;
[2889]22import java.util.zip.ZipEntry;
23import java.util.zip.ZipFile;
[906]24
25import org.openstreetmap.josm.Main;
26
27/**
28 * Mirrors a file to a local file.
29 * <p>
[3695]30 * The file mirrored is only downloaded if it has been more than 7 days since last download
[906]31 */
32public class MirroredInputStream extends InputStream {
[1169]33 InputStream fs = null;
[1711]34 File file = null;
[4262]35
[4240]36 public final static long DEFAULT_MAXTIME = -1l;
[906]37
[1523]38 public MirroredInputStream(String name) throws IOException {
[4240]39 this(name, null, DEFAULT_MAXTIME);
[1169]40 }
[906]41
[1523]42 public MirroredInputStream(String name, long maxTime) throws IOException {
[1169]43 this(name, null, maxTime);
44 }
[906]45
[1711]46 public MirroredInputStream(String name, String destDir) throws IOException {
[4240]47 this(name, destDir, DEFAULT_MAXTIME);
[1711]48 }
49
[3695]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 */
[1523]61 public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
[1169]62 URL url;
[1523]63 try {
[1169]64 url = new URL(name);
[1523]65 if (url.getProtocol().equals("file")) {
[1169]66 file = new File(name.substring("file:/".length()));
[2832]67 if (!file.exists()) {
[1169]68 file = new File(name.substring("file://".length()));
[2832]69 }
[1523]70 } else {
[3877]71 if(Main.applet) {
72 URLConnection conn = url.openConnection();
[4172]73 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);
74 conn.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000);
[3877]75 fs = new BufferedInputStream(conn.getInputStream());
76 file = new File(url.getFile());
77 } else {
78 file = checkLocal(url, destDir, maxTime);
79 }
[1169]80 }
[1523]81 } catch (java.net.MalformedURLException e) {
82 if(name.startsWith("resource://")) {
[1169]83 fs = getClass().getResourceAsStream(
[2832]84 name.substring("resource:/".length()));
85 if (fs == null)
86 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
[1169]87 return;
88 }
[1523]89 file = new File(name);
[1169]90 }
[1523]91 if (file == null)
[1169]92 throw new IOException();
93 fs = new FileInputStream(file);
94 }
[906]95
[3007]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.
[3321]101 *
[3007]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) {
[3011]108 if (file == null)
109 return null;
[2889]110 InputStream res = null;
111 try {
[3007]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
[2889]119 one file, prefer the one which matches namepart */
[3007]120 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
121 resentry = entry;
[2889]122 }
123 }
124 }
[3007]125 if (resentry != null) {
126 res = zipFile.getInputStream(resentry);
127 } else {
128 zipFile.close();
129 }
[2889]130 } catch (Exception e) {
[3041]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}",
[3321]133 file.getName(), e.toString(), extension, namepart));
[3041]134 }
[2889]135 }
136 return res;
137 }
138
[1711]139 public File getFile()
140 {
[2832]141 return file;
[1711]142 }
143
[1747]144 static public void cleanup(String name)
145 {
[2832]146 cleanup(name, null);
[1747]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 {
[3695]155 String prefKey = getPrefKey(url, destDir);
[4343]156 Collection<String> localPath = Main.pref.getCollection(prefKey);
[4022]157 if(localPath.size() == 2) {
158 String[] lp = (String[]) localPath.toArray();
[1747]159 File lfile = new File(lp[1]);
[2832]160 if(lfile.exists()) {
[1747]161 lfile.delete();
[2832]162 }
[1747]163 }
[3695]164 Main.pref.put(prefKey, null);
[1747]165 }
166 } catch (java.net.MalformedURLException e) {}
167 }
168
[3695]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());
[4022]185 return prefKey.toString().replaceAll("=","_");
[3695]186 }
187
[3321]188 private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
[3695]189 String prefKey = getPrefKey(url, destDir);
[4128]190 long age = 0L;
[4262]191 File localFile = null;
[4612]192 List<String> localPathEntry = new ArrayList<String>(Main.pref.getCollection(prefKey));
193 if (localPathEntry.size() == 2) {
194 localFile = new File(localPathEntry.get(1));
[4262]195 if(!localFile.exists())
196 localFile = null;
[3877]197 else {
[4262]198 if ( maxTime == DEFAULT_MAXTIME
[4240]199 || maxTime <= 0 // arbitrary value <= 0 is deprecated
200 ) {
[3877]201 maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60);
202 }
[4612]203 age = System.currentTimeMillis() - Long.parseLong(localPathEntry.get(0));
[4128]204 if (age < maxTime*1000) {
[4262]205 return localFile;
[3877]206 }
[1169]207 }
208 }
[2832]209 if(destDir == null) {
[1169]210 destDir = Main.pref.getPreferencesDir();
[2832]211 }
[906]212
[1169]213 File destDirFile = new File(destDir);
[2832]214 if (!destDirFile.exists()) {
[1169]215 destDirFile.mkdirs();
[2832]216 }
[906]217
[1743]218 String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
[4022]219 String localPath = "mirror_" + a;
[1169]220 destDirFile = new File(destDir, localPath + ".tmp");
221 BufferedOutputStream bos = null;
222 BufferedInputStream bis = null;
[1523]223 try {
[4262]224 HttpURLConnection con = connectFollowingRedirect(url);
225 bis = new BufferedInputStream(con.getInputStream());
[4145]226 FileOutputStream fos = new FileOutputStream(destDirFile);
227 bos = new BufferedOutputStream(fos);
[1169]228 byte[] buffer = new byte[4096];
229 int length;
[2832]230 while ((length = bis.read(buffer)) > -1) {
[1169]231 bos.write(buffer, 0, length);
[2832]232 }
[3877]233 bos.close();
234 bos = null;
[4145]235 /* close fos as well to be sure! */
236 fos.close();
237 fos = null;
[4262]238 localFile = new File(destDir, localPath);
239 if(Main.platform.rename(destDirFile, localFile)) {
[4145]240 Main.pref.putCollection(prefKey, Arrays.asList(new String[]
[4262]241 {Long.toString(System.currentTimeMillis()), localFile.toString()}));
[4145]242 } else {
243 System.out.println(tr("Failed to rename file {0} to {1}.",
[4262]244 destDirFile.getPath(), localFile.getPath()));
[4145]245 }
[4128]246 } catch (IOException e) {
[4130]247 if (age >= maxTime*1000 && age < maxTime*1000*2) {
[4128]248 System.out.println(tr("Failed to load {0}, use cached file and retry next time: {1}",
249 url, e));
[4262]250 return localFile;
[4128]251 } else {
252 throw e;
253 }
[1523]254 } finally {
255 if (bis != null) {
256 try {
[1169]257 bis.close();
[1523]258 } catch (IOException e) {
[1169]259 e.printStackTrace();
260 }
261 }
[1523]262 if (bos != null) {
263 try {
[1169]264 bos.close();
[1523]265 } catch (IOException e) {
[1169]266 e.printStackTrace();
267 }
268 }
269 }
[906]270
[4262]271 return localFile;
[1169]272 }
[4262]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) {
[4278]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());
[4262]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)) {
[4278]308 String msg = tr("Too many redirects to the download URL detected. Aborting.");
[4262]309 throw new IOException(msg);
310 }
311 System.out.println(tr("Download redirected to ''{0}''", downloadUrl));
312 break;
313 default:
[4278]314 String msg = tr("Failed to read from ''{0}''. Server responded with status code {1}.", downloadUrl, con.getResponseCode());
[4262]315 throw new IOException(msg);
316 }
317 }
318 }
319
[2832]320 @Override
[1169]321 public int available() throws IOException
322 { return fs.available(); }
[2832]323 @Override
[1169]324 public void close() throws IOException
325 { fs.close(); }
[2832]326 @Override
[1169]327 public int read() throws IOException
328 { return fs.read(); }
[2832]329 @Override
[1169]330 public int read(byte[] b) throws IOException
331 { return fs.read(b); }
[2832]332 @Override
[1169]333 public int read(byte[] b, int off, int len) throws IOException
334 { return fs.read(b,off, len); }
[2832]335 @Override
[1169]336 public long skip(long n) throws IOException
337 { return fs.skip(n); }
[906]338}
Note: See TracBrowser for help on using the repository browser.