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

Last change on this file since 32205 was 32163, checked in by donvip, 9 years ago

fix EDT violation

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