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

Last change on this file since 33241 was 32556, checked in by donvip, 9 years ago

checkstyle

  • Property svn:eol-style set to native
File size: 8.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
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.Callable;
16import java.util.concurrent.locks.Lock;
17import java.util.concurrent.locks.ReentrantLock;
18
19import javax.swing.JDialog;
20import javax.swing.JOptionPane;
21
22import org.openstreetmap.josm.Main;
23import org.openstreetmap.josm.gui.util.GuiHelper;
24
25/**
26 * This class handles the WMS layer cache mechanism. The design is oriented for a good performance (no
27 * wait status on GUI, fast saving even in big file). A separate thread is created for each WMS
28 * layer to not suspend the GUI until disk I/O is terminated (a file for the cache can take
29 * several MB's). If the cache file already exists, new images are just appended to the file
30 * (performance). Since we use the ObjectStream methods, it is required to modify the standard
31 * ObjectOutputStream in order to have objects appended readable (otherwise a stream header
32 * is inserted before each append and an exception is raised at objects read).
33 */
34public class CacheControl implements Runnable {
35
36 public static final String C_LAMBERT_CC_9Z = "CC";
37
38 public static final String C_UTM20N = "UTM";
39
40 public static class ObjectOutputStreamAppend extends ObjectOutputStream {
41 public ObjectOutputStreamAppend(OutputStream out) throws IOException {
42 super(out);
43 }
44
45 @Override
46 protected void writeStreamHeader() throws IOException {
47 reset();
48 }
49 }
50
51 public static boolean cacheEnabled = true;
52
53 public static int cacheSize = 500;
54
55 public WMSLayer wmsLayer;
56
57 private ArrayList<GeorefImage> imagesToSave = new ArrayList<>();
58 private Lock imagesLock = new ReentrantLock();
59
60 public boolean isCachePipeEmpty() {
61 imagesLock.lock();
62 boolean ret = imagesToSave.isEmpty();
63 imagesLock.unlock();
64 return ret;
65 }
66
67 public CacheControl(WMSLayer wmsLayer) {
68 cacheEnabled = Main.pref.getBoolean("cadastrewms.enableCaching", true);
69 this.wmsLayer = wmsLayer;
70 try {
71 cacheSize = Integer.parseInt(Main.pref.get("cadastrewms.cacheSize", String.valueOf(CadastrePreferenceSetting.DEFAULT_CACHE_SIZE)));
72 } catch (NumberFormatException e) {
73 cacheSize = CadastrePreferenceSetting.DEFAULT_CACHE_SIZE;
74 }
75 File path = new File(CadastrePlugin.cacheDir);
76 if (!path.exists())
77 path.mkdirs();
78 else // check directory capacity
79 checkDirSize(path);
80 new Thread(this).start();
81 }
82
83 private static void checkDirSize(File path) {
84 if (cacheSize != 0) {
85 long size = 0;
86 long oldestFileDate = Long.MAX_VALUE;
87 int oldestFile = 0;
88 File[] files = path.listFiles();
89 for (int i = 0; i < files.length; i++) {
90 size += files[i].length();
91 if (files[i].lastModified() < oldestFileDate) {
92 oldestFile = i;
93 oldestFileDate = files[i].lastModified();
94 }
95 }
96 if (size > (long) cacheSize*1024*1024) {
97 Main.info("Delete oldest file \""+ files[oldestFile].getName()
98 + "\" in cache dir to stay under the limit of " + cacheSize + " MB.");
99 files[oldestFile].delete();
100 checkDirSize(path);
101 }
102 }
103 }
104
105 public boolean loadCacheIfExist() {
106 if (!CadastrePlugin.isCadastreProjection()) {
107 CadastrePlugin.askToChangeProjection();
108 }
109 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
110 if (file.exists()) {
111 int reply = GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
112 @Override
113 public Integer call() throws Exception {
114 JOptionPane pane = new JOptionPane(
115 tr("Location \"{0}\" found in cache.\n"+
116 "Load cache first ?\n"+
117 "(No = new cache)", wmsLayer.getName()),
118 JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
119 // this below is a temporary workaround to fix the "always on top" issue
120 JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
121 CadastrePlugin.prepareDialog(dialog);
122 dialog.setVisible(true);
123 return (Integer) pane.getValue();
124 // till here
125 }
126 });
127
128 if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
129 return true;
130 } else {
131 delete(file);
132 }
133 }
134 return false;
135 }
136
137 public void deleteCacheFile() {
138 delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
139 }
140
141 private static void delete(File file) {
142 Main.info("Delete file "+file);
143 if (file.exists())
144 file.delete();
145 while (file.exists()) { // wait until file is really gone (otherwise appends to existing one)
146 CadastrePlugin.safeSleep(500);
147 }
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 (IOException | ClassNotFoundException 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.notifyAll();
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 {
220 wait();
221 } catch (InterruptedException e) {
222 Main.error(e);
223 }
224 }
225 }
226
227 private String WMSFileExtension() {
228 String ext = String.valueOf(wmsLayer.getLambertZone() + 1);
229 if (CadastrePlugin.isLambert_cc9())
230 ext = C_LAMBERT_CC_9Z + ext;
231 else if (CadastrePlugin.isUtm_france_dom())
232 ext = C_UTM20N + ext;
233 return ext;
234 }
235}
Note: See TracBrowser for help on using the repository browser.