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

Last change on this file since 3965 was 3877, checked in by stoecker, 13 years ago

fix input stream mirroring

  • Property svn:eol-style set to native
File size: 9.4 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.URL;
14import java.net.URLConnection;
15import java.util.Enumeration;
16import java.util.zip.ZipEntry;
17import java.util.zip.ZipFile;
18
19import org.openstreetmap.josm.Main;
20
21/**
22 * Mirrors a file to a local file.
23 * <p>
24 * The file mirrored is only downloaded if it has been more than 7 days since last download
25 */
26public class MirroredInputStream extends InputStream {
27 InputStream fs = null;
28 File file = null;
29
30 public MirroredInputStream(String name) throws IOException {
31 this(name, null, -1L);
32 }
33
34 public MirroredInputStream(String name, long maxTime) throws IOException {
35 this(name, null, maxTime);
36 }
37
38 public MirroredInputStream(String name, String destDir) throws IOException {
39 this(name, destDir, -1L);
40 }
41
42 /**
43 * Get an inputstream from a given filename, url or internal resource.
44 * @param name can be
45 * - relative or absolute file name
46 * - file:///SOME/FILE the same as above
47 * - resource://SOME/FILE file from the classpath (usually in the current *.jar)
48 * - http://... a url. It will be cached on disk.
49 * @param destDir the destination directory for the cache file. only applies for urls.
50 * @param maxTime the maximum age of the cache file (in seconds)
51 * @throws IOException when the resource with the given name could not be retrieved
52 */
53 public MirroredInputStream(String name, String destDir, long maxTime) throws IOException {
54 URL url;
55 try {
56 url = new URL(name);
57 if (url.getProtocol().equals("file")) {
58 file = new File(name.substring("file:/".length()));
59 if (!file.exists()) {
60 file = new File(name.substring("file://".length()));
61 }
62 } else {
63 if(Main.applet) {
64 URLConnection conn = url.openConnection();
65 conn.setConnectTimeout(5000);
66 conn.setReadTimeout(5000);
67 fs = new BufferedInputStream(conn.getInputStream());
68 file = new File(url.getFile());
69 } else {
70 file = checkLocal(url, destDir, maxTime);
71 }
72 }
73 } catch (java.net.MalformedURLException e) {
74 if(name.startsWith("resource://")) {
75 fs = getClass().getResourceAsStream(
76 name.substring("resource:/".length()));
77 if (fs == null)
78 throw new IOException(tr("Failed to open input stream for resource ''{0}''", name));
79 return;
80 }
81 file = new File(name);
82 }
83 if (file == null)
84 throw new IOException();
85 fs = new FileInputStream(file);
86 }
87
88 /**
89 * Replies an input stream for a file in a ZIP-file. Replies a file in the top
90 * level directory of the ZIP file which has an extension <code>extension</code>. If more
91 * than one files have this extension, the last file whose name includes <code>namepart</code>
92 * is opened.
93 *
94 * @param extension the extension of the file we're looking for
95 * @param namepart the name part
96 * @return an input stream. Null if this mirrored input stream doesn't represent a zip file or if
97 * there was no matching file in the ZIP file
98 */
99 public InputStream getZipEntry(String extension, String namepart) {
100 if (file == null)
101 return null;
102 InputStream res = null;
103 try {
104 ZipFile zipFile = new ZipFile(file);
105 ZipEntry resentry = null;
106 Enumeration<? extends ZipEntry> entries = zipFile.entries();
107 while (entries.hasMoreElements()) {
108 ZipEntry entry = entries.nextElement();
109 if (entry.getName().endsWith("." + extension)) {
110 /* choose any file with correct extension. When more than
111 one file, prefer the one which matches namepart */
112 if (resentry == null || entry.getName().indexOf(namepart) >= 0) {
113 resentry = entry;
114 }
115 }
116 }
117 if (resentry != null) {
118 res = zipFile.getInputStream(resentry);
119 } else {
120 zipFile.close();
121 }
122 } catch (Exception e) {
123 if(file.getName().endsWith(".zip")) {
124 System.err.println(tr("Warning: failed to open file with extension ''{2}'' and namepart ''{3}'' in zip file ''{0}''. Exception was: {1}",
125 file.getName(), e.toString(), extension, namepart));
126 }
127 }
128 return res;
129 }
130
131 public File getFile()
132 {
133 return file;
134 }
135
136 static public void cleanup(String name)
137 {
138 cleanup(name, null);
139 }
140 static public void cleanup(String name, String destDir)
141 {
142 URL url;
143 try {
144 url = new URL(name);
145 if (!url.getProtocol().equals("file"))
146 {
147 String prefKey = getPrefKey(url, destDir);
148 String localPath = Main.pref.get(prefKey);
149 if (localPath != null && localPath.length() > 0)
150 {
151 String[] lp = localPath.split(";");
152 File lfile = new File(lp[1]);
153 if(lfile.exists()) {
154 lfile.delete();
155 }
156 }
157 Main.pref.put(prefKey, null);
158 }
159 } catch (java.net.MalformedURLException e) {}
160 }
161
162 /**
163 * get preference key to store the location and age of the cached file.
164 * 2 resources that point to the same url, but that are to be stored in different
165 * directories will not share a cache file.
166 */
167 private static String getPrefKey(URL url, String destDir) {
168 StringBuilder prefKey = new StringBuilder("mirror.");
169 if (destDir != null) {
170 String prefDir = Main.pref.getPreferencesDir();
171 if (destDir.startsWith(prefDir)) {
172 destDir = destDir.substring(prefDir.length());
173 }
174 prefKey.append(destDir);
175 prefKey.append(".");
176 }
177 prefKey.append(url.toString());
178 return prefKey.toString();
179 }
180
181 private File checkLocal(URL url, String destDir, long maxTime) throws IOException {
182 String prefKey = getPrefKey(url, destDir);
183 String localPath = Main.pref.get(prefKey);
184 File file = null;
185 if (localPath != null && localPath.length() > 0) {
186 String[] lp = localPath.split(";");
187 file = new File(lp[1]);
188 if(!file.exists())
189 file = null;
190 else {
191 if (maxTime <= 0) {
192 maxTime = Main.pref.getInteger("mirror.maxtime", 7*24*60*60);
193 }
194 if (System.currentTimeMillis() - Long.parseLong(lp[0]) < maxTime*1000) {
195 return file;
196 }
197 }
198 }
199 if(destDir == null) {
200 destDir = Main.pref.getPreferencesDir();
201 }
202
203 File destDirFile = new File(destDir);
204 if (!destDirFile.exists()) {
205 destDirFile.mkdirs();
206 }
207
208 String a = url.toString().replaceAll("[^A-Za-z0-9_.-]", "_");
209 localPath = "mirror_" + a;
210 destDirFile = new File(destDir, localPath + ".tmp");
211 BufferedOutputStream bos = null;
212 BufferedInputStream bis = null;
213 try {
214 URLConnection conn = url.openConnection();
215 conn.setConnectTimeout(5000);
216 conn.setReadTimeout(5000);
217 bis = new BufferedInputStream(conn.getInputStream());
218 bos = new BufferedOutputStream( new FileOutputStream(destDirFile));
219 byte[] buffer = new byte[4096];
220 int length;
221 while ((length = bis.read(buffer)) > -1) {
222 bos.write(buffer, 0, length);
223 }
224 bos.close();
225 bos = null;
226 file = new File(destDir, localPath);
227 destDirFile.renameTo(file);
228 Main.pref.put(prefKey, System.currentTimeMillis() + ";" + file);
229 } finally {
230 if (bis != null) {
231 try {
232 bis.close();
233 } catch (IOException e) {
234 e.printStackTrace();
235 }
236 }
237 if (bos != null) {
238 try {
239 bos.close();
240 } catch (IOException e) {
241 e.printStackTrace();
242 }
243 }
244 }
245
246 return file;
247 }
248 @Override
249 public int available() throws IOException
250 { return fs.available(); }
251 @Override
252 public void close() throws IOException
253 { fs.close(); }
254 @Override
255 public int read() throws IOException
256 { return fs.read(); }
257 @Override
258 public int read(byte[] b) throws IOException
259 { return fs.read(b); }
260 @Override
261 public int read(byte[] b, int off, int len) throws IOException
262 { return fs.read(b,off, len); }
263 @Override
264 public long skip(long n) throws IOException
265 { return fs.skip(n); }
266}
Note: See TracBrowser for help on using the repository browser.