PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/socialauth-core/src/org/brickred/socialauth/util/HttpUtil.java

http://socialauth.googlecode.com/
Java | 475 lines | 314 code | 43 blank | 118 comment | 76 complexity | fedbfd5c02df8d068d433031266d8f4c MD5 | raw file
  1. /*
  2. ===========================================================================
  3. Copyright (c) 2010 BrickRed Technologies Limited
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sub-license, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. ===========================================================================
  20. */
  21. package org.brickred.socialauth.util;
  22. import java.io.DataOutputStream;
  23. import java.io.IOException;
  24. import java.io.InputStream;
  25. import java.io.OutputStream;
  26. import java.io.OutputStreamWriter;
  27. import java.io.UnsupportedEncodingException;
  28. import java.net.HttpURLConnection;
  29. import java.net.InetSocketAddress;
  30. import java.net.Proxy;
  31. import java.net.Proxy.Type;
  32. import java.net.URL;
  33. import java.net.URLEncoder;
  34. import java.security.KeyManagementException;
  35. import java.security.NoSuchAlgorithmException;
  36. import java.security.SecureRandom;
  37. import java.security.cert.CertificateException;
  38. import java.security.cert.X509Certificate;
  39. import java.util.ArrayList;
  40. import java.util.Collections;
  41. import java.util.Iterator;
  42. import java.util.List;
  43. import java.util.Map;
  44. import javax.net.ssl.KeyManager;
  45. import javax.net.ssl.SSLContext;
  46. import javax.net.ssl.TrustManager;
  47. import javax.net.ssl.X509TrustManager;
  48. import org.apache.commons.logging.Log;
  49. import org.apache.commons.logging.LogFactory;
  50. import org.brickred.socialauth.exception.SocialAuthException;
  51. /**
  52. * This class is used to make HTTP requests. We did try NOT writing this class
  53. * and instead use Apache Commons HTTP Client. However it has been reported by
  54. * users that Commons HTTP Client does not work on Google AppEngine. Hence we
  55. * have handcoded this class using HTTPURLConnection and incorporated only as
  56. * much functionality as is needed for OAuth clients.
  57. *
  58. * This class may be completed rewritten in future, or may be removed if a
  59. * version of Commons HTTP Client compatible with AppEngine is released.
  60. *
  61. * @author tarunn@brickred.com
  62. *
  63. */
  64. public class HttpUtil {
  65. private static final Log LOG = LogFactory.getLog(HttpUtil.class);
  66. private static Proxy proxyObj = null;
  67. private static int timeoutValue = 0;
  68. static {
  69. SSLContext ctx;
  70. try {
  71. ctx = SSLContext.getInstance("TLS");
  72. ctx.init(new KeyManager[0],
  73. new TrustManager[] { new DefaultTrustManager() },
  74. new SecureRandom());
  75. SSLContext.setDefault(ctx);
  76. } catch (NoSuchAlgorithmException e) {
  77. e.printStackTrace();
  78. } catch (KeyManagementException e) {
  79. e.printStackTrace();
  80. } catch (NoClassDefFoundError e) {
  81. LOG.warn("SSLContext is not supported by your applicaiton server."
  82. + e.getMessage());
  83. e.printStackTrace();
  84. } catch (Exception e) {
  85. LOG.warn("Error while createing SSLContext");
  86. e.printStackTrace();
  87. }
  88. }
  89. /**
  90. * Makes HTTP request using java.net.HTTPURLConnection
  91. *
  92. * @param urlStr
  93. * the URL String
  94. * @param requestMethod
  95. * Method type
  96. * @param body
  97. * Body to pass in request.
  98. * @param header
  99. * Header parameters
  100. * @return Response Object
  101. * @throws Exception
  102. */
  103. public static Response doHttpRequest(final String urlStr,
  104. final String requestMethod, final String body,
  105. final Map<String, String> header) throws Exception {
  106. HttpURLConnection conn;
  107. try {
  108. URL url = new URL(urlStr);
  109. if (proxyObj != null) {
  110. conn = (HttpURLConnection) url.openConnection(proxyObj);
  111. } else {
  112. conn = (HttpURLConnection) url.openConnection();
  113. }
  114. if (MethodType.POST.toString().equalsIgnoreCase(requestMethod)
  115. || MethodType.PUT.toString()
  116. .equalsIgnoreCase(requestMethod)) {
  117. conn.setDoOutput(true);
  118. }
  119. conn.setDoInput(true);
  120. conn.setInstanceFollowRedirects(true);
  121. if (timeoutValue > 0) {
  122. LOG.debug("Setting connection timeout : " + timeoutValue);
  123. conn.setConnectTimeout(timeoutValue);
  124. }
  125. if (requestMethod != null) {
  126. conn.setRequestMethod(requestMethod);
  127. }
  128. if (header != null) {
  129. for (String key : header.keySet()) {
  130. conn.setRequestProperty(key, header.get(key));
  131. }
  132. }
  133. // If use POST or PUT must use this
  134. OutputStreamWriter wr = null;
  135. if (body != null) {
  136. if (requestMethod != null
  137. && !MethodType.GET.toString().equals(requestMethod)
  138. && !MethodType.DELETE.toString().equals(requestMethod)) {
  139. wr = new OutputStreamWriter(conn.getOutputStream());
  140. wr.write(body);
  141. wr.flush();
  142. }
  143. }
  144. conn.connect();
  145. } catch (Exception e) {
  146. throw new SocialAuthException(e);
  147. }
  148. return new Response(conn);
  149. }
  150. /**
  151. *
  152. * @param urlStr
  153. * the URL String
  154. * @param requestMethod
  155. * Method type
  156. * @param params
  157. * Parameters to pass in request
  158. * @param header
  159. * Header parameters
  160. * @param inputStream
  161. * Input stream of image
  162. * @param fileName
  163. * Image file name
  164. * @param fileParamName
  165. * Image Filename parameter. It requires in some provider.
  166. * @return Response object
  167. * @throws Exception
  168. */
  169. public static Response doHttpRequest(final String urlStr,
  170. final String requestMethod, final Map<String, String> params,
  171. final Map<String, String> header, final InputStream inputStream,
  172. final String fileName, final String fileParamName) throws Exception {
  173. HttpURLConnection conn;
  174. try {
  175. URL url = new URL(urlStr);
  176. if (proxyObj != null) {
  177. conn = (HttpURLConnection) url.openConnection(proxyObj);
  178. } else {
  179. conn = (HttpURLConnection) url.openConnection();
  180. }
  181. if (requestMethod.equalsIgnoreCase(MethodType.POST.toString())
  182. || requestMethod
  183. .equalsIgnoreCase(MethodType.PUT.toString())) {
  184. conn.setDoOutput(true);
  185. }
  186. conn.setDoInput(true);
  187. conn.setInstanceFollowRedirects(true);
  188. if (timeoutValue > 0) {
  189. LOG.debug("Setting connection timeout : " + timeoutValue);
  190. conn.setConnectTimeout(timeoutValue);
  191. }
  192. if (requestMethod != null) {
  193. conn.setRequestMethod(requestMethod);
  194. }
  195. if (header != null) {
  196. for (String key : header.keySet()) {
  197. conn.setRequestProperty(key, header.get(key));
  198. }
  199. }
  200. // If use POST or PUT must use this
  201. OutputStream os = null;
  202. if (inputStream != null) {
  203. if (requestMethod != null
  204. && !MethodType.GET.toString().equals(requestMethod)
  205. && !MethodType.DELETE.toString().equals(requestMethod)) {
  206. LOG.debug(requestMethod + " request");
  207. String boundary = "----Socialauth-posting"
  208. + System.currentTimeMillis();
  209. conn.setRequestProperty("Content-Type",
  210. "multipart/form-data; boundary=" + boundary);
  211. boundary = "--" + boundary;
  212. os = conn.getOutputStream();
  213. DataOutputStream out = new DataOutputStream(os);
  214. write(out, boundary + "\r\n");
  215. if (fileParamName != null) {
  216. write(out, "Content-Disposition: form-data; name=\""
  217. + fileParamName + "\"; filename=\"" + fileName
  218. + "\"\r\n");
  219. } else {
  220. write(out,
  221. "Content-Disposition: form-data; filename=\""
  222. + fileName + "\"\r\n");
  223. }
  224. write(out, "Content-Type: " + "multipart/form-data"
  225. + "\r\n\r\n");
  226. int b;
  227. while ((b = inputStream.read()) != -1) {
  228. out.write(b);
  229. }
  230. // out.write(imageFile);
  231. write(out, "\r\n");
  232. Iterator<Map.Entry<String, String>> entries = params
  233. .entrySet().iterator();
  234. while (entries.hasNext()) {
  235. Map.Entry<String, String> entry = entries.next();
  236. write(out, boundary + "\r\n");
  237. write(out, "Content-Disposition: form-data; name=\""
  238. + entry.getKey() + "\"\r\n");
  239. write(out,
  240. "Content-Type: text/plain; charset=UTF-8\r\n\r\n");
  241. write(out, entry.getValue());
  242. write(out, "\r\n");
  243. }
  244. write(out, boundary + "--\r\n");
  245. write(out, "\r\n");
  246. }
  247. }
  248. conn.connect();
  249. } catch (Exception e) {
  250. throw new SocialAuthException(e);
  251. }
  252. return new Response(conn);
  253. }
  254. /**
  255. * Generates a query string from given Map while sorting the parameters in
  256. * the canonical order as required by oAuth before signing
  257. *
  258. * @param params
  259. * Parameters Map to generate query string
  260. * @return String
  261. * @throws Exception
  262. */
  263. public static String buildParams(final Map<String, String> params)
  264. throws Exception {
  265. List<String> argList = new ArrayList<String>();
  266. for (String key : params.keySet()) {
  267. String val = params.get(key);
  268. if (val != null && val.length() > 0) {
  269. String arg = key + "=" + encodeURIComponent(val);
  270. argList.add(arg);
  271. }
  272. }
  273. Collections.sort(argList);
  274. StringBuilder s = new StringBuilder();
  275. for (int i = 0; i < argList.size(); i++) {
  276. s.append(argList.get(i));
  277. if (i != argList.size() - 1) {
  278. s.append("&");
  279. }
  280. }
  281. return s.toString();
  282. }
  283. private static final String ALLOWED_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.!~*'()";
  284. public static String encodeURIComponent(final String value)
  285. throws Exception {
  286. if (value == null) {
  287. return "";
  288. }
  289. try {
  290. return URLEncoder.encode(value, "utf-8")
  291. // OAuth encodes some characters differently:
  292. .replace("+", "%20").replace("*", "%2A")
  293. .replace("%7E", "~");
  294. // This could be done faster with more hand-crafted code.
  295. } catch (UnsupportedEncodingException wow) {
  296. throw new SocialAuthException(wow.getMessage(), wow);
  297. }
  298. }
  299. /*
  300. * public static String encodeURIComponent(final String input) { if (input
  301. * == null || input.trim().length() == 0) { return input; }
  302. *
  303. * int l = input.length(); StringBuilder o = new StringBuilder(l * 3); try {
  304. * for (int i = 0; i < l; i++) { String e = input.substring(i, i + 1); if
  305. * (ALLOWED_CHARS.indexOf(e) == -1) { byte[] b = e.getBytes("utf-8");
  306. * o.append(getHex(b)); continue; } o.append(e); } return o.toString(); }
  307. * catch (UnsupportedEncodingException e) { e.printStackTrace(); } return
  308. * input; }
  309. */
  310. private static String getHex(final byte buf[]) {
  311. StringBuilder o = new StringBuilder(buf.length * 3);
  312. for (int i = 0; i < buf.length; i++) {
  313. int n = buf[i] & 0xff;
  314. o.append("%");
  315. if (n < 0x10) {
  316. o.append("0");
  317. }
  318. o.append(Long.toString(n, 16).toUpperCase());
  319. }
  320. return o.toString();
  321. }
  322. /**
  323. * It decodes the given string
  324. *
  325. * @param encodedURI
  326. * @return decoded string
  327. */
  328. public static String decodeURIComponent(final String encodedURI) {
  329. char actualChar;
  330. StringBuffer buffer = new StringBuffer();
  331. int bytePattern, sumb = 0;
  332. for (int i = 0, more = -1; i < encodedURI.length(); i++) {
  333. actualChar = encodedURI.charAt(i);
  334. switch (actualChar) {
  335. case '%': {
  336. actualChar = encodedURI.charAt(++i);
  337. int hb = (Character.isDigit(actualChar) ? actualChar - '0'
  338. : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
  339. actualChar = encodedURI.charAt(++i);
  340. int lb = (Character.isDigit(actualChar) ? actualChar - '0'
  341. : 10 + Character.toLowerCase(actualChar) - 'a') & 0xF;
  342. bytePattern = (hb << 4) | lb;
  343. break;
  344. }
  345. case '+': {
  346. bytePattern = ' ';
  347. break;
  348. }
  349. default: {
  350. bytePattern = actualChar;
  351. }
  352. }
  353. if ((bytePattern & 0xc0) == 0x80) { // 10xxxxxx
  354. sumb = (sumb << 6) | (bytePattern & 0x3f);
  355. if (--more == 0) {
  356. buffer.append((char) sumb);
  357. }
  358. } else if ((bytePattern & 0x80) == 0x00) { // 0xxxxxxx
  359. buffer.append((char) bytePattern);
  360. } else if ((bytePattern & 0xe0) == 0xc0) { // 110xxxxx
  361. sumb = bytePattern & 0x1f;
  362. more = 1;
  363. } else if ((bytePattern & 0xf0) == 0xe0) { // 1110xxxx
  364. sumb = bytePattern & 0x0f;
  365. more = 2;
  366. } else if ((bytePattern & 0xf8) == 0xf0) { // 11110xxx
  367. sumb = bytePattern & 0x07;
  368. more = 3;
  369. } else if ((bytePattern & 0xfc) == 0xf8) { // 111110xx
  370. sumb = bytePattern & 0x03;
  371. more = 4;
  372. } else { // 1111110x
  373. sumb = bytePattern & 0x01;
  374. more = 5;
  375. }
  376. }
  377. return buffer.toString();
  378. }
  379. private static class DefaultTrustManager implements X509TrustManager {
  380. @Override
  381. public void checkClientTrusted(final X509Certificate[] arg0,
  382. final String arg1) throws CertificateException {
  383. }
  384. @Override
  385. public void checkServerTrusted(final X509Certificate[] arg0,
  386. final String arg1) throws CertificateException {
  387. }
  388. @Override
  389. public X509Certificate[] getAcceptedIssuers() {
  390. return null;
  391. }
  392. }
  393. /**
  394. *
  395. * Sets the proxy host and port. This will be implicitly called if
  396. * "proxy.host" and "proxy.port" properties are given in properties file
  397. *
  398. * @param host
  399. * proxy host
  400. * @param port
  401. * proxy port
  402. */
  403. public static void setProxyConfig(final String host, final int port) {
  404. if (host != null) {
  405. int proxyPort = port;
  406. if (proxyPort < 0) {
  407. proxyPort = 0;
  408. }
  409. LOG.debug("Setting proxy - Host : " + host + " port : " + port);
  410. proxyObj = new Proxy(Type.HTTP, new InetSocketAddress(host, port));
  411. }
  412. }
  413. /**
  414. * Sets the connection time out. This will be implicitly called if
  415. * "http.connectionTimeOut" property is given in properties file
  416. *
  417. * @param timeout
  418. * httpconnection timeout value
  419. */
  420. public static void setConnectionTimeout(final int timeout) {
  421. timeoutValue = timeout;
  422. }
  423. public static void write(final DataOutputStream out, final String outStr)
  424. throws IOException {
  425. out.writeBytes(outStr);
  426. LOG.debug(outStr);
  427. }
  428. }