PageRenderTime 27ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Oauth/java/jmeter/core/commons/src/main/java/net/oauth/OAuth.java

https://github.com/levelcap/isohealth
Java | 355 lines | 259 code | 39 blank | 57 comment | 49 complexity | 755401b710c8302dcecebbf4456e9ccd MD5 | raw file
  1. /*
  2. * Copyright 2007 Netflix, Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. package net.oauth;
  17. import java.io.ByteArrayOutputStream;
  18. import java.io.IOException;
  19. import java.io.OutputStream;
  20. import java.io.UnsupportedEncodingException;
  21. import java.net.URLDecoder;
  22. import java.net.URLEncoder;
  23. import java.util.ArrayList;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.List;
  27. import java.util.Map;
  28. /**
  29. * Miscellaneous constants, methods and types.
  30. *
  31. * @author John Kristian
  32. */
  33. public class OAuth {
  34. public static final String VERSION_1_0 = "1.0";
  35. /** The encoding used to represent characters as bytes. */
  36. public static final String ENCODING = "UTF-8";
  37. /** The MIME type for a sequence of OAuth parameters. */
  38. public static final String FORM_ENCODED = "application/x-www-form-urlencoded";
  39. public static final String OAUTH_CONSUMER_KEY = "oauth_consumer_key";
  40. public static final String OAUTH_TOKEN = "oauth_token";
  41. public static final String OAUTH_TOKEN_SECRET = "oauth_token_secret";
  42. public static final String OAUTH_SIGNATURE_METHOD = "oauth_signature_method";
  43. public static final String OAUTH_SIGNATURE = "oauth_signature";
  44. public static final String OAUTH_TIMESTAMP = "oauth_timestamp";
  45. public static final String OAUTH_NONCE = "oauth_nonce";
  46. public static final String OAUTH_VERSION = "oauth_version";
  47. public static final String OAUTH_CALLBACK = "oauth_callback";
  48. public static final String OAUTH_CALLBACK_CONFIRMED = "oauth_callback_confirmed";
  49. public static final String OAUTH_VERIFIER = "oauth_verifier";
  50. public static final String HMAC_SHA1 = "HMAC-SHA1";
  51. public static final String RSA_SHA1 = "RSA-SHA1";
  52. /**
  53. * Strings used for <a href="http://wiki.oauth.net/ProblemReporting">problem
  54. * reporting</a>.
  55. */
  56. public static class Problems {
  57. public static final String VERSION_REJECTED = "version_rejected";
  58. public static final String PARAMETER_ABSENT = "parameter_absent";
  59. public static final String PARAMETER_REJECTED = "parameter_rejected";
  60. public static final String TIMESTAMP_REFUSED = "timestamp_refused";
  61. public static final String NONCE_USED = "nonce_used";
  62. public static final String SIGNATURE_METHOD_REJECTED = "signature_method_rejected";
  63. public static final String SIGNATURE_INVALID = "signature_invalid";
  64. public static final String CONSUMER_KEY_UNKNOWN = "consumer_key_unknown";
  65. public static final String CONSUMER_KEY_REJECTED = "consumer_key_rejected";
  66. public static final String CONSUMER_KEY_REFUSED = "consumer_key_refused";
  67. public static final String TOKEN_USED = "token_used";
  68. public static final String TOKEN_EXPIRED = "token_expired";
  69. public static final String TOKEN_REVOKED = "token_revoked";
  70. public static final String TOKEN_REJECTED = "token_rejected";
  71. public static final String ADDITIONAL_AUTHORIZATION_REQUIRED = "additional_authorization_required";
  72. public static final String PERMISSION_UNKNOWN = "permission_unknown";
  73. public static final String PERMISSION_DENIED = "permission_denied";
  74. public static final String USER_REFUSED = "user_refused";
  75. public static final String OAUTH_ACCEPTABLE_VERSIONS = "oauth_acceptable_versions";
  76. public static final String OAUTH_ACCEPTABLE_TIMESTAMPS = "oauth_acceptable_timestamps";
  77. public static final String OAUTH_PARAMETERS_ABSENT = "oauth_parameters_absent";
  78. public static final String OAUTH_PARAMETERS_REJECTED = "oauth_parameters_rejected";
  79. public static final String OAUTH_PROBLEM_ADVICE = "oauth_problem_advice";
  80. /**
  81. * A map from an <a
  82. * href="http://wiki.oauth.net/ProblemReporting">oauth_problem</a> value to
  83. * the appropriate HTTP response code.
  84. */
  85. public static final Map<String, Integer> TO_HTTP_CODE = mapToHttpCode();
  86. private static Map<String, Integer> mapToHttpCode() {
  87. Integer badRequest = new Integer(400);
  88. Integer unauthorized = new Integer(401);
  89. Integer serviceUnavailable = new Integer(503);
  90. Map<String, Integer> map = new HashMap<String, Integer>();
  91. map.put(Problems.VERSION_REJECTED, badRequest);
  92. map.put(Problems.PARAMETER_ABSENT, badRequest);
  93. map.put(Problems.PARAMETER_REJECTED, badRequest);
  94. map.put(Problems.TIMESTAMP_REFUSED, badRequest);
  95. map.put(Problems.SIGNATURE_METHOD_REJECTED, badRequest);
  96. map.put(Problems.NONCE_USED, unauthorized);
  97. map.put(Problems.TOKEN_USED, unauthorized);
  98. map.put(Problems.TOKEN_EXPIRED, unauthorized);
  99. map.put(Problems.TOKEN_REVOKED, unauthorized);
  100. map.put(Problems.TOKEN_REJECTED, unauthorized);
  101. map.put("token_not_authorized", unauthorized);
  102. map.put(Problems.SIGNATURE_INVALID, unauthorized);
  103. map.put(Problems.CONSUMER_KEY_UNKNOWN, unauthorized);
  104. map.put(Problems.CONSUMER_KEY_REJECTED, unauthorized);
  105. map.put(Problems.ADDITIONAL_AUTHORIZATION_REQUIRED, unauthorized);
  106. map.put(Problems.PERMISSION_UNKNOWN, unauthorized);
  107. map.put(Problems.PERMISSION_DENIED, unauthorized);
  108. map.put(Problems.USER_REFUSED, serviceUnavailable);
  109. map.put(Problems.CONSUMER_KEY_REFUSED, serviceUnavailable);
  110. return Collections.unmodifiableMap(map);
  111. }
  112. }
  113. /** Return true if the given Content-Type header means FORM_ENCODED. */
  114. public static boolean isFormEncoded(String contentType) {
  115. if (contentType == null) {
  116. return false;
  117. }
  118. int semi = contentType.indexOf(";");
  119. if (semi >= 0) {
  120. contentType = contentType.substring(0, semi);
  121. }
  122. return FORM_ENCODED.equalsIgnoreCase(contentType.trim());
  123. }
  124. /**
  125. * Construct a form-urlencoded document containing the given sequence of
  126. * name/value pairs. Use OAuth percent encoding (not exactly the encoding
  127. * mandated by HTTP).
  128. */
  129. public static String formEncode(Iterable<? extends Map.Entry> parameters)
  130. throws IOException {
  131. ByteArrayOutputStream b = new ByteArrayOutputStream();
  132. formEncode(parameters, b);
  133. return new String(b.toByteArray());
  134. }
  135. /**
  136. * Write a form-urlencoded document into the given stream, containing the
  137. * given sequence of name/value pairs.
  138. */
  139. public static void formEncode(Iterable<? extends Map.Entry> parameters,
  140. OutputStream into) throws IOException {
  141. if (parameters != null) {
  142. boolean first = true;
  143. for (Map.Entry parameter : parameters) {
  144. if (first) {
  145. first = false;
  146. } else {
  147. into.write('&');
  148. }
  149. into.write(percentEncode(toString(parameter.getKey()))
  150. .getBytes());
  151. into.write('=');
  152. into.write(percentEncode(toString(parameter.getValue()))
  153. .getBytes());
  154. }
  155. }
  156. }
  157. /** Parse a form-urlencoded document. */
  158. public static List<Parameter> decodeForm(String form) {
  159. List<Parameter> list = new ArrayList<Parameter>();
  160. if (!isEmpty(form)) {
  161. for (String nvp : form.split("\\&")) {
  162. int equals = nvp.indexOf('=');
  163. String name;
  164. String value;
  165. if (equals < 0) {
  166. name = decodePercent(nvp);
  167. value = null;
  168. } else {
  169. name = decodePercent(nvp.substring(0, equals));
  170. value = decodePercent(nvp.substring(equals + 1));
  171. }
  172. list.add(new Parameter(name, value));
  173. }
  174. }
  175. return list;
  176. }
  177. /** Construct a &-separated list of the given values, percentEncoded. */
  178. public static String percentEncode(Iterable values) {
  179. StringBuilder p = new StringBuilder();
  180. for (Object v : values) {
  181. if (p.length() > 0) {
  182. p.append("&");
  183. }
  184. p.append(OAuth.percentEncode(toString(v)));
  185. }
  186. return p.toString();
  187. }
  188. public static String percentEncode(String s) {
  189. if (s == null) {
  190. return "";
  191. }
  192. try {
  193. return URLEncoder.encode(s, ENCODING)
  194. // OAuth encodes some characters differently:
  195. .replace("+", "%20").replace("*", "%2A")
  196. .replace("%7E", "~");
  197. // This could be done faster with more hand-crafted code.
  198. } catch (UnsupportedEncodingException wow) {
  199. throw new RuntimeException(wow.getMessage(), wow);
  200. }
  201. }
  202. public static String decodePercent(String s) {
  203. try {
  204. return URLDecoder.decode(s, ENCODING);
  205. // This implements http://oauth.pbwiki.com/FlexibleDecoding
  206. } catch (java.io.UnsupportedEncodingException wow) {
  207. throw new RuntimeException(wow.getMessage(), wow);
  208. }
  209. }
  210. /**
  211. * Construct a Map containing a copy of the given parameters. If several
  212. * parameters have the same name, the Map will contain the first value,
  213. * only.
  214. */
  215. public static Map<String, String> newMap(Iterable<? extends Map.Entry> from) {
  216. Map<String, String> map = new HashMap<String, String>();
  217. if (from != null) {
  218. for (Map.Entry f : from) {
  219. String key = toString(f.getKey());
  220. if (!map.containsKey(key)) {
  221. map.put(key, toString(f.getValue()));
  222. }
  223. }
  224. }
  225. return map;
  226. }
  227. /** Construct a list of Parameters from name, value, name, value... */
  228. public static List<Parameter> newList(String... parameters) {
  229. List<Parameter> list = new ArrayList<Parameter>(parameters.length / 2);
  230. for (int p = 0; p + 1 < parameters.length; p += 2) {
  231. list.add(new Parameter(parameters[p], parameters[p + 1]));
  232. }
  233. return list;
  234. }
  235. /** A name/value pair. */
  236. public static class Parameter implements Map.Entry<String, String> {
  237. public Parameter(String key, String value) {
  238. this.key = key;
  239. this.value = value;
  240. }
  241. private final String key;
  242. private String value;
  243. public String getKey() {
  244. return key;
  245. }
  246. public String getValue() {
  247. return value;
  248. }
  249. public String setValue(String value) {
  250. try {
  251. return this.value;
  252. } finally {
  253. this.value = value;
  254. }
  255. }
  256. @Override
  257. public String toString() {
  258. return percentEncode(getKey()) + '=' + percentEncode(getValue());
  259. }
  260. @Override
  261. public int hashCode()
  262. {
  263. final int prime = 31;
  264. int result = 1;
  265. result = prime * result + ((key == null) ? 0 : key.hashCode());
  266. result = prime * result + ((value == null) ? 0 : value.hashCode());
  267. return result;
  268. }
  269. @Override
  270. public boolean equals(Object obj)
  271. {
  272. if (this == obj)
  273. return true;
  274. if (obj == null)
  275. return false;
  276. if (getClass() != obj.getClass())
  277. return false;
  278. final Parameter that = (Parameter) obj;
  279. if (key == null) {
  280. if (that.key != null)
  281. return false;
  282. } else if (!key.equals(that.key))
  283. return false;
  284. if (value == null) {
  285. if (that.value != null)
  286. return false;
  287. } else if (!value.equals(that.value))
  288. return false;
  289. return true;
  290. }
  291. }
  292. private static final String toString(Object from) {
  293. return (from == null) ? null : from.toString();
  294. }
  295. /**
  296. * Construct a URL like the given one, but with the given parameters added
  297. * to its query string.
  298. */
  299. public static String addParameters(String url, String... parameters)
  300. throws IOException {
  301. return addParameters(url, newList(parameters));
  302. }
  303. public static String addParameters(String url,
  304. Iterable<? extends Map.Entry<String, String>> parameters)
  305. throws IOException {
  306. String form = formEncode(parameters);
  307. if (form == null || form.length() <= 0) {
  308. return url;
  309. } else {
  310. return url + ((url.indexOf("?") < 0) ? '?' : '&') + form;
  311. }
  312. }
  313. public static boolean isEmpty(String str) {
  314. return (str == null) || (str.length() == 0);
  315. }
  316. }