lenya-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From andr...@apache.org
Subject svn commit: r756035 [3/3] - /lenya/contributions/2_0_X/modules/rest/java/src/org/json/
Date Thu, 19 Mar 2009 14:47:37 GMT
Added: lenya/contributions/2_0_X/modules/rest/java/src/org/json/Test.java
URL: http://svn.apache.org/viewvc/lenya/contributions/2_0_X/modules/rest/java/src/org/json/Test.java?rev=756035&view=auto
==============================================================================
--- lenya/contributions/2_0_X/modules/rest/java/src/org/json/Test.java (added)
+++ lenya/contributions/2_0_X/modules/rest/java/src/org/json/Test.java Thu Mar 19 14:47:37
2009
@@ -0,0 +1,413 @@
+package org.json;
+
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.io.StringWriter;
+
+/**
+ * Test class. This file is not formally a member of the org.json library.
+ * It is just a casual test tool.
+ */
+public class Test {
+
+    /**
+     * Entry point.
+     * @param args
+     */
+    public static void main(String args[]) {
+        Iterator it;
+        JSONArray a;
+        JSONObject j;
+        JSONStringer jj;
+        String s;
+        
+// Obj is a typical class that implements JSONString.        
+
+        class Obj implements JSONString {
+        	public String aString;
+        	public double aNumber;
+        	public boolean aBoolean;
+        	
+            public Obj(String string, double n, boolean b) {
+                this.aString = string;
+                this.aNumber = n;
+                this.aBoolean = b;
+            }
+            
+            public String toJSONString() {
+            	return "{" + JSONObject.quote(this.aString) + ":" + 
+            	JSONObject.doubleToString(this.aNumber) + "}";
+            }            
+            public String toString() {
+            	return this.aString + " " + this.aNumber + " " + this.aBoolean;
+            }
+        }      
+        
+        
+        try {     	
+        	String sa[] = {"aString", "aNumber", "aBoolean"};
+        	Obj obj = new Obj("A string, a number, and a boolean", 42, true);
+            
+            j = XML.toJSONObject("<![CDATA[This is a collection of test patterns and examples
for org.json.]]>");
+            System.out.println(j.toString());
+
+            jj = new JSONStringer();
+            s = jj.object()
+                .key("foo")
+                .value("bar")
+                .key("baz")
+                .array()
+                    .object()
+                        .key("quux")
+                        .value("Thanks, Josh!")
+                    .endObject()
+                .endArray()
+                .endObject()
+                .toString();
+            System.out.println(s);
+
+            System.out.println(new JSONStringer()
+                .object()
+                .key("a")
+                .array()
+                .array()
+                .array()
+                .value("b")
+                .endArray()
+                .endArray()
+                .endArray()
+                .endObject()
+                .toString());
+
+            jj = new JSONStringer();
+            jj.array();
+            jj.value(1);
+            jj.array();
+            jj.value(null);
+            jj.array();
+            jj.object();
+            jj.key("empty-array").array().endArray();
+            jj.key("answer").value(42);
+            jj.key("null").value(null);
+            jj.key("false").value(false);
+            jj.key("true").value(true);
+            jj.key("big").value(123456789e+88);
+            jj.key("small").value(123456789e-88);
+            jj.key("empty-object").object().endObject();
+            jj.key("long");
+            jj.value(9223372036854775807L);
+            jj.endObject();
+            jj.value("two");
+            jj.endArray();
+            jj.value(true);
+            jj.endArray();
+            jj.value(98.6);
+            jj.value(-100.0);
+            jj.object();
+            jj.endObject();
+            jj.object();
+            jj.key("one");
+            jj.value(1.00);
+            jj.endObject();
+            jj.value(obj);
+            jj.endArray();
+            System.out.println(jj.toString());
+
+            System.out.println(new JSONArray(jj.toString()).toString(4));
+
+            j = new JSONObject(obj, sa);
+            j.put("test", obj);
+            j.put("comment", "This object contains a test object that implements JSONString");
+            System.out.println(j.toString(4));          
+            
+            j = new JSONObject("{slashes: '///', closetag: '</script>', backslash:'\\\\',
ei: {quotes: '\"\\''},eo: {a: '\"quoted\"', b:\"don't\"}, quotes: [\"'\", '\"']}");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = new JSONObject(
+                "/*comment*/{foo: [true, false,9876543210,    0.0, 1.00000001,  1.000000000001,
1.00000000000000001," +
+                " .00000000000000001, 2.00, 0.1, 2e100, -32,[],{}, \"string\"], " +
+                "  to   : null, op : 'Good'," +
+                "ten:10} postfix comment");
+            j.put("String", "98.6");
+            j.put("JSONObject", new JSONObject());
+            j.put("JSONArray", new JSONArray());
+            j.put("int", 57);
+            j.put("double", 123456789012345678901234567890.);
+            j.put("true", true);
+            j.put("false", false);
+            j.put("null", JSONObject.NULL);
+            j.put("bool", "true");
+            j.put("zero", -0.0);
+            a = j.getJSONArray("foo");
+            a.put(666);
+            a.put(2001.99);
+            a.put("so \"fine\".");
+            a.put("so <fine>.");
+            a.put(true);
+            a.put(false);
+            a.put(new JSONArray());
+            a.put(new JSONObject());
+            System.out.println(j.toString(4));
+            System.out.println(XML.toString(j));
+
+            System.out.println("String: " + j.getDouble("String"));
+            System.out.println("  bool: " + j.getBoolean("bool"));
+            System.out.println("    to: " + j.getString("to"));
+            System.out.println("  true: " + j.getString("true"));
+            System.out.println("   foo: " + j.getJSONArray("foo"));
+            System.out.println("    op: " + j.getString("op"));
+            System.out.println("   ten: " + j.getInt("ten"));
+            System.out.println("  oops: " + j.optBoolean("oops"));
+
+            j = XML.toJSONObject("<xml one = 1 two=' \"2\" '><five></five>First
\u0009&lt;content&gt;<five></five> This is \"content\". <three>
 3  </three>JSON does not preserve the sequencing of elements and contents.<three>
 III  </three>  <three>  T H R E E</three><four/>Content text is an
implied structure in XML. <six content=\"6\"/>JSON does not have implied structure:<seven>7</seven>everything
is explicit.<![CDATA[CDATA blocks<are><supported>!]]></xml>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<mapping><empty/>   <class name = \"Customer\">
     <field name = \"ID\" type = \"string\">         <bind-xml name=\"ID\" node=\"attribute\"/>
     </field>      <field name = \"FirstName\" type = \"FirstName\"/>      <field
name = \"MI\" type = \"MI\"/>      <field name = \"LastName\" type = \"LastName\"/>
  </class>   <class name = \"FirstName\">      <field name = \"text\"> 
       <bind-xml name = \"text\" node = \"text\"/>      </field>   </class>
  <class name = \"MI\">      <field name = \"text\">         <bind-xml name
= \"text\" node = \"text\"/>      </field>   </class>   <class name = \"LastName\">
     <field name = \"text\">         <bind-xml name = \"text\" node = \"text\"/>
     </field>   </class></mapping>");
+
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<?xml version=\"1.0\" ?><Book Author=\"Anonymous\"><Title>Sample
Book</Title><Chapter id=\"1\">This is chapter 1. It is not very long or interesting.</Chapter><Chapter
id=\"2\">This is chapter 2. Although it is longer than chapter 1, it is not any more interesting.</Chapter></Book>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<!DOCTYPE bCard 'http://www.cs.caltech.edu/~adam/schemas/bCard'><bCard><?xml
default bCard        firstname = ''        lastname  = '' company   = '' email = '' homepage
 = ''?><bCard        firstname = 'Rohit'        lastname  = 'Khare'        company 
 = 'MCI'        email     = 'khare@mci.net'        homepage  = 'http://pest.w3.org/'/><bCard
       firstname = 'Adam'        lastname  = 'Rifkin'        company   = 'Caltech Infospheres
Project'        email     = 'adam@cs.caltech.edu'        homepage  = 'http://www.cs.caltech.edu/~adam/'/></bCard>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<?xml version=\"1.0\"?><customer>    <firstName>
       <text>Fred</text>    </firstName>    <ID>fbs0001</ID>
   <lastName> <text>Scerbo</text>    </lastName>    <MI>   
    <text>B</text>    </MI></customer>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<!ENTITY tp-address PUBLIC '-//ABC University::Special
Collections Library//TEXT (titlepage: name and address)//EN' 'tpspcoll.sgm'><list type='simple'><head>Repository
Address </head><item>Special Collections Library</item><item>ABC University</item><item>Main
Library, 40 Circle Drive</item><item>Ourtown, Pennsylvania</item><item>17654
USA</item></list>");
+            System.out.println(j.toString());
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<test intertag status=ok><empty/>deluxe<blip
sweet=true>&amp;&quot;toot&quot;&toot;&#x41;</blip><x>eks</x><w>bonus</w><w>bonus2</w></test>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = HTTP.toJSONObject("GET / HTTP/1.0\nAccept: image/gif, image/x-xbitmap, image/jpeg,
image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword,
*/*\nAccept-Language: en-us\nUser-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win
9x 4.90; T312461; Q312461)\nHost: www.nokko.com\nConnection: keep-alive\nAccept-encoding:
gzip, deflate\n");
+            System.out.println(j.toString(2));
+            System.out.println(HTTP.toString(j));
+            System.out.println("");
+
+            j = HTTP.toJSONObject("HTTP/1.1 200 Oki Doki\nDate: Sun, 26 May 2002 17:38:52
GMT\nServer: Apache/1.3.23 (Unix) mod_perl/1.26\nKeep-Alive: timeout=15, max=100\nConnection:
Keep-Alive\nTransfer-Encoding: chunked\nContent-Type: text/html\n");
+            System.out.println(j.toString(2));
+            System.out.println(HTTP.toString(j));
+            System.out.println("");
+
+            j = new JSONObject("{nix: null, nux: false, null: 'null', 'Request-URI': '/',
Method: 'GET', 'HTTP-Version': 'HTTP/1.0'}");
+            System.out.println(j.toString(2));
+            System.out.println("isNull: " + j.isNull("nix"));
+            System.out.println("   has: " + j.has("nix"));
+            System.out.println(XML.toString(j));
+            System.out.println(HTTP.toString(j));
+            System.out.println("");
+
+            j = XML.toJSONObject("<?xml version='1.0' encoding='UTF-8'?>"+"\n\n"+"<SOAP-ENV:Envelope"+
+              " xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""+
+              " xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\""+
+              " xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\">"+
+              "<SOAP-ENV:Body><ns1:doGoogleSearch"+
+              " xmlns:ns1=\"urn:GoogleSearch\""+
+              " SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"+
+              "<key xsi:type=\"xsd:string\">GOOGLEKEY</key> <q"+
+              " xsi:type=\"xsd:string\">'+search+'</q> <start"+
+              " xsi:type=\"xsd:int\">0</start> <maxResults"+
+              " xsi:type=\"xsd:int\">10</maxResults> <filter"+
+              " xsi:type=\"xsd:boolean\">true</filter> <restrict"+
+              " xsi:type=\"xsd:string\"></restrict> <safeSearch"+
+              " xsi:type=\"xsd:boolean\">false</safeSearch> <lr"+
+              " xsi:type=\"xsd:string\"></lr> <ie"+
+              " xsi:type=\"xsd:string\">latin1</ie> <oe"+
+              " xsi:type=\"xsd:string\">latin1</oe>"+
+              "</ns1:doGoogleSearch>"+
+              "</SOAP-ENV:Body></SOAP-ENV:Envelope>");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = new JSONObject("{Envelope: {Body: {\"ns1:doGoogleSearch\": {oe: \"latin1\",
filter: true, q: \"'+search+'\", key: \"GOOGLEKEY\", maxResults: 10, \"SOAP-ENV:encodingStyle\":
\"http://schemas.xmlsoap.org/soap/encoding/\", start: 0, ie: \"latin1\", safeSearch:false,
\"xmlns:ns1\": \"urn:GoogleSearch\"}}}}");
+            System.out.println(j.toString(2));
+            System.out.println(XML.toString(j));
+            System.out.println("");
+
+            j = CookieList.toJSONObject("  f%oo = b+l=ah  ; o;n%40e = t.wo ");
+            System.out.println(j.toString(2));
+            System.out.println(CookieList.toString(j));
+            System.out.println("");
+
+            j = Cookie.toJSONObject("f%oo=blah; secure ;expires = April 24, 2002");
+            System.out.println(j.toString(2));
+            System.out.println(Cookie.toString(j));
+            System.out.println("");
+
+            j = new JSONObject("{script: 'It is not allowed in HTML to send a close script
tag in a string<script>because it confuses browsers</script>so we insert a backslash
before the /'}");
+            System.out.println(j.toString());
+            System.out.println("");
+
+            JSONTokener jt = new JSONTokener("{op:'test', to:'session', pre:1}{op:'test',
to:'session', pre:2}");
+            j = new JSONObject(jt);
+            System.out.println(j.toString());
+            System.out.println("pre: " + j.optInt("pre"));
+            int i = jt.skipTo('{');
+            System.out.println(i);
+            j = new JSONObject(jt);
+            System.out.println(j.toString());
+            System.out.println("");
+
+            a = CDL.toJSONArray("No quotes, 'Single Quotes', \"Double Quotes\"\n1,'2',\"3\"\n,'It
is \"good,\"', \"It works.\"\n\n");
+
+            System.out.println(CDL.toString(a));
+            System.out.println("");
+            System.out.println(a.toString(4));
+            System.out.println("");
+
+            a = new JSONArray(" [\"<escape>\", next is an implied null , , ok,] ");
+            System.out.println(a.toString());
+            System.out.println("");
+            System.out.println(XML.toString(a));
+            System.out.println("");
+
+            j = new JSONObject("{ fun => with non-standard forms ; forgiving => This
package can be used to parse formats that are similar to but not stricting conforming to JSON;
why=To make it easier to migrate existing data to JSON,one = [[1.00]]; uno=[[{1=>1}]];'+':+6e66
;pluses=+++;empty = '' , 'double':0.666,true: TRUE, false: FALSE, null=NULL;[true] = [[!,@;*]];
string=>  o. k. ; # comment\r oct=0666; hex=0x666; dec=666; o=0999; noh=0x0x}");
+            System.out.println(j.toString(4));
+            System.out.println("");
+            if (j.getBoolean("true") && !j.getBoolean("false")) {
+                System.out.println("It's all good");
+            }
+
+            System.out.println("");
+            j = new JSONObject(j, new String[]{"dec", "oct", "hex", "missing"});
+            System.out.println(j.toString(4));
+
+            System.out.println("");
+            System.out.println(new JSONStringer().array().value(a).value(j).endArray());
+
+            j = new JSONObject("{string: \"98.6\", long: 2147483648, int: 2147483647, longer:
9223372036854775807, double: 9223372036854775808}");
+            System.out.println(j.toString(4));
+
+            System.out.println("\ngetInt");
+            System.out.println("int    " + j.getInt("int"));
+            System.out.println("long   " + j.getInt("long"));
+            System.out.println("longer " + j.getInt("longer"));
+            System.out.println("double " + j.getInt("double"));
+            System.out.println("string " + j.getInt("string"));
+
+            System.out.println("\ngetLong");
+            System.out.println("int    " + j.getLong("int"));
+            System.out.println("long   " + j.getLong("long"));
+            System.out.println("longer " + j.getLong("longer"));
+            System.out.println("double " + j.getLong("double"));
+            System.out.println("string " + j.getLong("string"));
+
+            System.out.println("\ngetDouble");
+            System.out.println("int    " + j.getDouble("int"));
+            System.out.println("long   " + j.getDouble("long"));
+            System.out.println("longer " + j.getDouble("longer"));
+            System.out.println("double " + j.getDouble("double"));
+            System.out.println("string " + j.getDouble("string"));
+
+            j.put("good sized", 9223372036854775807L);
+            System.out.println(j.toString(4));
+
+            a = new JSONArray("[2147483647, 2147483648, 9223372036854775807, 9223372036854775808]");
+            System.out.println(a.toString(4));
+
+            System.out.println("\nKeys: ");
+            it = j.keys();
+            while (it.hasNext()) {
+                s = (String)it.next();
+                System.out.println(s + ": " + j.getString(s));
+            }
+
+
+            System.out.println("\naccumulate: ");
+            j = new JSONObject();
+            j.accumulate("stooge", "Curly");
+            j.accumulate("stooge", "Larry");
+            j.accumulate("stooge", "Moe");
+            a = j.getJSONArray("stooge");
+            a.put(5, "Shemp");
+            System.out.println(j.toString(4));
+
+            System.out.println("\nwrite:");
+            System.out.println(j.write(new StringWriter()));
+
+            s = "<xml empty><a></a><a>1</a><a>22</a><a>333</a></xml>";
+            j = XML.toJSONObject(s);
+            System.out.println(j.toString(4));
+            System.out.println(XML.toString(j));
+            
+            s = "<book><chapter>Content of the first chapter</chapter><chapter>Content
of the second chapter      <chapter>Content of the first subchapter</chapter>
     <chapter>Content of the second subchapter</chapter></chapter><chapter>Third
Chapter</chapter></book>";
+            j = XML.toJSONObject(s);
+            System.out.println(j.toString(4));
+            System.out.println(XML.toString(j));
+            
+            Collection c = null;
+            Map m = null;
+            
+            j = new JSONObject(m);
+            a = new JSONArray(c);
+            j.append("stooge", "Joe DeRita");
+            j.put("map", m);
+            j.put("collection", c);
+            j.put("array", a);
+            a.put(m);
+            a.put(c);
+            System.out.println(j.toString(4));
+            
+            System.out.println("\nTesting Exceptions: ");
+
+            System.out.print("Exception: ");
+            try {
+                System.out.println(j.getDouble("stooge"));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+            System.out.print("Exception: ");
+            try {
+                System.out.println(j.getDouble("howard"));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+            System.out.print("Exception: ");
+            try {
+                System.out.println(j.put(null, "howard"));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+            System.out.print("Exception: ");
+            try {
+                System.out.println(a.getDouble(0));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+            System.out.print("Exception: ");
+            try {
+                System.out.println(a.get(-1));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+            System.out.print("Exception: ");
+            try {
+                System.out.println(a.put(Double.NaN));
+            } catch (Exception e) {
+                System.out.println(e);
+            }
+        } catch (Exception e) {
+            System.out.println(e.toString());
+        }
+    }
+}

Added: lenya/contributions/2_0_X/modules/rest/java/src/org/json/XML.java
URL: http://svn.apache.org/viewvc/lenya/contributions/2_0_X/modules/rest/java/src/org/json/XML.java?rev=756035&view=auto
==============================================================================
--- lenya/contributions/2_0_X/modules/rest/java/src/org/json/XML.java (added)
+++ lenya/contributions/2_0_X/modules/rest/java/src/org/json/XML.java Thu Mar 19 14:47:37
2009
@@ -0,0 +1,393 @@
+package org.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+import java.util.Iterator;
+
+
+/**
+ * This provides static methods to convert an XML text into a JSONObject,
+ * and to covert a JSONObject into an XML text.
+ * @author JSON.org
+ * @version 2
+ */
+public class XML {
+
+    /** The Character '&'. */
+    public static final Character AMP   = new Character('&');
+
+    /** The Character '''. */
+    public static final Character APOS  = new Character('\'');
+
+    /** The Character '!'. */
+    public static final Character BANG  = new Character('!');
+
+    /** The Character '='. */
+    public static final Character EQ    = new Character('=');
+
+    /** The Character '>'. */
+    public static final Character GT    = new Character('>');
+
+    /** The Character '<'. */
+    public static final Character LT    = new Character('<');
+
+    /** The Character '?'. */
+    public static final Character QUEST = new Character('?');
+
+    /** The Character '"'. */
+    public static final Character QUOT  = new Character('"');
+
+    /** The Character '/'. */
+    public static final Character SLASH = new Character('/');
+
+    /**
+     * Replace special characters with XML escapes:
+     * <pre>
+     * &amp; <small>(ampersand)</small> is replaced by &amp;amp;
+     * &lt; <small>(less than)</small> is replaced by &amp;lt;
+     * &gt; <small>(greater than)</small> is replaced by &amp;gt;
+     * &quot; <small>(double quote)</small> is replaced by &amp;quot;
+     * </pre>
+     * @param string The string to be escaped.
+     * @return The escaped string.
+     */
+    public static String escape(String string) {
+        StringBuffer sb = new StringBuffer();
+        for (int i = 0, len = string.length(); i < len; i++) {
+            char c = string.charAt(i);
+            switch (c) {
+            case '&':
+                sb.append("&amp;");
+                break;
+            case '<':
+                sb.append("&lt;");
+                break;
+            case '>':
+                sb.append("&gt;");
+                break;
+            case '"':
+                sb.append("&quot;");
+                break;
+            default:
+                sb.append(c);
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Scan the content following the named tag, attaching it to the context.
+     * @param x       The XMLTokener containing the source string.
+     * @param context The JSONObject that will include the new material.
+     * @param name    The tag name.
+     * @return true if the close tag is processed.
+     * @throws JSONException
+     */
+    private static boolean parse(XMLTokener x, JSONObject context,
+                                 String name) throws JSONException {
+        char       c;
+        int        i;
+        String     n;
+        JSONObject o = null;
+        String     s;
+        Object     t;
+
+// Test for and skip past these forms:
+//      <!-- ... -->
+//      <!   ...   >
+//      <![  ... ]]>
+//      <?   ...  ?>
+// Report errors for these forms:
+//      <>
+//      <=
+//      <<
+
+        t = x.nextToken();
+
+// <!
+
+        if (t == BANG) {
+            c = x.next();
+            if (c == '-') {
+                if (x.next() == '-') {
+                    x.skipPast("-->");
+                    return false;
+                }
+                x.back();
+            } else if (c == '[') {
+                t = x.nextToken();
+                if (t.equals("CDATA")) {
+                    if (x.next() == '[') {
+                        s = x.nextCDATA();
+                        if (s.length() > 0) {
+                            context.accumulate("content", s);
+                        }
+                        return false;
+                    }
+                }
+                throw x.syntaxError("Expected 'CDATA['");
+            }
+            i = 1;
+            do {
+                t = x.nextMeta();
+                if (t == null) {
+                    throw x.syntaxError("Missing '>' after '<!'.");
+                } else if (t == LT) {
+                    i += 1;
+                } else if (t == GT) {
+                    i -= 1;
+                }
+            } while (i > 0);
+            return false;
+        } else if (t == QUEST) {
+
+// <?
+
+            x.skipPast("?>");
+            return false;
+        } else if (t == SLASH) {
+
+// Close tag </
+
+            if (name == null || !x.nextToken().equals(name)) {
+                throw x.syntaxError("Mismatched close tag");
+            }
+            if (x.nextToken() != GT) {
+                throw x.syntaxError("Misshaped close tag");
+            }
+            return true;
+
+        } else if (t instanceof Character) {
+            throw x.syntaxError("Misshaped tag");
+
+// Open tag <
+
+        } else {
+            n = (String)t;
+            t = null;
+            o = new JSONObject();
+            for (;;) {
+                if (t == null) {
+                    t = x.nextToken();
+                }
+
+// attribute = value
+
+                if (t instanceof String) {
+                    s = (String)t;
+                    t = x.nextToken();
+                    if (t == EQ) {
+                        t = x.nextToken();
+                        if (!(t instanceof String)) {
+                            throw x.syntaxError("Missing value");
+                        }
+                        o.accumulate(s, t);
+                        t = null;
+                    } else {
+                        o.accumulate(s, "");
+                    }
+
+// Empty tag <.../>
+
+                } else if (t == SLASH) {
+                    if (x.nextToken() != GT) {
+                        throw x.syntaxError("Misshaped tag");
+                    }
+                    context.accumulate(n, o);
+                    return false;
+
+// Content, between <...> and </...>
+
+                } else if (t == GT) {
+                    for (;;) {
+                        t = x.nextContent();
+                        if (t == null) {
+                            if (name != null) {
+                                throw x.syntaxError("Unclosed tag " + name);
+                            }
+                            return false;
+                        } else if (t instanceof String) {
+                            s = (String)t;
+                            if (s.length() > 0) {
+                                o.accumulate("content", s);
+                            }
+
+// Nested element
+
+                        } else if (t == LT) {
+                            if (parse(x, o, n)) {
+                                if (o.length() == 0) {
+                                    context.accumulate(n, "");
+                                } else if (o.length() == 1 &&
+                                       o.opt("content") != null) {
+                                    context.accumulate(n, o.opt("content"));
+                                } else {
+                                    context.accumulate(n, o);
+                                }
+                                return false;
+                            }
+                        }
+                    }
+                } else {
+                    throw x.syntaxError("Misshaped tag");
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Convert a well-formed (but not necessarily valid) XML string into a
+     * JSONObject. Some information may be lost in this transformation
+     * because JSON is a data format and XML is a document format. XML uses
+     * elements, attributes, and content text, while JSON uses unordered
+     * collections of name/value pairs and arrays of values. JSON does not
+     * does not like to distinguish between elements and attributes.
+     * Sequences of similar elements are represented as JSONArrays. Content
+     * text may be placed in a "content" member. Comments, prologs, DTDs, and
+     * <code>&lt;[ [ ]]></code> are ignored.
+     * @param string The source string.
+     * @return A JSONObject containing the structured data from the XML string.
+     * @throws JSONException
+     */
+    public static JSONObject toJSONObject(String string) throws JSONException {
+        JSONObject o = new JSONObject();
+        XMLTokener x = new XMLTokener(string);
+        while (x.more()) {
+            x.skipPast("<");
+            parse(x, o, null);
+        }
+        return o;
+    }
+
+
+    /**
+     * Convert a JSONObject into a well-formed, element-normal XML string.
+     * @param o A JSONObject.
+     * @return  A string.
+     * @throws  JSONException
+     */
+    public static String toString(Object o) throws JSONException {
+        return toString(o, null);
+    }
+
+
+    /**
+     * Convert a JSONObject into a well-formed, element-normal XML string.
+     * @param o A JSONObject.
+     * @param tagName The optional name of the enclosing tag.
+     * @return A string.
+     * @throws JSONException
+     */
+    public static String toString(Object o, String tagName)
+            throws JSONException {
+        StringBuffer b = new StringBuffer();
+        int          i;
+        JSONArray    ja;
+        JSONObject   jo;
+        String       k;
+        Iterator     keys;
+        int          len;
+        String       s;
+        Object       v;
+        if (o instanceof JSONObject) {
+
+// Emit <tagName>
+
+            if (tagName != null) {
+                b.append('<');
+                b.append(tagName);
+                b.append('>');
+            }
+
+// Loop thru the keys.
+
+            jo = (JSONObject)o;
+            keys = jo.keys();
+            while (keys.hasNext()) {
+                k = keys.next().toString();
+                v = jo.get(k);
+                if (v instanceof String) {
+                    s = (String)v;
+                } else {
+                    s = null;
+                }
+
+// Emit content in body
+
+                if (k.equals("content")) {
+                    if (v instanceof JSONArray) {
+                        ja = (JSONArray)v;
+                        len = ja.length();
+                        for (i = 0; i < len; i += 1) {
+                            if (i > 0) {
+                                b.append('\n');
+                            }
+                            b.append(escape(ja.get(i).toString()));
+                        }
+                    } else {
+                        b.append(escape(v.toString()));
+                    }
+
+// Emit an array of similar keys
+
+                } else if (v instanceof JSONArray) {
+                    ja = (JSONArray)v;
+                    len = ja.length();
+                    for (i = 0; i < len; i += 1) {
+                        b.append(toString(ja.get(i), k));
+                    }
+                } else if (v.equals("")) {
+                    b.append('<');
+                    b.append(k);
+                    b.append("/>");
+
+// Emit a new tag <k>
+
+                } else {
+                    b.append(toString(v, k));
+                }
+            }
+            if (tagName != null) {
+
+// Emit the </tagname> close tag
+
+                b.append("</");
+                b.append(tagName);
+                b.append('>');
+            }
+            return b.toString();
+
+// XML does not have good support for arrays. If an array appears in a place
+// where XML is lacking, synthesize an <array> element.
+
+        } else if (o instanceof JSONArray) {
+            ja = (JSONArray)o;
+            len = ja.length();
+            for (i = 0; i < len; ++i) {
+                b.append(toString(
+                    ja.opt(i), (tagName == null) ? "array" : tagName));
+            }
+            return b.toString();
+        } else {
+            s = (o == null) ? "null" : escape(o.toString());
+            return (tagName == null) ? "\"" + s + "\"" :
+                (s.length() == 0) ? "<" + tagName + "/>" :
+                "<" + tagName + ">" + s + "</" + tagName + ">";
+        }
+    }
+}
\ No newline at end of file

Added: lenya/contributions/2_0_X/modules/rest/java/src/org/json/XMLTokener.java
URL: http://svn.apache.org/viewvc/lenya/contributions/2_0_X/modules/rest/java/src/org/json/XMLTokener.java?rev=756035&view=auto
==============================================================================
--- lenya/contributions/2_0_X/modules/rest/java/src/org/json/XMLTokener.java (added)
+++ lenya/contributions/2_0_X/modules/rest/java/src/org/json/XMLTokener.java Thu Mar 19 14:47:37
2009
@@ -0,0 +1,284 @@
+package org.json;
+
+/*
+Copyright (c) 2002 JSON.org
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+   http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/
+
+/**
+ * The XMLTokener extends the JSONTokener to provide additional methods
+ * for the parsing of XML texts.
+ * @author JSON.org
+ * @version 2
+ */
+public class XMLTokener extends JSONTokener {
+
+
+   /** The table of entity values. It initially contains Character values for
+    * amp, apos, gt, lt, quot.
+    */
+   public static final java.util.HashMap entity;
+
+   static {
+       entity = new java.util.HashMap(8);
+       entity.put("amp",  XML.AMP);
+       entity.put("apos", XML.APOS);
+       entity.put("gt",   XML.GT);
+       entity.put("lt",   XML.LT);
+       entity.put("quot", XML.QUOT);
+   }
+
+    /**
+     * Construct an XMLTokener from a string.
+     * @param s A source string.
+     */
+    public XMLTokener(String s) {
+        super(s);
+    }
+
+    /**
+     * Get the text in the CDATA block.
+     * @return The string up to the <code>]]&gt;</code>.
+     * @throws JSONException If the <code>]]&gt;</code> is not found.
+     */
+    public String nextCDATA() throws JSONException {
+        char         c;
+        int          i;
+        StringBuffer sb = new StringBuffer();
+        for (;;) {
+            c = next();
+            if (c == 0) {
+                throw syntaxError("Unclosed CDATA.");
+            }
+            sb.append(c);
+            i = sb.length() - 3;
+            if (i >= 0 && sb.charAt(i) == ']' &&
+                          sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>')
{
+                sb.setLength(i);
+                return sb.toString();
+            }
+        }
+    }
+
+
+    /**
+     * Get the next XML outer token, trimming whitespace. There are two kinds
+     * of tokens: the '<' character which begins a markup tag, and the content
+     * text between markup tags.
+     *
+     * @return  A string, or a '<' Character, or null if there is no more
+     * source text.
+     * @throws JSONException
+     */
+    public Object nextContent() throws JSONException {
+        char         c;
+        StringBuffer sb;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        if (c == 0) {
+            return null;
+        }
+        if (c == '<') {
+            return XML.LT;
+        }
+        sb = new StringBuffer();
+        for (;;) {
+            if (c == '<' || c == 0) {
+                back();
+                return sb.toString().trim();
+            }
+            if (c == '&') {
+                sb.append(nextEntity(c));
+            } else {
+                sb.append(c);
+            }
+            c = next();
+        }
+    }
+
+
+    /**
+     * Return the next entity. These entities are translated to Characters:
+     *     <code>&amp;  &apos;  &gt;  &lt;  &quot;</code>.
+     * @param a An ampersand character.
+     * @return  A Character or an entity String if the entity is not recognized.
+     * @throws JSONException If missing ';' in XML entity.
+     */
+    public Object nextEntity(char a) throws JSONException {
+        StringBuffer sb = new StringBuffer();
+        for (;;) {
+            char c = next();
+            if (Character.isLetterOrDigit(c) || c == '#') {
+                sb.append(Character.toLowerCase(c));
+            } else if (c == ';') {
+                break;
+            } else {
+                throw syntaxError("Missing ';' in XML entity: &" + sb);
+            }
+        }
+        String s = sb.toString();
+        Object e = entity.get(s);
+        return e != null ? e : a + s + ";";
+    }
+
+
+    /**
+     * Returns the next XML meta token. This is used for skipping over <!...>
+     * and <?...?> structures.
+     * @return Syntax characters (<code>< > / = ! ?</code>) are returned
as
+     *  Character, and strings and names are returned as Boolean. We don't care
+     *  what the values actually are.
+     * @throws JSONException If a string is not properly closed or if the XML
+     *  is badly structured.
+     */
+    public Object nextMeta() throws JSONException {
+        char c;
+        char q;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        switch (c) {
+        case 0:
+            throw syntaxError("Misshaped meta tag.");
+        case '<':
+            return XML.LT;
+        case '>':
+            return XML.GT;
+        case '/':
+            return XML.SLASH;
+        case '=':
+            return XML.EQ;
+        case '!':
+            return XML.BANG;
+        case '?':
+            return XML.QUEST;
+        case '"':
+        case '\'':
+            q = c;
+            for (;;) {
+                c = next();
+                if (c == 0) {
+                    throw syntaxError("Unterminated string.");
+                }
+                if (c == q) {
+                    return Boolean.TRUE;
+                }
+            }
+        default:
+            for (;;) {
+                c = next();
+                if (Character.isWhitespace(c)) {
+                    return Boolean.TRUE;
+                }
+                switch (c) {
+                case 0:
+                case '<':
+                case '>':
+                case '/':
+                case '=':
+                case '!':
+                case '?':
+                case '"':
+                case '\'':
+                    back();
+                    return Boolean.TRUE;
+                }
+            }
+        }
+    }
+
+
+    /**
+     * Get the next XML Token. These tokens are found inside of angle
+     * brackets. It may be one of these characters: <code>/ > = ! ?</code>
or it
+     * may be a string wrapped in single quotes or double quotes, or it may be a
+     * name.
+     * @return a String or a Character.
+     * @throws JSONException If the XML is not well formed.
+     */
+    public Object nextToken() throws JSONException {
+        char c;
+        char q;
+        StringBuffer sb;
+        do {
+            c = next();
+        } while (Character.isWhitespace(c));
+        switch (c) {
+        case 0:
+            throw syntaxError("Misshaped element.");
+        case '<':
+            throw syntaxError("Misplaced '<'.");
+        case '>':
+            return XML.GT;
+        case '/':
+            return XML.SLASH;
+        case '=':
+            return XML.EQ;
+        case '!':
+            return XML.BANG;
+        case '?':
+            return XML.QUEST;
+
+// Quoted string
+
+        case '"':
+        case '\'':
+            q = c;
+            sb = new StringBuffer();
+            for (;;) {
+                c = next();
+                if (c == 0) {
+                    throw syntaxError("Unterminated string.");
+                }
+                if (c == q) {
+                    return sb.toString();
+                }
+                if (c == '&') {
+                    sb.append(nextEntity(c));
+                } else {
+                    sb.append(c);
+                }
+            }
+        default:
+
+// Name
+
+            sb = new StringBuffer();
+            for (;;) {
+                sb.append(c);
+                c = next();
+                if (Character.isWhitespace(c)) {
+                    return sb.toString();
+                }
+                switch (c) {
+                case 0:
+                case '>':
+                case '/':
+                case '=':
+                case '!':
+                case '?':
+                case '[':
+                case ']':
+                    back();
+                    return sb.toString();
+                case '<':
+                case '"':
+                case '\'':
+                    throw syntaxError("Bad character in a name.");
+                }
+            }
+        }
+    }
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@lenya.apache.org
For additional commands, e-mail: commits-help@lenya.apache.org


Mime
View raw message