View Javadoc
1   /**
2    * This file Copyright (c) 2009-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.imaging;
35  
36  import info.magnolia.cms.core.HierarchyManager;
37  import info.magnolia.cms.util.BooleanUtil;
38  import info.magnolia.context.MgnlContext;
39  import info.magnolia.imaging.caching.CachingImageStreamer;
40  import info.magnolia.imaging.caching.CachingStrategy;
41  import info.magnolia.imaging.util.PathSplitter;
42  
43  import java.io.IOException;
44  
45  import javax.inject.Inject;
46  import javax.servlet.ServletConfig;
47  import javax.servlet.ServletException;
48  import javax.servlet.http.HttpServlet;
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  
52  import org.apache.commons.lang3.StringUtils;
53  import org.slf4j.Logger;
54  import org.slf4j.LoggerFactory;
55  
56  /**
57   * Servlet responsible for the actual generation of the images. TODO This
58   * servlet might need some investigation - improvements; particularly how the
59   * parameterProvider, and various factories are bound together.
60   * During development / tests of generators, set the storeGeneratedImages
61   * parameter to "false".
62   */
63  public class ImagingServlet extends HttpServlet {
64      private static final Logger log = LoggerFactory.getLogger(ImagingServlet.class);
65  
66      private boolean storeGeneratedImages = true;
67      private boolean validateFileExtension = false;
68      private final ImagingModule imagingModule;
69  
70      @Inject
71      public ImagingServlet(final ImagingModule imagingModule) {
72          this.imagingModule = imagingModule;
73      }
74  
75      @Override
76      public void init(ServletConfig config) throws ServletException {
77          super.init(config);
78          storeGeneratedImages = BooleanUtil.toBoolean(config.getInitParameter("storeGeneratedImages"), true);
79          validateFileExtension = BooleanUtil.toBoolean(config.getInitParameter("validateFileExtension"), false);
80      }
81  
82      @Override
83      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
84  
85          final String generatorName = getImageGeneratorName(request);
86          final ImageGenerator generator = getGenerator(generatorName);
87          if (generator == null) {
88              throw new IllegalArgumentException("No ImageGenerator with name " + generatorName);
89          }
90  
91          final ParameterProviderFactory parameterProviderFactory = generator.getParameterProviderFactory();
92          final ParameterProvider p = parameterProviderFactory.newParameterProviderFor(request);
93  
94          if (validateFileExtension) {
95              String outputFormat = generator.getOutputFormat(p).getFormatName();
96              String requestedPath = StringUtils.substringAfterLast(request.getPathInfo(), "/"); // don't take part of node name as extension, we support dots in node names!
97              String requestedFormat = StringUtils.substringAfterLast(requestedPath, ".");
98              if (!StringUtils.equals(outputFormat, requestedFormat)) {
99                  response.sendError(HttpServletResponse.SC_NOT_FOUND);
100                 return;
101             }
102         }
103 
104         try {
105             // TODO -- mimetype etc.
106             final ImageStreamer streamer = getStreamer(parameterProviderFactory);
107 
108             try {
109                 streamer.serveImage(generator, p, response.getOutputStream());
110                 response.flushBuffer();
111             } catch (IOException e) {
112                 // only log at debug level
113                 // tomcat usually throws a ClientAbortException anytime the user stop loading the page
114                 log.debug("Unable to spool resource due to a {} exception", e.getClass().getName());
115                 if (!response.isCommitted()) {
116                     response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
117                 }
118             }
119             // IOUtils.closeQuietly(response.getOutputStream());
120         } catch (ImagingException e) {
121             throw new ServletException(e); // TODO
122         }
123     }
124 
125     /**
126      * Determines the ImageGenerator to use, using the first path element of the
127      * pathInfo.
128      */
129     protected String getImageGeneratorName(HttpServletRequest request) {
130         final String pathInfo = request.getPathInfo();
131         return new PathSplitter(pathInfo).skipTo(0);
132     }
133 
134     protected ImageGenerator getGenerator(String generatorName) {
135         final ImagingModule module = getImagingModule();
136         return module.getGenerators().get(generatorName);
137     }
138 
139     protected ImageStreamer getStreamer(ParameterProviderFactory parameterProviderFactory) {
140         // TODO -- CachingImageStreamer currently has a non-static "currentJobs"
141         // map.
142         // TODO -- to investigate, but I highly suspect that it's not really
143         // useful if
144         // we use a different instance of CachingImageStreamer for every
145         // request.
146 
147         final DefaultImageStreamer newDefaultImageStreamer = new DefaultImageStreamer();
148         if (!storeGeneratedImages) {
149             return newDefaultImageStreamer;
150         } else {
151             final HierarchyManager hm = MgnlContext.getHierarchyManager("imaging");
152             final CachingStrategy cachingStrategy = parameterProviderFactory.getCachingStrategy();
153             return new CachingImageStreamer(hm, cachingStrategy, newDefaultImageStreamer);
154         }
155     }
156 
157     /**
158      * @deprecated since 3.2. Use {@link #getImagingModule}.
159      */
160     @Deprecated
161     protected ImagingModuleConfig getImagingConfiguration() {
162         return (ImagingModuleConfig) imagingModule;
163     }
164 
165     protected ImagingModule getImagingModule() {
166         return imagingModule;
167     }
168 }