1c7df3223dc509354c096a652be9ab4df281b37e
[jalview.git] / src / org / json / CDL.java
1 package org.json;
2
3 /*
4 Copyright (c) 2002 JSON.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in all
14 copies or substantial portions of the Software.
15
16 The Software shall be used for Good, not Evil.
17
18 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24 SOFTWARE.
25  */
26
27 /**
28  * This provides static methods to convert comma delimited text into a
29  * JSONArray, and to convert a JSONArray into comma delimited text. Comma
30  * delimited text is a very popular format for data interchange. It is
31  * understood by most database, spreadsheet, and organizer programs.
32  * <p>
33  * Each row of text represents a row in a table or a data record. Each row
34  * ends with a NEWLINE character. Each row contains one or more values.
35  * Values are separated by commas. A value can contain any character except
36  * for comma, unless is is wrapped in single quotes or double quotes.
37  * <p>
38  * The first row usually contains the names of the columns.
39  * <p>
40  * A comma delimited list can be converted into a JSONArray of JSONObjects.
41  * The names for the elements in the JSONObjects can be taken from the names
42  * in the first row.
43  * @author JSON.org
44  * @version 2016-05-01
45  */
46 public class CDL {
47
48     /**
49      * Get the next value. The value can be wrapped in quotes. The value can
50      * be empty.
51      * @param x A JSONTokener of the source text.
52      * @return The value string, or null if empty.
53      * @throws JSONException if the quoted string is badly formed.
54      */
55     private static String getValue(JSONTokener x) throws JSONException {
56         char c;
57         char q;
58         StringBuffer sb;
59         do {
60             c = x.next();
61         } while (c == ' ' || c == '\t');
62         switch (c) {
63         case 0:
64             return null;
65         case '"':
66         case '\'':
67             q = c;
68             sb = new StringBuffer();
69             for (;;) {
70                 c = x.next();
71                 if (c == q) {
72                     //Handle escaped double-quote
73                     char nextC = x.next();
74                     if(nextC != '\"') {
75                         // if our quote was the end of the file, don't step
76                         if(nextC > 0) {
77                             x.back();
78                         }
79                         break;
80                     }
81                 }
82                 if (c == 0 || c == '\n' || c == '\r') {
83                     throw x.syntaxError("Missing close quote '" + q + "'.");
84                 }
85                 sb.append(c);
86             }
87             return sb.toString();
88         case ',':
89             x.back();
90             return "";
91         default:
92             x.back();
93             return x.nextTo(',');
94         }
95     }
96
97     /**
98      * Produce a JSONArray of strings from a row of comma delimited values.
99      * @param x A JSONTokener of the source text.
100      * @return A JSONArray of strings.
101      * @throws JSONException
102      */
103     public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException {
104         JSONArray ja = new JSONArray();
105         for (;;) {
106             String value = getValue(x);
107             char c = x.next();
108             if (value == null ||
109                     (ja.length() == 0 && value.length() == 0 && c != ',')) {
110                 return null;
111             }
112             ja.put(value);
113             for (;;) {
114                 if (c == ',') {
115                     break;
116                 }
117                 if (c != ' ') {
118                     if (c == '\n' || c == '\r' || c == 0) {
119                         return ja;
120                     }
121                     throw x.syntaxError("Bad character '" + c + "' (" +
122                             (int)c + ").");
123                 }
124                 c = x.next();
125             }
126         }
127     }
128
129     /**
130      * Produce a JSONObject from a row of comma delimited text, using a
131      * parallel JSONArray of strings to provides the names of the elements.
132      * @param names A JSONArray of names. This is commonly obtained from the
133      *  first row of a comma delimited text file using the rowToJSONArray
134      *  method.
135      * @param x A JSONTokener of the source text.
136      * @return A JSONObject combining the names and values.
137      * @throws JSONException
138      */
139     public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x)
140             throws JSONException {
141         JSONArray ja = rowToJSONArray(x);
142         return ja != null ? ja.toJSONObject(names) :  null;
143     }
144
145     /**
146      * Produce a comma delimited text row from a JSONArray. Values containing
147      * the comma character will be quoted. Troublesome characters may be
148      * removed.
149      * @param ja A JSONArray of strings.
150      * @return A string ending in NEWLINE.
151      */
152     public static String rowToString(JSONArray ja) {
153         StringBuilder sb = new StringBuilder();
154         for (int i = 0; i < ja.length(); i += 1) {
155             if (i > 0) {
156                 sb.append(',');
157             }
158             Object object = ja.opt(i);
159             if (object != null) {
160                 String string = object.toString();
161                 if (string.length() > 0 && (string.indexOf(',') >= 0 ||
162                         string.indexOf('\n') >= 0 || string.indexOf('\r') >= 0 ||
163                         string.indexOf(0) >= 0 || string.charAt(0) == '"')) {
164                     sb.append('"');
165                     int length = string.length();
166                     for (int j = 0; j < length; j += 1) {
167                         char c = string.charAt(j);
168                         if (c >= ' ' && c != '"') {
169                             sb.append(c);
170                         }
171                     }
172                     sb.append('"');
173                 } else {
174                     sb.append(string);
175                 }
176             }
177         }
178         sb.append('\n');
179         return sb.toString();
180     }
181
182     /**
183      * Produce a JSONArray of JSONObjects from a comma delimited text string,
184      * using the first row as a source of names.
185      * @param string The comma delimited text.
186      * @return A JSONArray of JSONObjects.
187      * @throws JSONException
188      */
189     public static JSONArray toJSONArray(String string) throws JSONException {
190         return toJSONArray(new JSONTokener(string));
191     }
192
193     /**
194      * Produce a JSONArray of JSONObjects from a comma delimited text string,
195      * using the first row as a source of names.
196      * @param x The JSONTokener containing the comma delimited text.
197      * @return A JSONArray of JSONObjects.
198      * @throws JSONException
199      */
200     public static JSONArray toJSONArray(JSONTokener x) throws JSONException {
201         return toJSONArray(rowToJSONArray(x), x);
202     }
203
204     /**
205      * Produce a JSONArray of JSONObjects from a comma delimited text string
206      * using a supplied JSONArray as the source of element names.
207      * @param names A JSONArray of strings.
208      * @param string The comma delimited text.
209      * @return A JSONArray of JSONObjects.
210      * @throws JSONException
211      */
212     public static JSONArray toJSONArray(JSONArray names, String string)
213             throws JSONException {
214         return toJSONArray(names, new JSONTokener(string));
215     }
216
217     /**
218      * Produce a JSONArray of JSONObjects from a comma delimited text string
219      * using a supplied JSONArray as the source of element names.
220      * @param names A JSONArray of strings.
221      * @param x A JSONTokener of the source text.
222      * @return A JSONArray of JSONObjects.
223      * @throws JSONException
224      */
225     public static JSONArray toJSONArray(JSONArray names, JSONTokener x)
226             throws JSONException {
227         if (names == null || names.length() == 0) {
228             return null;
229         }
230         JSONArray ja = new JSONArray();
231         for (;;) {
232             JSONObject jo = rowToJSONObject(names, x);
233             if (jo == null) {
234                 break;
235             }
236             ja.put(jo);
237         }
238         if (ja.length() == 0) {
239             return null;
240         }
241         return ja;
242     }
243
244
245     /**
246      * Produce a comma delimited text from a JSONArray of JSONObjects. The
247      * first row will be a list of names obtained by inspecting the first
248      * JSONObject.
249      * @param ja A JSONArray of JSONObjects.
250      * @return A comma delimited text.
251      * @throws JSONException
252      */
253     public static String toString(JSONArray ja) throws JSONException {
254         JSONObject jo = ja.optJSONObject(0);
255         if (jo != null) {
256             JSONArray names = jo.names();
257             if (names != null) {
258                 return rowToString(names) + toString(names, ja);
259             }
260         }
261         return null;
262     }
263
264     /**
265      * Produce a comma delimited text from a JSONArray of JSONObjects using
266      * a provided list of names. The list of names is not included in the
267      * output.
268      * @param names A JSONArray of strings.
269      * @param ja A JSONArray of JSONObjects.
270      * @return A comma delimited text.
271      * @throws JSONException
272      */
273     public static String toString(JSONArray names, JSONArray ja)
274             throws JSONException {
275         if (names == null || names.length() == 0) {
276             return null;
277         }
278         StringBuffer sb = new StringBuffer();
279         for (int i = 0; i < ja.length(); i += 1) {
280             JSONObject jo = ja.optJSONObject(i);
281             if (jo != null) {
282                 sb.append(rowToString(jo.toJSONArray(names)));
283             }
284         }
285         return sb.toString();
286     }
287 }