View Javadoc

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