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