View Javadoc
1   /**
2    * This file Copyright (c) 2012-2016 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.templating.jsp.taglib;
35  
36  import info.magnolia.cms.core.Content;
37  import info.magnolia.cms.core.HierarchyManager;
38  import info.magnolia.cms.core.ItemType;
39  import info.magnolia.cms.util.NodeDataUtil;
40  import info.magnolia.context.MgnlContext;
41  import info.magnolia.jcr.util.NodeTypes;
42  import info.magnolia.repository.RepositoryConstants;
43  
44  import java.awt.Graphics2D;
45  import java.awt.Image;
46  import java.awt.image.BufferedImage;
47  import java.io.File;
48  import java.io.FileNotFoundException;
49  import java.io.IOException;
50  import java.io.InputStream;
51  import java.util.Calendar;
52  
53  import javax.imageio.ImageIO;
54  import javax.jcr.AccessDeniedException;
55  import javax.jcr.PathNotFoundException;
56  import javax.jcr.RepositoryException;
57  import javax.servlet.jsp.JspException;
58  import javax.servlet.jsp.JspWriter;
59  
60  import org.slf4j.LoggerFactory;
61  import org.slf4j.Logger;
62  
63  import org.tldgen.annotations.BodyContent;
64  import org.tldgen.annotations.Tag;
65  
66  /**
67   * Creates a scaled copy of an image. The maximum width and height of the images can be specified via the
68   * attributes. <br />
69   * <br />
70   * If the scaled image with the specified name does not exist in the repository, then this tag will create it and save
71   * it. If the scaled image already exists, then it will not be recreated. <br />
72   * <br />
73   * The name of the node that contains the original image is set by the attribute 'parentContentNode', and the name of
74   * the nodeData for the image is set by the attribute 'parentNodeDataName'. If 'parentContentNode' is null, the local
75   * content node is used. <br />
76   * <br />
77   * The name of the content node that contains the new scaled image is set by the attribute 'imageContentNodeName'. This
78   * node is created under the original image node. This ensures that, if the original images is deleted, so are all the
79   * scaled versions. <br />
80   * <br />
81   * This tag writes out the handle of the content node that contains the image. <br />
82   * <br />
83   *
84   * @jsp.tag name="scaleImage" body-content="empty"
85   */
86  @Tag(name="scaleImage", bodyContent=BodyContent.EMPTY)
87  
88  public class ScaleImageTag extends BaseImageTag {
89      private static final Logger log = LoggerFactory.getLogger(ScaleImageTag.class);
90  
91      /**
92       * Location for folder for temporary image creation.
93       */
94      private static final String TEMP_IMAGE_NAME = "tmp-img";
95  
96      /**
97       * The value of the extension nodeData in the properties node.
98       */
99      private static final String PROPERTIES_EXTENSION_VALUE = "PNG";
100 
101     /**
102      * Attribute: Image maximum height.
103      */
104     private int maxHeight = 0;
105 
106     /**
107      * Attribute: Image maximum width.
108      */
109     private int maxWidth = 0;
110 
111     /**
112      * Attribute: Allow resizing images beyond their original dimensions.
113      * Enabled by default for backwards compatibility but keep in mind this can
114      * result in images of very poor quality.
115      */
116     private boolean allowOversize = true;
117 
118     /**
119      * Attribute: The name of the new content node to create.
120      */
121     private String imageContentNodeName;
122 
123     /**
124      * Attribute: The name of the data node that contains the existing image.
125      */
126     private String parentNodeDataName;
127 
128     /**
129      * The maximum height of the image in pixels.
130      * @jsp.attribute required="false" rtexprvalue="true" type="int"
131      */
132     public void setMaxHeight(int maxHeight) {
133         this.maxHeight = maxHeight;
134     }
135 
136     /**
137      * The maximum width of the image in pixels.
138      * @jsp.attribute required="false" rtexprvalue="true" type="int"
139      */
140     public void setMaxWidth(int maxWidth) {
141         this.maxWidth = maxWidth;
142     }
143 
144     /**
145      * Allow resizing images beyond their original dimensions?
146      * @jsp.attribute required="false" rtexprvalue="true" type="boolean"
147      */
148     public void setAllowOversize(boolean allowOversize) {
149         this.allowOversize = allowOversize;
150     }
151 
152     /**
153      * The name of the content node that contains the image to be copied and scaled.
154      * @jsp.attribute required="false" rtexprvalue="true"
155      */
156     @Override
157     public void setParentContentNodeName(String parentContentNodeName) {
158         this.parentContentNodeName = parentContentNodeName;
159     }
160 
161     /**
162      * The name of the data node that contains the image data to be copied and scaled.
163      * @jsp.attribute required="true" rtexprvalue="true"
164      */
165     public void setParentNodeDataName(String parentNodeDataName) {
166         this.parentNodeDataName = parentNodeDataName;
167     }
168 
169     /**
170      * The name of the new contentNode that will contain the scaled version of the image.
171      * @jsp.attribute required="true" rtexprvalue="true"
172      */
173     @Override
174     public void setImageContentNodeName(String imageContentNodeName) {
175         this.imageContentNodeName = imageContentNodeName;
176     }
177 
178     @Override
179     public void doTag() throws JspException {
180         // initialize everything
181         Content parentContentNode;
182         Content imageContentNode;
183         JspWriter out = this.getJspContext().getOut();
184 
185         try {
186 
187             // set the parent node that contains the original image
188             if ((this.parentContentNodeName == null) || (this.parentContentNodeName.equals(""))) {
189                 parentContentNode = MgnlContext.getAggregationState().getCurrentContent();
190             }
191             else {
192                 HierarchyManager hm = MgnlContext.getHierarchyManager(RepositoryConstants.WEBSITE);
193                 // if this name starts with a '/', then assume it is a node handle
194                 // otherwise assume that its is a path relative to the local content node
195                 if (this.parentContentNodeName.startsWith("/")) {
196                     parentContentNode = hm.getContent(this.parentContentNodeName);
197                 }
198                 else {
199                     String handle = MgnlContext.getAggregationState().getCurrentContentNode().getPath();
200                     parentContentNode = hm.getContent(handle + "/" + this.parentContentNodeName);
201                 }
202             }
203 
204             // check if the new image node exists, if not then create it
205             if (parentContentNode.hasContent(this.imageContentNodeName)) {
206                 imageContentNode = parentContentNode.getContent(this.imageContentNodeName);
207             }
208             else {
209                 // create the node
210                 imageContentNode = parentContentNode.createContent(this.imageContentNodeName, ItemType.CONTENTNODE);
211                 parentContentNode.save();
212             }
213             // if the node does not have the image data or should be rescaled (i.e., something has c
214             // then create the image data
215             if (!imageContentNode.hasNodeData(this.parentNodeDataName) || rescale(parentContentNode, imageContentNode)) {
216                 this.createImageNodeData(parentContentNode, imageContentNode);
217             }
218             // write out the handle for the new image and exit
219             StringBuffer handle = new StringBuffer(imageContentNode.getHandle());
220             handle.append("/");
221             handle.append(getFilename());
222             out.write(handle.toString());
223         }
224         catch (PathNotFoundException e) {
225             log.error("PathNotFoundException occured in ScaleImage tag: {}", e.getMessage(), e);
226         }
227         catch (AccessDeniedException e) {
228             log.error("AccessDeniedException occured in ScaleImage tag: {}", e.getMessage(), e);
229         }
230         catch (RepositoryException e) {
231             log.error("RepositoryException occured in ScaleImage tag: {}", e.getMessage(), e);
232         }
233         catch (FileNotFoundException e) {
234             log.error("FileNotFoundException occured in ScaleImage tag: {}", e.getMessage(), e);
235         }
236         catch (IOException e) {
237             log.error("IOException occured in ScaleImage tag: {}", e.getMessage(), e);
238         }
239         this.cleanUp();
240     }
241 
242     /**
243      * Checks to see if the previously scaled image needs to be rescaled. This is true when the parent content node has
244      * been updated or the height or width parameters have changed.
245      * @param parentContentNode The node containing the scaled image node
246      * @param imageContentNode The scaled image node
247      * @return
248      */
249     protected boolean rescale(Content parentContentNode, Content imageContentNode) {
250 
251         try {
252             Calendar parentModified = NodeTypes.LastModified.getLastModified(parentContentNode.getJCRNode());
253             Calendar imageModified = NodeTypes.LastModified.getLastModified(imageContentNode.getJCRNode());
254 
255             if (parentModified.after(imageModified)) {
256                 return true;
257             }
258         } catch (RepositoryException e) {
259             // if we can't determine last modification of the nodes then do the safe thing and go for rescaling
260             return true;
261         }
262 
263         int originalHeight = (int) imageContentNode.getNodeData("maxHeight").getLong();
264         int originalWidth = (int) imageContentNode.getNodeData("maxWidth").getLong();
265 
266         return originalHeight != maxHeight || originalWidth != maxWidth;
267     }
268 
269     /**
270      * Set objects to null.
271      */
272     public void cleanUp() {
273         this.parentNodeDataName = null;
274         this.imageContentNodeName = null;
275         this.maxWidth = 0;
276         this.maxHeight = 0;
277     }
278 
279     /**
280      * Create an image file that is a scaled version of the original image.
281      * @param imageContentNode node
282      */
283     private void createImageNodeData(Content parentContentNode, Content imageContentNode) throws PathNotFoundException,
284         RepositoryException, IOException {
285 
286         // get the original image, as a buffered image
287         InputStream oriImgStr = parentContentNode.getNodeData(this.parentNodeDataName).getStream();
288         BufferedImage oriImgBuff = ImageIO.read(oriImgStr);
289         oriImgStr.close();
290         // create the new image file
291         File newImgFile = this.scaleImage(oriImgBuff);
292 
293         NodeDataUtil.getOrCreate(imageContentNode, "maxHeight").setValue(maxHeight);
294         NodeDataUtil.getOrCreate(imageContentNode, "maxWidth").setValue(maxWidth);
295 
296         createImageNode(newImgFile, imageContentNode);
297 
298         newImgFile.delete();
299     }
300 
301     /**
302      * Create an image file that is a scaled version of the original image.
303      * @param oriImgBuff the original image file
304      * @return the new image file
305      */
306     private File scaleImage(BufferedImage oriImgBuff) throws IOException {
307         // get the dimesnions of the original image
308         int oriWidth = oriImgBuff.getWidth();
309         int oriHeight = oriImgBuff.getHeight();
310         // get scale factor for the new image
311         double scaleFactor = this.scaleFactor(oriWidth, oriHeight);
312         // get the width and height of the new image
313         int newWidth = new Double(oriWidth * scaleFactor).intValue();
314         int newHeight = new Double(oriHeight * scaleFactor).intValue();
315         // create the thumbnail as a buffered image
316         Image newImg = oriImgBuff.getScaledInstance(newWidth, newHeight, Image.SCALE_AREA_AVERAGING);
317         BufferedImage newImgBuff = new BufferedImage(
318             newImg.getWidth(null),
319             newImg.getHeight(null),
320             BufferedImage.TYPE_INT_RGB);
321         Graphics2D g = newImgBuff.createGraphics();
322         g.drawImage(newImg, 0, 0, null);
323         g.dispose();
324         // create the new image file in the temporary dir
325         File newImgFile = File.createTempFile(TEMP_IMAGE_NAME, PROPERTIES_EXTENSION_VALUE);
326 
327         ImageIO.write(newImgBuff, PROPERTIES_EXTENSION_VALUE, newImgFile);
328         // return the file
329         return newImgFile;
330     }
331 
332     /**
333      * Calculate the scale factor for the image.
334      * @param originalWidth the image width
335      * @param originalHeight the image height
336      * @return the scale factor
337      */
338     private double scaleFactor(int originalWidth, int originalHeight) {
339         double scaleFactor;
340 
341         int scaleWidth = this.maxWidth;
342         int scaleHeight = this.maxHeight;
343 
344         if (!this.allowOversize) {
345             scaleWidth = Math.min(this.maxWidth, originalWidth);
346             scaleHeight = Math.min(this.maxHeight, originalHeight);
347         }
348 
349         if (scaleWidth <= 0 && scaleHeight <= 0) {
350             // may a copy at the same size
351             scaleFactor = 1;
352         }
353         else if (scaleWidth <= 0) {
354             // use height
355             scaleFactor = (double) scaleHeight / (double) originalHeight;
356         }
357         else if (scaleHeight <= 0) {
358             // use width
359             scaleFactor = (double) scaleWidth / (double) originalWidth;
360         }
361         else {
362             // create two scale factors, and see which is smaller
363             double scaleFactorWidth = (double) scaleWidth / (double) originalWidth;
364             double scaleFactorHeight = (double) scaleHeight / (double) originalHeight;
365             scaleFactor = Math.min(scaleFactorWidth, scaleFactorHeight);
366         }
367         return scaleFactor;
368     }
369 
370     @Override
371     protected String getFilename() {
372         return this.parentNodeDataName;
373     }
374 }