KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > riotfamily > website > txt2img > Txt2ImgController


1 /* ***** BEGIN LICENSE BLOCK *****
2  * Version: MPL 1.1
3  * The contents of this file are subject to the Mozilla Public License Version
4  * 1.1 (the "License"); you may not use this file except in compliance with
5  * the License. You may obtain a copy of the License at
6  * http://www.mozilla.org/MPL/
7  *
8  * Software distributed under the License is distributed on an "AS IS" basis,
9  * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
10  * for the specific language governing rights and limitations under the
11  * License.
12  *
13  * The Original Code is Riot.
14  *
15  * The Initial Developer of the Original Code is
16  * Neteye GmbH.
17  * Portions created by the Initial Developer are Copyright (C) 2007
18  * the Initial Developer. All Rights Reserved.
19  *
20  * Contributor(s):
21  * flx
22  *
23  * ***** END LICENSE BLOCK ***** */

24 package org.riotfamily.website.txt2img;
25
26 import java.io.IOException JavaDoc;
27 import java.io.InputStreamReader JavaDoc;
28 import java.io.PrintWriter JavaDoc;
29 import java.util.ArrayList JavaDoc;
30 import java.util.HashMap JavaDoc;
31 import java.util.Iterator JavaDoc;
32 import java.util.List JavaDoc;
33 import java.util.Locale JavaDoc;
34 import java.util.Map JavaDoc;
35 import java.util.regex.Pattern JavaDoc;
36
37 import javax.servlet.http.HttpServletRequest JavaDoc;
38 import javax.servlet.http.HttpServletResponse JavaDoc;
39
40 import org.riotfamily.cachius.spring.AbstractCacheableController;
41 import org.riotfamily.common.io.IOUtils;
42 import org.riotfamily.common.util.FormatUtils;
43 import org.riotfamily.common.web.util.ServletUtils;
44 import org.springframework.core.io.ClassPathResource;
45 import org.springframework.core.io.Resource;
46 import org.springframework.util.Assert;
47 import org.springframework.util.StringUtils;
48 import org.springframework.web.bind.ServletRequestUtils;
49 import org.springframework.web.servlet.ModelAndView;
50 import org.springframework.web.servlet.mvc.LastModified;
51 import org.springframework.web.servlet.support.RequestContextUtils;
52 import org.springframework.web.util.HtmlUtils;
53
54 /**
55  * @author Felix Gnass [fgnass at neteye dot de]
56  * @since 6.5
57  */

58 public class Txt2ImgController extends AbstractCacheableController
59         implements LastModified {
60
61     private static final Resource SCRIPT_RESOURCE = new ClassPathResource(
62             "txt2img.js", Txt2ImgController.class);
63
64     private static final Resource PIXEL_RESOURCE = new ClassPathResource(
65             "pixel.gif", Txt2ImgController.class);
66
67     private long lastModified = System.currentTimeMillis();
68
69     
70     private Map JavaDoc generators = new HashMap JavaDoc();
71     
72     private List JavaDoc selectors = new ArrayList JavaDoc();
73
74     private ImageGenerator defaultGenerator = new ImageGenerator();
75
76     private Pattern JavaDoc refererPattern;
77
78     /**
79      * Sets a List of {@link ReplacementRule} objects.
80      */

81     public void setRules(List JavaDoc rules) {
82         Iterator JavaDoc it = rules.iterator();
83         while (it.hasNext()) {
84             ReplacementRule rule = (ReplacementRule) it.next();
85             addRule(rule);
86         }
87     }
88
89     public void addRule(ReplacementRule rule) {
90         String JavaDoc[] sel = StringUtils.commaDelimitedListToStringArray(rule.getSelector());
91         for (int i = 0; i < sel.length; i++) {
92             selectors.add(sel[i]);
93             generators.put(sel[i], rule);
94         }
95     }
96     
97     /**
98      * Sets the generator to be used if no generator is found for a given
99      * CSS selector.
100      */

101     public void setDefaultGenerator(ImageGenerator defaultGenerator) {
102         this.defaultGenerator = defaultGenerator;
103     }
104
105     protected void appendCacheKey(StringBuffer JavaDoc key, HttpServletRequest JavaDoc request) {
106         key.append(ServletUtils.getRequestUrlWithQueryString(request));
107     }
108
109     public long getLastModified(HttpServletRequest JavaDoc request) {
110         return lastModified;
111     }
112
113     /**
114      * Sets a regular expression that is used to check the Referer header.
115      * You may use this setting to prevent other websites from using your
116      * ImageGenerator.
117      */

118     public void setRefererPattern(Pattern JavaDoc refererPattern) {
119         this.refererPattern = refererPattern;
120     }
121
122     public ModelAndView handleRequest(HttpServletRequest JavaDoc request,
123             HttpServletResponse JavaDoc response) throws Exception JavaDoc {
124
125         if (refererPattern != null) {
126             String JavaDoc referer = request.getHeader("Referer");
127             if (referer != null && !refererPattern.matcher(referer).matches()) {
128                 response.sendError(HttpServletResponse.SC_FORBIDDEN);
129             }
130         }
131         
132         String JavaDoc extension = FormatUtils.getExtension(request.getRequestURI());
133         String JavaDoc text = getText(request);
134         if (text != null) {
135             serveImage(text, request, response);
136         }
137         else if (extension.equals("gif")) {
138             servePixelGif(response);
139         }
140         else if (request.getParameter("empty") == null) {
141             serveScript(request, response);
142         }
143         return null;
144     }
145
146     /**
147      * Returns the locale for the given request. The method first checks for
148      * a parameter called 'locale' an parses it. If the parameter is not set,
149      * Spring's LocaleResolver mechanism is used.
150      */

151     protected Locale JavaDoc getLocale(HttpServletRequest JavaDoc request) {
152         String JavaDoc localeString = request.getParameter("locale");
153         if (StringUtils.hasText(localeString)) {
154             return StringUtils.parseLocaleString(localeString);
155         }
156         return RequestContextUtils.getLocale(request);
157     }
158
159     protected String JavaDoc getEncodedParam(HttpServletRequest JavaDoc request, String JavaDoc name) {
160         String JavaDoc value = request.getParameter(name);
161         return value != null ? FormatUtils.uriUnescape(value.replace('@', '%')) : null;
162     }
163
164     /**
165      * Returns the text to be rendered. The method unescapes HTML entities
166      * and optionally converts the String to upper or lower case, if the
167      * 'transform' HTTP parameter is set.
168      */

169     protected String JavaDoc getText(HttpServletRequest JavaDoc request) {
170         String JavaDoc text = getEncodedParam(request, "text");
171         if (text != null) {
172             text = HtmlUtils.htmlUnescape(text);
173             String JavaDoc transform = request.getParameter("transform");
174             if (StringUtils.hasText(transform)) {
175                 Locale JavaDoc locale = getLocale(request);
176                 if (transform.equalsIgnoreCase("uppercase")) {
177                     text = text.toUpperCase(locale);
178                 }
179                 if (transform.equalsIgnoreCase("lowercase")) {
180                     text = text.toLowerCase(locale);
181                 }
182             }
183         }
184         return text;
185     }
186
187     /**
188      * Serves an image containing the given text.
189      */

190     protected void serveImage(String JavaDoc text, HttpServletRequest JavaDoc request,
191             HttpServletResponse JavaDoc response) throws IOException JavaDoc {
192
193         ImageGenerator generator = defaultGenerator;
194         String JavaDoc selector = getEncodedParam(request, "selector");
195         if (selector != null) {
196             generator = (ImageGenerator) generators.get(selector);
197         }
198         Assert.notNull(generator, "No ImageGenerator found for selector '"
199                 + selector + "' and no default generator is set.");
200
201         text = FormatUtils.stripWhitespaces(text, true);
202         int maxWidth = ServletRequestUtils.getIntParameter(request, "width", 0);
203         if (maxWidth <= 0) {
204             maxWidth = Integer.MAX_VALUE;
205         }
206         String JavaDoc color = getEncodedParam(request, "color");
207         response.setContentType("image/png");
208         ServletUtils.setCacheHeaders(response, "1M");
209         generator.generate(text, maxWidth, color, response.getOutputStream());
210     }
211
212     /**
213      * Serves a JavaScript file that can be used to replace texts on the
214      * client side.
215      */

216     protected void serveScript(HttpServletRequest JavaDoc request,
217             HttpServletResponse JavaDoc response) throws IOException JavaDoc {
218
219         response.setContentType("text/javascript");
220         ServletUtils.setCacheHeaders(response, "1M");
221         PrintWriter JavaDoc out = response.getWriter();
222         out.println("var IEDOMReadyScript = '" + request.getRequestURI() + "?empty=true';");
223
224         IOUtils.copy(new InputStreamReader JavaDoc(
225                 SCRIPT_RESOURCE.getInputStream(), "UTF-8"), out);
226
227         out.print("var txt2img = new RiotImageReplacement('");
228         out.print(getGeneratorUrl(request));
229         out.print("?locale=");
230         out.print(RequestContextUtils.getLocale(request));
231         out.print("', '");
232         out.print(getPixelUrl(request));
233         out.print("', [");
234         Iterator JavaDoc it = selectors.iterator();
235         while (it.hasNext()) {
236             out.print("'");
237             out.print(it.next());
238             out.print("'");
239             if (it.hasNext()) {
240                 out.print(", ");
241             }
242         }
243         out.print("]);");
244     }
245
246     private String JavaDoc getGeneratorUrl(HttpServletRequest JavaDoc request) {
247         return FormatUtils.stripExtension(request.getRequestURI()) + ".png";
248     }
249     
250     private String JavaDoc getPixelUrl(HttpServletRequest JavaDoc request) {
251         return FormatUtils.stripExtension(request.getRequestURI()) + ".gif";
252     }
253
254     /**
255      * Serves a transparent 1x1 pixel GIF that is needed by the JavaScript
256      * to work around the PNG loading in IE &lt; 7.
257      */

258     protected void servePixelGif(HttpServletResponse JavaDoc response) throws IOException JavaDoc {
259         response.setContentType("image/gif");
260         ServletUtils.setCacheHeaders(response, "1M");
261         IOUtils.copy(PIXEL_RESOURCE.getInputStream(), response.getOutputStream());
262     }
263 }
264
Popular Tags