[DMAAP-48] Initial code import
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / json / Cookie.java
1 /*******************************************************************************\r
2  * ============LICENSE_START==================================================\r
3  * * org.onap.dmaap\r
4  * * ===========================================================================\r
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.\r
6  * * ===========================================================================\r
7  * * Licensed under the Apache License, Version 2.0 (the "License");\r
8  * * you may not use this file except in compliance with the License.\r
9  * * You may obtain a copy of the License at\r
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \r
13  *  * Unless required by applicable law or agreed to in writing, software\r
14  * * distributed under the License is distributed on an "AS IS" BASIS,\r
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
16  * * See the License for the specific language governing permissions and\r
17  * * limitations under the License.\r
18  * * ============LICENSE_END====================================================\r
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package org.json;\r
24 \r
25 /*\r
26 Copyright (c) 2002 JSON.org\r
27 \r
28 Permission is hereby granted, free of charge, to any person obtaining a copy\r
29 of this software and associated documentation files (the "Software"), to deal\r
30 in the Software without restriction, including without limitation the rights\r
31 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r
32 copies of the Software, and to permit persons to whom the Software is\r
33 furnished to do so, subject to the following conditions:\r
34 \r
35 The above copyright notice and this permission notice shall be included in all\r
36 copies or substantial portions of the Software.\r
37 \r
38 The Software shall be used for Good, not Evil.\r
39 \r
40 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r
41 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r
42 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r
43 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r
44 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r
45 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r
46 SOFTWARE.\r
47 */\r
48 \r
49 /**\r
50  * Convert a web browser cookie specification to a JSONObject and back.\r
51  * JSON and Cookies are both notations for name/value pairs.\r
52  * @author JSON.org\r
53  * @version 2010-12-24\r
54  */\r
55 public class Cookie {\r
56 \r
57     /**\r
58      * Produce a copy of a string in which the characters '+', '%', '=', ';'\r
59      * and control characters are replaced with "%hh". This is a gentle form\r
60      * of URL encoding, attempting to cause as little distortion to the\r
61      * string as possible. The characters '=' and ';' are meta characters in\r
62      * cookies. By convention, they are escaped using the URL-encoding. This is\r
63      * only a convention, not a standard. Often, cookies are expected to have\r
64      * encoded values. We encode '=' and ';' because we must. We encode '%' and\r
65      * '+' because they are meta characters in URL encoding.\r
66      * @param string The source string.\r
67      * @return       The escaped result.\r
68      */\r
69     public static String escape(String string) {\r
70         char         c;\r
71         String       s = string.trim();\r
72         StringBuffer sb = new StringBuffer();\r
73         int          length = s.length();\r
74         for (int i = 0; i < length; i += 1) {\r
75             c = s.charAt(i);\r
76             if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {\r
77                 sb.append('%');\r
78                 sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));\r
79                 sb.append(Character.forDigit((char)(c & 0x0f), 16));\r
80             } else {\r
81                 sb.append(c);\r
82             }\r
83         }\r
84         return sb.toString();\r
85     }\r
86 \r
87 \r
88     /**\r
89      * Convert a cookie specification string into a JSONObject. The string\r
90      * will contain a name value pair separated by '='. The name and the value\r
91      * will be unescaped, possibly converting '+' and '%' sequences. The\r
92      * cookie properties may follow, separated by ';', also represented as\r
93      * name=value (except the secure property, which does not have a value).\r
94      * The name will be stored under the key "name", and the value will be\r
95      * stored under the key "value". This method does not do checking or\r
96      * validation of the parameters. It only converts the cookie string into\r
97      * a JSONObject.\r
98      * @param string The cookie specification string.\r
99      * @return A JSONObject containing "name", "value", and possibly other\r
100      *  members.\r
101      * @throws JSONException\r
102      */\r
103     public static JSONObject toJSONObject(String string) throws JSONException {\r
104         String         name;\r
105         JSONObject     jo = new JSONObject();\r
106         Object         value;\r
107         JSONTokener x = new JSONTokener(string);\r
108         jo.put("name", x.nextTo('='));\r
109         x.next('=');\r
110         jo.put("value", x.nextTo(';'));\r
111         x.next();\r
112         while (x.more()) {\r
113             name = unescape(x.nextTo("=;"));\r
114             if (x.next() != '=') {\r
115                 if (name.equals("secure")) {\r
116                     value = Boolean.TRUE;\r
117                 } else {\r
118                     throw x.syntaxError("Missing '=' in cookie parameter.");\r
119                 }\r
120             } else {\r
121                 value = unescape(x.nextTo(';'));\r
122                 x.next();\r
123             }\r
124             jo.put(name, value);\r
125         }\r
126         return jo;\r
127     }\r
128 \r
129 \r
130     /**\r
131      * Convert a JSONObject into a cookie specification string. The JSONObject\r
132      * must contain "name" and "value" members.\r
133      * If the JSONObject contains "expires", "domain", "path", or "secure"\r
134      * members, they will be appended to the cookie specification string.\r
135      * All other members are ignored.\r
136      * @param jo A JSONObject\r
137      * @return A cookie specification string\r
138      * @throws JSONException\r
139      */\r
140     public static String toString(JSONObject jo) throws JSONException {\r
141         StringBuffer sb = new StringBuffer();\r
142 \r
143         sb.append(escape(jo.getString("name")));\r
144         sb.append("=");\r
145         sb.append(escape(jo.getString("value")));\r
146         if (jo.has("expires")) {\r
147             sb.append(";expires=");\r
148             sb.append(jo.getString("expires"));\r
149         }\r
150         if (jo.has("domain")) {\r
151             sb.append(";domain=");\r
152             sb.append(escape(jo.getString("domain")));\r
153         }\r
154         if (jo.has("path")) {\r
155             sb.append(";path=");\r
156             sb.append(escape(jo.getString("path")));\r
157         }\r
158         if (jo.optBoolean("secure")) {\r
159             sb.append(";secure");\r
160         }\r
161         return sb.toString();\r
162     }\r
163 \r
164     /**\r
165      * Convert <code>%</code><i>hh</i> sequences to single characters, and\r
166      * convert plus to space.\r
167      * @param string A string that may contain\r
168      *      <code>+</code>&nbsp;<small>(plus)</small> and\r
169      *      <code>%</code><i>hh</i> sequences.\r
170      * @return The unescaped string.\r
171      */\r
172     public static String unescape(String string) {\r
173         int length = string.length();\r
174         StringBuffer sb = new StringBuffer();\r
175         for (int i = 0; i < length; ++i) {\r
176             char c = string.charAt(i);\r
177             if (c == '+') {\r
178                 c = ' ';\r
179             } else if (c == '%' && i + 2 < length) {\r
180                 int d = JSONTokener.dehexchar(string.charAt(i + 1));\r
181                 int e = JSONTokener.dehexchar(string.charAt(i + 2));\r
182                 if (d >= 0 && e >= 0) {\r
183                     c = (char)(d * 16 + e);\r
184                     i += 2;\r
185                 }\r
186             }\r
187             sb.append(c);\r
188         }\r
189         return sb.toString();\r
190     }\r
191 }\r