KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > blojsom > plugin > comment > MathCommentAuthenticationPlugin


1 /**
2  * Copyright (c) 2003-2006, David A. Czarnecki
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions are met:
7  *
8  * Redistributions of source code must retain the above copyright notice, this list of conditions and the
9  * following disclaimer.
10  * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
11  * following disclaimer in the documentation and/or other materials provided with the distribution.
12  * Neither the name of "David A. Czarnecki" and "blojsom" nor the names of its contributors may be used to
13  * endorse or promote products derived from this software without specific prior written permission.
14  * Products derived from this software may not be called "blojsom", nor may "blojsom" appear in their name,
15  * without prior written permission of David A. Czarnecki.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
18  * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
19  * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
21  * EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
27  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
29  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */

31 package org.blojsom.plugin.comment;
32
33 import org.blojsom.blog.Blog;
34 import org.blojsom.blog.Entry;
35 import org.blojsom.plugin.PluginException;
36 import org.blojsom.plugin.comment.event.CommentResponseSubmissionEvent;
37 import org.blojsom.util.BlojsomUtils;
38 import org.blojsom.event.Listener;
39 import org.blojsom.event.Event;
40 import org.blojsom.event.EventBroadcaster;
41 import org.apache.commons.logging.Log;
42 import org.apache.commons.logging.LogFactory;
43
44 import javax.servlet.http.HttpServletRequest JavaDoc;
45 import javax.servlet.http.HttpServletResponse JavaDoc;
46 import javax.servlet.http.HttpSession JavaDoc;
47 import java.util.HashMap JavaDoc;
48 import java.util.Map JavaDoc;
49 import java.util.Iterator JavaDoc;
50
51 /**
52  * Math comment authenticator plugin
53  *
54  * @author David Czarnecki
55  * @version $Id: MathCommentAuthenticationPlugin.java,v 1.3 2006/08/22 18:56:06 czarneckid Exp $
56  * @since blojsom 3.0
57  */

58 public class MathCommentAuthenticationPlugin extends CommentModerationPlugin implements Listener {
59
60     private Log _logger = LogFactory.getLog(MathCommentAuthenticationPlugin.class);
61
62     private static final String JavaDoc MATH_COMMENT_MODERATION_ENABLED = "math-comment-moderation-enabled";
63     private static final String JavaDoc MATH_COMMENT_AUTHENTICATION_OPERATIONS_IP = "math-comment-authentication-operations";
64     private static final String JavaDoc MATH_COMMENT_AUTHENTICATION_BOUND_IP = "math-comment-authentication-bound";
65
66     private static final int AVAILABLE_OPERATIONS = 3;
67     private static final int BOUND_DEFAULT = 10;
68
69     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER = "BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER";
70     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE1 = "BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE1";
71     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE2 = "BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE2";
72     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_OPERATION = "BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_OPERATION";
73     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER_CHECK_PARAM = "mathAnswerCheck";
74     public static final String JavaDoc BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_STATUS_MESSAGE = "BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_STATUS_MESSAGE";
75
76     private EventBroadcaster _eventBroadcaster;
77
78     /**
79      * Math comment authenticator plugin
80      */

81     public MathCommentAuthenticationPlugin() {
82     }
83
84     /**
85      * Set the {@link EventBroadcaster} to use
86      *
87      * @param eventBroadcaster {@link EventBroadcaster}
88      */

89     public void setEventBroadcaster(EventBroadcaster eventBroadcaster) {
90         _eventBroadcaster = eventBroadcaster;
91     }
92
93     /**
94      * Initialize this plugin. This method only called when the plugin is instantiated.
95      *
96      * @throws PluginException If there is an error initializing the plugin
97      */

98     public void init() throws PluginException {
99         super.init();
100
101         _eventBroadcaster.addListener(this);
102     }
103
104     /**
105      * Process the blog entries
106      *
107      * @param httpServletRequest Request
108      * @param httpServletResponse Response
109      * @param blog {@link Blog} instance
110      * @param context Context
111      * @param entries Blog entries retrieved for the particular request
112      * @return Modified set of blog entries
113      * @throws PluginException If there is an error processing the blog entries
114      */

115     public Entry[] process(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
116         HttpSession JavaDoc httpSession = httpServletRequest.getSession();
117
118         int bound = BOUND_DEFAULT;
119         int availableOperations = AVAILABLE_OPERATIONS;
120         String JavaDoc boundProperty = blog.getProperty(MATH_COMMENT_AUTHENTICATION_BOUND_IP);
121         String JavaDoc availableOperationsProperty = blog.getProperty(MATH_COMMENT_AUTHENTICATION_OPERATIONS_IP);
122
123         if (!BlojsomUtils.checkNullOrBlank(boundProperty)) {
124             try {
125                 bound = Integer.parseInt(boundProperty);
126             } catch (NumberFormatException JavaDoc e) {
127             }
128         }
129
130         if (!BlojsomUtils.checkNullOrBlank(availableOperationsProperty)) {
131             try {
132                 availableOperations = Integer.parseInt(availableOperationsProperty);
133                 if (availableOperations < 1 || availableOperations > AVAILABLE_OPERATIONS) {
134                     availableOperations = AVAILABLE_OPERATIONS;
135                 } else {
136                     availableOperations -= 1;
137                 }
138             } catch (NumberFormatException JavaDoc e) {
139             }
140         }
141
142         int operation = (int) (Math.random() * (availableOperations + 1));
143         int value1 = (int) (Math.random() * bound);
144         int value2 = (int) (Math.random() * bound);
145         int answer;
146
147         answer = getAnswerForOperation(value1, value2, operation);
148
149         httpSession.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE1, new Integer JavaDoc(value1));
150         httpSession.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_VALUE2, new Integer JavaDoc(value2));
151         httpSession.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER, new Integer JavaDoc(answer));
152         httpSession.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_OPERATION, getOperatorForOperation(operation));
153
154         return entries;
155     }
156
157     /**
158      * Simple check to see if comment moderation is enabled
159      * <p/>
160      * @param httpServletRequest Request
161      * @param httpServletResponse Response
162      * @param blog {@link Blog} instance
163      * @param context Context
164      * @param entries Blog entries retrieved for the particular request
165      * @throws org.blojsom.plugin.PluginException
166      * If there is an error in moderating a comment
167      */

168     protected void moderateComment(HttpServletRequest JavaDoc httpServletRequest, HttpServletResponse JavaDoc httpServletResponse, Blog blog, Map JavaDoc context, Entry[] entries) throws PluginException {
169         if ("true".equalsIgnoreCase(blog.getProperty(COMMENT_MODERATION_ENABLED)) &&
170                 "true".equalsIgnoreCase(blog.getProperty(MATH_COMMENT_MODERATION_ENABLED))) {
171             HttpSession JavaDoc httpSession = httpServletRequest.getSession();
172
173             if ("y".equalsIgnoreCase(httpServletRequest.getParameter(CommentPlugin.COMMENT_PARAM)) && blog.getBlogCommentsEnabled().booleanValue()) {
174                 String JavaDoc mathAnswerCheck = BlojsomUtils.getRequestValue(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER_CHECK_PARAM, httpServletRequest);
175
176                 boolean passedCheck = false;
177                 if (httpSession.getAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER) != null) {
178                     Integer JavaDoc mathAnswer = (Integer JavaDoc) httpSession.getAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_ANSWER);
179
180                     try {
181                         int mathAnswerCheckValue = Integer.parseInt(mathAnswerCheck);
182                         int originalMathAnswerValue = mathAnswer.intValue();
183
184                         if (mathAnswerCheckValue == originalMathAnswerValue) {
185                             passedCheck = true;
186                         }
187                     } catch (NumberFormatException JavaDoc e) {
188                     }
189                 }
190
191                 Map JavaDoc commentMetaData;
192                 if (context.containsKey(CommentPlugin.BLOJSOM_PLUGIN_COMMENT_METADATA)) {
193                     commentMetaData = (Map JavaDoc) context.get(CommentPlugin.BLOJSOM_PLUGIN_COMMENT_METADATA);
194                 } else {
195                     commentMetaData = new HashMap JavaDoc();
196                 }
197
198                 if (!passedCheck) {
199                     commentMetaData.put(CommentPlugin.BLOJSOM_PLUGIN_COMMENT_METADATA_DESTROY, Boolean.TRUE);
200                     httpServletRequest.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_STATUS_MESSAGE, "Failed math comment authentication check.");
201                 } else {
202                     commentMetaData.put(CommentModerationPlugin.BLOJSOM_COMMENT_MODERATION_PLUGIN_APPROVED, Boolean.TRUE.toString());
203                     httpServletRequest.setAttribute(BLOJSOM_MATH_AUTHENTICATOR_PLUGIN_STATUS_MESSAGE, "Passed math comment authentication check.");
204                 }
205
206                 context.put(CommentPlugin.BLOJSOM_PLUGIN_COMMENT_METADATA, commentMetaData);
207             }
208         }
209     }
210
211     /**
212      * Return the result from the specified operation where 0 = addition, 1 = subtraction, 2 = multiplication
213      *
214      * @param value1 Value 1
215      * @param value2 Value 2
216      * @param operation Operation where 0 = addition, 1 = subtraction, 2 = multiplication
217      * @return Value of operation
218      */

219     protected int getAnswerForOperation(int value1, int value2, int operation) {
220         int answer;
221
222         switch (operation) {
223             case 0:
224                 {
225                     answer = value1 + value2;
226                     break;
227                 }
228             case 1:
229                 {
230                     answer = value1 - value2;
231                     break;
232                 }
233             case 2:
234                 {
235                     answer = value1 * value2;
236                     break;
237                 }
238             default:
239                 {
240                     answer = value1 + value2;
241                 }
242         }
243
244         return answer;
245     }
246
247     /**
248      * Return the appropriate operator for the operation
249      *
250      * @param operation Operation where 0 = addition, 1 = subtraction, 2 = multiplication
251      * @return + for addition, - for subtraction, and * for multiplication
252      */

253     protected String JavaDoc getOperatorForOperation(int operation) {
254         switch (operation) {
255             case 0:
256                 {
257                     return "+";
258                 }
259             case 1:
260                 {
261                     return "-";
262                 }
263             case 2:
264                 {
265                     return "*";
266                 }
267             default:
268                 {
269                     return "+";
270                 }
271         }
272     }
273
274     /**
275      * Handle an event broadcast from another component
276      *
277      * @param event {@link Event} to be handled
278      */

279     public void handleEvent(Event event) {
280     }
281
282     /**
283      * Process an event from another component
284      *
285      * @param event {@link Event} to be handled
286      */

287     public void processEvent(Event event) {
288         if (event instanceof CommentResponseSubmissionEvent) {
289             CommentResponseSubmissionEvent commentResponseSubmissionEvent = (CommentResponseSubmissionEvent) event;
290
291             try {
292                 HashMap JavaDoc context = new HashMap JavaDoc();
293                 moderateComment(commentResponseSubmissionEvent.getHttpServletRequest(),
294                         commentResponseSubmissionEvent.getHttpServletResponse(), commentResponseSubmissionEvent.getBlog(),
295                         context,
296                         new Entry[] {commentResponseSubmissionEvent.getEntry()});
297
298                 // Grab the comment metadata and populate the metadata for the current submission
299
Map JavaDoc operationMetadata = (Map JavaDoc) context.get(CommentPlugin.BLOJSOM_PLUGIN_COMMENT_METADATA);
300                 Map JavaDoc commentMetadata = commentResponseSubmissionEvent.getMetaData();
301
302                 Iterator JavaDoc keys = operationMetadata.keySet().iterator();
303                 while (keys.hasNext()) {
304                     Object JavaDoc key = keys.next();
305                     commentMetadata.put(key.toString(), operationMetadata.get(key).toString());
306                 }
307             } catch (PluginException e) {
308                 if (_logger.isErrorEnabled()) {
309                     _logger.error(e);
310                 }
311             }
312         }
313     }
314 }
Popular Tags