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

Last change on this file since 23190 was 23190, checked in by stoecker, 14 years ago

remove tabs

  • Property svn:eol-style set to native
File size: 8.7 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 if (cacheSize != 0) {
76 long size = 0;
77 long oldestFileDate = Long.MAX_VALUE;
78 int oldestFile = 0;
79 File[] files = path.listFiles();
80 for (int i = 0; i < files.length; i++) {
81 size += files[i].length();
82 if (files[i].lastModified() < oldestFileDate) {
83 oldestFile = i;
84 oldestFileDate = files[i].lastModified();
85 }
86 }
87 if (size > (long)cacheSize*1024*1024) {
88 System.out.println("Delete oldest file \""+ files[oldestFile].getName()
89 + "\" in cache dir to stay under the limit of " + cacheSize + " MB.");
90 files[oldestFile].delete();
91 checkDirSize(path);
92 }
93 }
94 }
95
96 public boolean loadCacheIfExist() {
97 try {
98 if (!wmsLayer.isBuildingsOnly()) {
99 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
100 if (file.exists()) {
101 JOptionPane pane = new JOptionPane(
102 tr("Location \"{0}\" found in cache.\n"+
103 "Load cache first ?\n"+
104 "(No = new cache)", wmsLayer.getName()),
105 JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
106 // this below is a temporary workaround to fix the "always on top" issue
107 JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
108 CadastrePlugin.prepareDialog(dialog);
109 dialog.setVisible(true);
110 int reply = (Integer)pane.getValue();
111 // till here
112
113 if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
114 return true;
115 } else {
116 delete(file);
117 }
118 }
119 } else {
120 int i=0;
121 while (new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "."+i+"."+ WMSFileExtension()).exists())
122 i++;
123 wmsLayer.setName(wmsLayer.getName()+"."+i);
124 }
125 } catch (Exception e) {
126 e.printStackTrace(System.out);
127 }
128 return false;
129 }
130
131 public void deleteCacheFile() {
132 try {
133 delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
134 } catch (Exception e) {
135 e.printStackTrace(System.out);
136 }
137 }
138
139 private void delete(File file) {
140 System.out.println("Delete file "+file);
141 if (file.exists())
142 file.delete();
143 while (file.exists()) // wait until file is really gone (otherwise appends to existing one)
144 CadastrePlugin.safeSleep(500);
145 }
146
147 public boolean loadCache(File file, int currentLambertZone) {
148 boolean successfulRead = false;
149 try {
150 FileInputStream fis = new FileInputStream(file);
151 ObjectInputStream ois = new ObjectInputStream(fis);
152 successfulRead = wmsLayer.read(ois, currentLambertZone);
153 ois.close();
154 fis.close();
155 } catch (Exception ex) {
156 ex.printStackTrace(System.out);
157 JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."), tr("Error"), JOptionPane.ERROR_MESSAGE);
158 return false;
159 }
160 if (successfulRead && wmsLayer.isRaster()) {
161 // serialized raster bufferedImage hangs-up on Java6. Recreate them here
162 wmsLayer.images.get(0).image = RasterImageModifier.fixRasterImage(wmsLayer.images.get(0).image);
163 }
164 return successfulRead;
165 }
166
167
168 public synchronized void saveCache(GeorefImage image) {
169 imagesLock.lock();
170 this.imagesToSave.add(image);
171 this.notify();
172 imagesLock.unlock();
173 }
174
175 /**
176 * Thread saving the grabbed images in background.
177 */
178 public synchronized void run() {
179 for (;;) {
180 imagesLock.lock();
181 //ArrayList<GeorefImage> images = new ArrayList<GeorefImage>(imagesToSave);
182 int size = imagesToSave.size();
183 imagesLock.unlock();
184 if (size > 0) {
185 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
186 try {
187 if (file.exists()) {
188 ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
189 new BufferedOutputStream(new FileOutputStream(file, true)));
190 for (int i=0; i < size; i++) {
191 oos.writeObject(imagesToSave.get(i));
192 }
193 oos.close();
194 } else {
195 ObjectOutputStream oos = new ObjectOutputStream(
196 new BufferedOutputStream(new FileOutputStream(file)));
197 wmsLayer.write(oos);
198 for (int i=0; i < size; i++) {
199 oos.writeObject(imagesToSave.get(i));
200 }
201 oos.close();
202 }
203 } catch (IOException e) {
204 e.printStackTrace(System.out);
205 }
206 imagesLock.lock();
207 for (int i=0; i < size; i++) {
208 imagesToSave.remove(0);
209 }
210 imagesLock.unlock();
211 }
212 try {wait();} catch (InterruptedException e) {
213 e.printStackTrace(System.out);
214 }
215 }
216 }
217
218 private String WMSFileExtension() {
219 String ext = String.valueOf((wmsLayer.getLambertZone() + 1));
220 if (Main.proj instanceof LambertCC9Zones)
221 ext = cLambertCC9Z + ext;
222 else if (Main.proj instanceof UTM_France_DOM)
223 ext = cUTM20N + ext;
224 return ext;
225 }
226
227}
Note: See TracBrowser for help on using the repository browser.