001 // License: GPL. Copyright 2007 by Immanuel Scholz and others 002 package org.openstreetmap.josm.io; 003 004 import static org.openstreetmap.josm.tools.I18n.tr; 005 006 import java.io.BufferedInputStream; 007 import java.io.BufferedOutputStream; 008 import java.io.File; 009 import java.io.FileInputStream; 010 import java.io.FileOutputStream; 011 import java.io.IOException; 012 import java.io.InputStream; 013 import java.net.HttpURLConnection; 014 import java.net.MalformedURLException; 015 import java.net.URL; 016 import java.net.URLConnection; 017 import java.util.ArrayList; 018 import java.util.Arrays; 019 import java.util.Collection; 020 import java.util.Enumeration; 021 import java.util.List; 022 import java.util.zip.ZipEntry; 023 import java.util.zip.ZipFile; 024 025 import org.openstreetmap.josm.Main; 026 import org.openstreetmap.josm.tools.Utils; 027 028 /** 029 * Mirrors a file to a local file. 030 * <p> 031 * The file mirrored is only downloaded if it has been more than 7 days since last download 032 */ 033 public class MirroredInputStream extends InputStream { 034 InputStream fs = null; 035 File file = null; 036 037 public final static long DEFAULT_MAXTIME = -1l; 038 039 public MirroredInputStream(String name) throws IOException { 040 this(name, null, DEFAULT_MAXTIME); 041 } 042 043 public MirroredInputStream(String name, long maxTime) throws IOException { 044 this(name, null, maxTime); 045 } 046 047 public MirroredInputStream(String name, String destDir) throws IOException { 048 this(name, destDir, DEFAULT_MAXTIME); 049 } 050 051 /** 052 * Get an inputstream from a given filename, url or internal resource. 053 * @param name can be 054 * - relative or absolute file name 055 * - file:///SOME/FILE the same as above 056 * - resource://SOME/FILE file from the classpath (usually in the current *.jar) 057 * - http://... a url. It will be cached on disk. 058 * @param destDir the destination directory for the cache file. only applies for urls. 059 * @param maxTime the maximum age of the cache file (in seconds) 060 * @throws IOException when the resource with the given name could not be retrieved 061 */ 062 public MirroredInputStream(String name, String destDir, long maxTime) throws IOException { 063 URL url; 064 try { 065 url = new URL(name); 066 if (url.getProtocol().equals("file")) { 067 file = new File(name.substring("file:/".length())); 068 if (!file.exists()) { 069 file = new File(name.substring("file://".length())); 070 } 071 } else { 072 if (Main.applet) { 073 URLConnection conn = url.openConnection(); 074 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000); 075 conn.setReadTimeout(Main.pref.getInteger("socket.timeout.read",30)*1000); 076 fs = new BufferedInputStream(conn.getInputStream()); 077 file = new File(url.getFile()); 078 } else { 079 file = checkLocal(url, destDir, maxTime); 080 } 081 } 082 } catch (java.net.MalformedURLException e) { 083 if (name.startsWith("resource://")) { 084 fs = getClass().getResourceAsStream( 085 name.substring("resource:/".length())); 086 if (fs == null) 087 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name)); 088 return; 089 } 090 file = new File(name); 091 } 092 if (file == null) 093 throw new IOException(); 094 fs = new FileInputStream(file); 095 } 096 097 /** 098 * Replies an input stream for a file in a ZIP-file. Replies a file in the top 099 * 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 }