Java Code Examples for org.openrdf.query.GraphQuery#evaluate()

The following examples show how to use org.openrdf.query.GraphQuery#evaluate() . 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: CustomSesameDataset.java    From GeoTriples with Apache License 2.0 6 votes vote down vote up
/**
 * Execute a CONSTRUCT/DESCRIBE SPARQL query against the graphs
 * 
 * @param qs
 *            CONSTRUCT or DESCRIBE SPARQL query
 * @param format
 *            the serialization format for the returned graph
 * @return serialized graph of results
 */
public String runSPARQL(String qs, RDFFormat format) {
	try {
		RepositoryConnection con = currentRepository.getConnection();
		try {
			GraphQuery query = con.prepareGraphQuery(
					org.openrdf.query.QueryLanguage.SPARQL, qs);
			StringWriter stringout = new StringWriter();
			RDFWriter w = Rio.createWriter(format, stringout);
			query.evaluate(w);
			return stringout.toString();
		} finally {
			con.close();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 2
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String queryString, String queryLanguage)
        throws QueryLanguageNotSupportedException, ModelRuntimeException {
	this.assertModel();
	// resolve the query language String to a QueryLanguage
	QueryLanguage language = ConversionUtil.toOpenRDFQueryLanguage(queryLanguage);
	
	try {
		// determine query result
		GraphQuery query = this.connection.prepareGraphQuery(language, queryString);
		GraphQueryResult queryResult = query.evaluate();
		
		// wrap it in a GraphIterable
		return new GraphIterable(queryResult, null);
	} catch(OpenRDFException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 3
Source File: SampleCode.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Execute a "construct" query.
 * 
 * @param repo
 * @param query
 * @param ql
 * @throws Exception
 */
public void executeConstructQuery(Repository repo, String query, 
    QueryLanguage ql) throws Exception {
    
    /*
     * With MVCC, you read from a historical state to avoid blocking and
     * being blocked by writers.  BigdataSailRepository.getQueryConnection
     * gives you a view of the repository at the last commit point.
     */
    RepositoryConnection cxn;
    if (repo instanceof BigdataSailRepository) { 
        cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
    } else {
        cxn = repo.getConnection();
    }
    
    try {

        // silly construct queries, can't guarantee distinct results
        final Set<Statement> results = new LinkedHashSet<Statement>();
        final GraphQuery graphQuery = cxn.prepareGraphQuery(ql, query);
        graphQuery.setIncludeInferred(true /* includeInferred */);
        graphQuery.evaluate(new StatementCollector(results));
        // do something with the results
        for (Statement stmt : results) {
            log.info(stmt);
        }

    } finally {
        // close the repository connection
        cxn.close();
    }
    
}
 
Example 4
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPreparedGraphQuery()
	throws Exception
{
	testCon.add(alice, name, nameAlice, context2);
	testCon.add(alice, mbox, mboxAlice, context2);
	testCon.add(context2, publisher, nameAlice);
	testCon.add(bob, name, nameBob, context1);
	testCon.add(bob, mbox, mboxBob, context1);
	testCon.add(context1, publisher, nameBob);
	StringBuilder queryBuilder = new StringBuilder(128);
       queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">");
	queryBuilder.append(" construct ");
	queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }");
	GraphQuery query = testCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding(NAME, nameBob);
	GraphQueryResult result = query.evaluate();
	try {
		assertThat(result, is(notNullValue()));
		assertThat(result.hasNext(), is(equalTo(true)));
		while (result.hasNext()) {
			Statement st = result.next();
			URI predicate = st.getPredicate();
			assertThat(predicate, anyOf(is(equalTo(name)), is(equalTo(mbox))));
			Value object = st.getObject();
			if (name.equals(predicate)) {
				assertEquals("unexpected value for name: " + object, nameBob, object);
			}
			else {
				assertThat(predicate, is(equalTo(mbox)));
				assertEquals("unexpected value for mbox: " + object, mboxBob, object);
			}
		}
	}
	finally {
		result.close();
	}
}
 
Example 5
Source File: LearningSparql_UPDATE_ITCase.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given update command both on remote and local model.
 * 
 * @param data the object holding test data (i.e. commands, queries, datafiles).
 * @throws Exception hopefully never otherwise the corresponding test fails.
 */
@SuppressWarnings("deprecation")
void executeUpdate(final MisteryGuest data) throws Exception {
	load(data);
	
	final String updateCommand = readFile(data.query);
	final Update localUpdate = localConnection.prepareUpdate(QueryLanguage.SPARQL, updateCommand);
	final Update cumulusUpdate = cumulusConnection.prepareUpdate(QueryLanguage.SPARQL, updateCommand);
	
	localUpdate.execute();
	cumulusUpdate.execute();
	
	try {
		assertTrue(ModelUtil.equals(
				statements(localConnection.getStatements(null, null, null, false).asList()), 
				statements(cumulusConnection.getStatements(null, null, null, false).asList())));
		
	} catch (final AssertionError exception) {
		final String queryString = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}";
		final GraphQuery localQuery = localConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		final GraphQuery cumulusQuery = cumulusConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		
		final GraphQueryResult debugLocalResult = localQuery.evaluate();
		final GraphQueryResult debugCumulusResult = cumulusQuery.evaluate();
			
		System.err.println("***** LOCAL ******");
		QueryResultIO.write(debugLocalResult, RDFFormat.NTRIPLES, System.err);

		System.err.println("***** CRDF ******");
		QueryResultIO.write(debugCumulusResult, RDFFormat.NTRIPLES, System.err);
		
		debugCumulusResult.close();
		debugLocalResult.close();
		throw exception;
	}
}
 
Example 6
Source File: IntegrationTestSupertypeLayer.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a given CONSTRUCT query against a given dataset.
 * 
 * @param data the mistery guest containing test data (query and dataset)
 * @throws Exception never, otherwise the test fails.
 */
protected void constructTest(final MisteryGuest data) throws Exception {
	load(data);
	
	final String queryString = queryString(data.query);
	final GraphQuery localQuery = localConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
	final GraphQuery cumulusQuery = cumulusConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
	
	GraphQueryResult localResult = localQuery.evaluate();
	GraphQueryResult cumulusResult = cumulusQuery.evaluate();
	try {
		assertTrue(
				ModelUtil.equals(
						statements(Iterations.asSet(localResult)), 
						statements(Iterations.asSet(cumulusResult))));			
	} catch (final AssertionError exception) {
		final GraphQueryResult debugLocalResult = localQuery.evaluate();
		final GraphQueryResult debugCumulusResult = cumulusQuery.evaluate();
			
		System.err.println("***** LOCAL ******");
		QueryResultIO.write(debugLocalResult, RDFFormat.NTRIPLES, System.err);

		System.err.println("***** CRDF ******");
		QueryResultIO.write(debugCumulusResult, RDFFormat.NTRIPLES, System.err);
		
		debugCumulusResult.close();
		debugLocalResult.close();
		throw exception;
	}
	
	cumulusResult.close();
	localResult.close();
}
 
Example 7
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String queryString)
        throws ModelRuntimeException {
	this.assertModel();
	GraphQuery query;
	try {
		query = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		GraphQueryResult graphQueryResult = query.evaluate();
		return new StatementIterable(graphQueryResult, null);
	} catch(OpenRDFException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 8
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String queryString)
        throws ModelRuntimeException {
	this.assertModel();
	GraphQuery query;
	try {
		query = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		GraphQueryResult graphQueryResult = query.evaluate();
		return new StatementIterable(graphQueryResult, null);
	} catch(OpenRDFException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 9
Source File: SparqlEvaluator.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Model asModel() throws OpenRDFException {
	GraphQuery qry = prepareGraphQuery();
	Model model = new LinkedHashModel();
	qry.evaluate(new StatementCollector(model));
	return model;
}
 
Example 10
Source File: DemoSesameServer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public static void _main(String[] args) throws Exception {

        String sesameURL, repoID;
        
        if (args != null && args.length == 2) {
            sesameURL = args[0];
            repoID = args[1];
        } else {
            sesameURL = DemoSesameServer.sesameURL;
            repoID = DemoSesameServer.repoID;
        }
        
        Repository repo = new HTTPRepository(sesameURL, repoID);
        repo.initialize();
        
        RepositoryConnection cxn = repo.getConnection();
        cxn.setAutoCommit(false);
        
        try { // load some statements built up programmatically
            
            URI mike = new URIImpl(BD.NAMESPACE + "Mike");
            URI bryan = new URIImpl(BD.NAMESPACE + "Bryan");
            URI loves = new URIImpl(BD.NAMESPACE + "loves");
            URI rdf = new URIImpl(BD.NAMESPACE + "RDF");
            Graph graph = new GraphImpl();
            graph.add(mike, loves, rdf);
            graph.add(bryan, loves, rdf);
            
            cxn.add(graph);
            cxn.commit();
            
        } finally {
            
            cxn.close();
            
        }
        
        { // show the entire contents of the repository

            SparqlBuilder sparql = new SparqlBuilder();
            sparql.addTriplePattern("?s", "?p", "?o");
            
            GraphQuery query = cxn.prepareGraphQuery(
                    QueryLanguage.SPARQL, sparql.toString());
            GraphQueryResult result = query.evaluate();
            while (result.hasNext()) {
                Statement stmt = result.next();
                System.err.println(stmt);
            }
            
        }
        
        
    }