Commit cdf43d88f6894f52f9908aa3a39d35d38905ab82

Authored by ljq
1 parent a37b2416

调度语音识别

Too many changes to show.

To preserve performance only 11 of 45 files are displayed.

... ... @@ -411,6 +411,24 @@
411 411 <groupId>org.hibernate</groupId>
412 412 <artifactId>hibernate-spatial</artifactId>
413 413 </dependency>
  414 +
  415 + <!-- 语音识别 -->
  416 + <dependency>
  417 + <groupId>net.java.dev.jna</groupId>
  418 + <artifactId>jna</artifactId>
  419 + <version>5.7.0</version>
  420 + </dependency>
  421 + <dependency>
  422 + <groupId>com.alphacephei</groupId>
  423 + <artifactId>vosk</artifactId>
  424 + <version>0.3.32</version>
  425 + </dependency>
  426 +
  427 + <dependency>
  428 + <groupId>com.belerweb</groupId>
  429 + <artifactId>pinyin4j</artifactId>
  430 + <version>2.5.1</version>
  431 + </dependency>
414 432 </dependencies>
415 433  
416 434 <dependencyManagement>
... ...
src/main/java/com/bsth/controller/realcontrol/PageForwardingController.java
1 1 package com.bsth.controller.realcontrol;
2 2  
  3 +import com.bsth.data.zndd.voice.UploadVideoServlet;
3 4 import com.bsth.entity.sys.Role;
4 5 import com.bsth.entity.sys.SysUser;
5 6 import com.bsth.security.util.SecurityUtils;
6 7 import org.slf4j.Logger;
7 8 import org.slf4j.LoggerFactory;
  9 +import org.springframework.beans.factory.annotation.Autowired;
8 10 import org.springframework.stereotype.Controller;
  11 +import org.springframework.web.bind.annotation.PathVariable;
9 12 import org.springframework.web.bind.annotation.RequestMapping;
  13 +import org.springframework.web.bind.annotation.RequestParam;
10 14 import org.springframework.web.servlet.ModelAndView;
11 15  
  16 +import javax.servlet.ServletException;
  17 +import javax.servlet.http.HttpServletRequest;
12 18 import javax.servlet.http.HttpServletResponse;
  19 +import java.io.IOException;
13 20  
14 21 /**
15 22 * 线调登入页面转发
... ... @@ -21,6 +28,8 @@ public class PageForwardingController {
21 28  
22 29 Logger logger = LoggerFactory.getLogger(this.getClass());
23 30  
  31 + @Autowired
  32 + UploadVideoServlet UploadVideoServlet;
24 33 @RequestMapping("/v2")
25 34 public ModelAndView v2(HttpServletResponse response){
26 35 ModelAndView mv = new ModelAndView();
... ... @@ -51,4 +60,9 @@ public class PageForwardingController {
51 60 mv.setViewName("/real_control_v2/main.html");
52 61 return mv;
53 62 }
  63 +
  64 + @RequestMapping(value = "zndd/do/{line}")
  65 + public void doPost(@PathVariable("line") String line, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  66 + UploadVideoServlet.doPost(line,request,response);
  67 + }
54 68 }
... ...
src/main/java/com/bsth/controller/zndd/LoggerZnddController.java
1 1 package com.bsth.controller.zndd;
2 2  
3 3 import com.bsth.controller.BaseController;
  4 +import com.bsth.entity.realcontrol.ScheduleRealInfo;
4 5 import com.bsth.entity.zndd.LoggerZndd;
5 6 import com.bsth.service.zndd.LoggerZnddService;
6 7 import org.springframework.beans.factory.annotation.Autowired;
7   -import org.springframework.web.bind.annotation.RequestMapping;
8   -import org.springframework.web.bind.annotation.RequestParam;
9   -import org.springframework.web.bind.annotation.RestController;
10   -
  8 +import org.springframework.web.bind.annotation.*;
11 9 import java.util.List;
12 10 import java.util.Map;
13 11  
... ... @@ -17,9 +15,17 @@ public class LoggerZnddController extends BaseController&lt;LoggerZndd, Integer&gt; {
17 15  
18 16 @Autowired
19 17 LoggerZnddService loggerZnddService;
  18 +
20 19 @RequestMapping("listall")
21 20 public List<Map<String, Object>> listAll(@RequestParam Map<String, Object> map){
22 21  
23 22 return loggerZnddService.listAll(map);
24 23 }
  24 +
  25 +
  26 + @RequestMapping(value = "/schlist", method = RequestMethod.POST)
  27 + public ScheduleRealInfo schlist(@RequestParam String lineCode,@RequestParam Integer dir){
  28 + return loggerZnddService.schlist(lineCode,dir);
  29 + }
  30 +
25 31 }
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/CDL.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/Cookie.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 + * Convert a web browser cookie specification to a JSONObject and back.
  29 + * JSON and Cookies are both notations for name/value pairs.
  30 + * @author JSON.org
  31 + * @version 2015-12-09
  32 + */
  33 +public class Cookie {
  34 +
  35 + /**
  36 + * Produce a copy of a string in which the characters '+', '%', '=', ';'
  37 + * and control characters are replaced with "%hh". This is a gentle form
  38 + * of URL encoding, attempting to cause as little distortion to the
  39 + * string as possible. The characters '=' and ';' are meta characters in
  40 + * cookies. By convention, they are escaped using the URL-encoding. This is
  41 + * only a convention, not a standard. Often, cookies are expected to have
  42 + * encoded values. We urlEncode '=' and ';' because we must. We urlEncode '%' and
  43 + * '+' because they are meta characters in URL encoding.
  44 + * @param string The source string.
  45 + * @return The escaped result.
  46 + */
  47 + public static String escape(String string) {
  48 + char c;
  49 + String s = string.trim();
  50 + int length = s.length();
  51 + StringBuilder sb = new StringBuilder(length);
  52 + for (int i = 0; i < length; i += 1) {
  53 + c = s.charAt(i);
  54 + if (c < ' ' || c == '+' || c == '%' || c == '=' || c == ';') {
  55 + sb.append('%');
  56 + sb.append(Character.forDigit((char)((c >>> 4) & 0x0f), 16));
  57 + sb.append(Character.forDigit((char)(c & 0x0f), 16));
  58 + } else {
  59 + sb.append(c);
  60 + }
  61 + }
  62 + return sb.toString();
  63 + }
  64 +
  65 +
  66 + /**
  67 + * Convert a cookie specification string into a JSONObject. The string
  68 + * will contain a name value pair separated by '='. The name and the value
  69 + * will be unescaped, possibly converting '+' and '%' sequences. The
  70 + * cookie properties may follow, separated by ';', also represented as
  71 + * name=value (except the secure property, which does not have a value).
  72 + * The name will be stored under the key "name", and the value will be
  73 + * stored under the key "value". This method does not do checking or
  74 + * validation of the parameters. It only converts the cookie string into
  75 + * a JSONObject.
  76 + * @param string The cookie specification string.
  77 + * @return A JSONObject containing "name", "value", and possibly other
  78 + * members.
  79 + * @throws JSONException
  80 + */
  81 + public static JSONObject toJSONObject(String string) throws JSONException {
  82 + String name;
  83 + JSONObject jo = new JSONObject();
  84 + Object value;
  85 + JSONTokener x = new JSONTokener(string);
  86 + jo.put("name", x.nextTo('='));
  87 + x.next('=');
  88 + jo.put("value", x.nextTo(';'));
  89 + x.next();
  90 + while (x.more()) {
  91 + name = unescape(x.nextTo("=;"));
  92 + if (x.next() != '=') {
  93 + if (name.equals("secure")) {
  94 + value = Boolean.TRUE;
  95 + } else {
  96 + throw x.syntaxError("Missing '=' in cookie parameter.");
  97 + }
  98 + } else {
  99 + value = unescape(x.nextTo(';'));
  100 + x.next();
  101 + }
  102 + jo.put(name, value);
  103 + }
  104 + return jo;
  105 + }
  106 +
  107 +
  108 + /**
  109 + * Convert a JSONObject into a cookie specification string. The JSONObject
  110 + * must contain "name" and "value" members.
  111 + * If the JSONObject contains "expires", "domain", "path", or "secure"
  112 + * members, they will be appended to the cookie specification string.
  113 + * All other members are ignored.
  114 + * @param jo A JSONObject
  115 + * @return A cookie specification string
  116 + * @throws JSONException
  117 + */
  118 + public static String toString(JSONObject jo) throws JSONException {
  119 + StringBuilder sb = new StringBuilder();
  120 +
  121 + sb.append(escape(jo.getString("name")));
  122 + sb.append("=");
  123 + sb.append(escape(jo.getString("value")));
  124 + if (jo.has("expires")) {
  125 + sb.append(";expires=");
  126 + sb.append(jo.getString("expires"));
  127 + }
  128 + if (jo.has("domain")) {
  129 + sb.append(";domain=");
  130 + sb.append(escape(jo.getString("domain")));
  131 + }
  132 + if (jo.has("path")) {
  133 + sb.append(";path=");
  134 + sb.append(escape(jo.getString("path")));
  135 + }
  136 + if (jo.optBoolean("secure")) {
  137 + sb.append(";secure");
  138 + }
  139 + return sb.toString();
  140 + }
  141 +
  142 + /**
  143 + * Convert <code>%</code><i>hh</i> sequences to single characters, and
  144 + * convert plus to space.
  145 + * @param string A string that may contain
  146 + * <code>+</code>&nbsp;<small>(plus)</small> and
  147 + * <code>%</code><i>hh</i> sequences.
  148 + * @return The unescaped string.
  149 + */
  150 + public static String unescape(String string) {
  151 + int length = string.length();
  152 + StringBuilder sb = new StringBuilder(length);
  153 + for (int i = 0; i < length; ++i) {
  154 + char c = string.charAt(i);
  155 + if (c == '+') {
  156 + c = ' ';
  157 + } else if (c == '%' && i + 2 < length) {
  158 + int d = JSONTokener.dehexchar(string.charAt(i + 1));
  159 + int e = JSONTokener.dehexchar(string.charAt(i + 2));
  160 + if (d >= 0 && e >= 0) {
  161 + c = (char)(d * 16 + e);
  162 + i += 2;
  163 + }
  164 + }
  165 + sb.append(c);
  166 + }
  167 + return sb.toString();
  168 + }
  169 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/CookieList.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 + * Convert a web browser cookie list string to a JSONObject and back.
  29 + * @author JSON.org
  30 + * @version 2015-12-09
  31 + */
  32 +public class CookieList {
  33 +
  34 + /**
  35 + * Convert a cookie list into a JSONObject. A cookie list is a sequence
  36 + * of name/value pairs. The names are separated from the values by '='.
  37 + * The pairs are separated by ';'. The names and the values
  38 + * will be unescaped, possibly converting '+' and '%' sequences.
  39 + *
  40 + * To add a cookie to a cookie list,
  41 + * cookielistJSONObject.put(cookieJSONObject.getString("name"),
  42 + * cookieJSONObject.getString("value"));
  43 + * @param string A cookie list string
  44 + * @return A JSONObject
  45 + * @throws JSONException
  46 + */
  47 + public static JSONObject toJSONObject(String string) throws JSONException {
  48 + JSONObject jo = new JSONObject();
  49 + JSONTokener x = new JSONTokener(string);
  50 + while (x.more()) {
  51 + String name = Cookie.unescape(x.nextTo('='));
  52 + x.next('=');
  53 + jo.put(name, Cookie.unescape(x.nextTo(';')));
  54 + x.next();
  55 + }
  56 + return jo;
  57 + }
  58 +
  59 + /**
  60 + * Convert a JSONObject into a cookie list. A cookie list is a sequence
  61 + * of name/value pairs. The names are separated from the values by '='.
  62 + * The pairs are separated by ';'. The characters '%', '+', '=', and ';'
  63 + * in the names and values are replaced by "%hh".
  64 + * @param jo A JSONObject
  65 + * @return A cookie list string
  66 + * @throws JSONException
  67 + */
  68 + public static String toString(JSONObject jo) throws JSONException {
  69 + boolean b = false;
  70 + final StringBuilder sb = new StringBuilder();
  71 + // Don't use the new entrySet API to maintain Android support
  72 + for (final String key : jo.keySet()) {
  73 + final Object value = jo.opt(key);
  74 + if (!JSONObject.NULL.equals(value)) {
  75 + if (b) {
  76 + sb.append(';');
  77 + }
  78 + sb.append(Cookie.escape(key));
  79 + sb.append("=");
  80 + sb.append(Cookie.escape(value.toString()));
  81 + b = true;
  82 + }
  83 + }
  84 + return sb.toString();
  85 + }
  86 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/HTTP.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 +import java.util.Locale;
  28 +
  29 +/**
  30 + * Convert an HTTP header to a JSONObject and back.
  31 + * @author JSON.org
  32 + * @version 2015-12-09
  33 + */
  34 +public class HTTP {
  35 +
  36 + /** Carriage return/line feed. */
  37 + public static final String CRLF = "\r\n";
  38 +
  39 + /**
  40 + * Convert an HTTP header string into a JSONObject. It can be a request
  41 + * header or a response header. A request header will contain
  42 + * <pre>{
  43 + * Method: "POST" (for example),
  44 + * "Request-URI": "/" (for example),
  45 + * "HTTP-Version": "HTTP/1.1" (for example)
  46 + * }</pre>
  47 + * A response header will contain
  48 + * <pre>{
  49 + * "HTTP-Version": "HTTP/1.1" (for example),
  50 + * "Status-Code": "200" (for example),
  51 + * "Reason-Phrase": "OK" (for example)
  52 + * }</pre>
  53 + * In addition, the other parameters in the header will be captured, using
  54 + * the HTTP field names as JSON names, so that <pre>
  55 + * Date: Sun, 26 May 2002 18:06:04 GMT
  56 + * Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
  57 + * Cache-Control: no-cache</pre>
  58 + * become
  59 + * <pre>{...
  60 + * Date: "Sun, 26 May 2002 18:06:04 GMT",
  61 + * Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
  62 + * "Cache-Control": "no-cache",
  63 + * ...}</pre>
  64 + * It does no further checking or conversion. It does not parse dates.
  65 + * It does not do '%' transforms on URLs.
  66 + * @param string An HTTP header string.
  67 + * @return A JSONObject containing the elements and attributes
  68 + * of the XML string.
  69 + * @throws JSONException
  70 + */
  71 + public static JSONObject toJSONObject(String string) throws JSONException {
  72 + JSONObject jo = new JSONObject();
  73 + HTTPTokener x = new HTTPTokener(string);
  74 + String token;
  75 +
  76 + token = x.nextToken();
  77 + if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) {
  78 +
  79 +// Response
  80 +
  81 + jo.put("HTTP-Version", token);
  82 + jo.put("Status-Code", x.nextToken());
  83 + jo.put("Reason-Phrase", x.nextTo('\0'));
  84 + x.next();
  85 +
  86 + } else {
  87 +
  88 +// Request
  89 +
  90 + jo.put("Method", token);
  91 + jo.put("Request-URI", x.nextToken());
  92 + jo.put("HTTP-Version", x.nextToken());
  93 + }
  94 +
  95 +// Fields
  96 +
  97 + while (x.more()) {
  98 + String name = x.nextTo(':');
  99 + x.next(':');
  100 + jo.put(name, x.nextTo('\0'));
  101 + x.next();
  102 + }
  103 + return jo;
  104 + }
  105 +
  106 +
  107 + /**
  108 + * Convert a JSONObject into an HTTP header. A request header must contain
  109 + * <pre>{
  110 + * Method: "POST" (for example),
  111 + * "Request-URI": "/" (for example),
  112 + * "HTTP-Version": "HTTP/1.1" (for example)
  113 + * }</pre>
  114 + * A response header must contain
  115 + * <pre>{
  116 + * "HTTP-Version": "HTTP/1.1" (for example),
  117 + * "Status-Code": "200" (for example),
  118 + * "Reason-Phrase": "OK" (for example)
  119 + * }</pre>
  120 + * Any other members of the JSONObject will be output as HTTP fields.
  121 + * The result will end with two CRLF pairs.
  122 + * @param jo A JSONObject
  123 + * @return An HTTP header string.
  124 + * @throws JSONException if the object does not contain enough
  125 + * information.
  126 + */
  127 + public static String toString(JSONObject jo) throws JSONException {
  128 + StringBuilder sb = new StringBuilder();
  129 + if (jo.has("Status-Code") && jo.has("Reason-Phrase")) {
  130 + sb.append(jo.getString("HTTP-Version"));
  131 + sb.append(' ');
  132 + sb.append(jo.getString("Status-Code"));
  133 + sb.append(' ');
  134 + sb.append(jo.getString("Reason-Phrase"));
  135 + } else if (jo.has("Method") && jo.has("Request-URI")) {
  136 + sb.append(jo.getString("Method"));
  137 + sb.append(' ');
  138 + sb.append('"');
  139 + sb.append(jo.getString("Request-URI"));
  140 + sb.append('"');
  141 + sb.append(' ');
  142 + sb.append(jo.getString("HTTP-Version"));
  143 + } else {
  144 + throw new JSONException("Not enough material for an HTTP header.");
  145 + }
  146 + sb.append(CRLF);
  147 + // Don't use the new entrySet API to maintain Android support
  148 + for (final String key : jo.keySet()) {
  149 + String value = jo.optString(key);
  150 + if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) &&
  151 + !"Reason-Phrase".equals(key) && !"Method".equals(key) &&
  152 + !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) {
  153 + sb.append(key);
  154 + sb.append(": ");
  155 + sb.append(jo.optString(key));
  156 + sb.append(CRLF);
  157 + }
  158 + }
  159 + sb.append(CRLF);
  160 + return sb.toString();
  161 + }
  162 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/HTTPTokener.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 + * The HTTPTokener extends the JSONTokener to provide additional methods
  29 + * for the parsing of HTTP headers.
  30 + * @author JSON.org
  31 + * @version 2015-12-09
  32 + */
  33 +public class HTTPTokener extends JSONTokener {
  34 +
  35 + /**
  36 + * Construct an HTTPTokener from a string.
  37 + * @param string A source string.
  38 + */
  39 + public HTTPTokener(String string) {
  40 + super(string);
  41 + }
  42 +
  43 +
  44 + /**
  45 + * Get the next token or string. This is used in parsing HTTP headers.
  46 + * @throws JSONException
  47 + * @return A String.
  48 + */
  49 + public String nextToken() throws JSONException {
  50 + char c;
  51 + char q;
  52 + StringBuilder sb = new StringBuilder();
  53 + do {
  54 + c = next();
  55 + } while (Character.isWhitespace(c));
  56 + if (c == '"' || c == '\'') {
  57 + q = c;
  58 + for (;;) {
  59 + c = next();
  60 + if (c < ' ') {
  61 + throw syntaxError("Unterminated string.");
  62 + }
  63 + if (c == q) {
  64 + return sb.toString();
  65 + }
  66 + sb.append(c);
  67 + }
  68 + }
  69 + for (;;) {
  70 + if (c == 0 || Character.isWhitespace(c)) {
  71 + return sb.toString();
  72 + }
  73 + sb.append(c);
  74 + c = next();
  75 + }
  76 + }
  77 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/JSONArray.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.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 +import java.io.IOException;
  28 +import java.io.StringWriter;
  29 +import java.io.Writer;
  30 +import java.lang.reflect.Array;
  31 +import java.math.BigDecimal;
  32 +import java.math.BigInteger;
  33 +import java.util.*;
  34 +
  35 +/**
  36 + * A JSONArray is an ordered sequence of values. Its external text form is a
  37 + * string wrapped in square brackets with commas separating the values. The
  38 + * internal form is an object having <code>get</code> and <code>opt</code>
  39 + * methods for accessing the values by index, and <code>put</code> methods for
  40 + * adding or replacing values. The values can be any of these types:
  41 + * <code>Boolean</code>, <code>JSONArray</code>, <code>JSONObject</code>,
  42 + * <code>Number</code>, <code>String</code>, or the
  43 + * <code>JSONObject.NULL object</code>.
  44 + * <p>
  45 + * The constructor can convert a JSON text into a Java object. The
  46 + * <code>toString</code> method converts to JSON text.
  47 + * <p>
  48 + * A <code>get</code> method returns a value if one can be found, and throws an
  49 + * exception if one cannot be found. An <code>opt</code> method returns a
  50 + * default value instead of throwing an exception, and so is useful for
  51 + * obtaining optional values.
  52 + * <p>
  53 + * The generic <code>get()</code> and <code>opt()</code> methods return an
  54 + * object which you can cast or query for type. There are also typed
  55 + * <code>get</code> and <code>opt</code> methods that do type checking and type
  56 + * coercion for you.
  57 + * <p>
  58 + * The texts produced by the <code>toString</code> methods strictly conform to
  59 + * JSON syntax rules. The constructors are more forgiving in the texts they will
  60 + * accept:
  61 + * <ul>
  62 + * <li>An extra <code>,</code>&nbsp;<small>(comma)</small> may appear just
  63 + * before the closing bracket.</li>
  64 + * <li>The <code>null</code> value will be inserted when there is <code>,</code>
  65 + * &nbsp;<small>(comma)</small> elision.</li>
  66 + * <li>Strings may be quoted with <code>'</code>&nbsp;<small>(single
  67 + * quote)</small>.</li>
  68 + * <li>Strings do not need to be quoted at all if they do not begin with a quote
  69 + * or single quote, and if they do not contain leading or trailing spaces, and
  70 + * if they do not contain any of these characters:
  71 + * <code>{ } [ ] / \ : , #</code> and if they do not look like numbers and
  72 + * if they are not the reserved words <code>true</code>, <code>false</code>, or
  73 + * <code>null</code>.</li>
  74 + * </ul>
  75 + *
  76 + * @author JSON.org
  77 + * @version 2016-08/15
  78 + */
  79 +public class JSONArray implements Iterable<Object> {
  80 +
  81 + /**
  82 + * The arrayList where the JSONArray's properties are kept.
  83 + */
  84 + private final ArrayList<Object> myArrayList;
  85 +
  86 + /**
  87 + * Construct an empty JSONArray.
  88 + */
  89 + public JSONArray() {
  90 + this.myArrayList = new ArrayList<Object>();
  91 + }
  92 +
  93 + /**
  94 + * Construct a JSONArray from a JSONTokener.
  95 + *
  96 + * @param x
  97 + * A JSONTokener
  98 + * @throws JSONException
  99 + * If there is a syntax error.
  100 + */
  101 + public JSONArray(JSONTokener x) throws JSONException {
  102 + this();
  103 + if (x.nextClean() != '[') {
  104 + throw x.syntaxError("A JSONArray text must start with '['");
  105 + }
  106 +
  107 + char nextChar = x.nextClean();
  108 + if (nextChar == 0) {
  109 + // array is unclosed. No ']' found, instead EOF
  110 + throw x.syntaxError("Expected a ',' or ']'");
  111 + }
  112 + if (nextChar != ']') {
  113 + x.back();
  114 + for (;;) {
  115 + if (x.nextClean() == ',') {
  116 + x.back();
  117 + this.myArrayList.add(JSONObject.NULL);
  118 + } else {
  119 + x.back();
  120 + this.myArrayList.add(x.nextValue());
  121 + }
  122 + switch (x.nextClean()) {
  123 + case 0:
  124 + // array is unclosed. No ']' found, instead EOF
  125 + throw x.syntaxError("Expected a ',' or ']'");
  126 + case ',':
  127 + nextChar = x.nextClean();
  128 + if (nextChar == 0) {
  129 + // array is unclosed. No ']' found, instead EOF
  130 + throw x.syntaxError("Expected a ',' or ']'");
  131 + }
  132 + if (nextChar == ']') {
  133 + return;
  134 + }
  135 + x.back();
  136 + break;
  137 + case ']':
  138 + return;
  139 + default:
  140 + throw x.syntaxError("Expected a ',' or ']'");
  141 + }
  142 + }
  143 + }
  144 + }
  145 +
  146 + /**
  147 + * Construct a JSONArray from a source JSON text.
  148 + *
  149 + * @param source
  150 + * A string that begins with <code>[</code>&nbsp;<small>(left
  151 + * bracket)</small> and ends with <code>]</code>
  152 + * &nbsp;<small>(right bracket)</small>.
  153 + * @throws JSONException
  154 + * If there is a syntax error.
  155 + */
  156 + public JSONArray(String source) throws JSONException {
  157 + this(new JSONTokener(source));
  158 + }
  159 +
  160 + /**
  161 + * Construct a JSONArray from a Collection.
  162 + *
  163 + * @param collection
  164 + * A Collection.
  165 + */
  166 + public JSONArray(Collection<?> collection) {
  167 + if (collection == null) {
  168 + this.myArrayList = new ArrayList<Object>();
  169 + } else {
  170 + this.myArrayList = new ArrayList<Object>(collection.size());
  171 + for (Object o: collection){
  172 + this.myArrayList.add(JSONObject.wrap(o));
  173 + }
  174 + }
  175 + }
  176 +
  177 + /**
  178 + * Construct a JSONArray from an array
  179 + *
  180 + * @throws JSONException
  181 + * If not an array.
  182 + */
  183 + public JSONArray(Object array) throws JSONException {
  184 + this();
  185 + if (array.getClass().isArray()) {
  186 + int length = Array.getLength(array);
  187 + this.myArrayList.ensureCapacity(length);
  188 + for (int i = 0; i < length; i += 1) {
  189 + this.put(JSONObject.wrap(Array.get(array, i)));
  190 + }
  191 + } else {
  192 + throw new JSONException(
  193 + "JSONArray initial value should be a string or collection or array.");
  194 + }
  195 + }
  196 +
  197 + @Override
  198 + public Iterator<Object> iterator() {
  199 + return this.myArrayList.iterator();
  200 + }
  201 +
  202 + /**
  203 + * Get the object value associated with an index.
  204 + *
  205 + * @param index
  206 + * The index must be between 0 and length() - 1.
  207 + * @return An object value.
  208 + * @throws JSONException
  209 + * If there is no value for the index.
  210 + */
  211 + public Object get(int index) throws JSONException {
  212 + Object object = this.opt(index);
  213 + if (object == null) {
  214 + throw new JSONException("JSONArray[" + index + "] not found.");
  215 + }
  216 + return object;
  217 + }
  218 +
  219 + /**
  220 + * Get the boolean value associated with an index. The string values "true"
  221 + * and "false" are converted to boolean.
  222 + *
  223 + * @param index
  224 + * The index must be between 0 and length() - 1.
  225 + * @return The truth.
  226 + * @throws JSONException
  227 + * If there is no value for the index or if the value is not
  228 + * convertible to boolean.
  229 + */
  230 + public boolean getBoolean(int index) throws JSONException {
  231 + Object object = this.get(index);
  232 + if (object.equals(Boolean.FALSE)
  233 + || (object instanceof String && ((String) object)
  234 + .equalsIgnoreCase("false"))) {
  235 + return false;
  236 + } else if (object.equals(Boolean.TRUE)
  237 + || (object instanceof String && ((String) object)
  238 + .equalsIgnoreCase("true"))) {
  239 + return true;
  240 + }
  241 + throw new JSONException("JSONArray[" + index + "] is not a boolean.");
  242 + }
  243 +
  244 + /**
  245 + * Get the double value associated with an index.
  246 + *
  247 + * @param index
  248 + * The index must be between 0 and length() - 1.
  249 + * @return The value.
  250 + * @throws JSONException
  251 + * If the key is not found or if the value cannot be converted
  252 + * to a number.
  253 + */
  254 + public double getDouble(int index) throws JSONException {
  255 + Object object = this.get(index);
  256 + try {
  257 + return object instanceof Number ? ((Number) object).doubleValue()
  258 + : Double.parseDouble((String) object);
  259 + } catch (Exception e) {
  260 + throw new JSONException("JSONArray[" + index + "] is not a number.", e);
  261 + }
  262 + }
  263 +
  264 + /**
  265 + * Get the float value associated with a key.
  266 + *
  267 + * @param index
  268 + * The index must be between 0 and length() - 1.
  269 + * @return The numeric value.
  270 + * @throws JSONException
  271 + * if the key is not found or if the value is not a Number
  272 + * object and cannot be converted to a number.
  273 + */
  274 + public float getFloat(int index) throws JSONException {
  275 + Object object = this.get(index);
  276 + try {
  277 + return object instanceof Number ? ((Number) object).floatValue()
  278 + : Float.parseFloat(object.toString());
  279 + } catch (Exception e) {
  280 + throw new JSONException("JSONArray[" + index
  281 + + "] is not a number.", e);
  282 + }
  283 + }
  284 +
  285 + /**
  286 + * Get the Number value associated with a key.
  287 + *
  288 + * @param index
  289 + * The index must be between 0 and length() - 1.
  290 + * @return The numeric value.
  291 + * @throws JSONException
  292 + * if the key is not found or if the value is not a Number
  293 + * object and cannot be converted to a number.
  294 + */
  295 + public Number getNumber(int index) throws JSONException {
  296 + Object object = this.get(index);
  297 + try {
  298 + if (object instanceof Number) {
  299 + return (Number)object;
  300 + }
  301 + return JSONObject.stringToNumber(object.toString());
  302 + } catch (Exception e) {
  303 + throw new JSONException("JSONArray[" + index + "] is not a number.", e);
  304 + }
  305 + }
  306 +
  307 + /**
  308 + * Get the enum value associated with an index.
  309 + *
  310 + * @param clazz
  311 + * The type of enum to retrieve.
  312 + * @param index
  313 + * The index must be between 0 and length() - 1.
  314 + * @return The enum value at the index location
  315 + * @throws JSONException
  316 + * if the key is not found or if the value cannot be converted
  317 + * to an enum.
  318 + */
  319 + public <E extends Enum<E>> E getEnum(Class<E> clazz, int index) throws JSONException {
  320 + E val = optEnum(clazz, index);
  321 + if(val==null) {
  322 + // JSONException should really take a throwable argument.
  323 + // If it did, I would re-implement this with the Enum.valueOf
  324 + // method and place any thrown exception in the JSONException
  325 + throw new JSONException("JSONArray[" + index + "] is not an enum of type "
  326 + + JSONObject.quote(clazz.getSimpleName()) + ".");
  327 + }
  328 + return val;
  329 + }
  330 +
  331 + /**
  332 + * Get the BigDecimal value associated with an index.
  333 + *
  334 + * @param index
  335 + * The index must be between 0 and length() - 1.
  336 + * @return The value.
  337 + * @throws JSONException
  338 + * If the key is not found or if the value cannot be converted
  339 + * to a BigDecimal.
  340 + */
  341 + public BigDecimal getBigDecimal (int index) throws JSONException {
  342 + Object object = this.get(index);
  343 + try {
  344 + return new BigDecimal(object.toString());
  345 + } catch (Exception e) {
  346 + throw new JSONException("JSONArray[" + index +
  347 + "] could not convert to BigDecimal.", e);
  348 + }
  349 + }
  350 +
  351 + /**
  352 + * Get the BigInteger value associated with an index.
  353 + *
  354 + * @param index
  355 + * The index must be between 0 and length() - 1.
  356 + * @return The value.
  357 + * @throws JSONException
  358 + * If the key is not found or if the value cannot be converted
  359 + * to a BigInteger.
  360 + */
  361 + public BigInteger getBigInteger (int index) throws JSONException {
  362 + Object object = this.get(index);
  363 + try {
  364 + return new BigInteger(object.toString());
  365 + } catch (Exception e) {
  366 + throw new JSONException("JSONArray[" + index +
  367 + "] could not convert to BigInteger.", e);
  368 + }
  369 + }
  370 +
  371 + /**
  372 + * Get the int value associated with an index.
  373 + *
  374 + * @param index
  375 + * The index must be between 0 and length() - 1.
  376 + * @return The value.
  377 + * @throws JSONException
  378 + * If the key is not found or if the value is not a number.
  379 + */
  380 + public int getInt(int index) throws JSONException {
  381 + Object object = this.get(index);
  382 + try {
  383 + return object instanceof Number ? ((Number) object).intValue()
  384 + : Integer.parseInt((String) object);
  385 + } catch (Exception e) {
  386 + throw new JSONException("JSONArray[" + index + "] is not a number.", e);
  387 + }
  388 + }
  389 +
  390 + /**
  391 + * Get the JSONArray associated with an index.
  392 + *
  393 + * @param index
  394 + * The index must be between 0 and length() - 1.
  395 + * @return A JSONArray value.
  396 + * @throws JSONException
  397 + * If there is no value for the index. or if the value is not a
  398 + * JSONArray
  399 + */
  400 + public JSONArray getJSONArray(int index) throws JSONException {
  401 + Object object = this.get(index);
  402 + if (object instanceof JSONArray) {
  403 + return (JSONArray) object;
  404 + }
  405 + throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
  406 + }
  407 +
  408 + /**
  409 + * Get the JSONObject associated with an index.
  410 + *
  411 + * @param index
  412 + * subscript
  413 + * @return A JSONObject value.
  414 + * @throws JSONException
  415 + * If there is no value for the index or if the value is not a
  416 + * JSONObject
  417 + */
  418 + public JSONObject getJSONObject(int index) throws JSONException {
  419 + Object object = this.get(index);
  420 + if (object instanceof JSONObject) {
  421 + return (JSONObject) object;
  422 + }
  423 + throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
  424 + }
  425 +
  426 + /**
  427 + * Get the long value associated with an index.
  428 + *
  429 + * @param index
  430 + * The index must be between 0 and length() - 1.
  431 + * @return The value.
  432 + * @throws JSONException
  433 + * If the key is not found or if the value cannot be converted
  434 + * to a number.
  435 + */
  436 + public long getLong(int index) throws JSONException {
  437 + Object object = this.get(index);
  438 + try {
  439 + return object instanceof Number ? ((Number) object).longValue()
  440 + : Long.parseLong((String) object);
  441 + } catch (Exception e) {
  442 + throw new JSONException("JSONArray[" + index + "] is not a number.", e);
  443 + }
  444 + }
  445 +
  446 + /**
  447 + * Get the string associated with an index.
  448 + *
  449 + * @param index
  450 + * The index must be between 0 and length() - 1.
  451 + * @return A string value.
  452 + * @throws JSONException
  453 + * If there is no string value for the index.
  454 + */
  455 + public String getString(int index) throws JSONException {
  456 + Object object = this.get(index);
  457 + if (object instanceof String) {
  458 + return (String) object;
  459 + }
  460 + throw new JSONException("JSONArray[" + index + "] not a string.");
  461 + }
  462 +
  463 + /**
  464 + * Determine if the value is null.
  465 + *
  466 + * @param index
  467 + * The index must be between 0 and length() - 1.
  468 + * @return true if the value at the index is null, or if there is no value.
  469 + */
  470 + public boolean isNull(int index) {
  471 + return JSONObject.NULL.equals(this.opt(index));
  472 + }
  473 +
  474 + /**
  475 + * Make a string from the contents of this JSONArray. The
  476 + * <code>separator</code> string is inserted between each element. Warning:
  477 + * This method assumes that the data structure is acyclical.
  478 + *
  479 + * @param separator
  480 + * A string that will be inserted between the elements.
  481 + * @return a string.
  482 + * @throws JSONException
  483 + * If the array contains an invalid number.
  484 + */
  485 + public String join(String separator) throws JSONException {
  486 + int len = this.length();
  487 + StringBuilder sb = new StringBuilder();
  488 +
  489 + for (int i = 0; i < len; i += 1) {
  490 + if (i > 0) {
  491 + sb.append(separator);
  492 + }
  493 + sb.append(JSONObject.valueToString(this.myArrayList.get(i)));
  494 + }
  495 + return sb.toString();
  496 + }
  497 +
  498 + /**
  499 + * Get the number of elements in the JSONArray, included nulls.
  500 + *
  501 + * @return The length (or size).
  502 + */
  503 + public int length() {
  504 + return this.myArrayList.size();
  505 + }
  506 +
  507 + /**
  508 + * Get the optional object value associated with an index.
  509 + *
  510 + * @param index
  511 + * The index must be between 0 and length() - 1. If not, null is returned.
  512 + * @return An object value, or null if there is no object at that index.
  513 + */
  514 + public Object opt(int index) {
  515 + return (index < 0 || index >= this.length()) ? null : this.myArrayList
  516 + .get(index);
  517 + }
  518 +
  519 + /**
  520 + * Get the optional boolean value associated with an index. It returns false
  521 + * if there is no value at that index, or if the value is not Boolean.TRUE
  522 + * or the String "true".
  523 + *
  524 + * @param index
  525 + * The index must be between 0 and length() - 1.
  526 + * @return The truth.
  527 + */
  528 + public boolean optBoolean(int index) {
  529 + return this.optBoolean(index, false);
  530 + }
  531 +
  532 + /**
  533 + * Get the optional boolean value associated with an index. It returns the
  534 + * defaultValue if there is no value at that index or if it is not a Boolean
  535 + * or the String "true" or "false" (case insensitive).
  536 + *
  537 + * @param index
  538 + * The index must be between 0 and length() - 1.
  539 + * @param defaultValue
  540 + * A boolean default.
  541 + * @return The truth.
  542 + */
  543 + public boolean optBoolean(int index, boolean defaultValue) {
  544 + try {
  545 + return this.getBoolean(index);
  546 + } catch (Exception e) {
  547 + return defaultValue;
  548 + }
  549 + }
  550 +
  551 + /**
  552 + * Get the optional double value associated with an index. NaN is returned
  553 + * if there is no value for the index, or if the value is not a number and
  554 + * cannot be converted to a number.
  555 + *
  556 + * @param index
  557 + * The index must be between 0 and length() - 1.
  558 + * @return The value.
  559 + */
  560 + public double optDouble(int index) {
  561 + return this.optDouble(index, Double.NaN);
  562 + }
  563 +
  564 + /**
  565 + * Get the optional double value associated with an index. The defaultValue
  566 + * is returned if there is no value for the index, or if the value is not a
  567 + * number and cannot be converted to a number.
  568 + *
  569 + * @param index
  570 + * subscript
  571 + * @param defaultValue
  572 + * The default value.
  573 + * @return The value.
  574 + */
  575 + public double optDouble(int index, double defaultValue) {
  576 + Object val = this.opt(index);
  577 + if (JSONObject.NULL.equals(val)) {
  578 + return defaultValue;
  579 + }
  580 + if (val instanceof Number){
  581 + return ((Number) val).doubleValue();
  582 + }
  583 + if (val instanceof String) {
  584 + try {
  585 + return Double.parseDouble((String) val);
  586 + } catch (Exception e) {
  587 + return defaultValue;
  588 + }
  589 + }
  590 + return defaultValue;
  591 + }
  592 +
  593 + /**
  594 + * Get the optional float value associated with an index. NaN is returned
  595 + * if there is no value for the index, or if the value is not a number and
  596 + * cannot be converted to a number.
  597 + *
  598 + * @param index
  599 + * The index must be between 0 and length() - 1.
  600 + * @return The value.
  601 + */
  602 + public float optFloat(int index) {
  603 + return this.optFloat(index, Float.NaN);
  604 + }
  605 +
  606 + /**
  607 + * Get the optional float value associated with an index. The defaultValue
  608 + * is returned if there is no value for the index, or if the value is not a
  609 + * number and cannot be converted to a number.
  610 + *
  611 + * @param index
  612 + * subscript
  613 + * @param defaultValue
  614 + * The default value.
  615 + * @return The value.
  616 + */
  617 + public float optFloat(int index, float defaultValue) {
  618 + Object val = this.opt(index);
  619 + if (JSONObject.NULL.equals(val)) {
  620 + return defaultValue;
  621 + }
  622 + if (val instanceof Number){
  623 + return ((Number) val).floatValue();
  624 + }
  625 + if (val instanceof String) {
  626 + try {
  627 + return Float.parseFloat((String) val);
  628 + } catch (Exception e) {
  629 + return defaultValue;
  630 + }
  631 + }
  632 + return defaultValue;
  633 + }
  634 +
  635 + /**
  636 + * Get the optional int value associated with an index. Zero is returned if
  637 + * there is no value for the index, or if the value is not a number and
  638 + * cannot be converted to a number.
  639 + *
  640 + * @param index
  641 + * The index must be between 0 and length() - 1.
  642 + * @return The value.
  643 + */
  644 + public int optInt(int index) {
  645 + return this.optInt(index, 0);
  646 + }
  647 +
  648 + /**
  649 + * Get the optional int value associated with an index. The defaultValue is
  650 + * returned if there is no value for the index, or if the value is not a
  651 + * number and cannot be converted to a number.
  652 + *
  653 + * @param index
  654 + * The index must be between 0 and length() - 1.
  655 + * @param defaultValue
  656 + * The default value.
  657 + * @return The value.
  658 + */
  659 + public int optInt(int index, int defaultValue) {
  660 + Object val = this.opt(index);
  661 + if (JSONObject.NULL.equals(val)) {
  662 + return defaultValue;
  663 + }
  664 + if (val instanceof Number){
  665 + return ((Number) val).intValue();
  666 + }
  667 +
  668 + if (val instanceof String) {
  669 + try {
  670 + return new BigDecimal(val.toString()).intValue();
  671 + } catch (Exception e) {
  672 + return defaultValue;
  673 + }
  674 + }
  675 + return defaultValue;
  676 + }
  677 +
  678 + /**
  679 + * Get the enum value associated with a key.
  680 + *
  681 + * @param clazz
  682 + * The type of enum to retrieve.
  683 + * @param index
  684 + * The index must be between 0 and length() - 1.
  685 + * @return The enum value at the index location or null if not found
  686 + */
  687 + public <E extends Enum<E>> E optEnum(Class<E> clazz, int index) {
  688 + return this.optEnum(clazz, index, null);
  689 + }
  690 +
  691 + /**
  692 + * Get the enum value associated with a key.
  693 + *
  694 + * @param clazz
  695 + * The type of enum to retrieve.
  696 + * @param index
  697 + * The index must be between 0 and length() - 1.
  698 + * @param defaultValue
  699 + * The default in case the value is not found
  700 + * @return The enum value at the index location or defaultValue if
  701 + * the value is not found or cannot be assigned to clazz
  702 + */
  703 + public <E extends Enum<E>> E optEnum(Class<E> clazz, int index, E defaultValue) {
  704 + try {
  705 + Object val = this.opt(index);
  706 + if (JSONObject.NULL.equals(val)) {
  707 + return defaultValue;
  708 + }
  709 + if (clazz.isAssignableFrom(val.getClass())) {
  710 + // we just checked it!
  711 + @SuppressWarnings("unchecked")
  712 + E myE = (E) val;
  713 + return myE;
  714 + }
  715 + return Enum.valueOf(clazz, val.toString());
  716 + } catch (IllegalArgumentException e) {
  717 + return defaultValue;
  718 + } catch (NullPointerException e) {
  719 + return defaultValue;
  720 + }
  721 + }
  722 +
  723 +
  724 + /**
  725 + * Get the optional BigInteger value associated with an index. The
  726 + * defaultValue is returned if there is no value for the index, or if the
  727 + * value is not a number and cannot be converted to a number.
  728 + *
  729 + * @param index
  730 + * The index must be between 0 and length() - 1.
  731 + * @param defaultValue
  732 + * The default value.
  733 + * @return The value.
  734 + */
  735 + public BigInteger optBigInteger(int index, BigInteger defaultValue) {
  736 + Object val = this.opt(index);
  737 + if (JSONObject.NULL.equals(val)) {
  738 + return defaultValue;
  739 + }
  740 + if (val instanceof BigInteger){
  741 + return (BigInteger) val;
  742 + }
  743 + if (val instanceof BigDecimal){
  744 + return ((BigDecimal) val).toBigInteger();
  745 + }
  746 + if (val instanceof Double || val instanceof Float){
  747 + return new BigDecimal(((Number) val).doubleValue()).toBigInteger();
  748 + }
  749 + if (val instanceof Long || val instanceof Integer
  750 + || val instanceof Short || val instanceof Byte){
  751 + return BigInteger.valueOf(((Number) val).longValue());
  752 + }
  753 + try {
  754 + final String valStr = val.toString();
  755 + if(JSONObject.isDecimalNotation(valStr)) {
  756 + return new BigDecimal(valStr).toBigInteger();
  757 + }
  758 + return new BigInteger(valStr);
  759 + } catch (Exception e) {
  760 + return defaultValue;
  761 + }
  762 + }
  763 +
  764 + /**
  765 + * Get the optional BigDecimal value associated with an index. The
  766 + * defaultValue is returned if there is no value for the index, or if the
  767 + * value is not a number and cannot be converted to a number.
  768 + *
  769 + * @param index
  770 + * The index must be between 0 and length() - 1.
  771 + * @param defaultValue
  772 + * The default value.
  773 + * @return The value.
  774 + */
  775 + public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) {
  776 + Object val = this.opt(index);
  777 + if (JSONObject.NULL.equals(val)) {
  778 + return defaultValue;
  779 + }
  780 + if (val instanceof BigDecimal){
  781 + return (BigDecimal) val;
  782 + }
  783 + if (val instanceof BigInteger){
  784 + return new BigDecimal((BigInteger) val);
  785 + }
  786 + if (val instanceof Double || val instanceof Float){
  787 + return new BigDecimal(((Number) val).doubleValue());
  788 + }
  789 + if (val instanceof Long || val instanceof Integer
  790 + || val instanceof Short || val instanceof Byte){
  791 + return new BigDecimal(((Number) val).longValue());
  792 + }
  793 + try {
  794 + return new BigDecimal(val.toString());
  795 + } catch (Exception e) {
  796 + return defaultValue;
  797 + }
  798 + }
  799 +
  800 + /**
  801 + * Get the optional JSONArray associated with an index.
  802 + *
  803 + * @param index
  804 + * subscript
  805 + * @return A JSONArray value, or null if the index has no value, or if the
  806 + * value is not a JSONArray.
  807 + */
  808 + public JSONArray optJSONArray(int index) {
  809 + Object o = this.opt(index);
  810 + return o instanceof JSONArray ? (JSONArray) o : null;
  811 + }
  812 +
  813 + /**
  814 + * Get the optional JSONObject associated with an index. Null is returned if
  815 + * the key is not found, or null if the index has no value, or if the value
  816 + * is not a JSONObject.
  817 + *
  818 + * @param index
  819 + * The index must be between 0 and length() - 1.
  820 + * @return A JSONObject value.
  821 + */
  822 + public JSONObject optJSONObject(int index) {
  823 + Object o = this.opt(index);
  824 + return o instanceof JSONObject ? (JSONObject) o : null;
  825 + }
  826 +
  827 + /**
  828 + * Get the optional long value associated with an index. Zero is returned if
  829 + * there is no value for the index, or if the value is not a number and
  830 + * cannot be converted to a number.
  831 + *
  832 + * @param index
  833 + * The index must be between 0 and length() - 1.
  834 + * @return The value.
  835 + */
  836 + public long optLong(int index) {
  837 + return this.optLong(index, 0);
  838 + }
  839 +
  840 + /**
  841 + * Get the optional long value associated with an index. The defaultValue is
  842 + * returned if there is no value for the index, or if the value is not a
  843 + * number and cannot be converted to a number.
  844 + *
  845 + * @param index
  846 + * The index must be between 0 and length() - 1.
  847 + * @param defaultValue
  848 + * The default value.
  849 + * @return The value.
  850 + */
  851 + public long optLong(int index, long defaultValue) {
  852 + Object val = this.opt(index);
  853 + if (JSONObject.NULL.equals(val)) {
  854 + return defaultValue;
  855 + }
  856 + if (val instanceof Number){
  857 + return ((Number) val).longValue();
  858 + }
  859 +
  860 + if (val instanceof String) {
  861 + try {
  862 + return new BigDecimal(val.toString()).longValue();
  863 + } catch (Exception e) {
  864 + return defaultValue;
  865 + }
  866 + }
  867 + return defaultValue;
  868 + }
  869 +
  870 + /**
  871 + * Get an optional {@link Number} value associated with a key, or <code>null</code>
  872 + * if there is no such key or if the value is not a number. If the value is a string,
  873 + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method
  874 + * would be used in cases where type coercion of the number value is unwanted.
  875 + *
  876 + * @param index
  877 + * The index must be between 0 and length() - 1.
  878 + * @return An object which is the value.
  879 + */
  880 + public Number optNumber(int index) {
  881 + return this.optNumber(index, null);
  882 + }
  883 +
  884 + /**
  885 + * Get an optional {@link Number} value associated with a key, or the default if there
  886 + * is no such key or if the value is not a number. If the value is a string,
  887 + * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method
  888 + * would be used in cases where type coercion of the number value is unwanted.
  889 + *
  890 + * @param index
  891 + * The index must be between 0 and length() - 1.
  892 + * @param defaultValue
  893 + * The default.
  894 + * @return An object which is the value.
  895 + */
  896 + public Number optNumber(int index, Number defaultValue) {
  897 + Object val = this.opt(index);
  898 + if (JSONObject.NULL.equals(val)) {
  899 + return defaultValue;
  900 + }
  901 + if (val instanceof Number){
  902 + return (Number) val;
  903 + }
  904 +
  905 + if (val instanceof String) {
  906 + try {
  907 + return JSONObject.stringToNumber((String) val);
  908 + } catch (Exception e) {
  909 + return defaultValue;
  910 + }
  911 + }
  912 + return defaultValue;
  913 + }
  914 +
  915 + /**
  916 + * Get the optional string value associated with an index. It returns an
  917 + * empty string if there is no value at that index. If the value is not a
  918 + * string and is not null, then it is converted to a string.
  919 + *
  920 + * @param index
  921 + * The index must be between 0 and length() - 1.
  922 + * @return A String value.
  923 + */
  924 + public String optString(int index) {
  925 + return this.optString(index, "");
  926 + }
  927 +
  928 + /**
  929 + * Get the optional string associated with an index. The defaultValue is
  930 + * returned if the key is not found.
  931 + *
  932 + * @param index
  933 + * The index must be between 0 and length() - 1.
  934 + * @param defaultValue
  935 + * The default value.
  936 + * @return A String value.
  937 + */
  938 + public String optString(int index, String defaultValue) {
  939 + Object object = this.opt(index);
  940 + return JSONObject.NULL.equals(object) ? defaultValue : object
  941 + .toString();
  942 + }
  943 +
  944 + /**
  945 + * Append a boolean value. This increases the array's length by one.
  946 + *
  947 + * @param value
  948 + * A boolean value.
  949 + * @return this.
  950 + */
  951 + public JSONArray put(boolean value) {
  952 + this.put(value ? Boolean.TRUE : Boolean.FALSE);
  953 + return this;
  954 + }
  955 +
  956 + /**
  957 + * Put a value in the JSONArray, where the value will be a JSONArray which
  958 + * is produced from a Collection.
  959 + *
  960 + * @param value
  961 + * A Collection value.
  962 + * @return this.
  963 + */
  964 + public JSONArray put(Collection<?> value) {
  965 + this.put(new JSONArray(value));
  966 + return this;
  967 + }
  968 +
  969 + /**
  970 + * Append a double value. This increases the array's length by one.
  971 + *
  972 + * @param value
  973 + * A double value.
  974 + * @throws JSONException
  975 + * if the value is not finite.
  976 + * @return this.
  977 + */
  978 + public JSONArray put(double value) throws JSONException {
  979 + Double d = new Double(value);
  980 + JSONObject.testValidity(d);
  981 + this.put(d);
  982 + return this;
  983 + }
  984 +
  985 + /**
  986 + * Append an int value. This increases the array's length by one.
  987 + *
  988 + * @param value
  989 + * An int value.
  990 + * @return this.
  991 + */
  992 + public JSONArray put(int value) {
  993 + this.put(new Integer(value));
  994 + return this;
  995 + }
  996 +
  997 + /**
  998 + * Append an long value. This increases the array's length by one.
  999 + *
  1000 + * @param value
  1001 + * A long value.
  1002 + * @return this.
  1003 + */
  1004 + public JSONArray put(long value) {
  1005 + this.put(new Long(value));
  1006 + return this;
  1007 + }
  1008 +
  1009 + /**
  1010 + * Put a value in the JSONArray, where the value will be a JSONObject which
  1011 + * is produced from a Map.
  1012 + *
  1013 + * @param value
  1014 + * A Map value.
  1015 + * @return this.
  1016 + */
  1017 + public JSONArray put(Map<?, ?> value) {
  1018 + this.put(new JSONObject(value));
  1019 + return this;
  1020 + }
  1021 +
  1022 + /**
  1023 + * Append an object value. This increases the array's length by one.
  1024 + *
  1025 + * @param value
  1026 + * An object value. The value should be a Boolean, Double,
  1027 + * Integer, JSONArray, JSONObject, Long, or String, or the
  1028 + * JSONObject.NULL object.
  1029 + * @return this.
  1030 + */
  1031 + public JSONArray put(Object value) {
  1032 + this.myArrayList.add(value);
  1033 + return this;
  1034 + }
  1035 +
  1036 + /**
  1037 + * Put or replace a boolean value in the JSONArray. If the index is greater
  1038 + * than the length of the JSONArray, then null elements will be added as
  1039 + * necessary to pad it out.
  1040 + *
  1041 + * @param index
  1042 + * The subscript.
  1043 + * @param value
  1044 + * A boolean value.
  1045 + * @return this.
  1046 + * @throws JSONException
  1047 + * If the index is negative.
  1048 + */
  1049 + public JSONArray put(int index, boolean value) throws JSONException {
  1050 + this.put(index, value ? Boolean.TRUE : Boolean.FALSE);
  1051 + return this;
  1052 + }
  1053 +
  1054 + /**
  1055 + * Put a value in the JSONArray, where the value will be a JSONArray which
  1056 + * is produced from a Collection.
  1057 + *
  1058 + * @param index
  1059 + * The subscript.
  1060 + * @param value
  1061 + * A Collection value.
  1062 + * @return this.
  1063 + * @throws JSONException
  1064 + * If the index is negative or if the value is not finite.
  1065 + */
  1066 + public JSONArray put(int index, Collection<?> value) throws JSONException {
  1067 + this.put(index, new JSONArray(value));
  1068 + return this;
  1069 + }
  1070 +
  1071 + /**
  1072 + * Put or replace a double value. If the index is greater than the length of
  1073 + * the JSONArray, then null elements will be added as necessary to pad it
  1074 + * out.
  1075 + *
  1076 + * @param index
  1077 + * The subscript.
  1078 + * @param value
  1079 + * A double value.
  1080 + * @return this.
  1081 + * @throws JSONException
  1082 + * If the index is negative or if the value is not finite.
  1083 + */
  1084 + public JSONArray put(int index, double value) throws JSONException {
  1085 + this.put(index, new Double(value));
  1086 + return this;
  1087 + }
  1088 +
  1089 + /**
  1090 + * Put or replace an int value. If the index is greater than the length of
  1091 + * the JSONArray, then null elements will be added as necessary to pad it
  1092 + * out.
  1093 + *
  1094 + * @param index
  1095 + * The subscript.
  1096 + * @param value
  1097 + * An int value.
  1098 + * @return this.
  1099 + * @throws JSONException
  1100 + * If the index is negative.
  1101 + */
  1102 + public JSONArray put(int index, int value) throws JSONException {
  1103 + this.put(index, new Integer(value));
  1104 + return this;
  1105 + }
  1106 +
  1107 + /**
  1108 + * Put or replace a long value. If the index is greater than the length of
  1109 + * the JSONArray, then null elements will be added as necessary to pad it
  1110 + * out.
  1111 + *
  1112 + * @param index
  1113 + * The subscript.
  1114 + * @param value
  1115 + * A long value.
  1116 + * @return this.
  1117 + * @throws JSONException
  1118 + * If the index is negative.
  1119 + */
  1120 + public JSONArray put(int index, long value) throws JSONException {
  1121 + this.put(index, new Long(value));
  1122 + return this;
  1123 + }
  1124 +
  1125 + /**
  1126 + * Put a value in the JSONArray, where the value will be a JSONObject that
  1127 + * is produced from a Map.
  1128 + *
  1129 + * @param index
  1130 + * The subscript.
  1131 + * @param value
  1132 + * The Map value.
  1133 + * @return this.
  1134 + * @throws JSONException
  1135 + * If the index is negative or if the the value is an invalid
  1136 + * number.
  1137 + */
  1138 + public JSONArray put(int index, Map<?, ?> value) throws JSONException {
  1139 + this.put(index, new JSONObject(value));
  1140 + return this;
  1141 + }
  1142 +
  1143 + /**
  1144 + * Put or replace an object value in the JSONArray. If the index is greater
  1145 + * than the length of the JSONArray, then null elements will be added as
  1146 + * necessary to pad it out.
  1147 + *
  1148 + * @param index
  1149 + * The subscript.
  1150 + * @param value
  1151 + * The value to put into the array. The value should be a
  1152 + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or
  1153 + * String, or the JSONObject.NULL object.
  1154 + * @return this.
  1155 + * @throws JSONException
  1156 + * If the index is negative or if the the value is an invalid
  1157 + * number.
  1158 + */
  1159 + public JSONArray put(int index, Object value) throws JSONException {
  1160 + JSONObject.testValidity(value);
  1161 + if (index < 0) {
  1162 + throw new JSONException("JSONArray[" + index + "] not found.");
  1163 + }
  1164 + if (index < this.length()) {
  1165 + this.myArrayList.set(index, value);
  1166 + } else if(index == this.length()){
  1167 + // simple append
  1168 + this.put(value);
  1169 + } else {
  1170 + // if we are inserting past the length, we want to grow the array all at once
  1171 + // instead of incrementally.
  1172 + this.myArrayList.ensureCapacity(index + 1);
  1173 + while (index != this.length()) {
  1174 + this.put(JSONObject.NULL);
  1175 + }
  1176 + this.put(value);
  1177 + }
  1178 + return this;
  1179 + }
  1180 +
  1181 + /**
  1182 + * Creates a JSONPointer using an initialization string and tries to
  1183 + * match it to an item within this JSONArray. For example, given a
  1184 + * JSONArray initialized with this document:
  1185 + * <pre>
  1186 + * [
  1187 + * {"b":"c"}
  1188 + * ]
  1189 + * </pre>
  1190 + * and this JSONPointer string:
  1191 + * <pre>
  1192 + * "/0/b"
  1193 + * </pre>
  1194 + * Then this method will return the String "c"
  1195 + * A JSONPointerException may be thrown from code called by this method.
  1196 + *
  1197 + * @param jsonPointer string that can be used to create a JSONPointer
  1198 + * @return the item matched by the JSONPointer, otherwise null
  1199 + */
  1200 + public Object query(String jsonPointer) {
  1201 + return query(new JSONPointer(jsonPointer));
  1202 + }
  1203 +
  1204 + /**
  1205 + * Uses a uaer initialized JSONPointer and tries to
  1206 + * match it to an item whithin this JSONArray. For example, given a
  1207 + * JSONArray initialized with this document:
  1208 + * <pre>
  1209 + * [
  1210 + * {"b":"c"}
  1211 + * ]
  1212 + * </pre>
  1213 + * and this JSONPointer:
  1214 + * <pre>
  1215 + * "/0/b"
  1216 + * </pre>
  1217 + * Then this method will return the String "c"
  1218 + * A JSONPointerException may be thrown from code called by this method.
  1219 + *
  1220 + * @param jsonPointer string that can be used to create a JSONPointer
  1221 + * @return the item matched by the JSONPointer, otherwise null
  1222 + */
  1223 + public Object query(JSONPointer jsonPointer) {
  1224 + return jsonPointer.queryFrom(this);
  1225 + }
  1226 +
  1227 + /**
  1228 + * Queries and returns a value from this object using {@code jsonPointer}, or
  1229 + * returns null if the query fails due to a missing key.
  1230 + *
  1231 + * @param jsonPointer the string representation of the JSON pointer
  1232 + * @return the queried value or {@code null}
  1233 + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
  1234 + */
  1235 + public Object optQuery(String jsonPointer) {
  1236 + return optQuery(new JSONPointer(jsonPointer));
  1237 + }
  1238 +
  1239 + /**
  1240 + * Queries and returns a value from this object using {@code jsonPointer}, or
  1241 + * returns null if the query fails due to a missing key.
  1242 + *
  1243 + * @param jsonPointer The JSON pointer
  1244 + * @return the queried value or {@code null}
  1245 + * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax
  1246 + */
  1247 + public Object optQuery(JSONPointer jsonPointer) {
  1248 + try {
  1249 + return jsonPointer.queryFrom(this);
  1250 + } catch (JSONPointerException e) {
  1251 + return null;
  1252 + }
  1253 + }
  1254 +
  1255 + /**
  1256 + * Remove an index and close the hole.
  1257 + *
  1258 + * @param index
  1259 + * The index of the element to be removed.
  1260 + * @return The value that was associated with the index, or null if there
  1261 + * was no value.
  1262 + */
  1263 + public Object remove(int index) {
  1264 + return index >= 0 && index < this.length()
  1265 + ? this.myArrayList.remove(index)
  1266 + : null;
  1267 + }
  1268 +
  1269 + /**
  1270 + * Determine if two JSONArrays are similar.
  1271 + * They must contain similar sequences.
  1272 + *
  1273 + * @param other The other JSONArray
  1274 + * @return true if they are equal
  1275 + */
  1276 + public boolean similar(Object other) {
  1277 + if (!(other instanceof JSONArray)) {
  1278 + return false;
  1279 + }
  1280 + int len = this.length();
  1281 + if (len != ((JSONArray)other).length()) {
  1282 + return false;
  1283 + }
  1284 + for (int i = 0; i < len; i += 1) {
  1285 + Object valueThis = this.myArrayList.get(i);
  1286 + Object valueOther = ((JSONArray)other).myArrayList.get(i);
  1287 + if(valueThis == valueOther) {
  1288 + continue;
  1289 + }
  1290 + if(valueThis == null) {
  1291 + return false;
  1292 + }
  1293 + if (valueThis instanceof JSONObject) {
  1294 + if (!((JSONObject)valueThis).similar(valueOther)) {
  1295 + return false;
  1296 + }
  1297 + } else if (valueThis instanceof JSONArray) {
  1298 + if (!((JSONArray)valueThis).similar(valueOther)) {
  1299 + return false;
  1300 + }
  1301 + } else if (!valueThis.equals(valueOther)) {
  1302 + return false;
  1303 + }
  1304 + }
  1305 + return true;
  1306 + }
  1307 +
  1308 + /**
  1309 + * Produce a JSONObject by combining a JSONArray of names with the values of
  1310 + * this JSONArray.
  1311 + *
  1312 + * @param names
  1313 + * A JSONArray containing a list of key strings. These will be
  1314 + * paired with the values.
  1315 + * @return A JSONObject, or null if there are no names or if this JSONArray
  1316 + * has no values.
  1317 + * @throws JSONException
  1318 + * If any of the names are null.
  1319 + */
  1320 + public JSONObject toJSONObject(JSONArray names) throws JSONException {
  1321 + if (names == null || names.length() == 0 || this.length() == 0) {
  1322 + return null;
  1323 + }
  1324 + JSONObject jo = new JSONObject(names.length());
  1325 + for (int i = 0; i < names.length(); i += 1) {
  1326 + jo.put(names.getString(i), this.opt(i));
  1327 + }
  1328 + return jo;
  1329 + }
  1330 +
  1331 + /**
  1332 + * Make a JSON text of this JSONArray. For compactness, no unnecessary
  1333 + * whitespace is added. If it is not possible to produce a syntactically
  1334 + * correct JSON text then null will be returned instead. This could occur if
  1335 + * the array contains an invalid number.
  1336 + * <p><b>
  1337 + * Warning: This method assumes that the data structure is acyclical.
  1338 + * </b>
  1339 + *
  1340 + * @return a printable, displayable, transmittable representation of the
  1341 + * array.
  1342 + */
  1343 + @Override
  1344 + public String toString() {
  1345 + try {
  1346 + return this.toString(0);
  1347 + } catch (Exception e) {
  1348 + return null;
  1349 + }
  1350 + }
  1351 +
  1352 + /**
  1353 + * Make a pretty-printed JSON text of this JSONArray.
  1354 + *
  1355 + * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
  1356 + * one element, then the array will be output on a single line:
  1357 + * <pre>{@code [1]}</pre>
  1358 + *
  1359 + * <p>If an array has 2 or more elements, then it will be output across
  1360 + * multiple lines: <pre>{@code
  1361 + * [
  1362 + * 1,
  1363 + * "value 2",
  1364 + * 3
  1365 + * ]
  1366 + * }</pre>
  1367 + * <p><b>
  1368 + * Warning: This method assumes that the data structure is acyclical.
  1369 + * </b>
  1370 + *
  1371 + * @param indentFactor
  1372 + * The number of spaces to add to each level of indentation.
  1373 + * @return a printable, displayable, transmittable representation of the
  1374 + * object, beginning with <code>[</code>&nbsp;<small>(left
  1375 + * bracket)</small> and ending with <code>]</code>
  1376 + * &nbsp;<small>(right bracket)</small>.
  1377 + * @throws JSONException
  1378 + */
  1379 + public String toString(int indentFactor) throws JSONException {
  1380 + StringWriter sw = new StringWriter();
  1381 + synchronized (sw.getBuffer()) {
  1382 + return this.write(sw, indentFactor, 0).toString();
  1383 + }
  1384 + }
  1385 +
  1386 + /**
  1387 + * Write the contents of the JSONArray as JSON text to a writer. For
  1388 + * compactness, no whitespace is added.
  1389 + * <p><b>
  1390 + * Warning: This method assumes that the data structure is acyclical.
  1391 + *</b>
  1392 + *
  1393 + * @return The writer.
  1394 + * @throws JSONException
  1395 + */
  1396 + public Writer write(Writer writer) throws JSONException {
  1397 + return this.write(writer, 0, 0);
  1398 + }
  1399 +
  1400 + /**
  1401 + * Write the contents of the JSONArray as JSON text to a writer.
  1402 + *
  1403 + * <p>If <code>indentFactor > 0</code> and the {@link JSONArray} has only
  1404 + * one element, then the array will be output on a single line:
  1405 + * <pre>{@code [1]}</pre>
  1406 + *
  1407 + * <p>If an array has 2 or more elements, then it will be output across
  1408 + * multiple lines: <pre>{@code
  1409 + * [
  1410 + * 1,
  1411 + * "value 2",
  1412 + * 3
  1413 + * ]
  1414 + * }</pre>
  1415 + * <p><b>
  1416 + * Warning: This method assumes that the data structure is acyclical.
  1417 + * </b>
  1418 + *
  1419 + * @param writer
  1420 + * Writes the serialized JSON
  1421 + * @param indentFactor
  1422 + * The number of spaces to add to each level of indentation.
  1423 + * @param indent
  1424 + * The indentation of the top level.
  1425 + * @return The writer.
  1426 + * @throws JSONException
  1427 + */
  1428 + public Writer write(Writer writer, int indentFactor, int indent)
  1429 + throws JSONException {
  1430 + try {
  1431 + boolean commanate = false;
  1432 + int length = this.length();
  1433 + writer.write('[');
  1434 +
  1435 + if (length == 1) {
  1436 + try {
  1437 + JSONObject.writeValue(writer, this.myArrayList.get(0),
  1438 + indentFactor, indent);
  1439 + } catch (Exception e) {
  1440 + throw new JSONException("Unable to write JSONArray value at index: 0", e);
  1441 + }
  1442 + } else if (length != 0) {
  1443 + final int newindent = indent + indentFactor;
  1444 +
  1445 + for (int i = 0; i < length; i += 1) {
  1446 + if (commanate) {
  1447 + writer.write(',');
  1448 + }
  1449 + if (indentFactor > 0) {
  1450 + writer.write('\n');
  1451 + }
  1452 + JSONObject.indent(writer, newindent);
  1453 + try {
  1454 + JSONObject.writeValue(writer, this.myArrayList.get(i),
  1455 + indentFactor, newindent);
  1456 + } catch (Exception e) {
  1457 + throw new JSONException("Unable to write JSONArray value at index: " + i, e);
  1458 + }
  1459 + commanate = true;
  1460 + }
  1461 + if (indentFactor > 0) {
  1462 + writer.write('\n');
  1463 + }
  1464 + JSONObject.indent(writer, indent);
  1465 + }
  1466 + writer.write(']');
  1467 + return writer;
  1468 + } catch (IOException e) {
  1469 + throw new JSONException(e);
  1470 + }
  1471 + }
  1472 +
  1473 + /**
  1474 + * Returns a java.util.List containing all of the elements in this array.
  1475 + * If an element in the array is a JSONArray or JSONObject it will also
  1476 + * be converted.
  1477 + * <p>
  1478 + * Warning: This method assumes that the data structure is acyclical.
  1479 + *
  1480 + * @return a java.util.List containing the elements of this array
  1481 + */
  1482 + public List<Object> toList() {
  1483 + List<Object> results = new ArrayList<Object>(this.myArrayList.size());
  1484 + for (Object element : this.myArrayList) {
  1485 + if (element == null || JSONObject.NULL.equals(element)) {
  1486 + results.add(null);
  1487 + } else if (element instanceof JSONArray) {
  1488 + results.add(((JSONArray) element).toList());
  1489 + } else if (element instanceof JSONObject) {
  1490 + results.add(((JSONObject) element).toMap());
  1491 + } else {
  1492 + results.add(element);
  1493 + }
  1494 + }
  1495 + return results;
  1496 + }
  1497 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/JSONException.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.org.json;
  2 +
  3 +/**
  4 + * The JSONException is thrown by the JSON.org classes when things are amiss.
  5 + *
  6 + * @author JSON.org
  7 + * @version 2015-12-09
  8 + */
  9 +public class JSONException extends RuntimeException {
  10 + /** Serialization ID */
  11 + private static final long serialVersionUID = 0;
  12 +
  13 + /**
  14 + * Constructs a JSONException with an explanatory message.
  15 + *
  16 + * @param message
  17 + * Detail about the reason for the exception.
  18 + */
  19 + public JSONException(final String message) {
  20 + super(message);
  21 + }
  22 +
  23 + /**
  24 + * Constructs a JSONException with an explanatory message and cause.
  25 + *
  26 + * @param message
  27 + * Detail about the reason for the exception.
  28 + * @param cause
  29 + * The cause.
  30 + */
  31 + public JSONException(final String message, final Throwable cause) {
  32 + super(message, cause);
  33 + }
  34 +
  35 + /**
  36 + * Constructs a new JSONException with the specified cause.
  37 + *
  38 + * @param cause
  39 + * The cause.
  40 + */
  41 + public JSONException(final Throwable cause) {
  42 + super(cause.getMessage(), cause);
  43 + }
  44 +
  45 +}
... ...
src/main/java/com/bsth/data/zndd/baidu/org/json/JSONML.java 0 → 100644
  1 +package com.bsth.data.zndd.baidu.org.json;
  2 +
  3 +/*
  4 +Copyright (c) 2008 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 an XML text into a JSONArray or
  29 + * JSONObject, and to covert a JSONArray or JSONObject into an XML text using
  30 + * the JsonML transform.
  31 + *
  32 + * @author JSON.org
  33 + * @version 2016-01-30
  34 + */
  35 +public class JSONML {
  36 + /**
  37 + * Parse XML values and store them in a JSONArray.
  38 + * @param x The XMLTokener containing the source string.
  39 + * @param arrayForm true if array form, false if object form.
  40 + * @param ja The JSONArray that is containing the current tag or null
  41 + * if we are at the outermost level.
  42 + * @param keepStrings Don't type-convert text nodes and attribute values
  43 + * @return A JSONArray if the value is the outermost tag, otherwise null.
  44 + * @throws JSONException
  45 + */
  46 + private static Object parse(
  47 + XMLTokener x,
  48 + boolean arrayForm,
  49 + JSONArray ja,
  50 + boolean keepStrings
  51 + ) throws JSONException {
  52 + String attribute;
  53 + char c;
  54 + String closeTag = null;
  55 + int i;
  56 + JSONArray newja = null;
  57 + JSONObject newjo = null;
  58 + Object token;
  59 + String tagName = null;
  60 +
  61 +// Test for and skip past these forms:
  62 +// <!-- ... -->
  63 +// <![ ... ]]>
  64 +// <! ... >
  65 +// <? ... ?>
  66 +
  67 + while (true) {
  68 + if (!x.more()) {
  69 + throw x.syntaxError("Bad XML");
  70 + }
  71 + token = x.nextContent();
  72 + if (token == XML.LT) {
  73 + token = x.nextToken();
  74 + if (token instanceof Character) {
  75 + if (token == XML.SLASH) {
  76 +
  77 +// Close tag </
  78 +
  79 + token = x.nextToken();
  80 + if (!(token instanceof String)) {
  81 + throw new JSONException(
  82 + "Expected a closing name instead of '" +
  83 + token + "'.");
  84 + }
  85 + if (x.nextToken() != XML.GT) {
  86 + throw x.syntaxError("Misshaped close tag");
  87 + }
  88 + return token;
  89 + } else if (token == XML.BANG) {
  90 +
  91 +// <!
  92 +
  93 + c = x.next();
  94 + if (c == '-') {
  95 + if (x.next() == '-') {
  96 + x.skipPast("-->");
  97 + } else {
  98 + x.back();
  99 + }
  100 + } else if (c == '[') {
  101 + token = x.nextToken();
  102 + if (token.equals("CDATA") && x.next() == '[') {
  103 + if (ja != null) {
  104 + ja.put(x.nextCDATA());
  105 + }
  106 + } else {
  107 + throw x.syntaxError("Expected 'CDATA['");
  108 + }
  109 + } else {
  110 + i = 1;
  111 + do {
  112 + token = x.nextMeta();
  113 + if (token == null) {
  114 + throw x.syntaxError("Missing '>' after '<!'.");
  115 + } else if (token == XML.LT) {
  116 + i += 1;
  117 + } else if (token == XML.GT) {
  118 + i -= 1;
  119 + }
  120 + } while (i > 0);
  121 + }
  122 + } else if (token == XML.QUEST) {
  123 +
  124 +// <?
  125 +
  126 + x.skipPast("?>");
  127 + } else {
  128 + throw x.syntaxError("Misshaped tag");
  129 + }
  130 +
  131 +// Open tag <
  132 +
  133 + } else {
  134 + if (!(token instanceof String)) {
  135 + throw x.syntaxError("Bad tagName '" + token + "'.");
  136 + }
  137 + tagName = (String)token;
  138 + newja = new JSONArray();
  139 + newjo = new JSONObject();
  140 + if (arrayForm) {
  141 + newja.put(tagName);
  142 + if (ja != null) {
  143 + ja.put(newja);
  144 + }
  145 + } else {
  146 + newjo.put("tagName", tagName);
  147 + if (ja != null) {
  148 + ja.put(newjo);
  149 + }
  150 + }
  151 + token = null;
  152 + for (;;) {
  153 + if (token == null) {
  154 + token = x.nextToken();
  155 + }
  156 + if (token == null) {
  157 + throw x.syntaxError("Misshaped tag");
  158 + }
  159 + if (!(token instanceof String)) {
  160 + break;
  161 + }
  162 +
  163 +// attribute = value
  164 +
  165 + attribute = (String)token;
  166 + if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
  167 + throw x.syntaxError("Reserved attribute.");
  168 + }
  169 + token = x.nextToken();
  170 + if (token == XML.EQ) {
  171 + token = x.nextToken();
  172 + if (!(token instanceof String)) {
  173 + throw x.syntaxError("Missing value");
  174 + }
  175 + newjo.accumulate(attribute, keepStrings ? ((String)token) :XML.stringToValue((String)token));
  176 + token = null;
  177 + } else {
  178 + newjo.accumulate(attribute, "");
  179 + }
  180 + }
  181 + if (arrayForm && newjo.length() > 0) {
  182 + newja.put(newjo);
  183 + }
  184 +
  185 +// Empty tag <.../>
  186 +
  187 + if (token == XML.SLASH) {
  188 + if (x.nextToken() != XML.GT) {
  189 + throw x.syntaxError("Misshaped tag");
  190 + }
  191 + if (ja == null) {
  192 + if (arrayForm) {
  193 + return newja;
  194 + }
  195 + return newjo;
  196 + }
  197 +
  198 +// Content, between <...> and </...>
  199 +
  200 + } else {
  201 + if (token != XML.GT) {
  202 + throw x.syntaxError("Misshaped tag");
  203 + }
  204 + closeTag = (String)parse(x, arrayForm, newja, keepStrings);
  205 + if (closeTag != null) {
  206 + if (!closeTag.equals(tagName)) {
  207 + throw x.syntaxError("Mismatched '" + tagName +
  208 + "' and '" + closeTag + "'");
  209 + }
  210 + tagName = null;
  211 + if (!arrayForm && newja.length() > 0) {
  212 + newjo.put("childNodes", newja);
  213 + }
  214 + if (ja == null) {
  215 + if (arrayForm) {
  216 + return newja;
  217 + }
  218 + return newjo;
  219 + }
  220 + }
  221 + }
  222 + }
  223 + } else {
  224 + if (ja != null) {
  225 + ja.put(token instanceof String
  226 + ? keepStrings ? XML.unescape((String)token) :XML.stringToValue((String)token)
  227 + : token);
  228 + }
  229 + }
  230 + }
  231 + }
  232 +
  233 +
  234 + /**
  235 + * Convert a well-formed (but not necessarily valid) XML string into a
  236 + * JSONArray using the JsonML transform. Each XML tag is represented as
  237 + * a JSONArray in which the first element is the tag name. If the tag has
  238 + * attributes, then the second element will be JSONObject containing the
  239 + * name/value pairs. If the tag contains children, then strings and
  240 + * JSONArrays will represent the child tags.
  241 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  242 + * @param string The source string.
  243 + * @return A JSONArray containing the structured data from the XML string.
  244 + * @throws JSONException Thrown on error converting to a JSONArray
  245 + */
  246 + public static JSONArray toJSONArray(String string) throws JSONException {
  247 + return (JSONArray)parse(new XMLTokener(string), true, null, false);
  248 + }
  249 +
  250 +
  251 + /**
  252 + * Convert a well-formed (but not necessarily valid) XML string into a
  253 + * JSONArray using the JsonML transform. Each XML tag is represented as
  254 + * a JSONArray in which the first element is the tag name. If the tag has
  255 + * attributes, then the second element will be JSONObject containing the
  256 + * name/value pairs. If the tag contains children, then strings and
  257 + * JSONArrays will represent the child tags.
  258 + * As opposed to toJSONArray this method does not attempt to convert
  259 + * any text node or attribute value to any type
  260 + * but just leaves it as a string.
  261 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  262 + * @param string The source string.
  263 + * @param keepStrings If true, then values will not be coerced into boolean
  264 + * or numeric values and will instead be left as strings
  265 + * @return A JSONArray containing the structured data from the XML string.
  266 + * @throws JSONException Thrown on error converting to a JSONArray
  267 + */
  268 + public static JSONArray toJSONArray(String string, boolean keepStrings) throws JSONException {
  269 + return (JSONArray)parse(new XMLTokener(string), true, null, keepStrings);
  270 + }
  271 +
  272 +
  273 + /**
  274 + * Convert a well-formed (but not necessarily valid) XML string into a
  275 + * JSONArray using the JsonML transform. Each XML tag is represented as
  276 + * a JSONArray in which the first element is the tag name. If the tag has
  277 + * attributes, then the second element will be JSONObject containing the
  278 + * name/value pairs. If the tag contains children, then strings and
  279 + * JSONArrays will represent the child content and tags.
  280 + * As opposed to toJSONArray this method does not attempt to convert
  281 + * any text node or attribute value to any type
  282 + * but just leaves it as a string.
  283 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  284 + * @param x An XMLTokener.
  285 + * @param keepStrings If true, then values will not be coerced into boolean
  286 + * or numeric values and will instead be left as strings
  287 + * @return A JSONArray containing the structured data from the XML string.
  288 + * @throws JSONException Thrown on error converting to a JSONArray
  289 + */
  290 + public static JSONArray toJSONArray(XMLTokener x, boolean keepStrings) throws JSONException {
  291 + return (JSONArray)parse(x, true, null, keepStrings);
  292 + }
  293 +
  294 +
  295 + /**
  296 + * Convert a well-formed (but not necessarily valid) XML string into a
  297 + * JSONArray using the JsonML transform. Each XML tag is represented as
  298 + * a JSONArray in which the first element is the tag name. If the tag has
  299 + * attributes, then the second element will be JSONObject containing the
  300 + * name/value pairs. If the tag contains children, then strings and
  301 + * JSONArrays will represent the child content and tags.
  302 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  303 + * @param x An XMLTokener.
  304 + * @return A JSONArray containing the structured data from the XML string.
  305 + * @throws JSONException Thrown on error converting to a JSONArray
  306 + */
  307 + public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
  308 + return (JSONArray)parse(x, true, null, false);
  309 + }
  310 +
  311 +
  312 + /**
  313 + * Convert a well-formed (but not necessarily valid) XML string into a
  314 + * JSONObject using the JsonML transform. Each XML tag is represented as
  315 + * a JSONObject with a "tagName" property. If the tag has attributes, then
  316 + * the attributes will be in the JSONObject as properties. If the tag
  317 + * contains children, the object will have a "childNodes" property which
  318 + * will be an array of strings and JsonML JSONObjects.
  319 +
  320 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  321 + * @param string The XML source text.
  322 + * @return A JSONObject containing the structured data from the XML string.
  323 + * @throws JSONException Thrown on error converting to a JSONObject
  324 + */
  325 + public static JSONObject toJSONObject(String string) throws JSONException {
  326 + return (JSONObject)parse(new XMLTokener(string), false, null, false);
  327 + }
  328 +
  329 +
  330 + /**
  331 + * Convert a well-formed (but not necessarily valid) XML string into a
  332 + * JSONObject using the JsonML transform. Each XML tag is represented as
  333 + * a JSONObject with a "tagName" property. If the tag has attributes, then
  334 + * the attributes will be in the JSONObject as properties. If the tag
  335 + * contains children, the object will have a "childNodes" property which
  336 + * will be an array of strings and JsonML JSONObjects.
  337 +
  338 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  339 + * @param string The XML source text.
  340 + * @param keepStrings If true, then values will not be coerced into boolean
  341 + * or numeric values and will instead be left as strings
  342 + * @return A JSONObject containing the structured data from the XML string.
  343 + * @throws JSONException Thrown on error converting to a JSONObject
  344 + */
  345 + public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException {
  346 + return (JSONObject)parse(new XMLTokener(string), false, null, keepStrings);
  347 + }
  348 +
  349 +
  350 + /**
  351 + * Convert a well-formed (but not necessarily valid) XML string into a
  352 + * JSONObject using the JsonML transform. Each XML tag is represented as
  353 + * a JSONObject with a "tagName" property. If the tag has attributes, then
  354 + * the attributes will be in the JSONObject as properties. If the tag
  355 + * contains children, the object will have a "childNodes" property which
  356 + * will be an array of strings and JsonML JSONObjects.
  357 +
  358 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  359 + * @param x An XMLTokener of the XML source text.
  360 + * @return A JSONObject containing the structured data from the XML string.
  361 + * @throws JSONException Thrown on error converting to a JSONObject
  362 + */
  363 + public static JSONObject toJSONObject(XMLTokener x) throws JSONException {
  364 + return (JSONObject)parse(x, false, null, false);
  365 + }
  366 +
  367 +
  368 + /**
  369 + * Convert a well-formed (but not necessarily valid) XML string into a
  370 + * JSONObject using the JsonML transform. Each XML tag is represented as
  371 + * a JSONObject with a "tagName" property. If the tag has attributes, then
  372 + * the attributes will be in the JSONObject as properties. If the tag
  373 + * contains children, the object will have a "childNodes" property which
  374 + * will be an array of strings and JsonML JSONObjects.
  375 +
  376 + * Comments, prologs, DTDs, and <code>&lt;[ [ ]]></code> are ignored.
  377 + * @param x An XMLTokener of the XML source text.
  378 + * @param keepStrings If true, then values will not be coerced into boolean
  379 + * or numeric values and will instead be left as strings
  380 + * @return A JSONObject containing the structured data from the XML string.
  381 + * @throws JSONException Thrown on error converting to a JSONObject
  382 + */
  383 + public static JSONObject toJSONObject(XMLTokener x, boolean keepStrings) throws JSONException {
  384 + return (JSONObject)parse(x, false, null, keepStrings);
  385 + }
  386 +
  387 +
  388 + /**
  389 + * Reverse the JSONML transformation, making an XML text from a JSONArray.
  390 + * @param ja A JSONArray.
  391 + * @return An XML string.
  392 + * @throws JSONException Thrown on error converting to a string
  393 + */
  394 + public static String toString(JSONArray ja) throws JSONException {
  395 + int i;
  396 + JSONObject jo;
  397 + int length;
  398 + Object object;
  399 + StringBuilder sb = new StringBuilder();
  400 + String tagName;
  401 +
  402 +// Emit <tagName
  403 +
  404 + tagName = ja.getString(0);
  405 + XML.noSpace(tagName);
  406 + tagName = XML.escape(tagName);
  407 + sb.append('<');
  408 + sb.append(tagName);
  409 +
  410 + object = ja.opt(1);
  411 + if (object instanceof JSONObject) {
  412 + i = 2;
  413 + jo = (JSONObject)object;
  414 +
  415 +// Emit the attributes
  416 +
  417 + // Don't use the new entrySet API to maintain Android support
  418 + for (final String key : jo.keySet()) {
  419 + final Object value = jo.opt(key);
  420 + XML.noSpace(key);
  421 + if (value != null) {
  422 + sb.append(' ');
  423 + sb.append(XML.escape(key));
  424 + sb.append('=');
  425 + sb.append('"');
  426 + sb.append(XML.escape(value.toString()));
  427 + sb.append('"');
  428 + }
  429 + }
  430 + } else {
  431 + i = 1;
  432 + }
  433 +
  434 +// Emit content in body
  435 +
  436 + length = ja.length();
  437 + if (i >= length) {
  438 + sb.append('/');
  439 + sb.append('>');
  440 + } else {
  441 + sb.append('>');
  442 + do {
  443 + object = ja.get(i);
  444 + i += 1;
  445 + if (object != null) {
  446 + if (object instanceof String) {
  447 + sb.append(XML.escape(object.toString()));
  448 + } else if (object instanceof JSONObject) {
  449 + sb.append(toString((JSONObject)object));
  450 + } else if (object instanceof JSONArray) {
  451 + sb.append(toString((JSONArray)object));
  452 + } else {
  453 + sb.append(object.toString());
  454 + }
  455 + }
  456 + } while (i < length);
  457 + sb.append('<');
  458 + sb.append('/');
  459 + sb.append(tagName);
  460 + sb.append('>');
  461 + }
  462 + return sb.toString();
  463 + }
  464 +
  465 + /**
  466 + * Reverse the JSONML transformation, making an XML text from a JSONObject.
  467 + * The JSONObject must contain a "tagName" property. If it has children,
  468 + * then it must have a "childNodes" property containing an array of objects.
  469 + * The other properties are attributes with string values.
  470 + * @param jo A JSONObject.
  471 + * @return An XML string.
  472 + * @throws JSONException Thrown on error converting to a string
  473 + */
  474 + public static String toString(JSONObject jo) throws JSONException {
  475 + StringBuilder sb = new StringBuilder();
  476 + int i;
  477 + JSONArray ja;
  478 + int length;
  479 + Object object;
  480 + String tagName;
  481 + Object value;
  482 +
  483 +//Emit <tagName
  484 +
  485 + tagName = jo.optString("tagName");
  486 + if (tagName == null) {
  487 + return XML.escape(jo.toString());
  488 + }
  489 + XML.noSpace(tagName);
  490 + tagName = XML.escape(tagName);
  491 + sb.append('<');
  492 + sb.append(tagName);
  493 +
  494 +//Emit the attributes
  495 +
  496 + // Don't use the new entrySet API to maintain Android support
  497 + for (final String key : jo.keySet()) {
  498 + if (!"tagName".equals(key) && !"childNodes".equals(key)) {
  499 + XML.noSpace(key);
  500 + value = jo.opt(key);
  501 + if (value != null) {
  502 + sb.append(' ');
  503 + sb.append(XML.escape(key));
  504 + sb.append('=');
  505 + sb.append('"');
  506 + sb.append(XML.escape(value.toString()));
  507 + sb.append('"');
  508 + }
  509 + }
  510 + }
  511 +
  512 +//Emit content in body
  513 +
  514 + ja = jo.optJSONArray("childNodes");
  515 + if (ja == null) {
  516 + sb.append('/');
  517 + sb.append('>');
  518 + } else {
  519 + sb.append('>');
  520 + length = ja.length();
  521 + for (i = 0; i < length; i += 1) {
  522 + object = ja.get(i);
  523 + if (object != null) {
  524 + if (object instanceof String) {
  525 + sb.append(XML.escape(object.toString()));
  526 + } else if (object instanceof JSONObject) {
  527 + sb.append(toString((JSONObject)object));
  528 + } else if (object instanceof JSONArray) {
  529 + sb.append(toString((JSONArray)object));
  530 + } else {
  531 + sb.append(object.toString());
  532 + }
  533 + }
  534 + }
  535 + sb.append('<');
  536 + sb.append('/');
  537 + sb.append(tagName);
  538 + sb.append('>');
  539 + }
  540 + return sb.toString();
  541 + }
  542 +}
... ...