Java Code Examples for org.openrdf.query.GraphQuery

The following examples show how to use org.openrdf.query.GraphQuery. These examples are extracted from open source projects. 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
@Test
public void testDescribeA()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:a");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI a = f.createURI("http://example.org/a");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Value> objects = result.filter(a, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			assertTrue(result.contains((Resource)object, null, null));
			assertEquals(2, result.filter((Resource)object, null, null).size());
		}
	}
}
 
Example 2
@Test
public void testDescribeAWhere()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ?x WHERE {?x rdfs:label \"a\". } ");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI a = f.createURI("http://example.org/a");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Value> objects = result.filter(a, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			assertTrue(result.contains((Resource)object, null, null));
			assertEquals(2, result.filter((Resource)object, null, null).size());
		}
	}
}
 
Example 3
@Test
public void testDescribeB()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:b");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI b = f.createURI("http://example.org/b");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Resource> subjects = result.filter(null, p, b).subjects();
	assertNotNull(subjects);
	for (Value subject : subjects) {
		if (subject instanceof BNode) {
			assertTrue(result.contains(null, null, subject));
		}
	}
}
 
Example 4
Source Project: GeoTriples   Source File: CustomSesameDataset.java    License: 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 5
@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 6
Source Project: database   Source File: SampleCode.java    License: 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 7
@Override
   public GraphQuery prepareGraphQuery(final QueryLanguage ql,
           final String query)
           throws RepositoryException, MalformedQueryException {

       return prepareGraphQuery(ql, query, null);    
	
}
 
Example 8
@Test
public void testDescribeWhere()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ?x WHERE {?x rdfs:label ?y . } ");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory vf = conn.getValueFactory();
	URI a = vf.createURI("http://example.org/a");
	URI b = vf.createURI("http://example.org/b");
	URI c = vf.createURI("http://example.org/c");
	URI e = vf.createURI("http://example.org/e");
	URI f = vf.createURI("http://example.org/f");
	URI p = vf.createURI("http://example.org/p");

	Model result = QueryResults.asModel(gq.evaluate());
	assertTrue(result.contains(a, p, null));
	assertTrue(result.contains(b, RDFS.LABEL, null));
	assertTrue(result.contains(c, RDFS.LABEL, null));
	assertTrue(result.contains(null, p, b));
	assertTrue(result.contains(e, RDFS.LABEL, null));
	assertTrue(result.contains(null, p, e));
	assertFalse(result.contains(f, null, null));
	Set<Value> objects = result.filter(a, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			assertTrue(result.contains((Resource)object, null, null));
			assertEquals(2, result.filter((Resource)object, null, null).size());
		}
	}
}
 
Example 9
@Test
public void testDescribeD()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:d");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI d = f.createURI("http://example.org/d");
	URI p = f.createURI("http://example.org/p");
	URI e = f.createURI("http://example.org/e");
	Model result = QueryResults.asModel(gq.evaluate());

	assertNotNull(result);
	assertTrue(result.contains(null, p, e));
	assertFalse(result.contains(e, null, null));
	Set<Value> objects = result.filter(d, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			Set<Value> childObjects = result.filter((BNode)object, null, null).objects();
			assertNotNull(childObjects);
			for (Value childObject : childObjects) {
				if (childObject instanceof BNode) {
					assertTrue(result.contains((BNode)childObject, null, null));
				}
			}
		}
	}
}
 
Example 10
@Test
public void testDescribeF()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:f");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory vf = conn.getValueFactory();
	URI f = vf.createURI("http://example.org/f");
	URI p = vf.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());

	assertNotNull(result);
	assertEquals(4, result.size());
	Set<Value> objects = result.filter(f, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			Set<Value> childObjects = result.filter((BNode)object, null, null).objects();
			assertNotNull(childObjects);
			for (Value childObject : childObjects) {
				if (childObject instanceof BNode) {
					assertTrue(result.contains((BNode)childObject, null, null));
				}
			}
		}
	}
}
 
Example 11
@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 12
/**
 * Test of insert and retrieval of a large literal.
 */
public void test_INSERT_veryLargeLiteral() throws Exception {

    final Graph g = new LinkedHashModel();
    
    final URI s = new URIImpl("http://www.bigdata.com/");
    final URI p = RDFS.LABEL;
    final Literal o = getVeryLargeLiteral();
    final Statement stmt = new StatementImpl(s, p, o);
    g.add(stmt);
    
    // Load the resource into the KB.
    assertEquals(
            1L,
            doInsertByBody("POST", RDFFormat.RDFXML, g, null/* defaultContext */));

    // Read back the data into a graph.
    final Graph g2;
    {
        final String queryStr = "DESCRIBE <" + s.stringValue() + ">";
        final GraphQuery query = cxn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
        g2 = asGraph(query.evaluate());
        
    }
    
    assertEquals(1, g2.size());
    
    assertTrue(g2.match(s, p, o).hasNext());
    
}
 
Example 13
Source Project: cumulusrdf   Source File: LearningSparql_UPDATE_ITCase.java    License: 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 14
Source Project: cumulusrdf   Source File: IntegrationTestSupertypeLayer.java    License: 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 15
@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 16
@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 17
/**
 * Creates a new graph streaming output that executes a CONSTRUCT query
 * and streams the result.
 * 
 * @param query the CONSTRUCT query to execute
 * @param writerFactory a RDF writer factory to use for serialisation
 * @param conn the connection to use for query execution
 */
public SPARQLGraphStreamingOutput(
		GraphQuery query,
		RDFWriterFactory writerFactory,
		RepositoryConnection conn) {
	super(conn);
	this.query = query;
	this.factory = writerFactory;
}
 
Example 18
Source Project: anno4j   Source File: SparqlEvaluator.java    License: 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 19
Source Project: anno4j   Source File: SparqlEvaluator.java    License: Apache License 2.0 4 votes vote down vote up
private GraphQuery prepareGraphQuery() throws MalformedQueryException,
		RepositoryException {
	String sparql = bindMultiples(query.toString());
	String base = query.getBaseURI();
	return bindSingles(con.prepareGraphQuery(SPARQL, sparql, base));
}
 
Example 20
Source Project: database   Source File: DemoSesameServer.java    License: 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);
            }
            
        }
        
        
    }
 
Example 21
@Override
   public GraphQuery prepareGraphQuery(final QueryLanguage ql,
           final String query, final String baseURI) throws RepositoryException,
           MalformedQueryException {

	if (ql != QueryLanguage.SPARQL) {
		
		throw new UnsupportedOperationException("unsupported query language: " + ql);
		
	}
	
	try {
		
		return new BigdataRemoteGraphQuery(repo.getRemoteRepository(), query, baseURI);
	
	} catch (Exception ex) {
		
		throw new RepositoryException(ex);
		
	}

}