]> gitweb.fperrin.net Git - GpsPrune.git/blob - src/tim/prune/gui/map/DiskTileCacher.java
fd2042a7714acfe2ca1f5b47693ce9df06b0a79f
[GpsPrune.git] / src / tim / prune / gui / map / DiskTileCacher.java
1 package tim.prune.gui.map;
2
3 import java.awt.Image;
4 import java.awt.Toolkit;
5 import java.awt.image.ImageObserver;
6 import java.io.File;
7 import java.io.FileOutputStream;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.net.URL;
11 import java.net.URLConnection;
12 import java.util.HashSet;
13
14 import tim.prune.GpsPrune;
15
16 /**
17  * Class to control the reading and saving of map tiles
18  * to a cache on disk
19  */
20 public class DiskTileCacher implements Runnable
21 {
22         /** URL to get image from */
23         private URL _url = null;
24         /** File to save image to */
25         private File _file = null;
26         /** Observer to be notified */
27         private ImageObserver _observer = null;
28         /** Time limit to cache images for */
29         private static final long CACHE_TIME_LIMIT = 20 * 24 * 60 * 60 * 1000; // 20 days in ms
30         /** Hashset of all blocked / 404 tiles to avoid requesting them again */
31         private static final HashSet<String> BLOCKED_URLS = new HashSet<String>();
32
33         /**
34          * Private constructor
35          * @param inUrl URL to get
36          * @param inFile file to save to
37          */
38         private DiskTileCacher(URL inUrl, File inFile, ImageObserver inObserver)
39         {
40                 _url = inUrl;
41                 _file = inFile;
42                 _observer = inObserver;
43         }
44
45         /**
46          * Get the specified tile from the disk cache
47          * @param inBasePath base path to whole disk cache
48          * @param inTilePath relative path to requested tile
49          * @return tile image if available, or null if not there
50          */
51         public static MapTile getTile(String inBasePath, String inTilePath)
52         {
53                 if (inBasePath == null) {return null;}
54                 File tileFile = new File(inBasePath, inTilePath);
55                 Image image = null;
56                 if (tileFile.exists() && tileFile.canRead() && tileFile.length() > 0)
57                 {
58                         long fileStamp = tileFile.lastModified();
59                         boolean isExpired = ((System.currentTimeMillis()-fileStamp) > CACHE_TIME_LIMIT);
60                         try
61                         {
62                                 image = Toolkit.getDefaultToolkit().createImage(tileFile.getAbsolutePath());
63                                 return new MapTile(image, isExpired);
64                         }
65                         catch (Exception e) {
66                                 System.err.println("createImage: " + e.getClass().getName() + " _ " + e.getMessage());
67                         }
68                 }
69                 return null;
70         }
71
72         /**
73          * Save the specified image tile to disk
74          * @param inUrl url to get image from
75          * @param inBasePath base path to disk cache
76          * @param inTilePath relative path to this tile
77          * @param inObserver observer to inform when load complete
78          */
79         public static void saveTile(URL inUrl, String inBasePath, String inTilePath, ImageObserver inObserver)
80         {
81                 if (inBasePath == null || inTilePath == null) {return;}
82                 // save file if possible
83                 File basePath = new File(inBasePath);
84                 if (!basePath.exists() || !basePath.isDirectory() || !basePath.canWrite()) {
85                         // Can't write to base path
86                         return;
87                 }
88                 File tileFile = new File(basePath, inTilePath);
89                 // Check if this file is already being loaded
90                 if (isBeingLoaded(tileFile)) {return;}
91                 // Check if it has already failed
92                 if (BLOCKED_URLS.contains(inUrl.toString())) {return;}
93
94                 File dir = tileFile.getParentFile();
95                 // Start a new thread to load the image if necessary
96                 if ((dir.exists() || dir.mkdirs()) && dir.canWrite())
97                 {
98                         new Thread(new DiskTileCacher(inUrl, tileFile, inObserver)).start();
99                 }
100         }
101
102         /**
103          * Check whether the given tile is already being loaded
104          * @param inFile desired file
105          * @return true if temporary file with this name exists
106          */
107         private static boolean isBeingLoaded(File inFile)
108         {
109                 File tempFile = new File(inFile.getAbsolutePath() + ".temp");
110                 if (!tempFile.exists()) {
111                         return false;
112                 }
113                 // File exists, so check if it was created recently
114                 final long fileAge = System.currentTimeMillis() - tempFile.lastModified();
115                 return fileAge < 1000000L; // overwrite if the temp file is still there after 1000s
116         }
117
118         /**
119          * Run method for loading URL asynchronously and saving to file
120          */
121         public void run()
122         {
123                 boolean finished = false;
124                 InputStream in = null;
125                 FileOutputStream out = null;
126                 File tempFile = new File(_file.getAbsolutePath() + ".temp");
127                 // Use a synchronized block across all threads to make sure this url is only fetched once
128                 synchronized (DiskTileCacher.class)
129                 {
130                         if (tempFile.exists()) {tempFile.delete();}
131                         try {
132                                 if (!tempFile.createNewFile()) {return;}
133                         }
134                         catch (Exception e) {return;}
135                 }
136                 try
137                 {
138                         // Open streams from URL and to file
139                         out = new FileOutputStream(tempFile);
140                         //System.out.println("Opening URL: " + _url.toString());
141                         // Set http user agent on connection
142                         URLConnection conn = _url.openConnection();
143                         conn.setRequestProperty("User-Agent", "GpsPrune v" + GpsPrune.VERSION_NUMBER);
144                         in = conn.getInputStream();
145                         int d = 0;
146                         // Loop over each byte in the stream (maybe buffering is more efficient?)
147                         while ((d = in.read()) >= 0) {
148                                 out.write(d);
149                         }
150                         finished = true;
151                 } catch (IOException e) {
152                         System.err.println("ioe: " + e.getClass().getName() + " - " + e.getMessage());
153                         BLOCKED_URLS.add(_url.toString());
154                 }
155                 finally
156                 {
157                         // clean up files
158                         try {in.close();} catch (Exception e) {} // ignore
159                         try {out.close();} catch (Exception e) {} // ignore
160                         if (!finished) {
161                                 tempFile.delete();
162                         }
163                 }
164                 // Move temp file to desired file location
165                 if (tempFile.exists() && !tempFile.renameTo(_file))
166                 {
167                         // File couldn't be moved - delete both to be sure
168                         tempFile.delete();
169                         _file.delete();
170                 }
171                 // Tell parent that load is finished (parameters ignored)
172                 _observer.imageUpdate(null, ImageObserver.ALLBITS, 0, 0, 0, 0);
173         }
174 }