PageRenderTime 22ms CodeModel.GetById 15ms app.highlight 5ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/java/com/google/ie/common/util/ReCaptchaUtility.java

http://thoughtsite.googlecode.com/
Java | 144 lines | 80 code | 14 blank | 50 comment | 12 complexity | 3706ab9cdcc94f52212844a33dd9b0d3 MD5 | raw file
  1/* Copyright 2010 Google Inc.
  2 * 
  3 * Licensed under the Apache License, Version 2.0 (the "License");
  4 * you may not use this file except in compliance with the License.
  5 * You may obtain a copy of the License at
  6 * 
  7 *      http://www.apache.org/licenses/LICENSE-2.0
  8 * 
  9 * Unless required by applicable law or agreed to in writing, software
 10 * distributed under the License is distributed on an "AS IS" BASIS.
 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 12 * See the License for the specific language governing permissions and
 13 * limitations under the License
 14 */
 15
 16package com.google.ie.common.util;
 17
 18import org.apache.log4j.Logger;
 19import org.springframework.beans.factory.annotation.Value;
 20import org.springframework.stereotype.Component;
 21
 22import java.io.ByteArrayOutputStream;
 23import java.io.IOException;
 24import java.io.InputStream;
 25import java.io.OutputStream;
 26import java.net.URL;
 27import java.net.URLConnection;
 28import java.net.URLEncoder;
 29
 30/**
 31 * Utility class to handle recaptcha verification
 32 * 
 33 * @author aksrivastava
 34 * 
 35 */
 36@Component
 37public class ReCaptchaUtility {
 38    /** Logger for logging information */
 39    private static final Logger LOG = Logger.getLogger(ReCaptchaUtility.class.getName());
 40    @Value("${reCaptchaVerifyUrl}")
 41    private String reCaptchaVerifyUrl;
 42
 43    @Value("${rcGlobalPrivateKey}")
 44    private String rcGlobalPrivateKey;
 45    private static final String UTF_8_ENCODING = "UTF-8";
 46    private static final String TRUE = "true";
 47
 48    /**
 49     * This method verifies the captcha input by the user.
 50     * 
 51     * @param remoteAddr the url of the recaptcha server
 52     * @param recaptchaChallengeField the captcha challenge value
 53     * @param recaptchaResponseField the captcha response value input by the
 54     *        user
 55     * @return boolean the verification result
 56     * @throws IOException
 57     */
 58    public boolean verifyCaptcha(String remoteAddr, String recaptchaChallengeField,
 59                    String recaptchaResponseField) throws IOException {
 60
 61        /* create post params */
 62        if (null == remoteAddr || null == recaptchaChallengeField || null == recaptchaResponseField) {
 63            return false;
 64        }
 65        String postParameters = "privatekey="
 66                        + URLEncoder.encode(rcGlobalPrivateKey, UTF_8_ENCODING)
 67                        + "&remoteip="
 68                        + URLEncoder.encode(remoteAddr, UTF_8_ENCODING) +
 69                        "&challenge=" + URLEncoder.encode(recaptchaChallengeField, UTF_8_ENCODING)
 70                        + "&response="
 71                        + URLEncoder.encode(recaptchaResponseField, UTF_8_ENCODING);
 72        /* create url */
 73        String message = this.sendPostRequest(reCaptchaVerifyUrl, postParameters);
 74        if (null == message) {
 75            return false;
 76        }
 77        /* validate with response */
 78        String[] arrayOfMsg = message.split("\r?\n");
 79        if (arrayOfMsg.length < 1) {
 80
 81            LOG.debug("No answer returned from recaptcha: " + message);
 82            return false;
 83        }
 84        boolean valid = TRUE.equals(arrayOfMsg[0]);
 85        if (!valid) {
 86            return false;
 87        }
 88        return true;
 89    }
 90
 91    /**
 92     * 
 93     * This method makes a post request to captcha server for verification of
 94     * captcha.
 95     * 
 96     * @param postUrl the url of the server
 97     * @param postParameters the parameters making the post request
 98     * @return String the message from the server in response to the request
 99     *         posted
100     * @throws IOException
101     */
102    private String sendPostRequest(String postUrl, String postParameters) throws IOException {
103        OutputStream out = null;
104        String message = null;
105        InputStream in = null;
106        try {
107            URL url = new URL(postUrl);
108
109            /* open connection with settings */
110            URLConnection urlConnection = url.openConnection();
111            urlConnection.setDoOutput(true);
112            urlConnection.setDoInput(true);
113
114            /* open output stream */
115            out = urlConnection.getOutputStream();
116            out.write(postParameters.getBytes());
117            out.flush();
118
119            /* open input stream */
120            in = urlConnection.getInputStream();
121
122            /* get output */
123            ByteArrayOutputStream bout = new ByteArrayOutputStream();
124            byte[] buf = new byte[1024];
125            while (true) {
126                int rc = in.read(buf);
127                if (rc <= 0)
128                    break;
129                bout.write(buf, 0, rc);
130            }
131            message = bout.toString();
132            /* close streams */
133            out.close();
134            in.close();
135            return message;
136        } catch (IOException e) {
137            LOG.error("Cannot load URL: " + e.getMessage());
138            out.close();
139            in.close();
140            return null;
141        }
142    }
143}
144