source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/CacheControl.java@ 20931

Last change on this file since 20931 was 20931, checked in by pieren, 16 years ago

add multi-cache management for buildings

  • Property svn:eol-style set to native
File size: 8.6 KB
Line 
1// License: GPL. v2 and later. Copyright 2008-2009 by Pieren <pieren3@gmail.com> and others
2package cadastre_fr;
3/**
4 * This class handles the WMS layer cache mechanism. The design is oriented for a good performance (no
5 * wait status on GUI, fast saving even in big file). A separate thread is created for each WMS
6 * layer to not suspend the GUI until disk I/O is terminated (a file for the cache can take
7 * several MB's). If the cache file already exists, new images are just appended to the file
8 * (performance). Since we use the ObjectStream methods, it is required to modify the standard
9 * ObjectOutputStream in order to have objects appended readable (otherwise a stream header
10 * is inserted before each append and an exception is raised at objects read).
11 */
12
13import static org.openstreetmap.josm.tools.I18n.tr;
14
15import java.io.*;
16import java.util.ArrayList;
17import java.util.concurrent.locks.Lock;
18import java.util.concurrent.locks.ReentrantLock;
19
20import javax.swing.JDialog;
21import javax.swing.JOptionPane;
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.data.projection.LambertCC9Zones;
24import org.openstreetmap.josm.data.projection.UTM_France_DOM;
25
26public class CacheControl implements Runnable {
27
28 public static final String cLambertCC9Z = "CC";
29
30 public static final String cUTM20N = "UTM";
31
32 public class ObjectOutputStreamAppend extends ObjectOutputStream {
33 public ObjectOutputStreamAppend(OutputStream out) throws IOException {
34 super(out);
35 }
36 protected void writeStreamHeader() throws IOException {
37 reset();
38 }
39 }
40
41 public static boolean cacheEnabled = true;
42
43 public static int cacheSize = 500;
44
45
46 public WMSLayer wmsLayer = null;
47
48 private ArrayList<GeorefImage> imagesToSave = new ArrayList<GeorefImage>();
49 private Lock imagesLock = new ReentrantLock();
50
51 public boolean isCachePipeEmpty() {
52 imagesLock.lock();
53 boolean ret = imagesToSave.isEmpty();
54 imagesLock.unlock();
55 return ret;
56 }
57
58 public CacheControl(WMSLayer wmsLayer) {
59 cacheEnabled = Main.pref.getBoolean("cadastrewms.enableCaching", true);
60 this.wmsLayer = wmsLayer;
61 try {
62 cacheSize = Integer.parseInt(Main.pref.get("cadastrewms.cacheSize", String.valueOf(CadastrePreferenceSetting.DEFAULT_CACHE_SIZE)));
63 } catch (NumberFormatException e) {
64 cacheSize = CadastrePreferenceSetting.DEFAULT_CACHE_SIZE;
65 }
66 File path = new File(CadastrePlugin.cacheDir);
67 if (!path.exists())
68 path.mkdirs();
69 else // check directory capacity
70 checkDirSize(path);
71 new Thread(this).start();
72 }
73
74 private void checkDirSize(File path) {
75 long size = 0;
76 long oldestFileDate = Long.MAX_VALUE;
77 int oldestFile = 0;
78 File[] files = path.listFiles();
79 for (int i = 0; i < files.length; i++) {
80 size += files[i].length();
81 if (files[i].lastModified() < oldestFileDate) {
82 oldestFile = i;
83 oldestFileDate = files[i].lastModified();
84 }
85 }
86 if (size > cacheSize*1024*1024) {
87 System.out.println("Delete oldest file \""+ files[oldestFile].getName()
88 + "\" in cache dir to stay under the limit of " + cacheSize + " MB.");
89 files[oldestFile].delete();
90 checkDirSize(path);
91 }
92 }
93
94 public boolean loadCacheIfExist() {
95 try {
96 if (!wmsLayer.isBuildingsOnly()) {
97 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
98 if (file.exists()) {
99 JOptionPane pane = new JOptionPane(
100 tr("Location \"{0}\" found in cache.\n"+
101 "Load cache first ?\n"+
102 "(No = new cache)", wmsLayer.getName()),
103 JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
104 // this below is a temporary workaround to fix the "always on top" issue
105 JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
106 CadastrePlugin.prepareDialog(dialog);
107 dialog.setVisible(true);
108 int reply = (Integer)pane.getValue();
109 // till here
110
111 if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
112 return true;
113 } else {
114 delete(file);
115 }
116 }
117 } else {
118 int i=0;
119 while (new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "."+i+"."+ WMSFileExtension()).exists())
120 i++;
121 wmsLayer.setName(wmsLayer.getName()+"."+i);
122 }
123 } catch (Exception e) {
124 e.printStackTrace(System.out);
125 }
126 return false;
127 }
128
129 public void deleteCacheFile() {
130 try {
131 delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
132 } catch (Exception e) {
133 e.printStackTrace(System.out);
134 }
135 }
136
137 private void delete(File file) {
138 System.out.println("Delete file "+file);
139 if (file.exists())
140 file.delete();
141 while (file.exists()) // wait until file is really gone (otherwise appends to existing one)
142 CadastrePlugin.safeSleep(500);
143 }
144
145 public boolean loadCache(File file, int currentLambertZone) {
146 boolean successfulRead = false;
147 try {
148 FileInputStream fis = new FileInputStream(file);
149 ObjectInputStream ois = new ObjectInputStream(fis);
150 successfulRead = wmsLayer.read(ois, currentLambertZone);
151 ois.close();
152 fis.close();
153 } catch (Exception ex) {
154 ex.printStackTrace(System.out);
155 JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."), tr("Error"), JOptionPane.ERROR_MESSAGE);
156 return false;
157 }
158 if (successfulRead && wmsLayer.isRaster()) {
159 // serialized raster bufferedImage hangs-up on Java6. Recreate them here
160 wmsLayer.images.get(0).image = RasterImageModifier.fixRasterImage(wmsLayer.images.get(0).image);
161 }
162 return successfulRead;
163 }
164
165
166 public synchronized void saveCache(GeorefImage image) {
167 imagesLock.lock();
168 this.imagesToSave.add(image);
169 this.notify();
170 imagesLock.unlock();
171 }
172
173 /**
174 * Thread saving the grabbed images in background.
175 */
176 public synchronized void run() {
177 for (;;) {
178 imagesLock.lock();
179 //ArrayList<GeorefImage> images = new ArrayList<GeorefImage>(imagesToSave);
180 int size = imagesToSave.size();
181 imagesLock.unlock();
182 if (size > 0) {
183 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
184 try {
185 if (file.exists()) {
186 ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
187 new BufferedOutputStream(new FileOutputStream(file, true)));
188 for (int i=0; i < size; i++) {
189 oos.writeObject(imagesToSave.get(i));
190 }
191 oos.close();
192 } else {
193 ObjectOutputStream oos = new ObjectOutputStream(
194 new BufferedOutputStream(new FileOutputStream(file)));
195 wmsLayer.write(oos);
196 for (int i=0; i < size; i++) {
197 oos.writeObject(imagesToSave.get(i));
198 }
199 oos.close();
200 }
201 } catch (IOException e) {
202 e.printStackTrace(System.out);
203 }
204 imagesLock.lock();
205 for (int i=0; i < size; i++) {
206 imagesToSave.remove(0);
207 }
208 imagesLock.unlock();
209 }
210 try {wait();} catch (InterruptedException e) {
211 e.printStackTrace(System.out);
212 }
213 }
214 }
215
216 private String WMSFileExtension() {
217 String ext = String.valueOf((wmsLayer.getLambertZone() + 1));
218 if (Main.proj instanceof LambertCC9Zones)
219 ext = cLambertCC9Z + ext;
220 else if (Main.proj instanceof UTM_France_DOM)
221 ext = cUTM20N + ext;
222 return ext;
223 }
224
225}
Note: See TracBrowser for help on using the repository browser.