You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@jena.apache.org by an...@apache.org on 2015/12/02 22:01:48 UTC

[4/4] jena git commit: Clean up classes in resultset package

Clean up classes in resultset package

Project: http://git-wip-us.apache.org/repos/asf/jena/repo
Commit: http://git-wip-us.apache.org/repos/asf/jena/commit/d4c73a31
Tree: http://git-wip-us.apache.org/repos/asf/jena/tree/d4c73a31
Diff: http://git-wip-us.apache.org/repos/asf/jena/diff/d4c73a31

Branch: refs/heads/master
Commit: d4c73a31f6cb9b7d5f10691dfe915112e3cdb1a3
Parents: aecb5f1
Author: Andy Seaborne <an...@apache.org>
Authored: Wed Dec 2 17:24:44 2015 +0000
Committer: Andy Seaborne <an...@apache.org>
Committed: Wed Dec 2 21:01:17 2015 +0000

----------------------------------------------------------------------
 .../apache/jena/sparql/resultset/JSONInput.java |  393 +++---
 .../sparql/resultset/JSONInputIterator.java     | 1289 ++++++++----------
 .../jena/sparql/resultset/JSONOutput.java       |   27 +-
 .../jena/sparql/resultset/JSONOutputASK.java    |   49 +-
 .../sparql/resultset/JSONOutputResultSet.java   |  387 +++---
 .../apache/jena/sparql/resultset/RDFInput.java  |  228 ++--
 .../jena/sparql/resultset/ResultSetApply.java   |   56 +-
 .../jena/sparql/resultset/ResultSetMem.java     |  106 +-
 .../jena/sparql/resultset/ResultsFormat.java    |   97 +-
 .../jena/sparql/resultset/SPARQLResult.java     |  231 ++--
 .../jena/sparql/resultset/SortedResultSet.java  |   10 +-
 .../apache/jena/sparql/resultset/TSVInput.java  |  121 +-
 .../jena/sparql/resultset/TSVInputIterator.java |  166 +--
 .../apache/jena/sparql/resultset/TSVOutput.java |   82 +-
 .../jena/sparql/resultset/TextOutput.java       |  112 +-
 .../apache/jena/sparql/resultset/XMLInput.java  |  106 +-
 .../apache/jena/sparql/resultset/XMLOutput.java |   39 +-
 .../jena/sparql/resultset/XMLOutputASK.java     |   90 +-
 18 files changed, 1700 insertions(+), 1889 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/jena/blob/d4c73a31/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInput.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInput.java b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInput.java
index 582f6b4..322a568 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInput.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInput.java
@@ -18,256 +18,231 @@
 
 package org.apache.jena.sparql.resultset;
 
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kBindings ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kBnode ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kBoolean ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kDatatype ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kHead ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kLink ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kLiteral ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kResults ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kType ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kTypedLiteral ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kUri ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kValue ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kVars ;
-import static org.apache.jena.sparql.resultset.JSONResultsKW.kXmlLang ;
-
-import java.io.InputStream ;
-import java.util.* ;
-
-import org.apache.jena.atlas.json.JSON ;
-import org.apache.jena.atlas.json.JsonArray ;
-import org.apache.jena.atlas.json.JsonObject ;
-import org.apache.jena.atlas.json.JsonValue ;
-import org.apache.jena.atlas.logging.Log ;
-import org.apache.jena.datatypes.RDFDatatype ;
-import org.apache.jena.datatypes.TypeMapper ;
-import org.apache.jena.graph.Node ;
-import org.apache.jena.graph.NodeFactory ;
-import org.apache.jena.query.ResultSet ;
-import org.apache.jena.rdf.model.Model ;
-import org.apache.jena.riot.lang.LabelToNode ;
-import org.apache.jena.riot.system.SyntaxLabels ;
-import org.apache.jena.sparql.core.Var ;
-import org.apache.jena.sparql.engine.QueryIterator ;
-import org.apache.jena.sparql.engine.ResultSetStream ;
-import org.apache.jena.sparql.engine.binding.Binding ;
-import org.apache.jena.sparql.engine.binding.BindingFactory ;
-import org.apache.jena.sparql.engine.binding.BindingMap ;
-import org.apache.jena.sparql.engine.iterator.QueryIterPlainWrapper ;
-import org.apache.jena.sparql.graph.GraphFactory ;
-
-public class JSONInput extends SPARQLResult
-{
-    public static ResultSet fromJSON(InputStream input)
-    {
-        SPARQLResult r = new JSONInput().process(input, null) ;
-        return r.getResultSet() ; 
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kBindings;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kBnode;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kBoolean;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kDatatype;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kHead;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kLink;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kLiteral;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kResults;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kType;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kTypedLiteral;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kUri;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kValue;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kVars;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.kXmlLang;
+
+import java.io.InputStream;
+import java.util.*;
+
+import org.apache.jena.atlas.json.JSON;
+import org.apache.jena.atlas.json.JsonArray;
+import org.apache.jena.atlas.json.JsonObject;
+import org.apache.jena.atlas.json.JsonValue;
+import org.apache.jena.atlas.logging.Log;
+import org.apache.jena.datatypes.RDFDatatype;
+import org.apache.jena.datatypes.TypeMapper;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.NodeFactory;
+import org.apache.jena.query.ResultSet;
+import org.apache.jena.rdf.model.Model;
+import org.apache.jena.riot.lang.LabelToNode;
+import org.apache.jena.riot.system.SyntaxLabels;
+import org.apache.jena.sparql.core.Var;
+import org.apache.jena.sparql.engine.QueryIterator;
+import org.apache.jena.sparql.engine.ResultSetStream;
+import org.apache.jena.sparql.engine.binding.Binding;
+import org.apache.jena.sparql.engine.binding.BindingFactory;
+import org.apache.jena.sparql.engine.binding.BindingMap;
+import org.apache.jena.sparql.engine.iterator.QueryIterPlainWrapper;
+import org.apache.jena.sparql.graph.GraphFactory;
+
+public class JSONInput extends SPARQLResult {
+    public static ResultSet fromJSON(InputStream input) {
+        SPARQLResult r = new JSONInput().process(input, null);
+        return r.getResultSet();
     }
-    
-    public static boolean booleanFromJSON(InputStream input)
-    {
-        SPARQLResult r = new JSONInput().process(input, null) ;
-        return r.getBooleanResult() ; 
+
+    public static boolean booleanFromJSON(InputStream input) {
+        SPARQLResult r = new JSONInput().process(input, null);
+        return r.getBooleanResult();
     }
-    
-    public static SPARQLResult make(InputStream input)
-    {
-        return make(input, null) ;
+
+    public static SPARQLResult make(InputStream input) {
+        return make(input, null);
     }
-    
-    public static SPARQLResult make(InputStream input, Model model)
-    {
-        return new JSONInput().process(input, model) ;
+
+    public static SPARQLResult make(InputStream input, Model model) {
+        return new JSONInput().process(input, model);
     }
 
     public JSONInput() {}
-    
-    public JSONInput(InputStream in)
-    {
-        this(in, null) ;
+
+    public JSONInput(InputStream in) {
+        this(in, null);
     }
 
     // See also XMLInputSAX for design structure.
-    public JSONInput(InputStream in, Model model)
-    {
+    public JSONInput(InputStream in, Model model) {
         if ( model == null )
-            model = GraphFactory.makeJenaDefaultModel() ;
-        process(in, model) ;
+            model = GraphFactory.makeJenaDefaultModel();
+        process(in, model);
     }
-    
-    Boolean booleanResult = null ;        // Valid if rows is null. 
-    List<Binding> rows = null ;
-    List<Var> vars = null ;
+
+    Boolean       booleanResult = null; // Valid if rows is null.
+    List<Binding> rows          = null;
+    List<Var>     vars          = null;
 
     // TODO Streaming version of JSON Result set processing
-    
-    private SPARQLResult process(InputStream in, Model model)
-    {
-        parse(in) ;
+
+    private SPARQLResult process(InputStream in, Model model) {
+        parse(in);
         if ( model == null )
-            model = GraphFactory.makeJenaDefaultModel() ;
-        if ( rows != null )
-        {
-            QueryIterator qIter = new QueryIterPlainWrapper(rows.iterator()) ;
-            ResultSet rs = new ResultSetStream(Var.varNames(vars), model, qIter) ;
-            super.set(rs) ;
-        }
-        else
-            super.set(booleanResult) ;
-        return this ;
+            model = GraphFactory.makeJenaDefaultModel();
+        if ( rows != null ) {
+            QueryIterator qIter = new QueryIterPlainWrapper(rows.iterator());
+            ResultSet rs = new ResultSetStream(Var.varNames(vars), model, qIter);
+            super.set(rs);
+        } else
+            super.set(booleanResult);
+        return this;
     }
-    
-    private void parse(InputStream in)
-    {
-        JsonObject obj = JSON.parse(in) ;
-        
-        if ( obj.hasKey(kBoolean) )
-        {
-            checkContains(obj, true, true, kHead, kBoolean) ;
-            booleanResult = obj.get(kBoolean).getAsBoolean().value() ;
-            rows = null ;
-            return ;
+
+    private void parse(InputStream in) {
+        JsonObject obj = JSON.parse(in);
+
+        if ( obj.hasKey(kBoolean) ) {
+            checkContains(obj, true, true, kHead, kBoolean);
+            booleanResult = obj.get(kBoolean).getAsBoolean().value();
+            rows = null;
+            return;
         }
-        
-        rows = new ArrayList<>(1000) ;
-        
-        checkContains(obj, true, true, kHead, kResults) ;
-        
+
+        rows = new ArrayList<>(1000);
+
+        checkContains(obj, true, true, kHead, kResults);
+
         // process head
-        if ( ! obj.get(kHead).isObject() )
-            throw new ResultSetException("Key 'head' must have a JSON object as value: found: "+obj.get(kHead)) ;
-        JsonObject head = obj.get(kHead).getAsObject() ;
-        
+        if ( !obj.get(kHead).isObject() )
+            throw new ResultSetException("Key 'head' must have a JSON object as value: found: " + obj.get(kHead));
+        JsonObject head = obj.get(kHead).getAsObject();
+
         // ---- Head
         // -- Link - array.
-        if ( head.hasKey(kLink) )
-        {
-            List<String> links = new ArrayList<>() ;
-
-            if ( head.get(kLink).isString() )
-            {
-                Log.warn(this, "Link field is a string, should be an array of strings") ;
-                links.add(head.get(kLink).getAsString().value()) ;
-            }
-            else
-            {
-                if ( ! head.get(kLink).isArray() )
-                    throw new ResultSetException("Key 'link' must have be an array: found: "+obj.get(kLink)) ;
-
-                for ( JsonValue v : head.get(kLink).getAsArray() )
-                {
-                    if ( ! v.isString() )
-                        throw new ResultSetException("Key 'link' must have be an array of strings: found: "+v) ;
-                    links.add(v.getAsString().value()) ;
+        if ( head.hasKey(kLink) ) {
+            List<String> links = new ArrayList<>();
+
+            if ( head.get(kLink).isString() ) {
+                Log.warn(this, "Link field is a string, should be an array of strings");
+                links.add(head.get(kLink).getAsString().value());
+            } else {
+                if ( !head.get(kLink).isArray() )
+                    throw new ResultSetException("Key 'link' must have be an array: found: " + obj.get(kLink));
+
+                for ( JsonValue v : head.get(kLink).getAsArray() ) {
+                    if ( !v.isString() )
+                        throw new ResultSetException("Key 'link' must have be an array of strings: found: " + v);
+                    links.add(v.getAsString().value());
                 }
             }
         }
         // -- Vars
-        vars = parseVars(head) ;
+        vars = parseVars(head);
 
         // ---- Results
-        JsonObject results = obj.get(kResults).getAsObject() ;
-        if ( ! results.get(kBindings).isArray() )
-            throw new ResultSetException("'bindings' must be an array") ;
-        JsonArray array = results.get(kBindings).getAsArray() ;
-        Iterator<JsonValue> iter = array.iterator() ;
-        
-        for ( ; iter.hasNext() ; )
-        {
-            BindingMap b = BindingFactory.create() ;
-            JsonValue v = iter.next() ;
-            if ( ! v.isObject() )
-                throw new ResultSetException("Entry in 'bindings' array must be an object {}")  ;
-            JsonObject x = v.getAsObject() ;
-            Set<String> varNames = x.keys() ;
-            for ( String vn : varNames )
-            {
-                //if ( ! vars.contains(vn) ) {}
-                JsonValue vt = x.get(vn) ;
-                if ( ! vt.isObject() )
-                    throw new ResultSetException("Binding for variable '"+vn+"' is not a JSON object: "+vt)  ;
-                Node n = parseOneTerm(vt.getAsObject()) ;
-                b.add(Var.alloc(vn), n) ;
+        JsonObject results = obj.get(kResults).getAsObject();
+        if ( !results.get(kBindings).isArray() )
+            throw new ResultSetException("'bindings' must be an array");
+        JsonArray array = results.get(kBindings).getAsArray();
+        Iterator<JsonValue> iter = array.iterator();
+
+        for ( ; iter.hasNext() ; ) {
+            BindingMap b = BindingFactory.create();
+            JsonValue v = iter.next();
+            if ( !v.isObject() )
+                throw new ResultSetException("Entry in 'bindings' array must be an object {}");
+            JsonObject x = v.getAsObject();
+            Set<String> varNames = x.keys();
+            for ( String vn : varNames ) {
+                // if ( ! vars.contains(vn) ) {}
+                JsonValue vt = x.get(vn);
+                if ( !vt.isObject() )
+                    throw new ResultSetException("Binding for variable '" + vn + "' is not a JSON object: " + vt);
+                Node n = parseOneTerm(vt.getAsObject());
+                b.add(Var.alloc(vn), n);
             }
-            rows.add(b) ;
+            rows.add(b);
         }
     }
-    
-    private List<Var> parseVars(JsonObject obj)
-    {
-        if ( ! obj.get(kVars).isArray() )
-            throw new ResultSetException("Key 'vars' must be a JSON array") ;
-        JsonArray a = obj.get(kVars).getAsArray() ;
-        Iterator<JsonValue> iter = a.iterator() ;
-        List<Var> vars = new ArrayList<>() ;
-        for ( ; iter.hasNext() ; )
-        {
-            JsonValue v = iter.next() ;
-            if ( ! v.isString() )
-                throw new ResultSetException("Entries in vars array must be strings") ;
-            Var var = Var.alloc(v.getAsString().value()) ;
-            vars.add(var) ;
+
+    private List<Var> parseVars(JsonObject obj) {
+        if ( !obj.get(kVars).isArray() )
+            throw new ResultSetException("Key 'vars' must be a JSON array");
+        JsonArray a = obj.get(kVars).getAsArray();
+        Iterator<JsonValue> iter = a.iterator();
+        List<Var> vars = new ArrayList<>();
+        for ( ; iter.hasNext() ; ) {
+            JsonValue v = iter.next();
+            if ( !v.isString() )
+                throw new ResultSetException("Entries in vars array must be strings");
+            Var var = Var.alloc(v.getAsString().value());
+            vars.add(var);
         }
-        return vars ;
+        return vars;
     }
 
-    LabelToNode labelMap = SyntaxLabels.createLabelToNode() ;
-    private Node parseOneTerm(JsonObject term)
-    {
-        checkContains(term, false, false, kType, kValue, kXmlLang, kDatatype) ;
-        
-        String type = stringOrNull(term, kType) ;
-        String v = stringOrNull(term, kValue) ;
-        
-        if ( kUri.equals(type) )
-        {
-            checkContains(term, false, true, kType, kValue) ;
-            String uri = v ;
-            Node n = NodeFactory.createURI(v) ;
-            return n ;
+    LabelToNode labelMap = SyntaxLabels.createLabelToNode();
+
+    private Node parseOneTerm(JsonObject term) {
+        checkContains(term, false, false, kType, kValue, kXmlLang, kDatatype);
+
+        String type = stringOrNull(term, kType);
+        String v = stringOrNull(term, kValue);
+
+        if ( kUri.equals(type) ) {
+            checkContains(term, false, true, kType, kValue);
+            String uri = v;
+            Node n = NodeFactory.createURI(v);
+            return n;
         }
-        
-        if ( kLiteral.equals(type) || kTypedLiteral.equals(type) )
-        {
-            String lang = stringOrNull(term, kXmlLang) ;
-            String dtStr = stringOrNull(term, kDatatype) ;
+
+        if ( kLiteral.equals(type) || kTypedLiteral.equals(type) ) {
+            String lang = stringOrNull(term, kXmlLang);
+            String dtStr = stringOrNull(term, kDatatype);
             if ( lang != null && dtStr != null )
-                throw new ResultSetException("Both language and datatype defined: "+term) ;
-            RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtStr) ;
-            return NodeFactory.createLiteral(v, lang, dt)  ;
+                throw new ResultSetException("Both language and datatype defined: " + term);
+            RDFDatatype dt = TypeMapper.getInstance().getSafeTypeByName(dtStr);
+            return NodeFactory.createLiteral(v, lang, dt);
         }
-        
+
         if ( kBnode.equals(type) )
-            return labelMap.get(null, v) ;
-        
-        throw new ResultSetException("Object key not recognized as valid for an RDF term: "+term) ;
+            return labelMap.get(null, v);
+
+        throw new ResultSetException("Object key not recognized as valid for an RDF term: " + term);
     }
-    
-    private static String stringOrNull(JsonObject obj, String key)
-    {
-        JsonValue v = obj.get(key) ;
-        if ( v == null ) return null ;
-        if ( ! v.isString() )
-            throw new ResultSetException("Not a string: key: "+key) ;
+
+    private static String stringOrNull(JsonObject obj, String key) {
+        JsonValue v = obj.get(key);
+        if ( v == null )
+            return null;
+        if ( !v.isString() )
+            throw new ResultSetException("Not a string: key: " + key);
         return v.getAsString().value();
-        
+
     }
-    
-    private static void checkContains(JsonObject term, boolean allowUndefinedKeys, boolean requireAllExpectedKeys, String...keys)
-    {
-        List<String> expectedKeys = Arrays.asList(keys) ;
+
+    private static void checkContains(JsonObject term, boolean allowUndefinedKeys, boolean requireAllExpectedKeys, String... keys) {
+        List<String> expectedKeys = Arrays.asList(keys);
         Set<String> declared = new HashSet<>();
-        for ( String k : term.keys() )
-        {
+        for ( String k : term.keys() ) {
             if ( !expectedKeys.contains(k) && !allowUndefinedKeys )
-                throw new ResultSetException("Expected only object keys "+Arrays.asList(keys)+" but encountered '"+k+"'") ;
-            if (expectedKeys.contains(k))
+                throw new ResultSetException("Expected only object keys " + Arrays.asList(keys) + " but encountered '" + k + "'");
+            if ( expectedKeys.contains(k) )
                 declared.add(k);
         }
-        
-        if (requireAllExpectedKeys && declared.size() < expectedKeys.size()) throw new ResultSetException("One or more of the required keys " + expectedKeys + " was not found");
+
+        if ( requireAllExpectedKeys && declared.size() < expectedKeys.size() )
+            throw new ResultSetException("One or more of the required keys " + expectedKeys + " was not found");
     }
 }
-

http://git-wip-us.apache.org/repos/asf/jena/blob/d4c73a31/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInputIterator.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInputIterator.java b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInputIterator.java
index 9b85f9e..26575af 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInputIterator.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONInputIterator.java
@@ -18,735 +18,640 @@
 
 package org.apache.jena.sparql.resultset;
 
-import java.io.InputStream ;
-import java.util.* ;
-
-import org.apache.jena.atlas.AtlasException ;
-import org.apache.jena.atlas.io.IO ;
-import org.apache.jena.atlas.io.IndentedWriter ;
-import org.apache.jena.atlas.io.PeekReader ;
-import org.apache.jena.atlas.iterator.PeekIterator ;
-import org.apache.jena.atlas.json.io.parser.TokenizerJSON ;
-import org.apache.jena.datatypes.TypeMapper ;
-import org.apache.jena.graph.Node ;
-import org.apache.jena.graph.NodeFactory ;
-import org.apache.jena.query.QueryException ;
-import org.apache.jena.riot.RiotParseException ;
-import org.apache.jena.riot.tokens.Token ;
-import org.apache.jena.riot.tokens.TokenType ;
-import org.apache.jena.sparql.core.Var ;
-import org.apache.jena.sparql.engine.binding.Binding ;
-import org.apache.jena.sparql.engine.binding.BindingFactory ;
-import org.apache.jena.sparql.engine.binding.BindingMap ;
-import org.apache.jena.sparql.engine.iterator.QueryIteratorBase ;
-import org.apache.jena.sparql.serializer.SerializationContext ;
+import java.io.InputStream;
+import java.util.*;
+
+import org.apache.jena.atlas.AtlasException;
+import org.apache.jena.atlas.io.IO;
+import org.apache.jena.atlas.io.IndentedWriter;
+import org.apache.jena.atlas.io.PeekReader;
+import org.apache.jena.atlas.iterator.PeekIterator;
+import org.apache.jena.atlas.json.io.parser.TokenizerJSON;
+import org.apache.jena.datatypes.TypeMapper;
+import org.apache.jena.graph.Node;
+import org.apache.jena.graph.NodeFactory;
+import org.apache.jena.query.QueryException;
+import org.apache.jena.riot.RiotParseException;
+import org.apache.jena.riot.tokens.Token;
+import org.apache.jena.riot.tokens.TokenType;
+import org.apache.jena.sparql.core.Var;
+import org.apache.jena.sparql.engine.binding.Binding;
+import org.apache.jena.sparql.engine.binding.BindingFactory;
+import org.apache.jena.sparql.engine.binding.BindingMap;
+import org.apache.jena.sparql.engine.iterator.QueryIteratorBase;
+import org.apache.jena.sparql.serializer.SerializationContext;
 
 /**
- * Streaming Iterator over SPARQL JSON results, not yet fully implemented (see JENA-267)
+ * Streaming Iterator over SPARQL JSON results, not yet fully implemented (see
+ * JENA-267)
  * <p>
- * Creating the Iterator automatically causes it to parse a small chunk of the stream to determine the variables in the result set either by reading the header or reading some portion of the results if the results appear before the header since JSON does not guarantee the order of keys within an object
+ * Creating the Iterator automatically causes it to parse a small chunk of the
+ * stream to determine the variables in the result set either by reading the
+ * header or reading some portion of the results if the results appear before
+ * the header since JSON does not guarantee the order of keys within an object
  * </p>
  */
 public class JSONInputIterator extends QueryIteratorBase {
-	
-	private InputStream input;
-
-	private boolean isBooleanResults = false, boolResult = false, headerSeen = false;
-	private Binding binding = null;
-	private TokenizerJSON tokens;
-	private PeekIterator<Token> peekIter;
-	
-	private Queue<Binding> cache = new LinkedList<>();
-	private Set<String> vars = new HashSet<>();
-	
-	/**
-	 * Creates a SPARQL JSON Iterator
-	 * <p>
-	 * Automatically parses some portion of the input to determine the variables in use
-	 * </p>
-	 */
-	public JSONInputIterator(InputStream input)
-	{
-		this.input = input;
-		this.tokens = new TokenizerJSON(PeekReader.makeUTF8(input));
-		this.peekIter = new PeekIterator<>(this.tokens);
-		
-		//We should always parse the first little bit to see the head stuff or to cache a chunk of results and infer the headers
-		//Primarily we are trying to find out what the variables are
-		preParse();
-	}
-	
-	/**
-	 * Returns the variables present in the result sets
-	 */
-	public Iterator<String> getVars()
-	{
-		return vars.iterator();
-	}
-	
-	/**
-	 * Gets whether the SPARQL JSON represents a boolean result set
-	 */
-	public boolean isBooleanResult()
-	{
-		return isBooleanResults;
-	}
-
-	/**
-	 * Does the pre-parsing which attempts to read the header of the results file and determine variables present
-	 * <p>
-	 * If the header is encountered first then we read this, if the results are encountered first we parse the first 100 results and determine the variables present from those instead
-	 * </p> 
-	 */
-	private void preParse()
-	{
-		//First off the { to start the object
-		expect("Expected the start of the JSON Results Object", TokenType.LBRACE);
-		
-		//Then expect to see a Property Name
-		//Loop here because we might see some things we can discard first
-		do
-		{
-			if (!isPropertyName())
-			{
-				Token t = nextToken();
-				String name = t.getImage();
-				checkColon();
-				
-				if (name.equals("head"))
-				{
-					if (headerSeen) exception(t, "Invalid duplicate header property");
-					parseHeader();
-					//Continue afterwards because we want to be in place to start streaming results
-				}
-				else if (name.equals("boolean"))
-				{
-					parseBoolean();
-					//Afterwards we continue because we want to see an empty head
-				}
-				else if (name.equals("results"))
-				{
-					if (isBooleanResults) exception(t, "Encountered results property when boolean property has already been countered");
-					
-					//Scroll to first result
-					parseToFirstResult();
-					
-					//If we already saw the header then exit at this point
-					if (headerSeen) return;
-
-					//If not we're going to pre-cache some chunk of results so we can infer the variable names
-					boolean complete = cacheResults(100);
-					
-					//If this exhausted the result set then we can continue looking for the header
-					//Otherwise we should exit as we may eventually see the header later...
-					if (!complete) 
-					{
-						//TODO Now determine variables present from this
-						return;
-					}
-				}
-				else
-				{
-					ignoreValue();
-				}
-				checkComma(TokenType.RBRACE);
-			}
-			else if (lookingAt(TokenType.RBRACE))
-			{
-				//We hit the end of the result object already
-				if (!headerSeen) exception(peekToken(), "End of JSON Results Object encountered before a valid header was seen");
-				nextToken();
-				
-				//Shouldn't be any further content
-				if (!lookingAt(TokenType.EOF)) exception(peekToken(), "Unexpected content after end of JSON Results Object");
-				
-				//Can stop our initial buffering at this stage
-				return;
-			}
-			else
-			{
-				exception(peekToken(), "Expected a JSON property name but got %s", peekToken());
-			}
-		} while (true);
-	}
-	
-	private void parseHeader()
-	{
-		do
-		{
-			if (isPropertyName())
-			{
-				Token t = nextToken();
-				String name = t.getImage();
-				checkColon();
-				
-				if (name.equals("vars"))
-				{
-					parseVars();
-				}
-				else if (name.equals("link"))
-				{
-					//Throw away the links
-					skipLinks();
-				}
-				else
-				{
-					exception(t, "Unexpected property %s encountered in head object", name);
-				}
-				checkComma(TokenType.RBRACE);
-			} 
-			else if (lookingAt(TokenType.RBRACE))
-			{
-				nextToken();
-				return;
-			}
-			else
-			{
-				exception(peekToken(), "Unexpected Token encountered while parsing head object");
-			}
-		} while (true);
-	}
-	
-	private void parseVars()
-	{
-		if (lookingAt(TokenType.LBRACKET))
-		{
-			nextToken();
-			vars.clear();
-			do
-			{
-				if (lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2))
-				{
-					Token t = nextToken();
-					String var = t.getImage();
-					vars.add(var);
-					checkComma(TokenType.RBRACKET);
-				}
-				else if (lookingAt(TokenType.RBRACKET))
-				{
-					nextToken();
-					return;
-				}
-				else
-				{
-					exception(peekToken(), "Unexpected Token encountered while parsing the variables list in the head object");
-				}
-			} while (true);
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token ecountered, expected a [ to start the array of variables in the head object");
-		}
-	}
-	
-	private void skipLinks()
-	{
-		if (lookingAt(TokenType.LBRACKET))
-		{
-			nextToken();
-			do
-			{
-				if (lookingAt(TokenType.RBRACKET))
-				{
-					//End of links
-					nextToken();
-					return;
-				}
-				else if (lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2))
-				{
-					//Ignore link and continue
-					nextToken();
-				}
-				else
-				{
-					exception(peekToken(), "Unexpected Token when a Link URI was expected");
-				}
-				checkComma(TokenType.RBRACKET);
-			} while (true);
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected token when a [ was expected to start the list of URIs for a link property");
-		}
-	}
-	
-	private void parseToFirstResult()
-	{
-		if (lookingAt(TokenType.LBRACE))
-		{
-			nextToken();
-			if (isPropertyName())
-			{
-				Token t = nextToken();
-				String name = t.getImage();
-				if (name.equals("bindings"))
-				{
-					checkColon();
-					if (lookingAt(TokenType.LBRACKET))
-					{
-						nextToken();
-					}
-					else
-					{
-						exception(peekToken(), "Unexpected Token encountered, expected a [ for the start of the bindings array");
-					}
-				}
-				else
-				{
-					exception(t, "Unexpected Token encountered, expected the bindings property");
-				}
-			}
-			else
-			{
-				exception(peekToken(), "Unexpected Token ecnountered, expected the bindings property");
-			}
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token encountered, expected a { to start the results list object");
-		}
-	}
-		
-	private void parseToEnd() {
-		//TODO Parse through to end of the JSON document consuming the header if we haven't seen it already
-		checkComma(TokenType.RBRACE);
-	}
-	
-	private void ignoreValue() {
-		if (isPropertyName()) {
-			//Just a string value so can discard and then check for the subsequent comma
-			nextToken();
-			checkComma(TokenType.RBRACE);
-		} else if (lookingAt(TokenType.DECIMAL) || lookingAt(TokenType.INTEGER) || lookingAt(TokenType.DOUBLE) || lookingAt(TokenType.KEYWORD))	{
-			//Just a numeric/keyword (boolean) value do discard and check for subsequent comma
-			nextToken();
-			checkComma(TokenType.RBRACE);
-		} else if (lookingAt(TokenType.LBRACE)) {
-			//Start of an Object
-			nextToken();
-			
-			//TODO We should really care about the syntactic validity of objects we are ignoring but that seems like a bit too much effort
-			int openBraces = 1;
-			while (openBraces >= 1)
-			{
-				Token next = nextToken();
-				if (next.getType().equals(TokenType.LBRACE)) {
-					openBraces++;
-				} else if (next.getType().equals(TokenType.RBRACE)) {
-					openBraces--;
-				}
-			}
-			checkComma(TokenType.RBRACE);
-		} else if (lookingAt(TokenType.LBRACKET)) {
-			//Start of an Array
-			nextToken();
-			
-			//TODO We should really care about the syntactic validity of objects we are ignoring but that seems like a bit too much effort
-			int openBraces = 1;
-			while (openBraces >= 1)
-			{
-				Token next = nextToken();
-				if (next.getType().equals(TokenType.LBRACKET)) {
-					openBraces++;
-				} else if (next.getType().equals(TokenType.RBRACKET)) {
-					openBraces--;
-				}
-			}
-			checkComma(TokenType.RBRACE);
-		} else {
-			exception(peekToken(), "Unexpected Token");
-		}
-	}
-	
-	/**
-	 * Caches the first N results so we can infer variables, indicates whether the caching exhausted the result set
-	 * @param n Number of results to cache
-	 */
-	private boolean cacheResults(int n)
-	{
-		for (int i = 0; i < n; i++)
-		{
-			if (parseNextBinding())
-			{
-				this.cache.add(this.binding);
-				this.binding = null;
-			}
-			else
-			{
-				return true;
-			}
-		}
-		return false;
-	}
-	
-	private void parseBoolean()
-	{
-		isBooleanResults = true;
-		if (lookingAt(TokenType.KEYWORD))
-		{
-			Token t = nextToken();
-			String keyword = t.getImage();
-			if (keyword.equals("true"))
-			{
-				boolResult = true;
-			}
-			else if (keyword.equals("false"))
-			{
-				boolResult = false;
-			}
-			else
-			{
-				exception(t, "Unexpected keyword %s encountered, expected true or false", keyword);
-			}
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected token when a true/false keyword was expected for the value of the boolean property");
-		}
-	}
-	
-	@Override
-	public void output(IndentedWriter out, SerializationContext sCxt) {
-		// Not needed - only called as part of printing/debugging query plans.
-		out.println("JSONInputIterator") ;
-	}
-
-	@Override
-	protected boolean hasNextBinding() {
-		if (isBooleanResults) return false;
-		
-		if (this.input != null)
-		{
-			if (this.cache.size() > 0) {
-				this.binding = this.cache.remove();
-				return true;
-			} else if (this.binding == null) {
-				return this.parseNextBinding();
-			} else {
-				return true;
-			}
-		}
-		else
-		{
-			return false;
-		}
-	}
-	
-	private boolean parseNextBinding() {
-		if (lookingAt(TokenType.LBRACE))
-		{
-			nextToken();
-			BindingMap b = BindingFactory.create();
-			do
-			{
-				if (isPropertyName())
-				{
-					Token t = nextToken();
-					String var = t.getImage();
-					checkColon();
-										
-					Node n = parseNode();
-					b.add(Var.alloc(var), n);
-					
-					checkComma(TokenType.RBRACE);
-				}
-				else if (lookingAt(TokenType.RBRACE))
-				{
-					nextToken();
-					checkComma(TokenType.RBRACKET);
-					break;
-				}
-				else
-				{
-					exception(peekToken(), "Unexpected Token encountered, expected a property name to indicate the value for a variable");
-				}
-			} while (true);
-			
-			this.binding = b;
-			return true;
-		}
-		else if (lookingAt(TokenType.RBRACKET))
-		{
-			//End of Bindings Array
-			nextToken();
-			if (lookingAt(TokenType.RBRACE))
-			{
-				nextToken();
-				parseToEnd();
-			}
-			else
-			{
-				exception(peekToken(), "Unexpected Token encountered, expected a } to end the results object");
-			}
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token encountered, expected a { for the start of a binding of ] to end the array of bindings");
-		}
-		return false;
-	}
-	
-	private Node parseNode() {
-		String type, value, lang, datatype;
-		type = value = lang = datatype = null;
-		
-		if (lookingAt(TokenType.LBRACE))
-		{
-			Token pos = nextToken();
-			
-			//Collect the Properties
-			do
-			{
-				if (isPropertyName())
-				{
-					Token t = nextToken();
-					String name = t.getImage();
-					checkColon();
-					
-					if (name.equals("type")) {
-						if (type != null) exception(t, "Illegal duplicate type property");
-						type = parseNodeInfo("type");
-					} else if (name.equals("value")) {
-						if (value != null) exception(t, "Illegal duplicate value property");
-						value = parseNodeInfo("value");
-					} else if (name.equals("datatype")) {
-						if (datatype != null) exception(t, "Illegal duplicate datatype property");
-						datatype = parseNodeInfo("datatype");
-					} else if (name.equals("xml:lang")) {
-						if (lang != null) exception(t, "Illegal duplicate xml:lang property");
-						lang = parseNodeInfo("xml:lang");
-					} else {
-						exception(t, "Unexpected Property Name '%s', expected one of type, value, datatype or xml:lang", name);
-					}					
-				}
-				else if (lookingAt(TokenType.RBRACE))
-				{
-					nextToken();
-					break;
-				}
-				else
-				{
-					exception(peekToken(), "Unexpected Token, expected a property name as part of a Node object");
-				}
-			} while (true);
-			
-			//Error if missing type or value
-			if (type == null) exception(pos, "Encountered a Node object with no type property");
-			if (value == null) exception(pos, "Encountered a Node object with no value property");
-			
-			//Generate a Node based on the properties we saw
-			if (type.equals("uri")) {
-				return NodeFactory.createURI(value);
-			} else if (type.equals("literal")) {
-				if (datatype != null) {
-					return NodeFactory.createLiteral(value, TypeMapper.getInstance().getSafeTypeByName(datatype));
-				} else if (lang != null) {
-					return NodeFactory.createLiteral(value, lang);
-				} else {
-					return NodeFactory.createLiteral(value);
-				}
-			} else if (type.equals("bnode")) {
-				return NodeFactory.createBlankNode(value);
-			} else {
-				exception(pos, "Encountered a Node object with an invalid type value '%s', expected one of uri, literal or bnode", type);
-			}
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token, expected a { for the start of a Node object");
-		}
-		return null;
-	}
-	
-	private String parseNodeInfo(String name) {
-		if (lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2))
-		{
-			Token t = nextToken();
-			String value = t.getImage();
-			checkComma(TokenType.RBRACE);
-			return value;
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token, expected a string as the value for the %s property", name);
-			return null;
-		}
-	}
-
-	@Override
-	protected Binding moveToNextBinding() {
-        if (!hasNext()) throw new NoSuchElementException() ;
+
+    private InputStream         input;
+
+    private boolean             isBooleanResults = false,
+                                    boolResult = false, headerSeen = false;
+    private Binding             binding          = null;
+    private TokenizerJSON       tokens;
+    private PeekIterator<Token> peekIter;
+
+    private Queue<Binding>      cache            = new LinkedList<>();
+    private Set<String>         vars             = new HashSet<>();
+
+    /**
+     * Creates a SPARQL JSON Iterator
+     * <p>
+     * Automatically parses some portion of the input to determine the variables
+     * in use
+     * </p>
+     */
+    public JSONInputIterator(InputStream input) {
+        this.input = input;
+        this.tokens = new TokenizerJSON(PeekReader.makeUTF8(input));
+        this.peekIter = new PeekIterator<>(this.tokens);
+
+        // We should always parse the first little bit to see the head stuff or
+        // to cache a chunk of results and infer the headers
+        // Primarily we are trying to find out what the variables are
+        preParse();
+    }
+
+    /**
+     * Returns the variables present in the result sets
+     */
+    public Iterator<String> getVars() {
+        return vars.iterator();
+    }
+
+    /**
+     * Gets whether the SPARQL JSON represents a boolean result set
+     */
+    public boolean isBooleanResult() {
+        return isBooleanResults;
+    }
+
+    /**
+     * Does the pre-parsing which attempts to read the header of the results
+     * file and determine variables present
+     * <p>
+     * If the header is encountered first then we read this, if the results are
+     * encountered first we parse the first 100 results and determine the
+     * variables present from those instead
+     * </p>
+     */
+    private void preParse() {
+        // First off the { to start the object
+        expect("Expected the start of the JSON Results Object", TokenType.LBRACE);
+
+        // Then expect to see a Property Name
+        // Loop here because we might see some things we can discard first
+        do {
+            if ( !isPropertyName() ) {
+                Token t = nextToken();
+                String name = t.getImage();
+                checkColon();
+
+                if ( name.equals("head") ) {
+                    if ( headerSeen )
+                        exception(t, "Invalid duplicate header property");
+                    parseHeader();
+                    // Continue afterwards because we want to be in place to
+                    // start streaming results
+                } else if ( name.equals("boolean") ) {
+                    parseBoolean();
+                    // Afterwards we continue because we want to see an empty
+                    // head
+                } else if ( name.equals("results") ) {
+                    if ( isBooleanResults )
+                        exception(t, "Encountered results property when boolean property has already been countered");
+
+                    // Scroll to first result
+                    parseToFirstResult();
+
+                    // If we already saw the header then exit at this point
+                    if ( headerSeen )
+                        return;
+
+                    // If not we're going to pre-cache some chunk of results so
+                    // we can infer the variable names
+                    boolean complete = cacheResults(100);
+
+                    // If this exhausted the result set then we can continue
+                    // looking for the header
+                    // Otherwise we should exit as we may eventually see the
+                    // header later...
+                    if ( !complete ) {
+                        // TODO Now determine variables present from this
+                        return;
+                    }
+                } else {
+                    ignoreValue();
+                }
+                checkComma(TokenType.RBRACE);
+            } else if ( lookingAt(TokenType.RBRACE) ) {
+                // We hit the end of the result object already
+                if ( !headerSeen )
+                    exception(peekToken(), "End of JSON Results Object encountered before a valid header was seen");
+                nextToken();
+
+                // Shouldn't be any further content
+                if ( !lookingAt(TokenType.EOF) )
+                    exception(peekToken(), "Unexpected content after end of JSON Results Object");
+
+                // Can stop our initial buffering at this stage
+                return;
+            } else {
+                exception(peekToken(), "Expected a JSON property name but got %s", peekToken());
+            }
+        } while (true);
+    }
+
+    private void parseHeader() {
+        do {
+            if ( isPropertyName() ) {
+                Token t = nextToken();
+                String name = t.getImage();
+                checkColon();
+
+                if ( name.equals("vars") ) {
+                    parseVars();
+                } else if ( name.equals("link") ) {
+                    // Throw away the links
+                    skipLinks();
+                } else {
+                    exception(t, "Unexpected property %s encountered in head object", name);
+                }
+                checkComma(TokenType.RBRACE);
+            } else if ( lookingAt(TokenType.RBRACE) ) {
+                nextToken();
+                return;
+            } else {
+                exception(peekToken(), "Unexpected Token encountered while parsing head object");
+            }
+        } while (true);
+    }
+
+    private void parseVars() {
+        if ( lookingAt(TokenType.LBRACKET) ) {
+            nextToken();
+            vars.clear();
+            do {
+                if ( lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2) ) {
+                    Token t = nextToken();
+                    String var = t.getImage();
+                    vars.add(var);
+                    checkComma(TokenType.RBRACKET);
+                } else if ( lookingAt(TokenType.RBRACKET) ) {
+                    nextToken();
+                    return;
+                } else {
+                    exception(peekToken(), "Unexpected Token encountered while parsing the variables list in the head object");
+                }
+            } while (true);
+        } else {
+            exception(peekToken(), "Unexpected Token ecountered, expected a [ to start the array of variables in the head object");
+        }
+    }
+
+    private void skipLinks() {
+        if ( lookingAt(TokenType.LBRACKET) ) {
+            nextToken();
+            do {
+                if ( lookingAt(TokenType.RBRACKET) ) {
+                    // End of links
+                    nextToken();
+                    return;
+                } else if ( lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2) ) {
+                    // Ignore link and continue
+                    nextToken();
+                } else {
+                    exception(peekToken(), "Unexpected Token when a Link URI was expected");
+                }
+                checkComma(TokenType.RBRACKET);
+            } while (true);
+        } else {
+            exception(peekToken(), "Unexpected token when a [ was expected to start the list of URIs for a link property");
+        }
+    }
+
+    private void parseToFirstResult() {
+        if ( lookingAt(TokenType.LBRACE) ) {
+            nextToken();
+            if ( isPropertyName() ) {
+                Token t = nextToken();
+                String name = t.getImage();
+                if ( name.equals("bindings") ) {
+                    checkColon();
+                    if ( lookingAt(TokenType.LBRACKET) ) {
+                        nextToken();
+                    } else {
+                        exception(peekToken(), "Unexpected Token encountered, expected a [ for the start of the bindings array");
+                    }
+                } else {
+                    exception(t, "Unexpected Token encountered, expected the bindings property");
+                }
+            } else {
+                exception(peekToken(), "Unexpected Token ecnountered, expected the bindings property");
+            }
+        } else {
+            exception(peekToken(), "Unexpected Token encountered, expected a { to start the results list object");
+        }
+    }
+
+    private void parseToEnd() {
+        // TODO Parse through to end of the JSON document consuming the header
+        // if we haven't seen it already
+        checkComma(TokenType.RBRACE);
+    }
+
+    private void ignoreValue() {
+        if ( isPropertyName() ) {
+            // Just a string value so can discard and then check for the
+            // subsequent comma
+            nextToken();
+            checkComma(TokenType.RBRACE);
+        } else if ( lookingAt(TokenType.DECIMAL) || lookingAt(TokenType.INTEGER) || lookingAt(TokenType.DOUBLE)
+                    || lookingAt(TokenType.KEYWORD) ) {
+            // Just a numeric/keyword (boolean) value do discard and check for
+            // subsequent comma
+            nextToken();
+            checkComma(TokenType.RBRACE);
+        } else if ( lookingAt(TokenType.LBRACE) ) {
+            // Start of an Object
+            nextToken();
+
+            // TODO We should really care about the syntactic validity of
+            // objects we are ignoring but that seems like a bit too much effort
+            int openBraces = 1;
+            while (openBraces >= 1) {
+                Token next = nextToken();
+                if ( next.getType().equals(TokenType.LBRACE) ) {
+                    openBraces++;
+                } else if ( next.getType().equals(TokenType.RBRACE) ) {
+                    openBraces--;
+                }
+            }
+            checkComma(TokenType.RBRACE);
+        } else if ( lookingAt(TokenType.LBRACKET) ) {
+            // Start of an Array
+            nextToken();
+
+            // TODO We should really care about the syntactic validity of
+            // objects we are ignoring but that seems like a bit too much effort
+            int openBraces = 1;
+            while (openBraces >= 1) {
+                Token next = nextToken();
+                if ( next.getType().equals(TokenType.LBRACKET) ) {
+                    openBraces++;
+                } else if ( next.getType().equals(TokenType.RBRACKET) ) {
+                    openBraces--;
+                }
+            }
+            checkComma(TokenType.RBRACE);
+        } else {
+            exception(peekToken(), "Unexpected Token");
+        }
+    }
+
+    /**
+     * Caches the first N results so we can infer variables, indicates whether
+     * the caching exhausted the result set
+     * 
+     * @param n
+     *            Number of results to cache
+     */
+    private boolean cacheResults(int n) {
+        for ( int i = 0 ; i < n ; i++ ) {
+            if ( parseNextBinding() ) {
+                this.cache.add(this.binding);
+                this.binding = null;
+            } else {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private void parseBoolean() {
+        isBooleanResults = true;
+        if ( lookingAt(TokenType.KEYWORD) ) {
+            Token t = nextToken();
+            String keyword = t.getImage();
+            if ( keyword.equals("true") ) {
+                boolResult = true;
+            } else if ( keyword.equals("false") ) {
+                boolResult = false;
+            } else {
+                exception(t, "Unexpected keyword %s encountered, expected true or false", keyword);
+            }
+        } else {
+            exception(peekToken(), "Unexpected token when a true/false keyword was expected for the value of the boolean property");
+        }
+    }
+
+    @Override
+    public void output(IndentedWriter out, SerializationContext sCxt) {
+        // Not needed - only called as part of printing/debugging query plans.
+        out.println("JSONInputIterator");
+    }
+
+    @Override
+    protected boolean hasNextBinding() {
+        if ( isBooleanResults )
+            return false;
+
+        if ( this.input != null ) {
+            if ( this.cache.size() > 0 ) {
+                this.binding = this.cache.remove();
+                return true;
+            } else if ( this.binding == null ) {
+                return this.parseNextBinding();
+            } else {
+                return true;
+            }
+        } else {
+            return false;
+        }
+    }
+
+    private boolean parseNextBinding() {
+        if ( lookingAt(TokenType.LBRACE) ) {
+            nextToken();
+            BindingMap b = BindingFactory.create();
+            do {
+                if ( isPropertyName() ) {
+                    Token t = nextToken();
+                    String var = t.getImage();
+                    checkColon();
+
+                    Node n = parseNode();
+                    b.add(Var.alloc(var), n);
+
+                    checkComma(TokenType.RBRACE);
+                } else if ( lookingAt(TokenType.RBRACE) ) {
+                    nextToken();
+                    checkComma(TokenType.RBRACKET);
+                    break;
+                } else {
+                    exception(peekToken(), "Unexpected Token encountered, expected a property name to indicate the value for a variable");
+                }
+            } while (true);
+
+            this.binding = b;
+            return true;
+        } else if ( lookingAt(TokenType.RBRACKET) ) {
+            // End of Bindings Array
+            nextToken();
+            if ( lookingAt(TokenType.RBRACE) ) {
+                nextToken();
+                parseToEnd();
+            } else {
+                exception(peekToken(), "Unexpected Token encountered, expected a } to end the results object");
+            }
+        } else {
+            exception(peekToken(),
+                      "Unexpected Token encountered, expected a { for the start of a binding of ] to end the array of bindings");
+        }
+        return false;
+    }
+
+    private Node parseNode() {
+        String type, value, lang, datatype;
+        type = value = lang = datatype = null;
+
+        if ( lookingAt(TokenType.LBRACE) ) {
+            Token pos = nextToken();
+
+            // Collect the Properties
+            do {
+                if ( isPropertyName() ) {
+                    Token t = nextToken();
+                    String name = t.getImage();
+                    checkColon();
+
+                    if ( name.equals("type") ) {
+                        if ( type != null )
+                            exception(t, "Illegal duplicate type property");
+                        type = parseNodeInfo("type");
+                    } else if ( name.equals("value") ) {
+                        if ( value != null )
+                            exception(t, "Illegal duplicate value property");
+                        value = parseNodeInfo("value");
+                    } else if ( name.equals("datatype") ) {
+                        if ( datatype != null )
+                            exception(t, "Illegal duplicate datatype property");
+                        datatype = parseNodeInfo("datatype");
+                    } else if ( name.equals("xml:lang") ) {
+                        if ( lang != null )
+                            exception(t, "Illegal duplicate xml:lang property");
+                        lang = parseNodeInfo("xml:lang");
+                    } else {
+                        exception(t, "Unexpected Property Name '%s', expected one of type, value, datatype or xml:lang", name);
+                    }
+                } else if ( lookingAt(TokenType.RBRACE) ) {
+                    nextToken();
+                    break;
+                } else {
+                    exception(peekToken(), "Unexpected Token, expected a property name as part of a Node object");
+                }
+            } while (true);
+
+            // Error if missing type or value
+            if ( type == null )
+                exception(pos, "Encountered a Node object with no type property");
+            if ( value == null )
+                exception(pos, "Encountered a Node object with no value property");
+
+            // Generate a Node based on the properties we saw
+            if ( type.equals("uri") ) {
+                return NodeFactory.createURI(value);
+            } else if ( type.equals("literal") ) {
+                if ( datatype != null ) {
+                    return NodeFactory.createLiteral(value, TypeMapper.getInstance().getSafeTypeByName(datatype));
+                } else if ( lang != null ) {
+                    return NodeFactory.createLiteral(value, lang);
+                } else {
+                    return NodeFactory.createLiteral(value);
+                }
+            } else if ( type.equals("bnode") ) {
+                return NodeFactory.createBlankNode(value);
+            } else {
+                exception(pos, "Encountered a Node object with an invalid type value '%s', expected one of uri, literal or bnode", type);
+            }
+        } else {
+            exception(peekToken(), "Unexpected Token, expected a { for the start of a Node object");
+        }
+        return null;
+    }
+
+    private String parseNodeInfo(String name) {
+        if ( lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2) ) {
+            Token t = nextToken();
+            String value = t.getImage();
+            checkComma(TokenType.RBRACE);
+            return value;
+        } else {
+            exception(peekToken(), "Unexpected Token, expected a string as the value for the %s property", name);
+            return null;
+        }
+    }
+
+    @Override
+    protected Binding moveToNextBinding() {
+        if ( !hasNext() )
+            throw new NoSuchElementException();
         Binding b = this.binding;
-        this.binding = null ;
+        this.binding = null;
         return b;
-	}
-
-	@Override
-	protected void closeIterator() {
-		IO.close(input);
-		input = null;
-	}
-
-	@Override
-	protected void requestCancel() {
-		//Don't need to do anything special to cancel
-		//Superclass should take care of that and call closeIterator() where we do our actual clean up
-	}
-
-	// JSON Parsing Helpers taken from LangRDFJSON
-	
-    private boolean isPropertyName()
-	{
-		return lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2);
-	}
-
-    private Token checkValidForStringProperty(String property)
-    {
-    	Token t = null;
-    	if (lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2))
-    	{
-    		t = nextToken();
-    	}
-    	else
-    	{
-    		exception(peekToken(), "JSON Values given for property " + property + " must be Strings") ;
-    	}
-    	return t;
-    }
-
-	private void checkColon()
-	{
-		if (!lookingAt(TokenType.COLON))
-		{
-			exception(peekToken(), "Expected a : character after a JSON Property Name but got %s", peekToken()) ;
-		}
-		nextToken() ;
-	}
-	
-	private void checkComma(TokenType terminator)
-	{
-		if (lookingAt(TokenType.COMMA))
-		{
-			nextToken();
-		}
-		else if (lookingAt(terminator))
-		{
-			return;
-		}
-		else
-		{
-			exception(peekToken(), "Unexpected Token encountered, expected a , or a %s", terminator);
-		}
-	}
-	
-	// Streaming Parsing Helper Functions nicked from LangEngine
-	
+    }
+
+    @Override
+    protected void closeIterator() {
+        IO.close(input);
+        input = null;
+    }
+
+    @Override
+    protected void requestCancel() {
+        // Don't need to do anything special to cancel
+        // Superclass should take care of that and call closeIterator() where we
+        // do our actual clean up
+    }
+
+    // JSON Parsing Helpers taken from LangRDFJSON
+
+    private boolean isPropertyName() {
+        return lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2);
+    }
+
+    private Token checkValidForStringProperty(String property) {
+        Token t = null;
+        if ( lookingAt(TokenType.STRING1) || lookingAt(TokenType.STRING2) ) {
+            t = nextToken();
+        } else {
+            exception(peekToken(), "JSON Values given for property " + property + " must be Strings");
+        }
+        return t;
+    }
+
+    private void checkColon() {
+        if ( !lookingAt(TokenType.COLON) ) {
+            exception(peekToken(), "Expected a : character after a JSON Property Name but got %s", peekToken());
+        }
+        nextToken();
+    }
+
+    private void checkComma(TokenType terminator) {
+        if ( lookingAt(TokenType.COMMA) ) {
+            nextToken();
+        } else if ( lookingAt(terminator) ) {
+            return;
+        } else {
+            exception(peekToken(), "Unexpected Token encountered, expected a , or a %s", terminator);
+        }
+    }
+
+    // Streaming Parsing Helper Functions nicked from LangEngine
+
     // ---- Managing tokens.
-    
-    protected final Token peekToken()
-    {
+
+    protected final Token peekToken() {
         // Avoid repeating.
-        if ( eof() ) return tokenEOF ;
-        return peekIter.peek() ;
+        if ( eof() )
+            return tokenEOF;
+        return peekIter.peek();
     }
-    
+
     // Set when we get to EOF to record line/col of the EOF.
-    private Token tokenEOF = null ;
+    private Token tokenEOF = null;
 
-    protected final boolean eof()
-    {
+    protected final boolean eof() {
         if ( tokenEOF != null )
-            return true ;
-        
-        if ( ! moreTokens() )
-        {
-            tokenEOF = new Token(tokens.getLine(), tokens.getColumn()) ;
-            tokenEOF.setType(TokenType.EOF) ;
-            return true ;
+            return true;
+
+        if ( !moreTokens() ) {
+            tokenEOF = new Token(tokens.getLine(), tokens.getColumn());
+            tokenEOF.setType(TokenType.EOF);
+            return true;
         }
-        return false ;
+        return false;
     }
 
-    protected final boolean moreTokens() 
-    {
-        return peekIter.hasNext() ;
+    protected final boolean moreTokens() {
+        return peekIter.hasNext();
     }
-    
-    protected final boolean lookingAt(TokenType tokenType)
-    {
+
+    protected final boolean lookingAt(TokenType tokenType) {
         if ( eof() )
-            return tokenType == TokenType.EOF ;
+            return tokenType == TokenType.EOF;
         if ( tokenType == TokenType.NODE )
-            return peekToken().isNode() ;
-        return peekToken().hasType(tokenType) ;
-    }
-    
-    // Remember line/col of last token for messages 
-    protected long currLine = -1 ;
-    protected long currCol = -1 ;
-    
-    protected final Token nextToken()
-    {
+            return peekToken().isNode();
+        return peekToken().hasType(tokenType);
+    }
+
+    // Remember line/col of last token for messages
+    protected long currLine = -1;
+    protected long currCol  = -1;
+
+    protected final Token nextToken() {
         if ( eof() )
-            return tokenEOF ;
-        
+            return tokenEOF;
+
         // Tokenizer errors appear here!
         try {
-            Token t = peekIter.next() ;
-            currLine = t.getLine() ;
-            currCol = t.getColumn() ;
-            return t ;
-        } catch (RiotParseException ex)
-        {
+            Token t = peekIter.next();
+            currLine = t.getLine();
+            currCol = t.getColumn();
+            return t;
+        }
+        catch (RiotParseException ex) {
             // Intercept to log it.
-            raiseException(ex) ;
-            throw ex ;
+            raiseException(ex);
+            throw ex;
         }
-        catch (AtlasException ex)
-        {
+        catch (AtlasException ex) {
             // Bad I/O
-            RiotParseException ex2 = new RiotParseException(ex.getMessage(), -1, -1) ;
-            raiseException(ex2) ;
-            throw ex2 ;
+            RiotParseException ex2 = new RiotParseException(ex.getMessage(), -1, -1);
+            raiseException(ex2);
+            throw ex2;
         }
     }
-    
-    protected final void expectOrEOF(String msg, TokenType tokenType)
-    {
+
+    protected final void expectOrEOF(String msg, TokenType tokenType) {
         // DOT or EOF
         if ( eof() )
-            return ;
-        expect(msg, tokenType) ;
-    }
-    
-    protected final void expect(String msg, TokenType ttype)
-    {
-        
-        if ( ! lookingAt(ttype) )
-        {
-            Token location = peekToken() ;
-            exception(location, msg) ;
+            return;
+        expect(msg, tokenType);
+    }
+
+    protected final void expect(String msg, TokenType ttype) {
+
+        if ( !lookingAt(ttype) ) {
+            Token location = peekToken();
+            exception(location, msg);
         }
-        nextToken() ;
+        nextToken();
     }
 
-    protected final void exception(Token token, String msg, Object... args)
-    { 
+    protected final void exception(Token token, String msg, Object... args) {
         if ( token != null )
-            exceptionDirect(String.format(msg, args), token.getLine(), token.getColumn()) ;
+            exceptionDirect(String.format(msg, args), token.getLine(), token.getColumn());
         else
-            exceptionDirect(String.format(msg, args), -1, -1) ;
+            exceptionDirect(String.format(msg, args), -1, -1);
     }
-    
-    protected final void exceptionDirect(String msg, long line, long col)
-    { 
-        raiseException(new RiotParseException(msg, line, col)) ;
+
+    protected final void exceptionDirect(String msg, long line, long col) {
+        raiseException(new RiotParseException(msg, line, col));
     }
-    
-    protected final void raiseException(RiotParseException ex)
-    { 
+
+    protected final void raiseException(RiotParseException ex) {
         throw new QueryException("Error passing SPARQL JSON results", ex);
     }
-	
-}
 
+}

http://git-wip-us.apache.org/repos/asf/jena/blob/d4c73a31/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutput.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutput.java b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutput.java
index d1479ac..f894f80 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutput.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutput.java
@@ -18,28 +18,25 @@
 
 package org.apache.jena.sparql.resultset;
 
-import java.io.OutputStream ;
+import java.io.OutputStream;
 
-import org.apache.jena.query.ResultSet ;
+import org.apache.jena.query.ResultSet;
 
-public class JSONOutput extends OutputBase
-{
+public class JSONOutput extends OutputBase {
     public JSONOutput() {}
-    
+
     @Override
-    public void format(OutputStream out, ResultSet resultSet)
-    {
+    public void format(OutputStream out, ResultSet resultSet) {
         // Use direct string output - more control
-    
-        JSONOutputResultSet jsonOut =  new JSONOutputResultSet(out) ;
-        ResultSetApply a = new ResultSetApply(resultSet, jsonOut) ;
-        a.apply() ;
+
+        JSONOutputResultSet jsonOut = new JSONOutputResultSet(out);
+        ResultSetApply a = new ResultSetApply(resultSet, jsonOut);
+        a.apply();
     }
 
     @Override
-    public void format(OutputStream out, boolean booleanResult)
-    {
-        JSONOutputASK jsonOut = new JSONOutputASK(out) ;
-        jsonOut.exec(booleanResult) ;
+    public void format(OutputStream out, boolean booleanResult) {
+        JSONOutputASK jsonOut = new JSONOutputASK(out);
+        jsonOut.exec(booleanResult);
     }
 }

http://git-wip-us.apache.org/repos/asf/jena/blob/d4c73a31/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputASK.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputASK.java b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputASK.java
index bf82c55..4b030e2 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputASK.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputASK.java
@@ -18,40 +18,37 @@
 
 package org.apache.jena.sparql.resultset;
 
+import static org.apache.jena.sparql.resultset.JSONResultsKW.*;
 
-import static org.apache.jena.sparql.resultset.JSONResultsKW.* ;
+import java.io.OutputStream;
 
-import java.io.OutputStream ;
-
-import org.apache.jena.atlas.io.IO ;
-import org.apache.jena.atlas.json.io.JSWriter ;
+import org.apache.jena.atlas.io.IO;
+import org.apache.jena.atlas.json.io.JSWriter;
 
 /** JSON Output (ASK format) */
 
-public class JSONOutputASK
-{
-    private OutputStream outStream ;
-    
+public class JSONOutputASK {
+    private OutputStream outStream;
+
     public JSONOutputASK(OutputStream outStream) {
         this.outStream = outStream;
-        
+
     }
 
-    public void exec(boolean result)
-    {
-        JSWriter out = new JSWriter(outStream) ;
-        
-        out.startOutput() ;
-
-        out.startObject() ;
-        out.key(kHead) ;
-        out.startObject() ;
-        out.finishObject() ;
-        out.pair(kBoolean, result) ;
-        out.finishObject() ;
-        
-        out.finishOutput() ;
-
-        IO.flush(outStream) ;
+    public void exec(boolean result) {
+        JSWriter out = new JSWriter(outStream);
+
+        out.startOutput();
+
+        out.startObject();
+        out.key(kHead);
+        out.startObject();
+        out.finishObject();
+        out.pair(kBoolean, result);
+        out.finishObject();
+
+        out.finishOutput();
+
+        IO.flush(outStream);
     }
 }

http://git-wip-us.apache.org/repos/asf/jena/blob/d4c73a31/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputResultSet.java
----------------------------------------------------------------------
diff --git a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputResultSet.java b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputResultSet.java
index ea0f383..1d0377a 100644
--- a/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputResultSet.java
+++ b/jena-arq/src/main/java/org/apache/jena/sparql/resultset/JSONOutputResultSet.java
@@ -18,254 +18,249 @@
 
 package org.apache.jena.sparql.resultset;
 
-import static org.apache.jena.sparql.resultset.JSONResultsKW.* ;
-
-import java.io.OutputStream ;
-import java.util.HashMap ;
-import java.util.Iterator ;
-import java.util.Map ;
-
-import org.apache.jena.atlas.io.IndentedWriter ;
-import org.apache.jena.atlas.json.io.JSWriter ;
-import org.apache.jena.atlas.logging.Log ;
-import org.apache.jena.query.ARQ ;
-import org.apache.jena.query.QuerySolution ;
-import org.apache.jena.query.ResultSet ;
-import org.apache.jena.rdf.model.Literal ;
-import org.apache.jena.rdf.model.RDFNode ;
-import org.apache.jena.rdf.model.Resource ;
-import org.apache.jena.rdf.model.impl.Util ;
+import static org.apache.jena.sparql.resultset.JSONResultsKW.*;
+
+import java.io.OutputStream;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.jena.atlas.io.IndentedWriter;
+import org.apache.jena.atlas.json.io.JSWriter;
+import org.apache.jena.atlas.logging.Log;
+import org.apache.jena.query.ARQ;
+import org.apache.jena.query.QuerySolution;
+import org.apache.jena.query.ResultSet;
+import org.apache.jena.rdf.model.Literal;
+import org.apache.jena.rdf.model.RDFNode;
+import org.apache.jena.rdf.model.Resource;
+import org.apache.jena.rdf.model.impl.Util;
 
 /**
- * A JSON writer for SPARQL Result Sets.  Uses Jena Atlas JSON support. 
+ * A JSON writer for SPARQL Result Sets. Uses Jena Atlas JSON support.
  * 
- * Format: <a href="http://www.w3.org/TR/sparql11-results-json/">SPARQL 1.1 Query Results JSON Format</a> 
- */ 
-
-public class JSONOutputResultSet implements ResultSetProcessor
-{
-    static boolean multiLineValues = false ;
-    static boolean multiLineVarNames = false ;
-    
-    private boolean outputGraphBNodeLabels = false ;
-    private IndentedWriter out ;
-    private int bNodeCounter = 0 ;
-    private Map<Resource, String> bNodeMap = new HashMap<>() ;
-    
-    JSONOutputResultSet(OutputStream outStream)
-    { this(new IndentedWriter(outStream)) ; }
-    
-    JSONOutputResultSet(IndentedWriter indentedOut)
-    {   out = indentedOut ;
-        outputGraphBNodeLabels = ARQ.isTrue(ARQ.outputGraphBNodeLabels) ;
+ * Format: <a href="http://www.w3.org/TR/sparql11-results-json/">SPARQL 1.1
+ * Query Results JSON Format</a>
+ */
+
+public class JSONOutputResultSet implements ResultSetProcessor {
+    static boolean                multiLineValues        = false;
+    static boolean                multiLineVarNames      = false;
+
+    private boolean               outputGraphBNodeLabels = false;
+    private IndentedWriter        out;
+    private int                   bNodeCounter           = 0;
+    private Map<Resource, String> bNodeMap               = new HashMap<>();
+
+    JSONOutputResultSet(OutputStream outStream) {
+        this(new IndentedWriter(outStream));
+    }
+
+    JSONOutputResultSet(IndentedWriter indentedOut) {
+        out = indentedOut;
+        outputGraphBNodeLabels = ARQ.isTrue(ARQ.outputGraphBNodeLabels);
     }
-    
+
     @Override
-    public void start(ResultSet rs)
-    {
-        out.println("{") ;
-        out.incIndent() ;
-        doHead(rs) ;
-        out.println(quoteName(kResults)+": {") ;
-        out.incIndent() ;
-        out.println(quoteName(kBindings)+": [") ;
-        out.incIndent() ;
-        firstSolution = true ;
+    public void start(ResultSet rs) {
+        out.println("{");
+        out.incIndent();
+        doHead(rs);
+        out.println(quoteName(kResults) + ": {");
+        out.incIndent();
+        out.println(quoteName(kBindings) + ": [");
+        out.incIndent();
+        firstSolution = true;
     }
 
     @Override
-    public void finish(ResultSet rs)
-    {
+    public void finish(ResultSet rs) {
         // Close last binding.
-        out.println() ;
-        
-        out.decIndent() ;       // bindings
-        out.println("]") ;
-        out.decIndent() ;
-        out.println("}") ;      // results
-        out.decIndent() ;
-        out.println("}") ;      // top level {}
-        out.flush() ;
+        out.println();
+
+        out.decIndent(); // bindings
+        out.println("]");
+        out.decIndent();
+        out.println("}"); // results
+        out.decIndent();
+        out.println("}"); // top level {}
+        out.flush();
     }
 
-    private void doHead(ResultSet rs)
-    {
-        out.println(quoteName(kHead)+": {") ;
-        out.incIndent() ;
-        doLink(rs) ;
-        doVars(rs) ;
-        out.decIndent() ;
-        out.println("} ,") ;
+    private void doHead(ResultSet rs) {
+        out.println(quoteName(kHead) + ": {");
+        out.incIndent();
+        doLink(rs);
+        doVars(rs);
+        out.decIndent();
+        out.println("} ,");
     }
-    
-    private void doLink(ResultSet rs)
-    {
+
+    private void doLink(ResultSet rs) {
         // ---- link
-        //out.println("\"link\": []") ;
+        // out.println("\"link\": []") ;
     }
-    
-    private void doVars(ResultSet rs)
-    {
+
+    private void doVars(ResultSet rs) {
         // On one line.
-        out.print(quoteName(kVars)+": [ ") ;
-        if ( multiLineVarNames ) out.println() ;
-        out.incIndent() ;
-        for (Iterator<String> iter = rs.getResultVars().iterator() ; iter.hasNext() ; )
-        {
-            String varname = iter.next() ;
-            out.print("\""+varname+"\"") ;
-            if ( multiLineVarNames ) out.println() ;
+        out.print(quoteName(kVars) + ": [ ");
+        if ( multiLineVarNames )
+            out.println();
+        out.incIndent();
+        for ( Iterator<String> iter = rs.getResultVars().iterator() ; iter.hasNext() ; ) {
+            String varname = iter.next();
+            out.print("\"" + varname + "\"");
+            if ( multiLineVarNames )
+                out.println();
             if ( iter.hasNext() )
-                out.print(" , ") ;
+                out.print(" , ");
         }
-        out.println(" ]") ;
-        out.decIndent() ;
+        out.println(" ]");
+        out.decIndent();
     }
 
-    boolean firstSolution = true ;
-    boolean firstBindingInSolution = true ;
-    
+    boolean firstSolution          = true;
+    boolean firstBindingInSolution = true;
+
     // NB assumes are on end of previous line.
     @Override
-    public void start(QuerySolution qs)
-    {
-        if ( ! firstSolution )
-            out.println(" ,") ;
-        firstSolution = false ;
-        out.println("{") ;
-        out.incIndent() ;
-        firstBindingInSolution = true ;
+    public void start(QuerySolution qs) {
+        if ( !firstSolution )
+            out.println(" ,");
+        firstSolution = false;
+        out.println("{");
+        out.incIndent();
+        firstBindingInSolution = true;
     }
 
     @Override
-    public void finish(QuerySolution qs)
-    {
-        out.println() ;     // Finish last binding
-        out.decIndent() ;
-        out.print("}") ;    // NB No newline
+    public void finish(QuerySolution qs) {
+        out.println(); // Finish last binding
+        out.decIndent();
+        out.print("}"); // NB No newline
     }
 
     @Override
-    public void binding(String varName, RDFNode value)
-    {
+    public void binding(String varName, RDFNode value) {
         if ( value == null )
-            return ;
-        
+            return;
+
         if ( !firstBindingInSolution )
-            out.println(" ,") ;
-        firstBindingInSolution = false ;
+            out.println(" ,");
+        firstBindingInSolution = false;
 
         // Do not use quoteName - varName may not be JSON-safe as a bare name.
-        out.print(quote(varName)+": { ") ;
-        if ( multiLineValues ) out.println() ;
-        
-        out.incIndent() ;
+        out.print(quote(varName) + ": { ");
+        if ( multiLineValues )
+            out.println();
+
+        out.incIndent();
         // Old, explicit unbound
-//        if ( value == null )
-//            printUnbound() ;
-//        else
-      	if ( value.isLiteral() )
-            printLiteral((Literal)value) ;
+        // if ( value == null )
+        // printUnbound() ;
+        // else
+        if ( value.isLiteral() )
+            printLiteral((Literal)value);
         else if ( value.isResource() )
-            printResource((Resource)value) ;
-        else 
-            Log.warn(this, "Unknown RDFNode type in result set: "+value.getClass()) ;
-        out.decIndent() ;
-        
-        if ( !multiLineValues ) out.print(" ") ; 
-        out.print("}") ;        // NB No newline
+            printResource((Resource)value);
+        else
+            Log.warn(this, "Unknown RDFNode type in result set: " + value.getClass());
+        out.decIndent();
+
+        if ( !multiLineValues )
+            out.print(" ");
+        out.print("}"); // NB No newline
     }
-    
-//    private void printUnbound()
-//    {
-//        out.print(quoteName(kType)+ ": "+quote(kUnbound)+" , ") ;
-//        if ( multiLineValues ) out.println() ;
-//        out.print(quoteName(kValue)+": null") ;
-//        if ( multiLineValues ) out.println() ;
-//    }
-
-    private void printLiteral(Literal literal)
-    {
-        String datatype = literal.getDatatypeURI() ;
-        String lang = literal.getLanguage() ;
-        
-        if ( Util.isSimpleString(literal) || Util.isLangString(literal) )
-        {
-            out.print(quoteName(kType)+": "+quote(kLiteral)+" , ") ;
-            if ( multiLineValues ) out.println() ;
-            
-            if ( lang != null && !lang.equals("") )
-            {
-                out.print(quoteName(kXmlLang)+": "+quote(lang)+" , ") ;
-                if ( multiLineValues ) out.println() ;
+
+    // private void printUnbound()
+    // {
+    // out.print(quoteName(kType)+ ": "+quote(kUnbound)+" , ") ;
+    // if ( multiLineValues ) out.println() ;
+    // out.print(quoteName(kValue)+": null") ;
+    // if ( multiLineValues ) out.println() ;
+    // }
+
+    private void printLiteral(Literal literal) {
+        String datatype = literal.getDatatypeURI();
+        String lang = literal.getLanguage();
+
+        if ( Util.isSimpleString(literal) || Util.isLangString(literal) ) {
+            out.print(quoteName(kType) + ": " + quote(kLiteral) + " , ");
+            if ( multiLineValues )
+                out.println();
+
+            if ( lang != null && !lang.equals("") ) {
+                out.print(quoteName(kXmlLang) + ": " + quote(lang) + " , ");
+                if ( multiLineValues )
+                    out.println();
             }
         } else {
-            out.print(quoteName(kDatatype)+": "+quote(datatype)+" , ") ;
-            if ( multiLineValues ) out.println() ;
-            
-            out.print(quoteName(kType)+": "+quote(kTypedLiteral)+" , ") ;
-            if ( multiLineValues ) out.println() ;
+            out.print(quoteName(kDatatype) + ": " + quote(datatype) + " , ");
+            if ( multiLineValues )
+                out.println();
+
+            out.print(quoteName(kType) + ": " + quote(kTypedLiteral) + " , ");
+            if ( multiLineValues )
+                out.println();
         }
-            
-        out.print(quoteName(kValue)+": "+quote(literal.getLexicalForm())) ;
-        if ( multiLineValues ) out.println() ;
+
+        out.print(quoteName(kValue) + ": " + quote(literal.getLexicalForm()));
+        if ( multiLineValues )
+            out.println();
     }
 
-    private void printResource(Resource resource)
-    {
-        if ( resource.isAnon() )
-        {
-            String label ; 
+    private void printResource(Resource resource) {
+        if ( resource.isAnon() ) {
+            String label;
             if ( outputGraphBNodeLabels )
-                label = resource.getId().getLabelString() ;
-            else
-            {
-                if ( ! bNodeMap.containsKey(resource))
-                    bNodeMap.put(resource, "b"+(bNodeCounter++)) ;
-                label = bNodeMap.get(resource) ;
+                label = resource.getId().getLabelString();
+            else {
+                if ( !bNodeMap.containsKey(resource) )
+                    bNodeMap.put(resource, "b" + (bNodeCounter++));
+                label = bNodeMap.get(resource);
             }
-            
-            out.print(quoteName(kType)+": "+quote(kBnode)+" , ") ;
-            if ( multiLineValues ) out.println() ;
-            
-            out.print(quoteName(kValue)+": "+quote(label)) ;
-            
-            if ( multiLineValues ) out.println() ;
-        }
-        else
-        {
-            out.print(quoteName(kType)+": "+quote(kUri)+" , ") ;
-            if ( multiLineValues ) out.println() ;
-            out.print(quoteName(kValue)+": "+quote(resource.getURI())) ;
-            if ( multiLineValues ) out.println() ;
-            return ;
+
+            out.print(quoteName(kType) + ": " + quote(kBnode) + " , ");
+            if ( multiLineValues )
+                out.println();
+
+            out.print(quoteName(kValue) + ": " + quote(label));
+
+            if ( multiLineValues )
+                out.println();
+        } else {
+            out.print(quoteName(kType) + ": " + quote(kUri) + " , ");
+            if ( multiLineValues )
+                out.println();
+            out.print(quoteName(kValue) + ": " + quote(resource.getURI()));
+            if ( multiLineValues )
+                out.println();
+            return;
         }
     }
-    
-    private static String quote(String string)
-    {
-        return JSWriter.outputQuotedString(string) ;
+
+    private static String quote(String string) {
+        return JSWriter.outputQuotedString(string);
     }
-    
+
     // Quote a name (known to be JSON-safe)
     // Never the RHS of a member entry (for example "false")
     // Some (the Java JSON code for one) JSON parsers accept an unquoted
     // string as a name of a name/value pair.
-    
-    private static String quoteName(String string)
-    {
+
+    private static String quoteName(String string) {
         // Safest to quote anyway.
-        return quote(string) ;
-        
+        return quote(string);
+
         // Assumes only called with safe names
-        //return string ;
-        
+        // return string ;
+
         // Better would be:
         // starts a-z, constains a-z,0-9, not a keyword(true, false, null)
-//        if ( string.contains(something not in a-z0-9)
-//        and         
-//        //return "\""+string+"\"" ;
-//        return JSONObject.quote(string) ;
+        // if ( string.contains(something not in a-z0-9)
+        // and
+        // //return "\""+string+"\"" ;
+        // return JSONObject.quote(string) ;
     }
 
 }