Java Code Examples for org.openrdf.query.BindingSet#getValue()

The following examples show how to use org.openrdf.query.BindingSet#getValue() . 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: 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 2
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInComparison3()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } ");

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

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	BindingSet bs = result.next();
	Value y = bs.getValue("y");
	assertNotNull(y);
	assertTrue(y instanceof Literal);
	assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
}
 
Example 3
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInComparison1()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1/0 , 1)) } ");

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

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	BindingSet bs = result.next();
	Value y = bs.getValue("y");
	assertNotNull(y);
	assertTrue(y instanceof Literal);
	assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);

}
 
Example 4
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPreparedTupleQuery2()
	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();
       queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">");
       queryBuilder.append(" SELECT ?name ?mbox");
       queryBuilder.append(" where { ?VAR foaf:name ?name . ?VAR foaf:mbox ?mbox . }");
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding("VAR", bob);
	TupleQueryResult result = query.evaluate();
	try {
		assertThat(result, is(notNullValue()));
		assertThat(result.hasNext(), is(equalTo(true)));
		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertThat(solution.hasBinding(NAME), is(equalTo(true)));
			assertThat(solution.hasBinding(MBOX), is(equalTo(true)));
			Value nameResult = solution.getValue(NAME);
			Value mboxResult = solution.getValue(MBOX);
			assertEquals("unexpected value for name: " + nameResult, nameBob, nameResult);
			assertEquals("unexpected value for mbox: " + mboxResult, mboxBob, mboxResult);
		}
	}
	finally {
		result.close();
	}
}
 
Example 5
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPreparedTupleQuery()
	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();
       queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">");
       queryBuilder.append(" select ?name ?mbox ");
       queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }");
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding(NAME, nameBob);
	TupleQueryResult result = query.evaluate();
	try {
		assertThat(result, is(notNullValue()));
		assertThat(result.hasNext(), is(equalTo(true)));
		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertThat(solution.hasBinding(NAME), is(equalTo(true)));
			assertThat(solution.hasBinding(MBOX), is(equalTo(true)));
			Value nameResult = solution.getValue(NAME);
			Value mboxResult = solution.getValue(MBOX);
			assertEquals("unexpected value for name: " + nameResult, nameBob, nameResult);
			assertEquals("unexpected value for mbox: " + mboxResult, mboxBob, mboxResult);
		}
	}
	finally {
		result.close();
	}
}
 
Example 6
Source File: BigdataSPARQLResultsJSONParserForConstruct.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void handleSolution(BindingSet bs)
        throws TupleQueryResultHandlerException {
    
    if (!bs.hasBinding("subject")) {
        throw new TupleQueryResultHandlerException("no subject: " + bs);
    }
    if (!bs.hasBinding("predicate")) {
        throw new TupleQueryResultHandlerException("no predicate: " + bs);
    }
    if (!bs.hasBinding("object")) {
        throw new TupleQueryResultHandlerException("no object: " + bs);
    }
    
    final Resource s = (Resource) bs.getValue("subject");
    final URI p = (URI) bs.getValue("predicate");
    final Value o = (Value) bs.getValue("object");
    final Resource c = bs.hasBinding("context") ? 
            (Resource) bs.getValue("context") : null;
    
    final Statement stmt = valueFactory.createStatement(s, p, o, c);
    
    try {
        getRDFHandler().handleStatement(stmt);
    } catch (RDFHandlerException e) {
        throw new TupleQueryResultHandlerException(e);
    }
            
}
 
Example 7
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testValuesInOptional()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1692.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } ");

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

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	int count = 0;
	while (result.hasNext()) {
		count++;
		BindingSet bs = result.next();
		System.out.println(bs);
		URI a = (URI)bs.getValue("a");
		assertNotNull(a);
		Value isX = bs.getValue("isX");
		Literal name = (Literal)bs.getValue("name");
		assertNotNull(name);
		if (a.stringValue().endsWith("a1")) {
			assertNotNull(isX);
		}
		else if (a.stringValue().endsWith(("a2"))) {
			assertNull(isX);
		}
	}
	assertEquals(2, count);
}
 
Example 8
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSES1970CountDistinctWildcard()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1970.trig");

	String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }";

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

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

		assertTrue(result.hasNext());
		BindingSet s = result.next();
		Literal count = (Literal)s.getValue("c");
		assertNotNull(count);

		assertEquals(3, count.intValue());

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 9
Source File: BigdataComplexSparqlQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
/**
 * TODO Write optimizer to pull this BindingsClause out of the join
 * group and make it global.
 */
public void testRequiredValues() throws Exception {
    loadTestData("/testdata-query/dataset-ses1692.trig");
    StringBuilder query = new StringBuilder();
    query.append(" PREFIX : <http://example.org/>\n");
    query.append(" SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. ?a a :X . VALUES(?isX) { (:X) } } ");

    BigdataSailTupleQuery tq = (BigdataSailTupleQuery)
            conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());
    
    if (logger.isInfoEnabled()) {
        logger.info("optimized ast:\n"+tq.optimize());
        logger.info("query plan:\n"+BOpUtility.toString(tq.getASTContainer().getQueryPlan()));
    }

    TupleQueryResult result = tq.evaluate();
    assertNotNull(result);
    assertTrue(result.hasNext());

    int count = 0;
    while (result.hasNext()) {
        count++;
        BindingSet bs = result.next();
        System.out.println(bs);
        URI a = (URI)bs.getValue("a");
        assertNotNull(a);
        Value isX = bs.getValue("isX");
        Literal name = (Literal)bs.getValue("name");
        assertNotNull(name);
        if (a.stringValue().endsWith("a1")) {
            assertNotNull(isX);
        }
        else if (a.stringValue().endsWith(("a2"))) {
            assertNull(isX);
        }
    }
    assertEquals(1, count);
}
 
Example 10
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNullContext2()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append(" SELECT * ");
	query.append(" FROM sesame:nil ");
	query.append(" WHERE { ?s ?p ?o } ");

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

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

		while (result.hasNext()) {
			BindingSet bs = result.next();
			assertNotNull(bs);

			Resource s = (Resource)bs.getValue("s");

			assertNotNull(s);
			assertFalse(bob.equals(s)); // should not be present in default
													// graph
			assertFalse(alice.equals(s)); // should not be present in default
													// graph
		}
		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 11
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNullContext1()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append(" SELECT * ");
	query.append(" FROM DEFAULT ");
	query.append(" WHERE { ?s ?p ?o } ");

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

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

		while (result.hasNext()) {
			BindingSet bs = result.next();
			assertNotNull(bs);

			Resource s = (Resource)bs.getValue("s");

			assertNotNull(s);
			assertFalse(bob.equals(s)); // should not be present in default
													// graph
			assertFalse(alice.equals(s)); // should not be present in default
													// graph
		}
		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 12
Source File: ObjectCursor.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private Object createRDFObject(Value value, List<BindingSet> properties)
		throws QueryEvaluationException {
	if (value == null)
		return null;
	if (value instanceof Literal)
		return of.createObject((Literal) value);
	Object obj;
	if (properties.get(0).hasBinding(binding + "_class")) {
		Set<URI> list = new HashSet<URI>(properties.size());
		for (BindingSet bindings : properties) {
			Value t = bindings.getValue(binding + "_class");
			if (t instanceof URI) {
				list.add((URI) t);
			}
		}
		obj = manager.getObject(list, (Resource) value);
	} else {
		try {
			obj = manager.getObject(value);
		} catch (RepositoryException e) {
			throw new QueryEvaluationException(e);
		}
	}
	if (obj instanceof PropertyConsumer) {
		((PropertyConsumer) obj).usePropertyBindings(binding, properties);
	}
	return obj;
}
 
Example 13
Source File: ObjectArrayCursor.java    From anno4j with Apache License 2.0 5 votes vote down vote up
private Object createRDFObject(Value value, String binding, List<BindingSet> properties)
		throws QueryEvaluationException {
	if (value == null)
		return null;
	if (value instanceof Literal)
		return of.createObject((Literal) value);
	Object obj;
	if (properties.get(0).hasBinding(binding + "_class")) {
		Set<URI> list = new HashSet<URI>(properties.size());
		for (BindingSet bindings : properties) {
			Value t = bindings.getValue(binding + "_class");
			if (t instanceof URI) {
				list.add((URI) t);
			}
		}
		obj = manager.getObject(list, (Resource) value);
	} else {
		try {
			obj = manager.getObject(value);
		} catch (RepositoryException e) {
			throw new QueryEvaluationException(e);
		}
	}
	if (obj instanceof PropertyConsumer) {
		((PropertyConsumer) obj).usePropertyBindings(binding, properties);
	}
	return obj;
}
 
Example 14
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testSES1081SameTermWithValues()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1081.trig");
	StringBuilder query = new StringBuilder();
	query.append("PREFIX ex: <http://example.org/>\n");
	query.append(" SELECT * \n");
	query.append(" WHERE { \n ");
	query.append("          ?s ex:p ?a . \n");
	query.append("          FILTER sameTerm(?a, ?e) \n ");
	query.append("          VALUES ?e { ex:b } \n ");
	query.append(" } ");

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

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

		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			assertNotNull(bs);

			Value s = bs.getValue("s");
			Value a = bs.getValue("a");

			assertNotNull(s);
			assertNotNull(a);
			assertEquals(f.createURI("http://example.org/a"), s);
			assertEquals(f.createURI("http://example.org/b"), a);
		}
		result.close();

		assertEquals(1, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 15
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testGroupConcatDistinct()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)");
	query.append("WHERE { ex:groupconcat-test ?p ?l . }");

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

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

		while (result.hasNext()) {
			BindingSet bs = result.next();
			assertNotNull(bs);

			Value concat = bs.getValue("concat");

			assertTrue(concat instanceof Literal);

			String lexValue = ((Literal)concat).getLabel();

			int occ = countCharOccurrences(lexValue, 'a');
			assertEquals(1, occ);
			occ = countCharOccurrences(lexValue, 'b');
			assertEquals(1, occ);
			occ = countCharOccurrences(lexValue, 'c');
			assertEquals(1, occ);
			occ = countCharOccurrences(lexValue, 'd');
			assertEquals(1, occ);
		}
		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 16
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testSameTermRepeatInUnion()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append("PREFIX foaf:<http://xmlns.com/foaf/0.1/>\n");
	query.append("SELECT * {\n");
	query.append("    {\n");
	query.append("        ?sameTerm foaf:mbox ?mbox\n");
	query.append("        FILTER sameTerm(?sameTerm,$william)\n");
	query.append("    } UNION {\n");
	query.append("        ?x foaf:knows ?sameTerm\n");
	query.append("        FILTER sameTerm(?sameTerm,$william)\n");
	query.append("    }\n");
	query.append("}");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());
	tq.setBinding("william", conn.getValueFactory().createURI("http://example.org/william"));

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

		int count = 0;
		while (result.hasNext()) {
		   BindingSet bs = result.next();
			count++;
			assertNotNull(bs);
			
			System.out.println(bs);
			
			Value mbox = bs.getValue("mbox");
			Value x = bs.getValue("x");
			
			assertTrue(mbox instanceof Literal || x instanceof URI);				
		}
		result.close();

		assertEquals(3, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 17
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 4 votes vote down vote up
@Test
public void testSameTermRepeatInUnionAndOptional()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT * {\n");
	query.append("    {\n");
	query.append("        ex:a ?p ?prop1\n");
	query.append("        FILTER (?p = ex:prop1)\n");
	query.append("    } UNION {\n");
	query.append("          ?s ex:p ex:A ; ");
	query.append("          { ");
	query.append("              { ");
	query.append("                 ?s ?p ?l .");
	query.append("                 FILTER(?p = rdfs:label) ");
	query.append("              } ");
	query.append("              OPTIONAL { ");
	query.append("                 ?s ?p ?opt1 . ");
	query.append("                 FILTER (?p = ex:prop1) ");
	query.append("              } ");
	query.append("              OPTIONAL { ");
	query.append("                 ?s ?p ?opt2 . ");
	query.append("                 FILTER (?p = ex:prop2) ");
	query.append("              } ");
	query.append("          }");
	query.append("    }\n");
	query.append("}");

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

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

		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			assertNotNull(bs);

			System.out.println(bs);

			Value prop1 = bs.getValue("prop1");
			Value l = bs.getValue("l");

			assertTrue(prop1 instanceof Literal || l instanceof Literal);
			if (l instanceof Literal) {
				Value opt1 = bs.getValue("opt1");
				assertNull(opt1);

				Value opt2 = bs.getValue("opt2");
				assertNull(opt2);
			}
		}
		result.close();

		assertEquals(2, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 18
Source File: RangeQueriesTest.java    From cumulusrdf with Apache License 2.0 4 votes vote down vote up
/**
 * Compares range results obtained from SPARQL and Range query.
 * 
 * @throws Exception never, otherwise the test fails.
 */
@Test
public void rangeResults() throws Exception {
	final String sparql_query = String.format(
			"SELECT * WHERE { ?s <%s> ?o . FILTER(?o >= %s && ?o <= %s ) } ORDER BY ASC(?o)",
			_predicate, _lowerBound, _upperBound);

	final TupleQuery q = _repositoryConnection.prepareTupleQuery(QueryLanguage.SPARQL, sparql_query);
	final TupleQueryResult sparqlResults = q.evaluate();
	assertTrue(sparqlResults != null && sparqlResults.hasNext());

	final Value[] query = { null, buildResource(_predicate) };

	final Iterator<Statement> rangeResultIterator = _tripleStore.range(
			query,
			buildLiteral(String.valueOf(_lowerBound)),
			true,
			buildLiteral(String.valueOf(_upperBound)),
			true,
			false,
			Integer.MAX_VALUE);

	assertTrue(rangeResultIterator != null && rangeResultIterator.hasNext());
	final List<Statement> rangeResult = asList(rangeResultIterator);

	int howManyBindings = 0;
	int howManyTriples = rangeResult.size();

	while (sparqlResults.hasNext()) {
		howManyBindings++;
		final BindingSet sparqlBindings = sparqlResults.next();

		final Literal objectFromSparqlQuery = (Literal) sparqlBindings.getValue("o");

		for (Iterator<Statement> iterator = rangeResult.iterator(); iterator.hasNext();) {
			final Statement rangeResultTriple = iterator.next();
			final Literal objectFromRangeQuery = (Literal) rangeResultTriple.getObject();

			final BigDecimal valueFromRangeQuery = ((TripleStore) _tripleStore).asDecimal(objectFromRangeQuery, null);
			assertNotNull("Literal object cannot be null for this kind of (range) query result.", valueFromRangeQuery);

			final BigDecimal valueFromSparqlQuery = ((TripleStore) _tripleStore).asDecimal(objectFromSparqlQuery, null);
			assertNotNull("Literal object cannot be null for this kind of (SPARQL) query result.", valueFromSparqlQuery);

			if (isTheSameValue(valueFromRangeQuery.doubleValue(), valueFromSparqlQuery.doubleValue(), 1 / 10 ^ 6)) {
				iterator.remove();
			}
		}
	}

	assertTrue(
			"SPARQL returned " + howManyBindings
					+ " bindings, RangeQuery returned " + howManyTriples
					+ ", remaining triples : "
					+ rangeResult,
			rangeResult.isEmpty());
}
 
Example 19
Source File: SparqlEvaluator.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public Value asValue() throws OpenRDFException {
	BindingSet bs = asBindingSet();
	if (bs == null)
		return null;
	return bs.getValue(bs.getBindingNames().iterator().next());
}
 
Example 20
Source File: TestFederatedQuery.java    From database with GNU General Public License v2.0 4 votes vote down vote up
public void testSimpleServiceQuery() throws Exception {

        // test setup
        final String EX_NS = "http://example.org/";
        final ValueFactory f = new ValueFactoryImpl();
        final URI bob = f.createURI(EX_NS, "bob");
        final URI alice = f.createURI(EX_NS, "alice");
        final URI william = f.createURI(EX_NS, "william");

        // clears the repository and adds new data
        prepareTest("simple-default-graph.ttl",
                Arrays.asList("simple.ttl"));
            
        final StringBuilder qb = new StringBuilder();
        qb.append(" SELECT * \n"); 
        qb.append(" WHERE { \n");
        qb.append("     SERVICE <" + getRepositoryUrl(1) + "> { \n");
        qb.append("             ?X <"   + FOAF.NAME + "> ?Y \n ");
        qb.append("     } \n ");
        qb.append("     ?X a <" + FOAF.PERSON + "> . \n");
        qb.append(" } \n");

        final BigdataSailRemoteRepositoryConnection conn = m_repo.getBigdataSailRemoteRepository().getConnection();
        
        try {

            final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL,
                    qb.toString());

            final TupleQueryResult tqr = tq.evaluate();

            assertNotNull(tqr);
            assertTrue("No solutions.", tqr.hasNext());

            int count = 0;
            while (tqr.hasNext()) {
                final BindingSet bs = tqr.next();
                count++;

                final Value x = bs.getValue("X");
                final Value y = bs.getValue("Y");

                assertFalse(william.equals(x));

                assertTrue(bob.equals(x) || alice.equals(x));
                if (bob.equals(x)) {
                    f.createLiteral("Bob").equals(y);
                } else if (alice.equals(x)) {
                    f.createLiteral("Alice").equals(y);
                }
            }

            assertEquals(2, count);

        } finally {
            conn.close();
        }

    }