org.openrdf.query.QueryLanguage Java Examples

The following examples show how to use org.openrdf.query.QueryLanguage. 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: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddToDefault()
	throws Exception
{
	logger.debug("executing testAddToDefault");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("ADD GRAPH <" + graph1.stringValue() + "> TO DEFAULT");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, graph1));
}
 
Example #2
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInsertEmptyWhere()
	throws Exception
{
	logger.debug("executing test testInsertEmptyWhere");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT { <" + bob + "> rdfs:label \"Bob\" . } WHERE { }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));

	operation.execute();

	assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));
}
 
Example #3
Source File: SesameDriver.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public Collection<? extends SesameMatch> runQuery(final RailwayQuery query, final String queryDefinition)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final Collection<SesameMatch> results = new ArrayList<>();

	final TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryDefinition);
	final TupleQueryResult queryResults = tupleQuery.evaluate();
	try {
		while (queryResults.hasNext()) {
			final BindingSet bs = queryResults.next();
			final SesameMatch match = SesameMatch.createMatch(query, bs);
			results.add(match);
		}
	} finally {
		queryResults.close();
	}

	return results;
}
 
Example #4
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteTransformedWhere()
	throws Exception
{
	logger.debug("executing testDeleteTransformedWhere");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE {?y foaf:name ?n } WHERE {?x ex:containsPerson ?y . ?y foaf:name ?n . }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertTrue(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	operation.execute();

	String msg = "foaf:name properties should have been deleted";
	assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	msg = "ex:containsPerson properties should not have been deleted";
	assertTrue(msg, con.hasStatement(graph1, f.createURI(EX_NS, "containsPerson"), bob, true));
	assertTrue(msg, con.hasStatement(graph2, f.createURI(EX_NS, "containsPerson"), alice, true));

}
 
Example #5
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteDataFromGraph()
	throws Exception
{
	logger.debug("executing testDeleteDataFromGraph");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE DATA { GRAPH ex:graph1 {ex:alice foaf:knows ex:bob. } } ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1));
	operation.execute();

	String msg = "statement should have been deleted from graph1";
	assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1));
}
 
Example #6
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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 #7
Source File: ClazzBuildingSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasPropertyTransitive(RDFSProperty property) throws RepositoryException {
    try {
        BooleanQuery query = getObjectConnection().prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   {" +
                        "       <" + property.getResourceAsString() + "> rdfs:domain <" + getResourceAsString() + "> . " +
                        "   }" +
                        "   UNION" +
                        "   {" +
                        "       <" + getResourceAsString() + "> rdfs:subClassOf+ ?s ." +
                        "       <" + property.getResourceAsString() + "> rdfs:domain ?s ." +
                        "   }" +
                        "}"
        );

        return query.evaluate();
    } catch (QueryEvaluationException | MalformedQueryException e) {
        throw new RepositoryException(e);
    }
}
 
Example #8
Source File: ClazzBuildingSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Whether the mapping for the given property needs to be redefined in this class.
 * This is the case if the class has a (direct) {@code owl:Restriction} on the property
 * for this class.
 * @param property The property to check for.
 * @return Returns true if the property mapping needs a redefinition in the Java class generated
 * for this class.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
 boolean needsRedefinition(RDFSProperty property) throws RepositoryException {
    try {
        BooleanQuery query = getObjectConnection().prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   ?r a owl:Restriction . " +
                        "   <" + getResourceAsString() + "> rdfs:subClassOf ?r . " +
                        "   ?r owl:onProperty <" + property.getResourceAsString() + "> . " +
                        "}"
        );

        return query.evaluate();

    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example #9
Source File: SchemaSanitizingObjectSupport.java    From anno4j with Apache License 2.0 6 votes vote down vote up
/**
 * Complements transitive edges for transitive properties ({@code owl:TransitiveProperty}).
 * @throws RepositoryException Thrown if an error occurs while updating the repository.
 */
private void sanitizeTransitivity() throws RepositoryException {
    ObjectConnection connection = getObjectConnection();
    try {
        connection.prepareUpdate(QueryLanguage.SPARQL,
                "INSERT {" +
                        "   <" + getResourceAsString() + "> ?p ?z . " +
                        "} WHERE {" +
                        "   <" + getResourceAsString() + "> ?p ?y . " +
                        "   ?y ?p ?z . " +
                        "   ?p a owl:TransitiveProperty . " +
                        "}"
        ).execute();

    } catch (MalformedQueryException | UpdateExecutionException e) {
        throw new RepositoryException(e);
    }
}
 
Example #10
Source File: TestTicket4249.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example #11
Source File: SchemaSanitizingObjectSupportTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
@Test
public void testEquivalenceSubpropertySanitizing() throws Exception {
    // Prepare the resources used in the test:
    SanitizingTestResource resource = anno4j.createObject(SanitizingTestResource.class);
    SanitizingTestResource x1 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x1"));
    SanitizingTestResource x2 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x2"));

    // Declare x1,x2 equivalent:
    anno4j.getObjectRepository().getConnection().prepareUpdate(QueryLanguage.SPARQL,
            "INSERT DATA {" +
                    "   <" + x1 + "> owl:sameAs <" + x2 + "> . " +
                    "}"
    ).execute();

    // Setup values:
    resource.setObjectSubproperty(Sets.newHashSet(x2));
    assertEquals(Sets.newHashSet(x2), resource.getObjectSuperproperty());
    assertEquals(Sets.newHashSet(x2), resource.getObjectSubproperty());

    // Setting superproperty to equivalent value:
    resource.setObjectSuperproperty(Sets.newHashSet(x1));
    assertEquals(Sets.newHashSet(x1), resource.getObjectSuperproperty());
    assertEquals(Sets.newHashSet(x2), resource.getObjectSubproperty());
}
 
Example #12
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDropDefault()
	throws Exception
{
	logger.debug("executing testDropDefault");

	String update = "DROP DEFAULT";

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update);

	// Verify statements exist in the named graphs.
	assertTrue(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	// Verify statements exist in the default graph.
	assertTrue(con.hasStatement(null, null, null, false, new Resource[] { null }));

	operation.execute();
	assertTrue(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	// Verify that no statements remain in the 'default' graph.
	assertFalse(con.hasStatement(null, null, null, false, new Resource[] { null }));

}
 
Example #13
Source File: TestNanoSparqlClient.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void testServiceNodeBindings() throws Exception {
        final BigdataSailRemoteRepository repo = m_repo.getBigdataSailRemoteRepository();
        final BigdataSailRemoteRepositoryConnection cxn = 
            (BigdataSailRemoteRepositoryConnection) repo.getConnection();
        
        try {
          String queryStr = "select * where {SERVICE <http://DBpedia.org/sparql> { <http://dbpedia.org/resource/Tonga_(Nyasa)_language> rdfs:label ?langLabel. }}";
//                String queryStr = "SELECT * WHERE { BIND (<http://dbpedia.org/resource/Tonga_(Nyasa)_language> AS ?ref) . SERVICE <http://DBpedia.org/sparql> { ?ref rdfs:label ?langLabel. } }";
            final org.openrdf.query.TupleQuery tq = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
            final TupleQueryResult tqr = tq.evaluate();
            try {
                int cnt = 0;
                while (tqr.hasNext()) {
                    tqr.next();
                    cnt++;
                }
                assertEquals(cnt, 2);
            } finally {
                tqr.close();
            }
        } finally {
            cxn.close();
        }
    }
 
Example #14
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSES2024PropertyPathAnonVarSharing() throws Exception {
	loadTestData("/testdata-query/dataset-ses2024.trig");
	String query = "PREFIX : <http://example.org/> SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }" ;

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);

	try {
		TupleQueryResult result = tq.evaluate();
		assertNotNull(result);

		BindingSet bs = result.next();
		Literal l1 = (Literal)bs.getValue("l1");
		Literal l2 = (Literal)bs.getValue("l2");

		assertNotNull(l1);
		assertFalse(l1.equals(l2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #15
Source File: Test_Ticket_1893.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void checkResults(final BigdataSailRemoteRepositoryConnection conn, final int count)
		throws QueryEvaluationException, RepositoryException,
		MalformedQueryException {
	final TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, QUERY).evaluate();
	
	Collection<Value> subjects = new ArrayList<>();
	try {
		while(result.hasNext()) {
			BindingSet bs = result.next();
			subjects.add(bs.getBinding("s").getValue());
		}
	} finally {
		result.close();
	}
	if(log.isInfoEnabled()) log.info(subjects);
	assertEquals(count, subjects.size());
}
 
Example #16
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testClearGraph()
	throws Exception
{
	logger.debug("executing testClearGraph");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("CLEAR GRAPH <" + graph1.stringValue() + "> ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	operation.execute();
	assertFalse(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	assertTrue(con.hasStatement(null, null, null, false));
}
 
Example #17
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCopyToDefault()
	throws Exception
{
	logger.debug("executing testCopyToDefault");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("COPY GRAPH <" + graph1.stringValue() + "> TO DEFAULT");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertFalse(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertFalse(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, graph1));
}
 
Example #18
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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 #19
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 #20
Source File: LoadPdb.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public static void executeSelectQuery(Repository repo, String query) throws Exception {

		RepositoryConnection cxn = repo.getConnection();
		int counter = 0;
		try {

			final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			tupleQuery.setIncludeInferred(true /* includeInferred */);
			TupleQueryResult result = tupleQuery.evaluate();
			// do something with the results
			while (result.hasNext()) {
				BindingSet bindingSet = result.next();
				LOG.info(bindingSet);
				counter++;
			}

		} finally {
			// close the repository connection
			cxn.close();
//			LOG.info
            System.err.println
            ("Number of results: " + counter);
		}

	}
 
Example #21
Source File: Test_Ticket_2091.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Execute a query including constants in projection expression.
 * The test succeeeds if the query successfully evaluates with 
 * QUERY_ENGINE_CHUNK_HANDLER set to NativeHeapStandloneChunkHandler,
 * as it requires results to be encoded in respect to namespace of value factory,
 * which fails if constant has not been resolved against target DB value factory.
 * @throws Exception
 */
public void test_simple() throws Exception {

	setMethodisPostUrlEncodedData();
	BigdataSailRemoteRepositoryConnection conn = m_repo.getBigdataSailRemoteRepository().getConnection();
	conn.prepareUpdate(QueryLanguage.SPARQL, "prefix wd: <http://wd/> \n" + 
			"prefix wdt: <http://wdt/> " +
			"INSERT DATA { wd:Q2 wdt:P31 wd:Q3917681 } ").execute();

	final TupleQueryResult result = 
			conn.prepareTupleQuery(QueryLanguage.SPARQL, QUERY).evaluate();
	
	Collection<Value> subjects = new ArrayList<>();
	try {
		while(result.hasNext()) {
			BindingSet bs = result.next();
			subjects.add(bs.getBinding("s").getValue());
		}
	} finally {
		result.close();
	}
	if(log.isInfoEnabled()) log.info(subjects);
	assertEquals(1, subjects.size());

}
 
Example #22
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInsertNonMatchingWhere()
	throws Exception
{
	logger.debug("executing test testInsertNonMatchingWhere");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT { ?x rdfs:label ?y . } WHERE { ?x rdfs:comment ?y }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertFalse(con.hasStatement(bob, RDFS.LABEL, null, true));

	operation.execute();

	assertFalse(con.hasStatement(bob, RDFS.LABEL, null, true));
}
 
Example #23
Source File: Test_Ticket_1717.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test supposed to check if constants in BIND expressions will be resolved
 */
public void test_ticket_1717() throws Exception {

   {
     // Clear DB per task description (Executing the query over the empty database)
     m_repo.remove(new RemoveOp(null, null, null));
     String query = "SELECT ?z ?s1 {  ?s ?p ?o .   BIND(?o+1 AS ?z)  BIND(?z+1 AS ?z2) }";
     final TupleQuery tq = m_repo.getBigdataSailRemoteRepository().getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query, null);
       final TupleQueryResult tqr = tq.evaluate();
       try {
           int count = 0;
           while (tqr.hasNext()) {
               System.out.println(tqr.next());
               count++;
            }
           assertEquals(0,count); // asserting successful execution of the query, as it was failing while parsing
       } finally {
            tqr.close();
       }
   }
}
 
Example #24
Source File: SimpleStoredQueryService.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Executes the SPARQL query returned by
 * {@link #getQuery(ServiceCallCreateParams, ServiceParams)}
 */
@Override
protected TupleQueryResult doQuery(
        final BigdataSailRepositoryConnection cxn,
        final ServiceCallCreateParams createParams,
        final ServiceParams serviceParams) throws Exception {

    final String queryStr = getQuery(createParams, serviceParams);

    final String baseURI = createParams.getServiceURI().stringValue();

    final BigdataSailTupleQuery query = (BigdataSailTupleQuery) cxn
            .prepareTupleQuery(QueryLanguage.SPARQL, queryStr, baseURI);

    return query.evaluate();

}
 
Example #25
Source File: SPARQLUpdateTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteWhereShortcut()
	throws Exception
{
	logger.debug("executing testDeleteWhereShortcut");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE WHERE {?x foaf:name ?y }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertTrue(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	operation.execute();

	String msg = "foaf:name properties should have been deleted";
	assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	msg = "foaf:knows properties should not have been deleted";
	assertTrue(msg, con.hasStatement(bob, FOAF.KNOWS, null, true));
	assertTrue(msg, con.hasStatement(alice, FOAF.KNOWS, null, true));
}
 
Example #26
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testOptionalFilter()
	throws Exception
{
	String optional = "{ ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } }";
	URI s = vf.createURI("urn:test:s");
	URI p1 = vf.createURI(URN_TEST_P1);
	URI p2 = vf.createURI(URN_TEST_P2);
	Value v1 = vf.createLiteral(1);
	Value v2 = vf.createLiteral(2);
	Value v3 = vf.createLiteral(3);
	testCon.add(s, p1, v1);
	testCon.add(s, p2, v2);
	testCon.add(s, p1, v3);
	String qry = "PREFIX :<urn:test:> SELECT ?s ?v1 ?v2 WHERE " + optional;
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, qry);
	TupleQueryResult result = query.evaluate();
	Set<List<Value>> set = new HashSet<List<Value>>();
	while (result.hasNext()) {
		BindingSet bindings = result.next();
		set.add(Arrays.asList(bindings.getValue("v1"), bindings.getValue("v2")));
	}
	result.close();
	assertThat(set, hasItem(Arrays.asList(v1, v2)));
	assertThat(set, hasItem(Arrays.asList(v3, null)));
}
 
Example #27
Source File: TestPathConstraints.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void showOptimizedAST(final BigdataGraph graph, 
        final String queryStr) throws Exception {
    
    final BigdataSailRepositoryConnection cxn = (BigdataSailRepositoryConnection) graph.cxn();
    try {
        final BigdataSailTupleQuery query = (BigdataSailTupleQuery) cxn
                .prepareQuery(QueryLanguage.SPARQL, queryStr);
        final QueryRoot optimized = query.optimize();
        if (log.isDebugEnabled()) {
            log.debug("optimized:\n" + optimized);
        }
    } finally {
        cxn.close();
    }

}
 
Example #28
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteDefaultGraph()
	throws Exception
{
	URI g1 = vf.createURI("urn:test:g1");
	URI g2 = vf.createURI("urn:test:g2");
	testCon.add(vf.createURI(URN_TEST_S1), vf.createURI(URN_TEST_P1), vf.createURI(URN_TEST_O1), g1);
	testCon.add(vf.createURI("urn:test:s2"), vf.createURI(URN_TEST_P2), vf.createURI("urn:test:o2"), g2);
	Update up = testCon.prepareUpdate(QueryLanguage.SPARQL, SPARQL_DEL_ALL);
	DatasetImpl ds = new DatasetImpl();
	ds.addDefaultGraph(g1);
	ds.addDefaultRemoveGraph(g1);
	up.setDataset(ds);
	up.execute();
	assertThat(size(g1), is(equalTo(0)));
	assertThat(size(g2), is(equalTo(1)));
}
 
Example #29
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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 #30
Source File: SPARQLUpdateTestv2.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected long countSolutions(final String query)
        throws QueryEvaluationException, RepositoryException,
        MalformedQueryException {
    TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL,
            query).evaluate();
    try {
        long n = 0;
        while (result.hasNext()) {
            final BindingSet bset = result.next();
            n++;
            if (logger.isInfoEnabled())
                logger.info(bset.toString());
        }
        return n;
    } finally {
        result.close();
    }
}