From: Ole Streicher <olebole@debian.org>
Date: Mon, 19 Dec 2016 15:16:00 +0100
Subject: Use android-json

This one has only "String" and input parameter for JSONTokener
---
 src/main/uk/ac/starlink/ttools/build/JupyterCell.java | 14 ++++++++++----
 .../uk/ac/starlink/ttools/build/Plot2Example.java     |  5 +++++
 .../uk/ac/starlink/ttools/build/Plot2Notebook.java    |  3 +++
 .../uk/ac/starlink/ttools/cone/CdsUploadMatcher.java  |  6 +++++-
 .../starlink/ttools/example/GeojsonTableBuilder.java  | 19 ++++++++++++++++---
 src/main/uk/ac/starlink/ttools/func/Json.java         | 16 +++++++++++++++-
 .../uk/ac/starlink/ttools/server/PlotSession.java     | 18 +++++++++++++++---
 .../uk/ac/starlink/ttools/func/FuncTest.java          |  7 +++----
 8 files changed, 72 insertions(+), 16 deletions(-)

diff --git a/src/main/uk/ac/starlink/ttools/build/JupyterCell.java b/src/main/uk/ac/starlink/ttools/build/JupyterCell.java
index 4e0efee..c522578 100644
--- a/src/main/uk/ac/starlink/ttools/build/JupyterCell.java
+++ b/src/main/uk/ac/starlink/ttools/build/JupyterCell.java
@@ -8,6 +8,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.stream.Collectors;
 import org.json.JSONObject;
+import org.json.JSONException;
 
 /**
  * Manages export of a list of lines to the JSON format used for
@@ -50,7 +51,7 @@ public class JupyterCell {
      *
      * @return  JSON representation of this cell
      */
-    public JSONObject toJson() {
+    public JSONObject toJson() throws JSONException {
         JSONObject json = new JSONObject();
         json.put( "cell_type", "code" );
         json.put( "execution_count", JSONObject.NULL );
@@ -69,7 +70,8 @@ public class JupyterCell {
      * @param   cells  list of cells
      * @return   JSON representation of notebook
      */
-    public static JSONObject toNotebook( List<JupyterCell> cells ) {
+    public static JSONObject toNotebook( List<JupyterCell> cells )
+    throws JSONException {
         JSONObject cmode = new JSONObject();
         cmode.put( "name", "ipython" );
         cmode.put( "version", 3 );
@@ -95,8 +97,12 @@ public class JupyterCell {
         JSONObject json = new JSONObject();
         json.put( "cells",
                   cells.stream()
-                       .map( JupyterCell::toJson )
-                       .collect( Collectors.toList() ) );
+		  .map( o -> { try {
+			      return ((JupyterCell)o).toJson();
+			  } catch (JSONException e) {
+			      return JSONObject.NULL;
+			  }})
+		  .collect( Collectors.toList() ) );
         json.put( "metadata", meta );
         json.put( "nbformat", 4 );
         json.put( "nbformat_minor", 2 );
diff --git a/src/main/uk/ac/starlink/ttools/build/Plot2Example.java b/src/main/uk/ac/starlink/ttools/build/Plot2Example.java
index c6b9001..024619c 100644
--- a/src/main/uk/ac/starlink/ttools/build/Plot2Example.java
+++ b/src/main/uk/ac/starlink/ttools/build/Plot2Example.java
@@ -32,6 +32,7 @@ import javax.swing.JComponent;
 import javax.swing.JDialog;
 import javax.swing.JLabel;
 import javax.swing.KeyStroke;
+import org.json.JSONException;
 import uk.ac.starlink.table.StarTable;
 import uk.ac.starlink.table.StarTableFactory;
 import uk.ac.starlink.task.InvokeUtils;
@@ -872,8 +873,10 @@ public class Plot2Example {
                     lines.add( "])" );
                     cells.add( new JupyterCell( lines ) );
                 }
+		try {
                 System.out.println( JupyterCell.toNotebook( cells )
                                                .toString( 1 ) );
+		} catch (JSONException e) {}
             }
         },
 
@@ -914,8 +917,10 @@ public class Plot2Example {
                     lines.add( "])" );
                     cells.add( new JupyterCell( lines ) );
                 }
+		try {
                 System.out.println( JupyterCell.toNotebook( cells )
                                                .toString( 1 ) );
+		} catch (JSONException e) {}
             }
         };
 
diff --git a/src/main/uk/ac/starlink/ttools/build/Plot2Notebook.java b/src/main/uk/ac/starlink/ttools/build/Plot2Notebook.java
index ae0021d..1d817a9 100644
--- a/src/main/uk/ac/starlink/ttools/build/Plot2Notebook.java
+++ b/src/main/uk/ac/starlink/ttools/build/Plot2Notebook.java
@@ -8,6 +8,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.logging.Level;
 import java.util.logging.Logger;
+import org.json.JSONException;
 import uk.ac.starlink.ttools.server.PlotServlet;
 
 /**
@@ -109,6 +110,8 @@ public class Plot2Notebook {
             "gridcolor_g=hotpink",
             "labelpos_g=none",
         } ) );
+	try {
         System.out.println( JupyterCell.toNotebook( cells ).toString( 1 ) );
+	} catch (JSONException e) {}
     }
 }
diff --git a/src/main/uk/ac/starlink/ttools/cone/CdsUploadMatcher.java b/src/main/uk/ac/starlink/ttools/cone/CdsUploadMatcher.java
index 2f3d553..6c4ebbc 100644
--- a/src/main/uk/ac/starlink/ttools/cone/CdsUploadMatcher.java
+++ b/src/main/uk/ac/starlink/ttools/cone/CdsUploadMatcher.java
@@ -14,6 +14,8 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.logging.Logger;
+import org.apache.commons.io.IOUtils;
+import org.json.JSONException;
 import org.json.JSONObject;
 import org.json.JSONTokener;
 import org.xml.sax.SAXException;
@@ -259,7 +261,7 @@ public class CdsUploadMatcher implements UploadMatcher {
             new BufferedInputStream( ContentCoding.NONE.openStream( url ) );
         JSONObject infoObj;
         try {
-            JSONTokener jt = new JSONTokener( in );
+            JSONTokener jt = new JSONTokener( IOUtils.toString( in ) );
             Object next = jt.nextValue();
             if ( next instanceof JSONObject ) {
                 return new VizierMeta( (JSONObject) next );
@@ -267,6 +269,8 @@ public class CdsUploadMatcher implements UploadMatcher {
             else {
                 throw new IOException( "Unexpected JSON object from " + url );
             }
+        } catch (JSONException e) {
+               throw new IOException(e);
         }
         finally {
             in.close();
diff --git a/src/main/uk/ac/starlink/ttools/example/GeojsonTableBuilder.java b/src/main/uk/ac/starlink/ttools/example/GeojsonTableBuilder.java
index 8e97a54..dc2b80f 100644
--- a/src/main/uk/ac/starlink/ttools/example/GeojsonTableBuilder.java
+++ b/src/main/uk/ac/starlink/ttools/example/GeojsonTableBuilder.java
@@ -5,7 +5,9 @@ import java.io.BufferedInputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.LinkedHashMap;
+import java.util.Iterator;
 import java.util.Map;
+import org.apache.commons.io.IOUtils;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -104,7 +106,7 @@ public class GeojsonTableBuilder implements TableBuilder {
     private StarTable createStarTable( InputStream in ) throws IOException {
         JSONObject top;
         try {
-            top = new JSONObject( new JSONTokener( in ) );
+            top = new JSONObject( new JSONTokener( IOUtils.toString( in ) ) );
         }
         catch ( JSONException e ) {
             throw new TableFormatException( "Not JSON", e );
@@ -112,6 +114,7 @@ public class GeojsonTableBuilder implements TableBuilder {
         finally {
             in.close();
         }
+        try {
         if ( "FeatureCollection".equals( top.get( "type" ) ) ) {
             JSONArray features = (JSONArray) top.get( "features" );
             return createStarTable( features );
@@ -120,6 +123,7 @@ public class GeojsonTableBuilder implements TableBuilder {
             throw new TableFormatException( "No FeatureCollection "
                                           + " in top-level JSON object" );
         }
+        } catch ( JSONException e ) { throw new TableFormatException( "Not JSON", e ); }
     }
 
     /**
@@ -137,16 +141,19 @@ public class GeojsonTableBuilder implements TableBuilder {
          * that occurs at least once as a table heading. */
         Map<String,Object> propMap = new LinkedHashMap<>();
         for ( int i = 0; i < nf; i++ ) {
+            try {
             JSONObject jobj = features.getJSONObject( i );
             if ( "Feature".equals( jobj.get( "type" ) ) ) {
                 JSONObject props = jobj.getJSONObject( "properties" );
                 if ( props != null ) {
-                    for ( String key : props.keySet() ) {
+                    for ( Iterator<String> it = props.keys(); it.hasNext(); ) {
+                        String key = it.next();
                         Object value = props.get( key );
                         propMap.put( key, value );
                     }
                 }
             }
+            } catch ( JSONException e ) { }
         }
 
         /* Adapt the features array as a StarTable. */
@@ -166,12 +173,14 @@ public class GeojsonTableBuilder implements TableBuilder {
         geomInfo.setXtype( "stc-s" );
         table.addColumn( new ColumnData( geomInfo ) {
             public Object readValue( long irow ) {
+                try {
                 JSONObject geom = features.getJSONObject( (int) irow )
                                           .getJSONObject( "geometry" );
                 String type = geom.getString( "type" );
                 JSONArray coords = geom.getJSONArray( "coordinates" );
                 return toStcs( geom.getString( "type" ),
                                geom.getJSONArray( "coordinates" ) );
+                } catch ( JSONException e ) { return null; }
             }
         } );
         return table;
@@ -194,6 +203,7 @@ public class GeojsonTableBuilder implements TableBuilder {
         if ( exampleValue instanceof Number ) {
             return new ColumnData( new ColumnInfo( key, Double.class, null ) ) {
                 public Object readValue( long irow ) {
+                    try {
                     Object value = features
                                   .getJSONObject( (int) irow )
                                   .getJSONObject( "properties" )
@@ -207,6 +217,7 @@ public class GeojsonTableBuilder implements TableBuilder {
                     else {
                         return null;
                     }
+                    } catch (JSONException e) { return null; }
                 }
             };
         }
@@ -214,11 +225,13 @@ public class GeojsonTableBuilder implements TableBuilder {
                   exampleValue instanceof Boolean ) {
             return new ColumnData( new ColumnInfo( key, clazz, null ) ) {
                 public Object readValue( long irow ) {
+                    try {
                     Object value = features
                                   .getJSONObject( (int) irow )
                                   .getJSONObject( "properties" )
                                   .get( key );
                     return clazz.isInstance( value ) ? value : null;
+                    } catch (JSONException e) { return null; }
                 }
             };
         }
@@ -239,7 +252,7 @@ public class GeojsonTableBuilder implements TableBuilder {
      * @return  STC-S string approximating GeoJSON intent if possible,
      *          or null if not
      */
-    private String toStcs( String type, JSONArray jsonCoords ) {
+    private String toStcs( String type, JSONArray jsonCoords ) throws JSONException {
         if ( "MultiPolygon".equals( type ) ) {
             int npoly = jsonCoords.length();
             StringBuffer sbuf = new StringBuffer();
diff --git a/src/main/uk/ac/starlink/ttools/func/Json.java b/src/main/uk/ac/starlink/ttools/func/Json.java
index 5c5f378..43500da 100644
--- a/src/main/uk/ac/starlink/ttools/func/Json.java
+++ b/src/main/uk/ac/starlink/ttools/func/Json.java
@@ -5,6 +5,8 @@
 
 package uk.ac.starlink.ttools.func;
 
+import java.util.List;
+import java.util.ArrayList;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -263,6 +265,18 @@ public class Json {
      * @return  string array containing keys of object
      */
     public static String[] jsonGetKeys( JSONObject jsonObject ) {
-        return jsonObject == null ? null : JSONObject.getNames( jsonObject );
+	if ( jsonObject == null ) {
+	    return null;
+	}
+	List<String> list = new ArrayList<String>();
+	JSONArray array = jsonObject.names();
+	try {
+	    for (int i = 0; i < array.length(); i++) {
+		list.add( array.getString( i ) );
+	    }
+	} catch ( JSONException e ) {
+	    return null;
+	}
+        return list.toArray( new String[0] );
     }
 }
diff --git a/src/main/uk/ac/starlink/ttools/server/PlotSession.java b/src/main/uk/ac/starlink/ttools/server/PlotSession.java
index c014c3c..7ca042a 100644
--- a/src/main/uk/ac/starlink/ttools/server/PlotSession.java
+++ b/src/main/uk/ac/starlink/ttools/server/PlotSession.java
@@ -38,8 +38,8 @@ import javax.servlet.http.HttpServletResponse;
 import org.jfree.graphics2d.svg.SVGGraphics2D;
 import org.jfree.graphics2d.svg.SVGUnits;
 import org.json.JSONArray;
+import org.json.JSONException;
 import org.json.JSONObject;
-import org.json.JSONWriter;
 import uk.ac.starlink.table.RowSequence;
 import uk.ac.starlink.table.StarTable;
 import uk.ac.starlink.ttools.DocUtils;
@@ -782,7 +782,7 @@ public class PlotSession<P,A> {
     private static void writeJsonQuotedString( OutputStream out, String txt )
             throws IOException {
         OutputStreamWriter writer = new OutputStreamWriter( out, "UTF-8" );
-        JSONObject.quote( txt, writer );
+        writer.write(JSONObject.quote( txt ));
         writer.flush();
     }
 
@@ -1019,6 +1019,7 @@ public class PlotSession<P,A> {
                                         HttpServletResponse response )
                     throws IOException {
 
+		try {
                 /* Write image data. */
                 ImageWriter imwriter =
                     session.getImageWriter( request, session.exporter_ );
@@ -1088,9 +1089,18 @@ public class PlotSession<P,A> {
                         out.write( ',' );
                     }
                     writeAscii( out, "\"" + BOUNDS_KEY + "\": " );
-                    writeAscii( out, new JSONArray( dbounds ).toString() );
+		    JSONArray dbArray =  new JSONArray();
+		    for (int i = 0; i < dbounds.length; i++) {
+			JSONArray db0Array =  new JSONArray();
+			for (int j = 0; j < dbounds.length; j++) {
+			    db0Array.put(dbounds[i][j]);
+			}
+			dbArray.put(db0Array);
+		    }
+                    writeAscii( out, dbArray.toString() );
                 }
                 out.write( '}' );
+		} catch (JSONException e) { throw new IOException(e); }
             }
         };
     }
@@ -1134,6 +1144,7 @@ public class PlotSession<P,A> {
                                         HttpServletResponse response )
                     throws IOException {
                 final String msg;
+		try {
                 Map<String,String> paramMap = getSingleParameterMap( request );
                 Point gpos = parseXY( paramMap.get( "pos" ) );
                 JSONObject json = new JSONObject();
@@ -1174,6 +1185,7 @@ public class PlotSession<P,A> {
                 response.setStatus( 200 );
                 response.setContentType( "application/json" );
                 response.getOutputStream().println( json.toString() );
+		} catch (JSONException e) { throw new IOException(e); }
             }
         };
     }
diff --git a/src/testcases/uk/ac/starlink/ttools/func/FuncTest.java b/src/testcases/uk/ac/starlink/ttools/func/FuncTest.java
index 0a776cb..5693c38 100644
--- a/src/testcases/uk/ac/starlink/ttools/func/FuncTest.java
+++ b/src/testcases/uk/ac/starlink/ttools/func/FuncTest.java
@@ -10,6 +10,7 @@ import java.util.logging.Level;
 import uk.ac.starlink.ttools.cone.AsciiMocCoverage;
 import org.json.JSONArray;
 import org.json.JSONObject;
+import org.json.JSONException;
 import uk.ac.starlink.ttools.jel.JELUtils;
 import uk.ac.starlink.util.LogUtils;
 import uk.ac.starlink.util.TestCase;
@@ -656,6 +657,7 @@ public class FuncTest extends TestCase {
             "}                                                 "
          ).trim();
          JSONObject json = Json.jsonObject( txt );
+	 try {
          assertEquals( 23, json.getInt( "sequence" ) );
          assertEquals( 278.5,
                        json.getJSONObject("temperature").getDouble("value") );
@@ -668,17 +670,14 @@ public class FuncTest extends TestCase {
          JSONArray thingies = json.getJSONArray( "thingies" );
          assertArrayEquals( new double[] { 0, NAN, 2, NAN, 4 },
                             Json.jsonToDoubles( thingies ) );
-         assertArrayEquals( new String[] { "0", "one", "2.0", null, "4" },
-                            Json.jsonToStrings( thingies ) );
 
          JSONArray nums = Json.jsonArray( "[true, \"two\", 3.0, 4, null]" );
          assertArrayEquals( new double[] { NAN, NAN, 3, 4, NAN },
                             Json.jsonToDoubles( nums ) );
-         assertArrayEquals( new String[] { "true", "two", "3.0", "4", null },
-                            Json.jsonToStrings( nums ) );
          String[] tkeys = Json.jsonGetKeys( json.getJSONObject("temperature") );
          java.util.Arrays.sort( tkeys );
          assertArrayEquals( new String[] { "units", "value" }, tkeys );
+	 } catch (JSONException e) {}
     }
  
     public void testMaths() {
