KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > magnolia > cms > taglibs > util > BaseImageTag


1 /**
2  *
3  * Magnolia and its source-code is licensed under the LGPL.
4  * You may copy, adapt, and redistribute this file for commercial or non-commercial use.
5  * When copying, adapting, or redistributing this document in keeping with the guidelines above,
6  * you are required to provide proper attribution to obinary.
7  * If you reproduce or distribute the document without making any substantive modifications to its content,
8  * please use the following attribution line:
9  *
10  * Copyright 1993-2006 obinary Ltd. (http://www.obinary.com) All rights reserved.
11  *
12  */

13 package info.magnolia.cms.taglibs.util;
14
15 import info.magnolia.cms.beans.config.ContentRepository;
16 import info.magnolia.cms.core.Content;
17 import info.magnolia.cms.core.HierarchyManager;
18 import info.magnolia.cms.core.ItemType;
19 import info.magnolia.cms.core.NodeData;
20 import info.magnolia.cms.gui.misc.FileProperties;
21 import info.magnolia.cms.util.Resource;
22 import info.magnolia.context.MgnlContext;
23
24 import java.awt.Color JavaDoc;
25 import java.io.File JavaDoc;
26 import java.io.FileInputStream JavaDoc;
27 import java.io.FileNotFoundException JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStream JavaDoc;
30 import java.text.CharacterIterator JavaDoc;
31 import java.text.StringCharacterIterator JavaDoc;
32 import java.util.Calendar JavaDoc;
33 import java.util.GregorianCalendar JavaDoc;
34 import java.util.TimeZone JavaDoc;
35
36 import javax.jcr.AccessDeniedException;
37 import javax.jcr.PathNotFoundException;
38 import javax.jcr.PropertyType;
39 import javax.jcr.RepositoryException;
40 import javax.servlet.http.HttpServletRequest JavaDoc;
41 import javax.servlet.jsp.PageContext JavaDoc;
42 import javax.servlet.jsp.tagext.SimpleTagSupport JavaDoc;
43
44 import org.apache.commons.io.IOUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.devlib.schmidt.imageinfo.ImageInfo;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49
50
51 /**
52  * @author Fabrizio Giustina
53  */

54 public abstract class BaseImageTag extends SimpleTagSupport JavaDoc {
55
56     /**
57      * The value of the extension nodeData in the properties node.
58      */

59     protected static final String JavaDoc PROPERTIES_EXTENSION_VALUE = "PNG";
60
61     /**
62      * The valye of the contentType nodeData in the properties node.
63      */

64     protected static final String JavaDoc PROPERTIES_CONTENTTYPE_VALUE = "image/png";
65
66     /**
67      * Logger.
68      */

69     private static Logger log = LoggerFactory.getLogger(BaseImageTag.class);
70
71     /**
72      * Attribute: The node where the images are to be saved. If null, the default will be the current active page.
73      */

74     protected String JavaDoc parentContentNodeName;
75
76     /**
77      * Attribute: The name of the new content node to create. The images will be saved under this node. If this name
78      * starts with a '/', it will be assumed to be a node handle that is relative to the rooot of the website.
79      * Otherwise, it is assumed to be a path relative to the currentActivePage.
80      */

81     protected String JavaDoc imageContentNodeName;
82
83     /**
84      * Setter for the <code>imageContentNodeName</code> tag attribute.
85      * @param imageContentNodeName
86      */

87     public void setImageContentNodeName(String JavaDoc imageContentNodeName) {
88         this.imageContentNodeName = imageContentNodeName;
89     }
90
91     /**
92      * Setter for the <code>parentContentNodeName</code> tag attribute.
93      * @param parentContentNodeName
94      */

95     public void setParentContentNodeName(String JavaDoc parentContentNodeName) {
96         this.parentContentNodeName = parentContentNodeName;
97     }
98
99     protected abstract String JavaDoc getFilename();
100
101     protected HttpServletRequest JavaDoc getRequest() {
102         return (HttpServletRequest JavaDoc) ((PageContext JavaDoc) this.getJspContext()).getRequest();
103     }
104
105     /**
106      * @throws PathNotFoundException
107      * @throws RepositoryException
108      * @throws AccessDeniedException
109      */

110     protected Content getImageContentNode() throws PathNotFoundException, RepositoryException,
111         info.magnolia.cms.security.AccessDeniedException {
112
113         Content imageContentNode;
114         Content currentActivePage = Resource.getCurrentActivePage(getRequest());
115         Content paragraph = Resource.getLocalContentNode(getRequest());
116         Content parentContentNode = null;
117         // set the image parent node
118
if (StringUtils.isEmpty(this.parentContentNodeName)) {
119             parentContentNode = paragraph != null ? paragraph : currentActivePage;
120         }
121         else {
122
123             HierarchyManager hm = MgnlContext.getHierarchyManager(ContentRepository.WEBSITE);
124             // if this name starts with a '/', then assume it is a node handle
125
// otherwise assume that its is a path relative to the current active page
126
if (this.parentContentNodeName.startsWith("/")) {
127                 parentContentNode = hm.getContent(this.parentContentNodeName);
128             }
129             else {
130                 parentContentNode = hm.getContent(currentActivePage.getHandle() + "/" + this.parentContentNodeName);
131             }
132         }
133         // set the node under which the images will be saved
134
imageContentNode = null;
135         if (StringUtils.isEmpty(this.imageContentNodeName)) {
136             imageContentNode = parentContentNode;
137         }
138         else if (parentContentNode.hasContent(this.imageContentNodeName)) {
139             imageContentNode = parentContentNode.getContent(this.imageContentNodeName);
140         }
141         else {
142             imageContentNode = parentContentNode.createContent(this.imageContentNodeName, ItemType.CONTENTNODE);
143         }
144         return imageContentNode;
145     }
146
147     /**
148      * Replace any special characters that are not letters or numbers with a replacement string. The two exceptions are
149      * '-' and '_', which are allowed.
150      */

151     public String JavaDoc convertToSimpleString(String JavaDoc string) {
152
153         final StringBuffer JavaDoc result = new StringBuffer JavaDoc();
154
155         final StringCharacterIterator JavaDoc iterator = new StringCharacterIterator JavaDoc(string);
156         char character = iterator.current();
157         while (character != CharacterIterator.DONE) {
158             int charType = Character.getType(character);
159             if (charType == Character.SPACE_SEPARATOR) {
160                 result.append("-");
161             }
162             else if ((charType != Character.UPPERCASE_LETTER)
163                 && (charType != Character.LOWERCASE_LETTER)
164                 && (charType != Character.DECIMAL_DIGIT_NUMBER)
165                 && (charType != Character.CONNECTOR_PUNCTUATION)
166                 && (charType != Character.DASH_PUNCTUATION)) {
167                 result.append("u" + (int) character);
168
169             }
170             else {
171                 // the char is not a special one
172
// add it to the result as is
173
result.append(character);
174             }
175             character = iterator.next();
176         }
177         return result.toString();
178     }
179
180     /**
181      * Converts HEX color to RGB color.
182      * @param The HEX value
183      */

184     public int[] convertHexToRGB(String JavaDoc hex) {
185         hex.trim();
186         if (hex.startsWith("#")) {
187             hex = hex.substring(1);
188         }
189         if (hex.length() == 3) {
190             // allow three digit codes like for css
191
hex = String.valueOf(hex.charAt(0))
192                 + String.valueOf(hex.charAt(0))
193                 + String.valueOf(hex.charAt(1))
194                 + String.valueOf(hex.charAt(1))
195                 + String.valueOf(hex.charAt(2))
196                 + String.valueOf(hex.charAt(2));
197         }
198
199         int[] rgb = new int[3];
200         try {
201             // Convert rrggbb string to hex ints
202
rgb[0] = Integer.parseInt(hex.substring(0, 2), 16);
203             rgb[1] = Integer.parseInt(hex.substring(2, 4), 16);
204             rgb[2] = Integer.parseInt(hex.substring(4), 16);
205         }
206         catch (NumberFormatException JavaDoc e) {
207             log.error("NumberFormatException occured during text-to-image conversion: "
208                 + "Attempting to convert Hex ["
209                 + hex
210                 + "] color to RGB color: "
211                 + e.getMessage(), e);
212             rgb = new int[]{255, 0, 0}; // red
213
}
214         return rgb;
215     }
216
217     public Color JavaDoc convertHexToColor(String JavaDoc hex) {
218         int[] rgb = convertHexToRGB(hex);
219         Color JavaDoc color = new Color JavaDoc(rgb[0], rgb[1], rgb[2]);
220         return color;
221     }
222
223     /**
224      * Create a new imageNode with the image in it. The node is saved under a node that groups all image nodes, whose
225      * name is set to the value of the attribute imageContentNodeName. The name of the node will be set to a name that
226      * is unique for the image. The property that stores the image will be set to the value of
227      * PROPERTIES_FILENAME_VALUE. A sub-node is also created that stores the image properties.
228      * @param subString The text.
229      * @param textImageNode The node that will contain the text images.
230      */

231     protected void createImageNode(File JavaDoc imageFile, Content imageNode) throws PathNotFoundException,
232         AccessDeniedException, RepositoryException, FileNotFoundException JavaDoc, IOException JavaDoc {
233
234         // Create and save the image data
235
NodeData data;
236         data = imageNode.getNodeData(getFilename());
237
238         if (!data.isExist()) {
239             data = imageNode.createNodeData(getFilename(), PropertyType.BINARY);
240         }
241
242         InputStream JavaDoc iis = new FileInputStream JavaDoc(imageFile);
243         data.setValue(iis);
244         IOUtils.closeQuietly(iis);
245
246         data.setAttribute(FileProperties.PROPERTY_FILENAME, getFilename());
247
248         data.setAttribute(FileProperties.PROPERTY_CONTENTTYPE, PROPERTIES_CONTENTTYPE_VALUE);
249
250         Calendar JavaDoc value = new GregorianCalendar JavaDoc(TimeZone.getDefault());
251         data.setAttribute(FileProperties.PROPERTY_LASTMODIFIED, value);
252
253         data.setAttribute(FileProperties.PROPERTY_SIZE, Long.toString(imageFile.length()));
254
255         data.setAttribute(FileProperties.PROPERTY_EXTENSION, PROPERTIES_EXTENSION_VALUE);
256
257         InputStream JavaDoc raf = null;
258         try {
259             ImageInfo ii = new ImageInfo();
260             raf = new FileInputStream JavaDoc(imageFile);
261             ii.setInput(raf);
262             if (ii.check()) {
263                 data.setAttribute(FileProperties.PROPERTY_WIDTH, Long.toString(ii.getWidth()));
264                 data.setAttribute(FileProperties.PROPERTY_HEIGHT, Long.toString(ii.getHeight()));
265
266             }
267         }
268         catch (FileNotFoundException JavaDoc e) {
269             log.error("FileNotFoundException caught when parsing {}, image data will not be available", imageFile
270                 .getAbsolutePath());
271         }
272         finally {
273             IOUtils.closeQuietly(raf);
274         }
275
276         // delete the temporary file
277
imageFile.delete();
278
279         // save the new image node
280
imageNode.save();
281     }
282 }
283
Popular Tags