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

Last change on this file since 32211 was 32211, checked in by donvip, 10 years ago

sonar - fix many issues

  • 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
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 @Override
45 protected void writeStreamHeader() throws IOException {
46 reset();
47 }
48 }
49
50 public static boolean cacheEnabled = true;
51
52 public static int cacheSize = 500;
53
54 public WMSLayer wmsLayer;
55
56 private ArrayList<GeorefImage> imagesToSave = new ArrayList<>();
57 private Lock imagesLock = new ReentrantLock();
58
59 public boolean isCachePipeEmpty() {
60 imagesLock.lock();
61 boolean ret = imagesToSave.isEmpty();
62 imagesLock.unlock();
63 return ret;
64 }
65
66 public CacheControl(WMSLayer wmsLayer) {
67 cacheEnabled = Main.pref.getBoolean("cadastrewms.enableCaching", true);
68 this.wmsLayer = wmsLayer;
69 try {
70 cacheSize = Integer.parseInt(Main.pref.get("cadastrewms.cacheSize", String.valueOf(CadastrePreferenceSetting.DEFAULT_CACHE_SIZE)));
71 } catch (NumberFormatException e) {
72 cacheSize = CadastrePreferenceSetting.DEFAULT_CACHE_SIZE;
73 }
74 File path = new File(CadastrePlugin.cacheDir);
75 if (!path.exists())
76 path.mkdirs();
77 else // check directory capacity
78 checkDirSize(path);
79 new Thread(this).start();
80 }
81
82 private static void checkDirSize(File path) {
83 if (cacheSize != 0) {
84 long size = 0;
85 long oldestFileDate = Long.MAX_VALUE;
86 int oldestFile = 0;
87 File[] files = path.listFiles();
88 for (int i = 0; i < files.length; i++) {
89 size += files[i].length();
90 if (files[i].lastModified() < oldestFileDate) {
91 oldestFile = i;
92 oldestFileDate = files[i].lastModified();
93 }
94 }
95 if (size > (long)cacheSize*1024*1024) {
96 Main.info("Delete oldest file \""+ files[oldestFile].getName()
97 + "\" in cache dir to stay under the limit of " + cacheSize + " MB.");
98 files[oldestFile].delete();
99 checkDirSize(path);
100 }
101 }
102 }
103
104 public boolean loadCacheIfExist() {
105 if (!CadastrePlugin.isCadastreProjection()) {
106 CadastrePlugin.askToChangeProjection();
107 }
108 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
109 if (file.exists()) {
110 int reply = GuiHelper.runInEDTAndWaitAndReturn(new Callable<Integer>() {
111 @Override
112 public Integer call() throws Exception {
113 JOptionPane pane = new JOptionPane(
114 tr("Location \"{0}\" found in cache.\n"+
115 "Load cache first ?\n"+
116 "(No = new cache)", wmsLayer.getName()),
117 JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null);
118 // this below is a temporary workaround to fix the "always on top" issue
119 JDialog dialog = pane.createDialog(Main.parent, tr("Select Feuille"));
120 CadastrePlugin.prepareDialog(dialog);
121 dialog.setVisible(true);
122 return (Integer)pane.getValue();
123 // till here
124 }
125 });
126
127 if (reply == JOptionPane.OK_OPTION && loadCache(file, wmsLayer.getLambertZone())) {
128 return true;
129 } else {
130 delete(file);
131 }
132 }
133 return false;
134 }
135
136 public void deleteCacheFile() {
137 delete(new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension()));
138 }
139
140 private static void delete(File file) {
141 Main.info("Delete file "+file);
142 if (file.exists())
143 file.delete();
144 while (file.exists()) // wait until file is really gone (otherwise appends to existing one)
145 CadastrePlugin.safeSleep(500);
146 }
147
148 public boolean loadCache(File file, int currentLambertZone) {
149 boolean successfulRead = false;
150 try (
151 FileInputStream fis = new FileInputStream(file);
152 ObjectInputStream ois = new ObjectInputStream(fis);
153 ) {
154 successfulRead = wmsLayer.read(file, ois, currentLambertZone);
155 } catch (IOException | ClassNotFoundException ex) {
156 Main.error(ex);
157 GuiHelper.runInEDTAndWait(new Runnable() {
158 @Override
159 public void run() {
160 JOptionPane.showMessageDialog(Main.parent, tr("Error loading file.\nProbably an old version of the cache file."),
161 tr("Error"), JOptionPane.ERROR_MESSAGE);
162 }
163 });
164 return false;
165 }
166 if (successfulRead && wmsLayer.isRaster()) {
167 // serialized raster bufferedImage hangs-up on Java6. Recreate them here
168 wmsLayer.getImage(0).image = RasterImageModifier.fixRasterImage(wmsLayer.getImage(0).image);
169 }
170 return successfulRead;
171 }
172
173 public synchronized void saveCache(GeorefImage image) {
174 imagesLock.lock();
175 this.imagesToSave.add(image);
176 this.notifyAll();
177 imagesLock.unlock();
178 }
179
180 /**
181 * Thread saving the grabbed images in background.
182 */
183 @Override
184 public synchronized void run() {
185 for (;;) {
186 imagesLock.lock();
187 int size = imagesToSave.size();
188 imagesLock.unlock();
189 if (size > 0) {
190 File file = new File(CadastrePlugin.cacheDir + wmsLayer.getName() + "." + WMSFileExtension());
191 try {
192 if (file.exists()) {
193 try (ObjectOutputStreamAppend oos = new ObjectOutputStreamAppend(
194 new BufferedOutputStream(new FileOutputStream(file, true)))) {
195 for (int i=0; i < size; i++) {
196 oos.writeObject(imagesToSave.get(i));
197 }
198 }
199 } else {
200 try (ObjectOutputStream oos = new ObjectOutputStream(
201 new BufferedOutputStream(new FileOutputStream(file)))) {
202 wmsLayer.write(file, oos);
203 for (int i=0; i < size; i++) {
204 oos.writeObject(imagesToSave.get(i));
205 }
206 }
207 }
208 } catch (IOException e) {
209 Main.error(e);
210 }
211 imagesLock.lock();
212 for (int i=0; i < size; i++) {
213 imagesToSave.remove(0);
214 }
215 imagesLock.unlock();
216 }
217 try {wait();} catch (InterruptedException e) {
218 Main.error(e);
219 }
220 }
221 }
222
223 private String WMSFileExtension() {
224 String ext = String.valueOf(wmsLayer.getLambertZone() + 1);
225 if (CadastrePlugin.isLambert_cc9())
226 ext = C_LAMBERT_CC_9Z + ext;
227 else if (CadastrePlugin.isUtm_france_dom())
228 ext = C_UTM20N + ext;
229 return ext;
230 }
231}
Note: See TracBrowser for help on using the repository browser.