/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. package com.google.ie.common.util;
  16. import org.apache.log4j.Logger;
  17. import org.springframework.beans.factory.annotation.Value;
  18. import org.springframework.stereotype.Component;
  19. import java.io.ByteArrayOutputStream;
  20. import java.io.IOException;
  21. import java.io.InputStream;
  22. import java.io.OutputStream;
  23. import java.net.URL;
  24. import java.net.URLConnection;
  25. import java.net.URLEncoder;
  26. /**
  27. * Utility class to handle recaptcha verification
  28. *
  29. * @author aksrivastava
  30. *
  31. */
  32. @Component
  33. public class ReCaptchaUtility {
  34. /** Logger for logging information */
  35. private static final Logger LOG = Logger.getLogger(ReCaptchaUtility.class.getName());
  36. @Value("${reCaptchaVerifyUrl}")
  37. private String reCaptchaVerifyUrl;
  38. @Value("${rcGlobalPrivateKey}")
  39. private String rcGlobalPrivateKey;
  40. private static final String UTF_8_ENCODING = "UTF-8";
  41. private static final String TRUE = "true";
  42. /**
  43. * This method verifies the captcha input by the user.
  44. *
  45. * @param remoteAddr the url of the recaptcha server
  46. * @param recaptchaChallengeField the captcha challenge value
  47. * @param recaptchaResponseField the captcha response value input by the
  48. * user
  49. * @return boolean the verification result
  50. * @throws IOException
  51. */
  52. public boolean verifyCaptcha(String remoteAddr, String recaptchaChallengeField,
  53. String recaptchaResponseField) throws IOException {
  54. /* create post params */
  55. if (null == remoteAddr || null == recaptchaChallengeField || null == recaptchaResponseField) {
  56. return false;
  57. }
  58. String postParameters = "privatekey="
  59. + URLEncoder.encode(rcGlobalPrivateKey, UTF_8_ENCODING)
  60. + "&remoteip="
  61. + URLEncoder.encode(remoteAddr, UTF_8_ENCODING) +
  62. "&challenge=" + URLEncoder.encode(recaptchaChallengeField, UTF_8_ENCODING)
  63. + "&response="
  64. + URLEncoder.encode(recaptchaResponseField, UTF_8_ENCODING);
  65. /* create url */
  66. String message = this.sendPostRequest(reCaptchaVerifyUrl, postParameters);
  67. if (null == message) {
  68. return false;
  69. }
  70. /* validate with response */
  71. String[] arrayOfMsg = message.split("\r?\n");
  72. if (arrayOfMsg.length < 1) {
  73. LOG.debug("No answer returned from recaptcha: " + message);
  74. return false;
  75. }
  76. boolean valid = TRUE.equals(arrayOfMsg[0]);
  77. if (!valid) {
  78. return false;
  79. }
  80. return true;
  81. }
  82. /**
  83. *
  84. * This method makes a post request to captcha server for verification of
  85. * captcha.
  86. *
  87. * @param postUrl the url of the server
  88. * @param postParameters the parameters making the post request
  89. * @return String the message from the server in response to the request
  90. * posted
  91. * @throws IOException
  92. */
  93. private String sendPostRequest(String postUrl, String postParameters) throws IOException {
  94. OutputStream out = null;
  95. String message = null;
  96. InputStream in = null;
  97. try {
  98. URL url = new URL(postUrl);
  99. /* open connection with settings */
  100. URLConnection urlConnection = url.openConnection();
  101. urlConnection.setDoOutput(true);
  102. urlConnection.setDoInput(true);
  103. /* open output stream */
  104. out = urlConnection.getOutputStream();
  105. out.write(postParameters.getBytes());
  106. out.flush();
  107. /* open input stream */
  108. in = urlConnection.getInputStream();
  109. /* get output */
  110. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  111. byte[] buf = new byte[1024];
  112. while (true) {
  113. int rc = in.read(buf);
  114. if (rc <= 0)
  115. break;
  116. bout.write(buf, 0, rc);
  117. }
  118. message = bout.toString();
  119. /* close streams */
  120. out.close();
  121. in.close();
  122. return message;
  123. } catch (IOException e) {
  124. LOG.error("Cannot load URL: " + e.getMessage());
  125. out.close();
  126. in.close();
  127. return null;
  128. }
  129. }
  130. }