1 18 19 package org.apache.roller.ui.rendering.util; 20 21 import java.util.ResourceBundle ; 22 import javax.servlet.http.HttpServletRequest ; 23 import javax.servlet.http.HttpSession ; 24 import org.apache.commons.logging.Log; 25 import org.apache.commons.logging.LogFactory; 26 27 28 31 public class MathCommentAuthenticator implements CommentAuthenticator { 32 33 private transient ResourceBundle bundle = 34 ResourceBundle.getBundle("ApplicationResources"); 35 36 private static Log mLogger = LogFactory.getLog(MathCommentAuthenticator.class); 37 38 39 public String getHtml(HttpServletRequest request) { 40 41 String answer = ""; 42 43 HttpSession session = request.getSession(true); 44 if (session.getAttribute("mathAnswer") == null) { 45 int value1 = (int)(Math.random()*10.0); 47 int value2 = (int)(Math.random()*100.0); 48 int sum = value1 + value2; 49 session.setAttribute("mathValue1", new Integer (value1)); 50 session.setAttribute("mathValue2", new Integer (value2)); 51 session.setAttribute("mathAnswer", new Integer (sum)); 52 } else { 53 answer = request.getParameter("answer"); 55 answer = (answer == null) ? "" : answer; 56 } 57 58 Integer value1o = (Integer )request.getSession().getAttribute("mathValue1"); 60 Integer value2o = (Integer )request.getSession().getAttribute("mathValue2"); 61 62 StringBuffer sb = new StringBuffer (); 63 64 sb.append("<p>"); 65 sb.append(bundle.getString("comments.mathAuthenticatorQuestion")); 66 sb.append("</p><p>"); 67 sb.append(value1o); 68 sb.append(" + "); 69 sb.append(value2o); 70 sb.append(" = "); 71 sb.append("<input name=\"answer\" value=\""); 72 sb.append(answer); 73 sb.append("\" /></p>"); 74 75 return sb.toString(); 76 } 77 78 79 public boolean authenticate(HttpServletRequest request) { 80 81 boolean authentic = false; 82 83 HttpSession session = request.getSession(false); 84 String answerString = request.getParameter("answer"); 85 86 if (answerString != null && session != null) { 87 try { 88 int answer = Integer.parseInt(answerString); 89 Integer sum = (Integer ) session.getAttribute("mathAnswer"); 90 91 if (sum != null && answer == sum.intValue()) { 92 authentic = true; 93 session.removeAttribute("mathAnswer"); 94 session.removeAttribute("mathValue1"); 95 session.removeAttribute("mathValue2"); 96 } 97 } catch (NumberFormatException ignored) { 98 } catch (Exception e) { 100 mLogger.error(e); 102 } 103 } 104 105 return authentic; 106 } 107 108 } 109 110 | Popular Tags |