QueryResultsOutputUtil { public static void toBindingSetJSONFile( final OutputStream out, final TupleExpr query, final QueryResultStream<VisibilityBindingSet> resultsStream, final AtomicBoolean shutdownSignal) throws TupleQueryResultHandlerException, IllegalStateException, RyaStreamsException { requireNonNull(out); requireNonNull(query); requireNonNull(resultsStream); requireNonNull(shutdownSignal); final SPARQLResultsJSONWriter writer = new SPARQLResultsJSONWriter(out); final WriterConfig config = writer.getWriterConfig(); config.set(BasicWriterSettings.PRETTY_PRINT, false); writer.startQueryResult( Lists.newArrayList(query.getBindingNames()) ); while(!shutdownSignal.get()) { for(final VisibilityBindingSet result : resultsStream.poll(1000)) { writer.handleSolution(result); } } writer.endQueryResult(); } private  QueryResultsOutputUtil(); static void toNtriplesFile(
            final OutputStream out,
            final QueryResultStream<VisibilityStatement> resultsStream,
            final AtomicBoolean shutdownSignal); static void toBindingSetJSONFile(
            final OutputStream out,
            final TupleExpr query,
            final QueryResultStream<VisibilityBindingSet> resultsStream,
            final AtomicBoolean shutdownSignal);  }
@Test public void toBindingSetJSONFile() throws Exception { final String sparql = "SELECT * WHERE { " + "?name <urn:worksAt> ?company . " + "OPTIONAL{ ?name <urn:ssn> ?ssn} " + "}"; final TupleExpr query = new SPARQLParser().parseQuery(sparql, null).getTupleExpr(); final AtomicBoolean shutdownSignal = new AtomicBoolean(false); final QueryResultStream<VisibilityBindingSet> resultsStream = mock(QueryResultStream.class); when(resultsStream.poll(anyLong())).thenAnswer(invocation -> { shutdownSignal.set(true); final List<VisibilityBindingSet> results = new ArrayList<>(); MapBindingSet bs = new MapBindingSet(); bs.addBinding("name", VF.createLiteral("alice")); bs.addBinding("company", VF.createLiteral("Taco Shop")); bs.addBinding("ssn", VF.createIRI("urn:111-11-1111")); results.add(new VisibilityBindingSet(bs, "")); bs = new MapBindingSet(); bs.addBinding("name", VF.createLiteral("bob")); bs.addBinding("company", VF.createLiteral("Cafe")); results.add(new VisibilityBindingSet(bs, "")); return results; }); final ByteArrayOutputStream out = new ByteArrayOutputStream(); QueryResultsOutputUtil.toBindingSetJSONFile(out, query, resultsStream, shutdownSignal); final String expected = "{\"head\":{\"vars\":[\"name\",\"company\",\"ssn\"]},\"results\":{" + "\"bindings\":[{\"name\":{\"type\":\"literal\",\"value\":\"alice\"},\"company\":{" + "\"type\":\"literal\",\"value\":\"Taco Shop\"},\"ssn\":{\"type\":\"uri\",\"value\":" + "\"urn:111-11-1111\"}},{\"name\":{\"type\":\"literal\",\"value\":\"bob\"},\"company\"" + ":{\"type\":\"literal\",\"value\":\"Cafe\"}}]}}"; final String json = new String(out.toByteArray(), Charsets.UTF_8); System.out.println(json); assertEquals(expected, json); }