KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > opencms > frontend > templateone > form > CmsCaptchaField


1 /*
2  * File : $Source: /usr/local/cvs/opencms/src-modules/org/opencms/frontend/templateone/form/CmsCaptchaField.java,v $
3  * Date : $Date: 2006/03/27 14:52:20 $
4  * Version: $Revision: 1.9 $
5  *
6  * This library is part of OpenCms -
7  * the Open Source Content Mananagement System
8  *
9  * Copyright (C) 2002 - 2004 Alkacon Software (http://www.alkacon.com)
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * For further information about Alkacon Software, please see the
22  * company website: http://www.alkacon.com
23  *
24  * For further information about OpenCms, please see the
25  * project website: http://www.opencms.org
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  */

31
32 package org.opencms.frontend.templateone.form;
33
34 import org.opencms.flex.CmsFlexController;
35 import org.opencms.i18n.CmsMessages;
36 import org.opencms.jsp.CmsJspActionElement;
37 import org.opencms.main.CmsLog;
38 import org.opencms.util.CmsStringUtil;
39
40 import java.awt.image.BufferedImage JavaDoc;
41 import java.io.ByteArrayOutputStream JavaDoc;
42 import java.io.IOException JavaDoc;
43 import java.util.Locale JavaDoc;
44
45 import javax.servlet.ServletOutputStream JavaDoc;
46 import javax.servlet.http.HttpServletResponse JavaDoc;
47
48 import org.apache.commons.logging.Log;
49
50 import com.octo.captcha.CaptchaException;
51 import com.octo.captcha.service.image.ImageCaptchaService;
52 import com.sun.image.codec.jpeg.JPEGCodec;
53 import com.sun.image.codec.jpeg.JPEGImageEncoder;
54
55 /**
56  * Creates captcha images and validates the pharses submitted by a request parameter.
57  * <p>
58  *
59  * @author Thomas Weckert
60  *
61  * @author Achim Westermann
62  *
63  * @version $Revision: 1.9 $
64  */

65 public class CmsCaptchaField extends A_CmsField {
66
67     /** Request parameter name of the captcha phrase. */
68     public static final String JavaDoc C_PARAM_CAPTCHA_PHRASE = "captchaphrase";
69
70     /** The log object for this class. */
71     private static final Log LOG = CmsLog.getLog(CmsCaptchaField.class);
72
73     /** HTML field type: captcha image. */
74     private static final String JavaDoc TYPE = "captcha";
75
76     /** The settings to render captcha images. */
77     private CmsCaptchaSettings m_captchaSettings;
78
79     /**
80      * Creates a new captcha field.
81      * <p>
82      *
83      * @param captchaSettings the settings to render captcha images
84      * @param fieldLabel the localized label of this field
85      * @param fieldValue the submitted value of this field
86      */

87     public CmsCaptchaField(CmsCaptchaSettings captchaSettings, String JavaDoc fieldLabel, String JavaDoc fieldValue) {
88
89         super();
90
91         m_captchaSettings = captchaSettings;
92
93         setName(C_PARAM_CAPTCHA_PHRASE);
94         setValue(fieldValue);
95         setLabel(fieldLabel);
96         setMandatory(true);
97     }
98
99     /**
100      * Returns the type of the input field, e.g. "text" or "select".
101      * <p>
102      *
103      * @return the type of the input field
104      */

105     public static String JavaDoc getStaticType() {
106
107         return TYPE;
108     }
109
110     /**
111      * @see org.opencms.frontend.templateone.form.I_CmsField#buildHtml(CmsFormHandler,
112      * org.opencms.i18n.CmsMessages, String)
113      */

114     public String JavaDoc buildHtml(CmsFormHandler formHandler, CmsMessages messages, String JavaDoc errorKey) {
115
116         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
117         String JavaDoc fieldLabel = getLabel();
118         String JavaDoc errorMessage = "";
119         String JavaDoc mandatory = "";
120
121         CmsCaptchaSettings captchaSettings = getCaptchaSettings();
122
123         if (CmsStringUtil.isNotEmpty(errorKey)) {
124
125             if (CmsFormHandler.ERROR_MANDATORY.equals(errorKey)) {
126                 errorMessage = messages.key("form.error.mandatory");
127             } else if (CmsStringUtil.isNotEmpty(getErrorMessage())) {
128                 errorMessage = getErrorMessage();
129             } else {
130                 errorMessage = messages.key("form.error.validation");
131             }
132
133             errorMessage = messages.key("form.html.error.start") + errorMessage + messages.key("form.html.error.end");
134             fieldLabel = messages.key("form.html.label.error.start")
135                 + fieldLabel
136                 + messages.key("form.html.label.error.end");
137         }
138
139         if (isMandatory()) {
140             mandatory = messages.key("form.html.mandatory");
141         }
142
143         // line #1
144
buf.append(messages.key("form.html.row.start")).append("\n");
145
146         // line #2
147
buf.append(messages.key("form.html.label.start")).append(fieldLabel).append(mandatory).append(
148             messages.key("form.html.label.end")).append("\n");
149
150         // line #3
151
buf.append(messages.key("form.html.field.start")).append("\n");
152
153         // line #4
154
buf.append("<img SRC=\"").append(
155             formHandler.link("/system/modules/org.opencms.frontend.templateone.form/pages/captcha?"
156                 + captchaSettings.toRequestParams(formHandler.getCmsObject()))).append("\" width=\"").append(
157             captchaSettings.getImageWidth()).append("\" height=\"").append(captchaSettings.getImageHeight()).append(
158             "\" alt=\"\">").append("\n");
159
160         // line #5
161
buf.append("<br>\n");
162
163         // line #6
164
buf.append("<input type=\"text\" name=\"").append(getName()).append("\" value=\"").append(getValue()).append(
165             "\"").append(formHandler.getFormConfiguration().getFormFieldAttributes()).append(">").append(errorMessage).append(
166             messages.key("form.html.field.end")).append("\n");
167
168         // line #7
169
buf.append(messages.key("form.html.row.end")).append("\n");
170
171         return buf.toString();
172     }
173
174     /**
175      * Returns the captcha settings of this field.
176      * <p>
177      *
178      * @return the captcha settings of this field
179      */

180     public CmsCaptchaSettings getCaptchaSettings() {
181
182         return m_captchaSettings;
183     }
184
185     /**
186      * @see org.opencms.frontend.templateone.form.I_CmsField#getType()
187      */

188     public String JavaDoc getType() {
189
190         return TYPE;
191     }
192
193     /**
194      * Validates the captcha phrase entered by the user.
195      * <p>
196      *
197      * @param jsp the Cms JSP
198      * @param captchaPhrase the captcha phrase to be validate
199      * @return true, if the captcha phrase entered by the user is correct, false otherwise
200      */

201     public boolean validateCaptchaPhrase(CmsJspActionElement jsp, String JavaDoc captchaPhrase) {
202
203         boolean result = false;
204         String JavaDoc sessionId = jsp.getRequest().getSession().getId();
205
206         if (CmsStringUtil.isNotEmpty(captchaPhrase)) {
207
208             ImageCaptchaService captchaService = CmsCaptchaServiceCache.getSharedInstance().getCaptchaService(
209                 m_captchaSettings,
210                 jsp.getCmsObject());
211             if (captchaService != null) {
212                 result = captchaService.validateResponseForID(sessionId, captchaPhrase).booleanValue();
213             }
214         }
215
216         return result;
217     }
218
219     /**
220      * Writes a Captcha JPEG image to the servlet response output stream.
221      * <p>
222      *
223      * @param cms an initialized Cms JSP action element
224      * @throws IOException if something goes wrong
225      */

226     public void writeCaptchaImage(CmsJspActionElement cms) throws IOException JavaDoc {
227
228         ByteArrayOutputStream JavaDoc captchaImageOutput = new ByteArrayOutputStream JavaDoc();
229         ServletOutputStream JavaDoc out = null;
230         BufferedImage JavaDoc captchaImage = null;
231         int maxTries = 10;
232         do {
233             try {
234
235                 maxTries--;
236                 String JavaDoc sessionId = cms.getRequest().getSession().getId();
237                 Locale JavaDoc locale = cms.getRequestContext().getLocale();
238
239                 captchaImage = CmsCaptchaServiceCache.getSharedInstance().getCaptchaService(
240                     m_captchaSettings,
241                     cms.getCmsObject()).getImageChallengeForID(sessionId, locale);
242             } catch (CaptchaException cex) {
243                 if (LOG.isErrorEnabled()) {
244                     LOG.error(cex);
245                     LOG.error(Messages.get().getBundle().key(
246                         Messages.LOG_ERR_CAPTCHA_CONFIG_IMAGE_SIZE_2,
247                         new Object JavaDoc[] {m_captchaSettings.getPresetPath(), new Integer JavaDoc(maxTries)}));
248                 }
249                 m_captchaSettings.setImageHeight(m_captchaSettings.getImageHeight() + 40);
250                 m_captchaSettings.setImageWidth(m_captchaSettings.getImageWidth() + 80);
251             }
252         } while (captchaImage == null && maxTries > 0);
253         try {
254
255             JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder(captchaImageOutput);
256             jpegEncoder.encode(captchaImage);
257
258             CmsFlexController controller = CmsFlexController.getController(cms.getRequest());
259             HttpServletResponse JavaDoc response = controller.getTopResponse();
260             response.setHeader("Cache-Control", "no-store");
261             response.setHeader("Pragma", "no-cache");
262             response.setDateHeader("Expires", 0);
263             response.setContentType("image/jpeg");
264
265             out = cms.getResponse().getOutputStream();
266             out.write(captchaImageOutput.toByteArray());
267             out.flush();
268
269         } catch (Exception JavaDoc e) {
270
271             if (LOG.isErrorEnabled()) {
272                 LOG.error(e);
273             }
274
275             cms.getResponse().sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
276         } finally {
277
278             try {
279                 if (out != null) {
280                     out.close();
281                 }
282             } catch (Throwable JavaDoc t) {
283                 // intentionally left blank
284
}
285         }
286     }
287
288 }
289
Popular Tags