org.apache.jena.query.ResultSetFormatter Java Examples

The following examples show how to use org.apache.jena.query.ResultSetFormatter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: QueryTestCaseType.java    From shacl with Apache License 2.0 6 votes vote down vote up
public static String createResultSetJSON(String queryString, Model model) {
	CurrentThreadFunctions old = CurrentThreadFunctionRegistry.register(model);
	try {
		Query query = ARQFactory.get().createQuery(model, queryString);
		try(QueryExecution qexec = ARQFactory.get().createQueryExecution(query, model)) {
   			ResultSet actualResults = qexec.execSelect();
   			ByteArrayOutputStream os = new ByteArrayOutputStream();
   			ResultSetFormatter.outputAsJSON(os, actualResults);
               return os.toString("UTF-8");
		}
	} 
	catch (UnsupportedEncodingException e) {
		throw ExceptionUtil.throwUnchecked(e);
	}
	finally {
		CurrentThreadFunctionRegistry.unregister(old);
	}
}
 
Example #2
Source File: DBPediaService.java    From baleen with Apache License 2.0 6 votes vote down vote up
/**
 * Search DBPedia for candidates with a language restriction on certain variables
 *
 * @param selectVars The placeholders for variables to find eg ?x ?y
 * @param whereClauses An array of StringTriple in Subject, Predicate, Object form
 * @param filterClause Clause String to filter results
 * @param limit The maximum number of Candidates to return
 * @param idField A uniquely identifying field contained in the returned Candidates
 * @param nameField The name field used to find the Candidates
 * @param languageSpecificVars Variables to restrict to the specified language
 * @return a Set of DBPediaCandidates
 * @throws ParseException Exception thrown if the SPARQL query fails to parse
 */
public Set<DefaultCandidate> searchForCandidates(
    String[] selectVars,
    StringTriple[] whereClauses,
    String filterClause,
    int limit,
    String idField,
    String nameField,
    String[] languageSpecificVars)
    throws ParseException {

  Query query = buildQuery(selectVars, whereClauses, filterClause, limit, languageSpecificVars);

  QueryExecution qe = QueryExecutionFactory.sparqlService(DBPEDIA_SPARQL_ENDPOINT, query);

  ResultSet rs = qe.execSelect();

  if (LOGGER.isDebugEnabled()) {
    ResultSet rsToPrint = qe.execSelect();
    LOGGER.debug(ResultSetFormatter.asText(rsToPrint));
  }

  return getCandidates(rs, idField, nameField);
}
 
Example #3
Source File: ExTDB4.java    From xcurator with Apache License 2.0 6 votes vote down vote up
public static void main(String... argv)
{
    // Direct way: Make a TDB-back Jena model in the named directory.
    String directory = "MyDatabases/DB1" ;
    Dataset dataset = TDBFactory.createDataset(directory) ;
    
    // Potentially expensive query.
    String sparqlQueryString = "SELECT (count(*) AS ?count) { ?s ?p ?o }" ;
    // See http://incubator.apache.org/jena/documentation/query/app_api.html
    
    Query query = QueryFactory.create(sparqlQueryString) ;
    QueryExecution qexec = QueryExecutionFactory.create(query, dataset) ;
    ResultSet results = qexec.execSelect() ;
    ResultSetFormatter.out(results) ;
    qexec.close() ;

    dataset.close();
}
 
Example #4
Source File: tarql.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processResults(TarqlQueryExecution ex) throws IOException {
	if (testQuery && ex.getFirstQuery().getConstructTemplate() != null) {
		IndentedWriter out = new IndentedWriter(System.out); 
		new FmtTemplate(out, new SerializationContext(ex.getFirstQuery())).format(ex.getFirstQuery().getConstructTemplate());
		out.flush();
	}
	if (ex.getFirstQuery().isSelectType()) {
		System.out.println(ResultSetFormatter.asText(ex.execSelect()));
	} else if (ex.getFirstQuery().isAskType()) {
		System.out.println(ResultSetFormatter.asText(ex.execSelect()));
	} else if (ex.getFirstQuery().isConstructType()) {
		resultTripleIterator = resultTripleIterator.andThen(ex.execTriples());
	} else {
		cmdError("Only query forms CONSTRUCT, SELECT and ASK are supported");
	}
}
 
Example #5
Source File: Test.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateTest() {
		// Add a new book to the collection
//		String service = "http://219.248.137.7:13030/icbms/update";
//		UpdateRequest ur = UpdateFactory
//				.create(""
//						+ "delete  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  ?value . } "
//						+ "insert  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  \"19\" . } " //<-- 19대신 여기 온도를 넣어주세
//						+ "WHERE   { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }");
//		UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service);
//		up.execute();

		// Query the collection, dump output
//		String service1 = "http://219.248.137.7:13030/icbms/";
//		QueryExecution qe = QueryExecutionFactory.sparqlService(service1,
//				"SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 ");
//
//		ResultSet results = qe.execSelect();
//		ResultSetFormatter.out(System.out, results);
//		qe.close();
		Model model = ModelFactory.createDefaultModel();
		Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6")));
		model.add(s);
		String query = "select * {?s ?p ?o }";
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		ResultSetFormatter.out(System.out, results);
		qe.close();
	}
 
Example #6
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleCount() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select  (count(?s) as ?count) where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();

	// 값을 console에 출력함
	ResultSetFormatter.out(rs);
}
 
Example #7
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleAll() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select ?s ?p ?o {?s ?p ?o}";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}
 
Example #8
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * DW데이타 지우기
 * @throws Exception
 * @return void
 */
public static final void deleteDWTripleAll2() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint");

	String queryString = "delete data where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}
 
Example #9
Source File: Driver.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
static void client(int loops, CountDownLatch cdlStart, CountDownLatch cdlFinish) {
    //conn2 = RDFConnectionFactory.connect("http://localhost:"+F2_PORT+DS_NAME) ;

    Runnable r = ()->{
        RDFConnection conn1 = RDFConnectionFactory.connect("http://localhost:"+F1_PORT+DS_NAME) ;
        try {
            cdlStart.countDown();
            cdlStart.await();
        }
        catch (InterruptedException e) {
            e.printStackTrace(System.err);
            return ;
        }

        try (RDFConnection conn = conn1) {
            for ( int i = 0 ; i < loops ; i++ ) {
                String now = DateTimeUtils.nowAsXSDDateTimeString()+"-"+i;
                try {
                    // This can abort and the update is then lost
                    conn.update("INSERT DATA { <x:s> <x:p> '"+now+"' }");

                } catch (DeltaException ex) {
                    System.out.flush();
                    System.err.println("\nSystem abort\n");
                }
                try ( QueryExecution qExec = conn.query("SELECT * { ?s ?p ?o}") ) {
                    ResultSetFormatter.consume(qExec.execSelect());
                    // QueryExecUtils.executeQuery(qExec);
                }

            }
        }
        cdlFinish.countDown();
    };

    new Thread(r).start();
}
 
Example #10
Source File: DeltaEx06_LocalDatasetToFuseki.java    From rdf-delta with Apache License 2.0 5 votes vote down vote up
public static void main2(String ...args) {
    // ---- Fuseki server with patch operation.
    int PORT = 2020 ;
    // In-memory dataset
    DatasetGraph dsgFuseki = DatasetGraphFactory.createTxnMem();

    String serviceName = "patch";
    FusekiServer server = fusekiServerWithPatch("/ds", PORT, dsgFuseki, serviceName);
    server.start();

    // ---- Destination for changes is the Fuseki patch opration.
    String url = "http://localhost:"+PORT+"/ds/"+serviceName;

    RDFChanges changeSender = DeltaClientLib.destination(url);
    // In the case of http/https URLs, this is done with
    //    RDFChanges changeSender = new RDFChangesHTTP(url);

    // ---- Local dataset.
    DatasetGraph dsgLocal = DatasetGraphFactory.createTxnMem();
    // Combined datasetgraph and changes.
    // Changes will be POSTed to the URL.
    DatasetGraph dsg = RDFPatchOps.changes(dsgLocal, changeSender);

    // ---- Do something. Read in data.ttl inside a transaction.
    // (data.ttl is in src/main/resources/)
    Txn.executeWrite(dsg,
        ()->RDFDataMgr.read(dsg, "data.ttl")
        );

    // ---- Query Fuseki
    RDFConnection conn = RDFConnectionFactory.connect("http://localhost:"+PORT+"/ds");
    try( QueryExecution qExec = conn.query("PREFIX ex: <http://example.org/> SELECT * { ?s ?p ?o }") ) {
        ResultSet rs = qExec.execSelect();
        ResultSetFormatter.out(rs, qExec.getQuery());
    }
}
 
Example #11
Source File: Test.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void updateTest() {
		// Add a new book to the collection
//		String service = "http://219.248.137.7:13030/icbms/update";
//		UpdateRequest ur = UpdateFactory
//				.create(""
//						+ "delete  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  ?value . } "
//						+ "insert  { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue>  \"19\" . } " //<-- 19대신 여기 온도를 넣어주세
//						+ "WHERE   { <http://www.pineone.com/campus/TemperatureObservationValue_LB0001> <http://data.nasa.gov/qudt/owl/qudt#hasNumericValue> ?value . }");
//		UpdateProcessor up = UpdateExecutionFactory.createRemote(ur, service);
//		up.execute();

		// Query the collection, dump output
//		String service1 = "http://219.248.137.7:13030/icbms/";
//		QueryExecution qe = QueryExecutionFactory.sparqlService(service1,
//				"SELECT * WHERE {<http://www.pineone.com/campus/Student_S00001> ?r ?y} limit 20 ");
//
//		ResultSet results = qe.execSelect();
//		ResultSetFormatter.out(System.out, results);
//		qe.close();
		Model model = ModelFactory.createDefaultModel();
		Statement s = model.createStatement(model.createResource("ex:e1"),model.createProperty("ex:p1"), ResourceFactory.createTypedLiteral(new String("0.6")));
		model.add(s);
		String query = "select * {?s ?p ?o }";
		QueryExecution qe = QueryExecutionFactory.create(query, model);
		ResultSet results = qe.execSelect();
		ResultSetFormatter.out(System.out, results);
		qe.close();
	}
 
Example #12
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleCount() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select  (count(?s) as ?count) where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();

	// 값을 console에 출력함
	ResultSetFormatter.out(rs);
}
 
Example #13
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static final void getTripleAll() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.sparql.endpoint");

	String queryString = "select ?s ?p ?o {?s ?p ?o}";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}
 
Example #14
Source File: Utils.java    From SDA with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * DW데이타 지우기
 * @throws Exception
 * @return void
 */
public static final void deleteDWTripleAll2() throws Exception {
	String serviceURI = Utils.getSdaProperty("com.pineone.icbms.sda.knowledgebase.dw.sparql.endpoint");

	String queryString = "delete data where {?s ?p ?o }";
	QueryExecution queryExec = QueryExecutionFactory.sparqlService(serviceURI, queryString);

	ResultSet rs = queryExec.execSelect();
	ResultSetFormatter.out(rs);
}
 
Example #15
Source File: ResultSizeRetriever.java    From IGUANA with GNU Affero General Public License v3.0 4 votes vote down vote up
public static int retrieveSize(String endpoint, String query) {
	QueryExecution exec = QueryExecutionFactory.sparqlService(endpoint, query);
	return ResultSetFormatter.consume(exec.execSelect());
}
 
Example #16
Source File: AlgebraExec.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public static void main (String[] argv)
{
    String BASE = "http://example/" ; 
    BasicPattern bp = new BasicPattern() ;
    Var var_x = Var.alloc("x") ;
    Var var_z = Var.alloc("z") ;
    
    // ---- Build expression
    bp.add(new Triple(var_x, NodeFactory.createURI(BASE+"p"), var_z)) ;
    Op op = new OpBGP(bp) ;
    //Expr expr = ExprUtils.parse("?z < 2 ") ;
    Expr expr = new E_LessThan(new ExprVar(var_z), NodeValue.makeNodeInteger(2)) ;
    op = OpFilter.filter(expr, op) ;

    // ---- Example setup
    Model m = makeModel() ;
    m.write(System.out, "TTL") ;
    System.out.println("--------------") ;
    System.out.print(op) ;
    System.out.println("--------------") ;

    // ---- Execute expression
    QueryIterator qIter = Algebra.exec(op, m.getGraph()) ;
    
    // -------- Either read the query iterator directly ...
    if ( false )
    {
        for ( ; qIter.hasNext() ; )
        {
            Binding b = qIter.nextBinding() ;
            Node n = b.get(var_x) ;
            System.out.println(NodeFmtLib.displayStr(n)) ;
            System.out.println(b) ; 
        }
        qIter.close() ;
    }
    else
    {
        // -------- Or make ResultSet from it (but not both - reading an
        //          iterator consumes the current solution)
        List<String> varNames = new ArrayList<String>() ;
        varNames.add("x") ;
        varNames.add("z") ;
        ResultSet rs = new ResultSetStream(varNames, m, qIter);
        ResultSetFormatter.out(rs) ;
        qIter.close() ;
    }
    System.exit(0) ;
}