1
2
3
4
5
6
7 package nl.mineleni.cbsviewer.servlet.wms.cache;
8
9 import java.awt.image.BufferedImage;
10 import java.io.File;
11 import java.io.IOException;
12 import java.util.Map;
13 import java.util.Map.Entry;
14
15 import javax.imageio.ImageIO;
16
17 import org.opengis.geometry.BoundingBox;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21
22
23
24
25
26 public class WMSCache extends Cache<BoundingBox, CacheImage, BufferedImage> {
27
28 private static final Logger LOGGER = LoggerFactory
29 .getLogger(WMSCache.class);
30
31
32 private String cacheDir;
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49 public WMSCache(final Map<BoundingBox, BufferedImage> cacheData,
50 final String cacheDir, final int maxSize, final int secondsToLive)
51 throws IOException {
52 this(cacheDir, maxSize);
53 for (final Entry<BoundingBox, BufferedImage> e : cacheData.entrySet()) {
54 this.put(e.getKey(), new CacheImage(e.getValue(), secondsToLive));
55 }
56 }
57
58
59
60
61
62
63
64
65
66
67
68 public WMSCache(final String cacheDir, final int maxSize)
69 throws IOException {
70 super(maxSize);
71
72 final File f = new File(cacheDir);
73 final boolean createdDirs = f.mkdirs();
74 if (createdDirs && LOGGER.isDebugEnabled()) {
75 LOGGER.debug("Directory tree aangemaakt voor "
76 + f.getCanonicalPath());
77 }
78 if (f.isDirectory() && f.canWrite()) {
79 LOGGER.debug("Cache directory is: " + f.getCanonicalPath());
80 this.cacheDir = cacheDir;
81 } else {
82 LOGGER.debug("Cache directory: " + f.getCanonicalPath()
83 + " is niet geldig.");
84 throw new IOException("De gevraagde cache directory (" + cacheDir
85 + ") is niet schrijfbaar.");
86 }
87 }
88
89
90
91
92
93
94 public String getCacheDir() {
95 return this.cacheDir;
96 }
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111 public void put(final BoundingBox bbox, final BufferedImage cacheValue,
112 final long secondsToLive) {
113
114 final CacheImage c = new CacheImage(cacheValue, secondsToLive);
115
116 try {
117 final File temp = File.createTempFile("wmscache", ".png", new File(
118 this.cacheDir));
119 temp.deleteOnExit();
120 c.setFileName(temp.getCanonicalPath());
121 ImageIO.write(cacheValue, "png", temp);
122 LOGGER.debug("Opslaan in cache: " + bbox + ", pad:"
123 + temp.getCanonicalPath());
124 } catch (final IOException e) {
125 LOGGER.error("Cache image opslaan is niet gelukt.", e);
126 }
127 super.put(bbox, c);
128 }
129
130
131
132
133
134
135
136 @Override
137 public void remove(final BoundingBox bbox) {
138 super.remove(bbox);
139 final CachableImage<BufferedImage> entry = this.get(bbox);
140 if ((entry != null) && !(new File(entry.getName())).delete()) {
141 LOGGER.warn("Het cachebestand kon niet worden verwijderd.");
142 }
143 }
144
145
146
147
148
149
150
151
152 public BufferedImage getImage(final BoundingBox bbox) {
153 if (this.get(bbox) == null) {
154 return null;
155 }
156 return this.get(bbox).getImage();
157 }
158 }