[DMAAP-48] Initial code import
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / json / HTTP.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 import java.util.Iterator;\r
50 \r
51 /**\r
52  * Convert an HTTP header to a JSONObject and back.\r
53  * @author JSON.org\r
54  * @version 2010-12-24\r
55  */\r
56 public class HTTP {\r
57 \r
58     /** Carriage return/line feed. */\r
59     public static final String CRLF = "\r\n";\r
60 \r
61     /**\r
62      * Convert an HTTP header string into a JSONObject. It can be a request\r
63      * header or a response header. A request header will contain\r
64      * <pre>{\r
65      *    Method: "POST" (for example),\r
66      *    "Request-URI": "/" (for example),\r
67      *    "HTTP-Version": "HTTP/1.1" (for example)\r
68      * }</pre>\r
69      * A response header will contain\r
70      * <pre>{\r
71      *    "HTTP-Version": "HTTP/1.1" (for example),\r
72      *    "Status-Code": "200" (for example),\r
73      *    "Reason-Phrase": "OK" (for example)\r
74      * }</pre>\r
75      * In addition, the other parameters in the header will be captured, using\r
76      * the HTTP field names as JSON names, so that <pre>\r
77      *    Date: Sun, 26 May 2002 18:06:04 GMT\r
78      *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s\r
79      *    Cache-Control: no-cache</pre>\r
80      * become\r
81      * <pre>{...\r
82      *    Date: "Sun, 26 May 2002 18:06:04 GMT",\r
83      *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",\r
84      *    "Cache-Control": "no-cache",\r
85      * ...}</pre>\r
86      * It does no further checking or conversion. It does not parse dates.\r
87      * It does not do '%' transforms on URLs.\r
88      * @param string An HTTP header string.\r
89      * @return A JSONObject containing the elements and attributes\r
90      * of the XML string.\r
91      * @throws JSONException\r
92      */\r
93     public static JSONObject toJSONObject(String string) throws JSONException {\r
94         JSONObject     jo = new JSONObject();\r
95         HTTPTokener    x = new HTTPTokener(string);\r
96         String         token;\r
97 \r
98         token = x.nextToken();\r
99         if (token.toUpperCase().startsWith("HTTP")) {\r
100 \r
101 // Response\r
102 \r
103             jo.put("HTTP-Version", token);\r
104             jo.put("Status-Code", x.nextToken());\r
105             jo.put("Reason-Phrase", x.nextTo('\0'));\r
106             x.next();\r
107 \r
108         } else {\r
109 \r
110 // Request\r
111 \r
112             jo.put("Method", token);\r
113             jo.put("Request-URI", x.nextToken());\r
114             jo.put("HTTP-Version", x.nextToken());\r
115         }\r
116 \r
117 // Fields\r
118 \r
119         while (x.more()) {\r
120             String name = x.nextTo(':');\r
121             x.next(':');\r
122             jo.put(name, x.nextTo('\0'));\r
123             x.next();\r
124         }\r
125         return jo;\r
126     }\r
127 \r
128 \r
129     /**\r
130      * Convert a JSONObject into an HTTP header. A request header must contain\r
131      * <pre>{\r
132      *    Method: "POST" (for example),\r
133      *    "Request-URI": "/" (for example),\r
134      *    "HTTP-Version": "HTTP/1.1" (for example)\r
135      * }</pre>\r
136      * A response header must contain\r
137      * <pre>{\r
138      *    "HTTP-Version": "HTTP/1.1" (for example),\r
139      *    "Status-Code": "200" (for example),\r
140      *    "Reason-Phrase": "OK" (for example)\r
141      * }</pre>\r
142      * Any other members of the JSONObject will be output as HTTP fields.\r
143      * The result will end with two CRLF pairs.\r
144      * @param jo A JSONObject\r
145      * @return An HTTP header string.\r
146      * @throws JSONException if the object does not contain enough\r
147      *  information.\r
148      */\r
149     public static String toString(JSONObject jo) throws JSONException {\r
150         Iterator<String> keys = jo.keys();\r
151         String       string;\r
152         StringBuffer sb = new StringBuffer();\r
153         if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {\r
154             sb.append(jo.getString("HTTP-Version"));\r
155             sb.append(' ');\r
156             sb.append(jo.getString("Status-Code"));\r
157             sb.append(' ');\r
158             sb.append(jo.getString("Reason-Phrase"));\r
159         } else if (jo.has("Method") && jo.has("Request-URI")) {\r
160             sb.append(jo.getString("Method"));\r
161             sb.append(' ');\r
162             sb.append('"');\r
163             sb.append(jo.getString("Request-URI"));\r
164             sb.append('"');\r
165             sb.append(' ');\r
166             sb.append(jo.getString("HTTP-Version"));\r
167         } else {\r
168             throw new JSONException("Not enough material for an HTTP header.");\r
169         }\r
170         sb.append(CRLF);\r
171         while (keys.hasNext()) {\r
172             string = keys.next().toString();\r
173             if (!"HTTP-Version".equals(string)      && !"Status-Code".equals(string) &&\r
174                     !"Reason-Phrase".equals(string) && !"Method".equals(string) &&\r
175                     !"Request-URI".equals(string)   && !jo.isNull(string)) {\r
176                 sb.append(string);\r
177                 sb.append(": ");\r
178                 sb.append(jo.getString(string));\r
179                 sb.append(CRLF);\r
180             }\r
181         }\r
182         sb.append(CRLF);\r
183         return sb.toString();\r
184     }\r
185 }\r