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 log.debug("Locked imaging JCR storage in order to store data corresponding to {}", parameterProvider);
231 try {
232 final OutputFormat outputFormat = generator.getOutputFormat(parameterProvider);
233 final MediaType contentType = getMediaType(outputFormat);
234
235 final Session systemSession = systemContext.getJCRSession(session.getWorkspace().getName());
236
237 final String cachePath = cachingStrategy.getCachePath(generator, parameterProvider);
238 final Node cacheNode = NodeUtil.createPath(session.getRootNode(), cachePath, NodeTypes.Content.NAME);
239 final Node resourceNode = NodeUtil.createPath(cacheNode, GENERATED_IMAGE_NODE_NAME, NodeTypes.Resource.NAME);
240
241 final ByteArrayInputStream tempIn = new ByteArrayInputStream(tempOut.toByteArray());
242 Property imageData = resourceNode.setProperty(JcrConstants.JCR_DATA, cacheNode.getSession().getValueFactory().createBinary(tempIn));
243
244 final String formatName = generator.getOutputFormat(parameterProvider).getFormatName();
245 final String mimeType = MIMEMapping.getMIMEType(formatName);
246 resourceNode.setProperty(JcrConstants.JCR_MIMETYPE, mimeType);
247 resourceNode.setProperty(JcrConstants.JCR_MIMETYPE, contentType.toString());
248 resourceNode.setProperty(JcrConstants.JCR_LASTMODIFIED, Calendar.getInstance());
249
250
251
252 NodeTypes.LastModified.update(cacheNode);
253
254
255 NodeTypes.LastModified.update(resourceNode);
256
257
258 try {
259 systemSession.save();
260 } catch (InvalidItemStateException e){
261 log.warn("Item found in invalid state. Attempting to refresh the session.");
262 systemSession.refresh(false);
263 return systemSession.getNode(cachePath + "/" + GENERATED_IMAGE_NODE_NAME).getProperty(JcrConstants.JCR_DATA);
264 }
265
266 return imageData;
267 } catch (RepositoryException e) {
268 throw new ImagingException("Can't store rendered image: " + e.getMessage(), e);
269 } finally {
270 log.debug("Unlocked after storing data for {}", parameterProvider);
271 lock.unlock();
272 }
273 }
274
275
276
277
278
279
280
281 private void unwrapRuntimeException(Exception e) throws ImagingException, IOException {
282 final Throwable cause = e.getCause();
283 if (cause instanceof ImagingException) {
284 throw (ImagingException) cause;
285 } else if (cause instanceof IOException) {
286 throw (IOException) cause;
287 } else if (cause instanceof RuntimeException) {
288 unwrapRuntimeException((RuntimeException) cause);
289 } else if (cause == null) {
290
291 throw new IllegalStateException("Unexpected and unhandled exception: " + (e.getMessage() != null ? e.getMessage() : ""), e);
292 } else {
293
294 throw new ImagingException(e.getMessage(), cause);
295 }
296 }
297
298 private static class TemporaryImageResponse implements ImageResponse {
299 private final OutputStream tempOut;
300
301 public TemporaryImageResponse(OutputStream tempOut) {
302 this.tempOut = tempOut;
303 }
304
305 @Override
306 public void setMediaType(MediaType mediaType) throws IOException {
307
308 }
309
310 @Override
311 public OutputStream getOutputStream() throws IOException {
312 return tempOut;
313 }
314 }
315 }