Cookie.java 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. package com.usky.xml;
  2. import java.util.Locale;
  3. /*
  4. Copyright (c) 2002 JSON.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in all
  12. copies or substantial portions of the Software.
  13. The Software shall be used for Good, not Evil.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. */
  22. /**
  23. * Convert a web browser cookie specification to a JSONObject and back.
  24. * JSON and Cookies are both notations for name/value pairs.
  25. * See also: <a href="https://tools.ietf.org/html/rfc6265">https://tools.ietf.org/html/rfc6265</a>
  26. * @author JSON.org
  27. * @version 2015-12-09
  28. */
  29. public class Cookie {
  30. /**
  31. * Produce a copy of a string in which the characters '+', '%', '=', ';'
  32. * and control characters are replaced with "%hh". This is a gentle form
  33. * of URL encoding, attempting to cause as little distortion to the
  34. * string as possible. The characters '=' and ';' are meta characters in
  35. * cookies. By convention, they are escaped using the URL-encoding. This is
  36. * only a convention, not a standard. Often, cookies are expected to have
  37. * encoded values. We encode '=' and ';' because we must. We encode '%' and
  38. * '+' because they are meta characters in URL encoding.
  39. * @param string The source string.
  40. * @return The escaped result.
  41. */
  42. public static String escape(String string) {
  43. char c;
  44. String s = string.trim();
  45. int length = s.length();
  46. StringBuilder sb = new StringBuilder(length);
  47. for (int i = 0; i < length; i += 1) {
  48. c = s.charAt(i);
  49. if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
  50. sb.append('%');
  51. sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
  52. sb.append(Character.forDigit((char)(c & 0x0f), 16));
  53. } else {
  54. sb.append(c);
  55. }
  56. }
  57. return sb.toString();
  58. }
  59. /**
  60. * Convert a cookie specification string into a JSONObject. The string
  61. * must contain a name value pair separated by '='. The name and the value
  62. * will be unescaped, possibly converting '+' and '%' sequences. The
  63. * cookie properties may follow, separated by ';', also represented as
  64. * name=value (except the Attribute properties like "Secure" or "HttpOnly",
  65. * which do not have a value. The value {@link Boolean#TRUE} will be used for these).
  66. * The name will be stored under the key "name", and the value will be
  67. * stored under the key "value". This method does not do checking or
  68. * validation of the parameters. It only converts the cookie string into
  69. * a JSONObject. All attribute names are converted to lower case keys in the
  70. * JSONObject (HttpOnly =&gt; httponly). If an attribute is specified more than
  71. * once, only the value found closer to the end of the cookie-string is kept.
  72. * @param string The cookie specification string.
  73. * @return A JSONObject containing "name", "value", and possibly other
  74. * members.
  75. * @throws JSONException If there is an error parsing the Cookie String.
  76. * Cookie strings must have at least one '=' character and the 'name'
  77. * portion of the cookie must not be blank.
  78. */
  79. public static JSONObject toJSONObject(String string) {
  80. final JSONObject jo = new JSONObject();
  81. String name;
  82. Object value;
  83. JSONTokener x = new JSONTokener(string);
  84. name = unescape(x.nextTo('=').trim());
  85. //per RFC6265, if the name is blank, the cookie should be ignored.
  86. if("".equals(name)) {
  87. throw new JSONException("Cookies must have a 'name'");
  88. }
  89. jo.put("name", name);
  90. // per RFC6265, if there is no '=', the cookie should be ignored.
  91. // the 'next' call here throws an exception if the '=' is not found.
  92. x.next('=');
  93. jo.put("value", unescape(x.nextTo(';')).trim());
  94. // discard the ';'
  95. x.next();
  96. // parse the remaining cookie attributes
  97. while (x.more()) {
  98. name = unescape(x.nextTo("=;")).trim().toLowerCase(Locale.ROOT);
  99. // don't allow a cookies attributes to overwrite it's name or value.
  100. if("name".equalsIgnoreCase(name)) {
  101. throw new JSONException("Illegal attribute name: 'name'");
  102. }
  103. if("value".equalsIgnoreCase(name)) {
  104. throw new JSONException("Illegal attribute name: 'value'");
  105. }
  106. // check to see if it's a flag property
  107. if (x.next() != '=') {
  108. value = Boolean.TRUE;
  109. } else {
  110. value = unescape(x.nextTo(';')).trim();
  111. x.next();
  112. }
  113. // only store non-blank attributes
  114. if(!"".equals(name) && !"".equals(value)) {
  115. jo.put(name, value);
  116. }
  117. }
  118. return jo;
  119. }
  120. /**
  121. * Convert a JSONObject into a cookie specification string. The JSONObject
  122. * must contain "name" and "value" members (case insensitive).
  123. * If the JSONObject contains other members, they will be appended to the cookie
  124. * specification string. User-Agents are instructed to ignore unknown attributes,
  125. * so ensure your JSONObject is using only known attributes.
  126. * See also: <a href="https://tools.ietf.org/html/rfc6265">https://tools.ietf.org/html/rfc6265</a>
  127. * @param jo A JSONObject
  128. * @return A cookie specification string
  129. * @throws JSONException thrown if the cookie has no name.
  130. */
  131. public static String toString(JSONObject jo) throws JSONException {
  132. StringBuilder sb = new StringBuilder();
  133. String name = null;
  134. Object value = null;
  135. for(String key : jo.keySet()){
  136. if("name".equalsIgnoreCase(key)) {
  137. name = jo.getString(key).trim();
  138. }
  139. if("value".equalsIgnoreCase(key)) {
  140. value=jo.getString(key).trim();
  141. }
  142. if(name != null && value != null) {
  143. break;
  144. }
  145. }
  146. if(name == null || "".equals(name.trim())) {
  147. throw new JSONException("Cookie does not have a name");
  148. }
  149. if(value == null) {
  150. value = "";
  151. }
  152. sb.append(escape(name));
  153. sb.append("=");
  154. sb.append(escape((String)value));
  155. for(String key : jo.keySet()){
  156. if("name".equalsIgnoreCase(key)
  157. || "value".equalsIgnoreCase(key)) {
  158. // already processed above
  159. continue;
  160. }
  161. value = jo.opt(key);
  162. if(value instanceof Boolean) {
  163. if(Boolean.TRUE.equals(value)) {
  164. sb.append(';').append(escape(key));
  165. }
  166. // don't emit false values
  167. } else {
  168. sb.append(';')
  169. .append(escape(key))
  170. .append('=')
  171. .append(escape(value.toString()));
  172. }
  173. }
  174. return sb.toString();
  175. }
  176. /**
  177. * Convert <code>%</code><i>hh</i> sequences to single characters, and
  178. * convert plus to space.
  179. * @param string A string that may contain
  180. * <code>+</code>&nbsp;<small>(plus)</small> and
  181. * <code>%</code><i>hh</i> sequences.
  182. * @return The unescaped string.
  183. */
  184. public static String unescape(String string) {
  185. int length = string.length();
  186. StringBuilder sb = new StringBuilder(length);
  187. for (int i = 0; i < length; ++i) {
  188. char c = string.charAt(i);
  189. if (c == '+') {
  190. c = ' ';
  191. } else if (c == '%' && i + 2 < length) {
  192. int d = JSONTokener.dehexchar(string.charAt(i + 1));
  193. int e = JSONTokener.dehexchar(string.charAt(i + 2));
  194. if (d >= 0 && e >= 0) {
  195. c = (char)(d * 16 + e);
  196. i += 2;
  197. }
  198. }
  199. sb.append(c);
  200. }
  201. return sb.toString();
  202. }
  203. }