1 package org.roller.presentation.velocity; 2 3 import javax.servlet.http.HttpServletRequest ; 4 import javax.servlet.http.HttpServletResponse ; 5 import javax.servlet.http.HttpSession ; 6 import org.apache.velocity.context.Context; 7 import org.roller.pojos.CommentData; 8 import org.roller.presentation.RollerSession; 9 import org.apache.commons.logging.Log; 10 import org.apache.commons.logging.LogFactory; 11 import java.util.ResourceBundle ; 12 13 17 public class MathCommentAuthenticator implements CommentAuthenticator 18 { 19 private transient ResourceBundle bundle = 20 ResourceBundle.getBundle("ApplicationResources"); 21 22 private static Log mLogger = 23 LogFactory.getFactory().getInstance(MathCommentAuthenticator.class); 24 25 public String getHtml( 26 Context context, 27 HttpServletRequest request, 28 HttpServletResponse response) 29 { 30 String answer = ""; 31 HttpSession session = request.getSession(); 32 if (session.getAttribute("mathAnswer") == null) 33 { 34 int value1 = (int)(Math.random()*10.0); 36 int value2 = (int)(Math.random()*100.0); 37 int sum = value1 + value2; 38 session.setAttribute("mathValue1", new Integer (value1)); 39 session.setAttribute("mathValue2", new Integer (value2)); 40 session.setAttribute("mathAnswer", new Integer (sum)); 41 } 42 else 43 { 44 answer = request.getParameter("answer"); 46 answer = (answer == null) ? "" : answer; 47 } 48 49 Integer value1o = 51 (Integer )request.getSession().getAttribute("mathValue1"); 52 Integer value2o = 53 (Integer )request.getSession().getAttribute("mathValue2"); 54 55 StringBuffer sb = new StringBuffer (); 56 57 sb.append("<p>"); 58 sb.append(bundle.getString("comments.mathAuthenticatorQuestion")); 59 sb.append("</p><p>"); 60 sb.append(value1o); 61 sb.append(" + "); 62 sb.append(value2o); 63 sb.append(" = "); 64 sb.append("<input name=\"answer\" value=\""); 65 sb.append(answer); 66 sb.append("\" /></p>"); 67 68 return sb.toString(); 69 } 70 71 public boolean authenticate( 72 CommentData comment, 73 HttpServletRequest request) 74 { 75 boolean ret = false; 76 String answerString = request.getParameter("answer"); 77 if (answerString != null || answerString.trim().length()==0) 78 { 79 try 80 { 81 int answer = Integer.parseInt(answerString); 82 Integer sum = 83 (Integer )request.getSession().getAttribute("mathAnswer"); 84 if (answer == sum.intValue()) 85 { 86 ret = true; 87 request.getSession().removeAttribute("mathAnswer"); 88 request.getSession().removeAttribute("mathValue1"); 89 request.getSession().removeAttribute("mathValue2"); 90 } 91 } 92 catch (NumberFormatException ignored) {} 93 catch (Exception e) 94 { 95 mLogger.error(e); 96 } 97 } 98 return ret; 99 } 100 } 101 102 | Popular Tags |