1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34 package info.magnolia.imaging.caching;
35
36 import info.magnolia.cms.beans.config.MIMEMapping;
37 import info.magnolia.context.SystemContext;
38 import info.magnolia.imaging.AbstractImageStreamer;
39 import info.magnolia.imaging.ImageGenerator;
40 import info.magnolia.imaging.ImageResponse;
41 import info.magnolia.imaging.ImageStreamer;
42 import info.magnolia.imaging.ImagingException;
43 import info.magnolia.imaging.OutputFormat;
44 import info.magnolia.imaging.ParameterProvider;
45 import info.magnolia.jcr.util.NodeTypes;
46 import info.magnolia.jcr.util.NodeUtil;
47
48 import java.io.ByteArrayInputStream;
49 import java.io.ByteArrayOutputStream;
50 import java.io.IOException;
51 import java.io.InputStream;
52 import java.io.OutputStream;
53 import java.util.Calendar;
54 import java.util.concurrent.ExecutionException;
55 import java.util.concurrent.TimeUnit;
56 import java.util.concurrent.locks.ReentrantLock;
57
58 import javax.jcr.InvalidItemStateException;
59 import javax.jcr.Node;
60 import javax.jcr.Property;
61 import javax.jcr.RepositoryException;
62 import javax.jcr.Session;
63
64 import org.apache.commons.io.IOUtils;
65 import org.apache.jackrabbit.JcrConstants;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 import com.google.common.cache.CacheBuilder;
70 import com.google.common.cache.CacheLoader;
71 import com.google.common.cache.LoadingCache;
72 import com.google.common.net.MediaType;
73
74
75
76
77
78
79 public class CachingImageStreamer<P> extends AbstractImageStreamer<P> {
80
81 private static final Logger log = LoggerFactory.getLogger(CachingImageStreamer.class);
82
83 private static final String GENERATED_IMAGE_NODE_NAME = "generated-image";
84
85 private final Session session;
86 private final CachingStrategy<P> cachingStrategy;
87 private final ImageStreamer<P> delegate;
88 private final SystemContext systemContext;
89
90
91
92
93
94
95
96
97
98
99
100
101 private final LoadingCache<ImageGenerationJob<P>, Property> currentJobs;
102
103
104
105
106
107
108
109
110
111
112 private static final ReentrantLock lock = new ReentrantLock();
113
114 public CachingImageStreamer(Session session, CachingStrategy<P> cachingStrategy, ImageStreamer<P> delegate, SystemContext systemContext) {
115 this.session = session;
116 this.cachingStrategy = cachingStrategy;
117 this.delegate = delegate;
118 this.systemContext = systemContext;
119
120 CacheBuilder<Object, Object> cb = CacheBuilder.newBuilder();
121 this.currentJobs = cb
122
123
124 .expireAfterWrite(500, TimeUnit.MILLISECONDS)
125
126
127 .build(new CacheLoader<ImageGenerationJob<P>, Property>() {
128
129 @Override
130 public Property load(ImageGenerationJob<P> job) throws Exception {
131 try {
132 return generateAndStore(job.getGenerator(), job.getParams());
133 } catch (IOException | ImagingException e) {
134
135 throw new RuntimeException(e);
136 }
137 }
138
139 });
140 }
141
142 @Override
143 public void serveImage(ImageGenerator<ParameterProvider<P>> generator, ParameterProvider<P> params, ImageResponse imageResponse) throws ImagingException, IOException {
144 Property imgProp = fetchFromCache(generator, params);
145 if (imgProp == null) {
146
147 try {
148 imgProp = currentJobs.get(new ImageGenerationJob<>(generator, params));
149 } catch (ExecutionException e) {
150
151 unwrapRuntimeException(e);
152 }
153 }
154 serve(imgProp, imageResponse);
155 }
156
157
158
159
160 @Deprecated
161 public void serveImage(ImageGenerator<ParameterProvider<P>> generator, ParameterProvider<P> params, OutputStream out) throws IOException, ImagingException {
162 serveImage(generator, params, new TemporaryImageResponse(out));
163 }
164
165
166
167
168
169 protected Property fetchFromCache(ImageGenerator<ParameterProvider<P>> generator, ParameterProvider<P> parameterProvider) {
170 final String cachePath = cachingStrategy.getCachePath(generator, parameterProvider);
171 if (cachePath == null) {
172
173 return null;
174 }
175 try {
176 if (!session.itemExists(cachePath)) {
177 return null;
178 }
179 final Node imageNode = session.getNode(cachePath);
180 if (!imageNode.hasNode(GENERATED_IMAGE_NODE_NAME)) {
181 return null;
182 }
183 final Property property = imageNode.getNode(GENERATED_IMAGE_NODE_NAME).getProperty(JcrConstants.JCR_DATA);
184 InputStream in;
185 try {
186 in = property.getBinary().getStream();
187 } catch (RepositoryException e) {
188
189
190 return null;
191 }
192 IOUtils.closeQuietly(in);
193
194 if (cachingStrategy.shouldRegenerate(property, parameterProvider)) {
195 return null;
196 }
197 return property;
198 } catch (RepositoryException e) {
199 throw new RuntimeException(e);
200 }
201 }
202
203 protected void serve(Property binary, ImageResponse imageResponse) throws IOException {
204 final InputStream in;
205 try {
206 in = binary.getBinary().getStream();
207 } catch (RepositoryException e) {
208 throw new IllegalStateException("Can't get InputStream from " + binary);
209 }
210 final String contentType;
211 try {
212 contentType = binary.getParent().getProperty(JcrConstants.JCR_MIMETYPE).getString();
213 } catch (RepositoryException e) {
214 throw new IllegalStateException("Can't get content-type from " + binary);
215 }
216 imageResponse.setMediaType(MediaType.parse(contentType));
217
218 final OutputStream out = imageResponse.getOutputStream();
219 IOUtils.copy(in, out);
220 IOUtils.closeQuietly(in);
221 }
222
223 protected Property generateAndStore(final ImageGenerator<ParameterProvider<P>> generator, final ParameterProvider<P> parameterProvider) throws IOException, ImagingException {
224
225 final ByteArrayOutputStream tempOut = new ByteArrayOutputStream();
226 delegate.serveImage(generator, parameterProvider, new TemporaryImageResponse(tempOut));
227
228
229 lock.lock();
230 try {
231 final OutputFormat outputFormat = generator.getOutputFormat(parameterProvider);
232 final MediaType contentType = getMediaType(outputFormat);
233
234 final Session systemSession = systemContext.getJCRSession(session.getWorkspace().getName());
235
236 final String cachePath = cachingStrategy.getCachePath(generator, parameterProvider);
237 final Node cacheNode = NodeUtil.createPath(session.getRootNode(), cachePath, NodeTypes.Content.NAME);
238 final Node resourceNode = NodeUtil.createPath(cacheNode, GENERATED_IMAGE_NODE_NAME, NodeTypes.Resource.NAME);
239
240 final ByteArrayInputStream tempIn = new ByteArrayInputStream(tempOut.toByteArray());
241 Property imageData = resourceNode.setProperty(JcrConstants.JCR_DATA, cacheNode.getSession().getValueFactory().createBinary(tempIn));
242
243 final String formatName = generator.getOutputFormat(parameterProvider).getFormatName();
244 final String mimeType = MIMEMapping.getMIMEType(formatName);
245 resourceNode.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
246 resourceNode.setProperty(JcrConstants.JCR_MIMETYPE, contentType.toString());
247 resourceNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
248
249
250
251 NodeTypes.LastModified.update(cacheNode);
252
253
254 NodeTypes.LastModified.update(resourceNode);
255
256
257 try {
258 systemSession.save();
259 } catch (InvalidItemStateException e){
260 log.warn("Item found in invalid state. Attempting to refresh the session.");
261 systemSession.refresh(false);
262 return systemSession.getNode(cachePath + "/" + GENERATED_IMAGE_NODE_NAME).getProperty(JcrConstants.JCR_DATA);
263 }
264
265 return imageData;
266 } catch (RepositoryException e) {
267 throw new ImagingException("Can't store rendered image: " + e.getMessage(), e);
268 } finally {
269 lock.unlock();
270 }
271 }
272
273
274
275
276
277
278
279 private void unwrapRuntimeException(Exception e) throws ImagingException, IOException {
280 final Throwable cause = e.getCause();
281 if (cause instanceof ImagingException) {
282 throw (ImagingException) cause;
283 } else if (cause instanceof IOException) {
284 throw (IOException) cause;
285 } else if (cause instanceof RuntimeException) {
286 unwrapRuntimeException((RuntimeException) cause);
287 } else if (cause == null) {
288
289 throw new IllegalStateException("Unexpected and unhandled exception: " + (e.getMessage() != null ? e.getMessage() : ""), e);
290 } else {
291
292 throw new ImagingException(e.getMessage(), cause);
293 }
294 }
295
296 private static class TemporaryImageResponse implements ImageResponse {
297 private final OutputStream tempOut;
298
299 public TemporaryImageResponse(OutputStream tempOut) {
300 this.tempOut = tempOut;
301 }
302
303 @Override
304 public void setMediaType(MediaType mediaType) throws IOException {
305
306 }
307
308 @Override
309 public OutputStream getOutputStream() throws IOException {
310 return tempOut;
311 }
312 }
313 }