Java Code Examples for org.eclipse.rdf4j.query.QueryResults#asList()

The following examples show how to use org.eclipse.rdf4j.query.QueryResults#asList() . 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: SPARQLServiceEvaluationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verify that BIND clause alias from the SERVICE clause gets added to the result set.
 *
 * @see <a href="https://github.com/eclipse/rdf4j/issues/646">#646</a>
 */
@Test
public void testValuesBindClauseHandling() throws Exception {
	String query = "select * { service <" + getRepositoryUrl(1) + "> { Bind(1 as ?val) . VALUES ?x {1 2} . } }";

	try (RepositoryConnection conn = localRepository.getConnection()) {
		TupleQuery tq = conn.prepareTupleQuery(query);
		TupleQueryResult tqr = tq.evaluate();

		assertNotNull(tqr);
		assertTrue(tqr.hasNext());

		List<BindingSet> result = QueryResults.asList(tqr);
		assertEquals(2, result.size());
		for (BindingSet bs : result) {
			assertTrue(bs.hasBinding("val"));
			assertEquals(1, Literals.getIntValue(bs.getValue("val"), 0));
			assertTrue(bs.hasBinding("x"));
			int x = Literals.getIntValue(bs.getValue("x"), 0);
			assertTrue(x == 1 || x == 2);
		}
	}
}
 
Example 2
Source File: SPARQLServiceEvaluationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verify that all relevant variable names from the SERVICE clause get added to the result set when a BIND clause is
 * present.
 *
 * @see <a href="https://github.com/eclipse/rdf4j/issues/703">#703</a>
 */
@Test
public void testVariableNameHandling() throws Exception {
	String query = "select * { service <" + getRepositoryUrl(1) + "> { ?s ?p ?o . Bind(str(?o) as ?val) .  } }";

	// add some data to the remote endpoint (we don't care about the exact contents)
	prepareTest(null, Arrays.asList("/testcases-service/data13.ttl"));
	try (RepositoryConnection conn = localRepository.getConnection()) {
		TupleQuery tq = conn.prepareTupleQuery(query);
		TupleQueryResult tqr = tq.evaluate();

		assertNotNull(tqr);
		assertTrue(tqr.hasNext());

		List<BindingSet> result = QueryResults.asList(tqr);
		assertTrue(result.size() > 0);
		for (BindingSet bs : result) {
			assertTrue(bs.hasBinding("val"));
			assertTrue(bs.hasBinding("s"));
			assertTrue(bs.hasBinding("p"));
			assertTrue(bs.hasBinding("o"));
		}
	}
}
 
Example 3
Source File: EvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDatetimeSubtypesStrict() {
	ValueFactory vf = strictRepo.getValueFactory();

	try (RepositoryConnection conn = strictRepo.getConnection()) {
		Literal l1 = vf.createLiteral("2009", XMLSchema.GYEAR);
		Literal l2 = vf.createLiteral("2009-01", XMLSchema.GYEARMONTH);
		IRI s1 = vf.createIRI("urn:s1");
		IRI s2 = vf.createIRI("urn:s2");
		conn.add(s1, RDFS.LABEL, l1);
		conn.add(s2, RDFS.LABEL, l2);

		String query = "SELECT * WHERE { ?s rdfs:label ?l . FILTER(?l >= \"2008\"^^xsd:gYear) }";

		List<BindingSet> result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate());
		assertEquals(1, result.size());
	}
}
 
Example 4
Source File: EvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDatetimeSubtypesExtended() {
	ValueFactory vf = extendedRepo.getValueFactory();

	try (RepositoryConnection conn = extendedRepo.getConnection()) {
		Literal l1 = vf.createLiteral("2009", XMLSchema.GYEAR);
		Literal l2 = vf.createLiteral("2009-01", XMLSchema.GYEARMONTH);
		IRI s1 = vf.createIRI("urn:s1");
		IRI s2 = vf.createIRI("urn:s2");
		conn.add(s1, RDFS.LABEL, l1);
		conn.add(s2, RDFS.LABEL, l2);

		String query = "SELECT * WHERE { ?s rdfs:label ?l . FILTER(?l >= \"2008\"^^xsd:gYear) }";

		List<BindingSet> result = QueryResults.asList(conn.prepareTupleQuery(query).evaluate());
		assertEquals(2, result.size());
	}
}
 
Example 5
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES1979MinMaxInf() throws Exception {
	loadTestData("/testdata-query/dataset-ses1979.trig");
	String query = "prefix : <http://example.org/> select (min(?o) as ?min) (max(?o) as ?max) where { ?s :float ?o }";

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

	try (TupleQueryResult evaluate = tq.evaluate();) {
		List<BindingSet> result = QueryResults.asList(evaluate);
		assertNotNull(result);
		assertEquals(1, result.size());

		assertEquals(vf.createLiteral(Float.NEGATIVE_INFINITY), result.get(0).getValue("min"));
		assertEquals(vf.createLiteral(Float.POSITIVE_INFINITY), result.get(0).getValue("max"));
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 6
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * See https://github.com/eclipse/rdf4j/issues/1018
 */
@Test
public void testBindError() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data { <urn:test:subj> <urn:test:pred> _:blank }");

	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	StringBuilder qb = new StringBuilder();

	qb.append("SELECT * \n");
	qb.append("WHERE { \n");
	qb.append("  VALUES (?NAValue) { (<http://null>) } \n ");
	qb.append("  BIND(IF(?NAValue != <http://null>, ?NAValue, ?notBoundVar) as ?ValidNAValue) \n ");
	qb.append("  { ?disjClass (owl:disjointWith|^owl:disjointWith)? ?disjClass2 . }\n");
	qb.append("}\n");

	List<BindingSet> result = QueryResults.asList(conn.prepareTupleQuery(qb.toString()).evaluate());

	assertEquals("query should return 2 solutions", 2, result.size());
}
 
Example 7
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
/**
 * See https://github.com/eclipse/rdf4j/issues/1405
 */
public void testBindScope() throws Exception {
	String query = "SELECT * {\n" +
			"  { BIND (\"a\" AS ?a) }\n" +
			"  { BIND (?a AS ?b) } \n" +
			"}";

	TupleQuery q = conn.prepareTupleQuery(query);
	List<BindingSet> result = QueryResults.asList(q.evaluate());

	assertEquals(1, result.size());

	assertEquals(conn.getValueFactory().createLiteral("a"), result.get(0).getValue("a"));
	assertNull(result.get(0).getValue("b"));
}
 
Example 8
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * https://github.com/eclipse/rdf4j/issues/1026
 */
@Test
public void testFilterExistsExternalValuesClause() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data {\n");
	ub.append("  <http://subj1> a <http://type> .\n");
	ub.append("  <http://subj2> a <http://type> .\n");
	ub.append("  <http://subj1> <http://predicate> <http://obj1> .\n");
	ub.append("  <http://subj2> <http://predicate> <http://obj2> .\n");
	ub.append("}");
	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	String query = "select ?s  {\n" + "    ?s a* <http://type> .\n"
			+ "    FILTER EXISTS {?s <http://predicate> ?o}\n"
			+ "} limit 100 values ?o {<http://obj1>}";

	TupleQuery tq = conn.prepareTupleQuery(query);

	List<BindingSet> result = QueryResults.asList(tq.evaluate());
	assertEquals("single result expected", 1, result.size());
	assertEquals("http://subj1", result.get(0).getValue("s").stringValue());
}
 
Example 9
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testValuesClauseNamedGraph() throws Exception {
	String ex = "http://example.org/";
	String data = "@prefix foaf: <" + FOAF.NAMESPACE + "> .\n"
			+ "@prefix ex: <" + ex + "> .\n"
			+ "ex:graph1 {\n" +
			"	ex:Person1 rdf:type foaf:Person ;\n" +
			"		foaf:name \"Person 1\" .	ex:Person2 rdf:type foaf:Person ;\n" +
			"		foaf:name \"Person 2\" .	ex:Person3 rdf:type foaf:Person ;\n" +
			"		foaf:name \"Person 3\" .\n" +
			"}";

	conn.add(new StringReader(data), "", RDFFormat.TRIG);

	String query = "SELECT  ?person ?name ?__index \n"
			+ "WHERE { "
			+ "        VALUES (?person ?name  ?__index) { \n"
			+ "                  (<http://example.org/Person1> UNDEF \"0\") \n"
			+ "                  (<http://example.org/Person3> UNDEF \"2\")  } \n"
			+ "        GRAPH <http://example.org/graph1> { ?person <http://xmlns.com/foaf/0.1/name> ?name .   } }";

	TupleQuery q = conn.prepareTupleQuery(query);

	List<BindingSet> result = QueryResults.asList(q.evaluate());
	assertThat(result).hasSize(2);
}
 
Example 10
Source File: RDFStarSupportTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSparqlStar() {
	Triple rdfStarTriple = vf.createTriple(bob, FOAF.NAME, nameBob);

	testCon.add(rdfStarTriple, RDF.TYPE, RDF.ALT);

	String query = "PREFIX foaf: <" + FOAF.NAMESPACE + ">\nSELECT DISTINCT * WHERE { <<?s foaf:name ?o>> ?b ?c. }";

	List<BindingSet> result = QueryResults.asList(testCon.prepareTupleQuery(query).evaluate());
	assertThat(result).hasSize(1);

	BindingSet bs = result.get(0);
	assertThat(bs.getValue("s")).isEqualTo(bob);
	assertThat(bs.getValue("o")).isEqualTo(nameBob);
	assertThat(bs.getValue("b")).isEqualTo(RDF.TYPE);
	assertThat(bs.getValue("c")).isEqualTo(RDF.ALT);

}
 
Example 11
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
/**
 * See https://github.com/eclipse/rdf4j/issues/1642
 */
public void testBindScopeUnion() {

	ValueFactory f = conn.getValueFactory();
	String query = "prefix ex: <http://example.org/> \n" +
			"select * {\n" +
			"  bind(ex:v1 as ?v)\n" +
			"  bind(strafter(str(?v),str(ex:)) as ?b)\n" +
			"  {\n" +
			"    bind(?b as ?b1)\n" +
			"  } union {\n" +
			"    bind(?b as ?b2)\n" +
			"  }\n" +
			"}";

	TupleQuery q = conn.prepareTupleQuery(query);
	List<BindingSet> result = QueryResults.asList(q.evaluate());

	assertEquals(2, result.size());

	IRI v1 = f.createIRI("http://example.org/v1");
	Literal b = f.createLiteral("v1");
	for (BindingSet bs : result) {
		assertThat(bs.getValue("v")).isEqualTo(v1);
		assertThat(bs.getValue("b1")).isNull();
		assertThat(bs.getValue("b2")).isNull();
	}

}
 
Example 12
Source File: AbstractLuceneSailGeoSPARQLTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testComplexDistanceQueryMathExpr()
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	try (RepositoryConnection connection = repository.getConnection()) {
		String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
				+ "select ?toUri ?dist ?g where { graph ?g {?toUri geo:asWKT ?to.}"
				+ " bind((geof:distance(?from, ?to, ?units) / 1000) as ?dist)" + " filter(?dist < ?range)" + " }";
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("from", TEST_POINT);
		query.setBinding("units", GEOF.UOM_METRE);
		query.setBinding("range", sail.getValueFactory().createLiteral(1.5));

		List<BindingSet> result = QueryResults.asList(query.evaluate());

		// check the results
		Map<IRI, Literal> expected = new LinkedHashMap<>();
		expected.put(SUBJECT_1, sail.getValueFactory().createLiteral(760.0 / 1000.0));

		for (BindingSet bindings : result) {
			System.out.println(bindings);
			IRI subj = (IRI) bindings.getValue("toUri");
			// check ordering
			IRI expectedUri = expected.keySet().iterator().next();
			assertEquals(expectedUri, subj);

			Literal dist = expected.remove(subj);
			assertNotNull(dist);
			assertEquals(dist.doubleValue(), ((Literal) bindings.getValue("dist")).doubleValue(), ERROR);

			assertNotNull(bindings.getValue("g"));
		}
		assertTrue(expected.isEmpty());
	}

}
 
Example 13
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testSES2154SubselectOptional() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data { \n");
	ub.append(" <urn:s1> a <urn:C> .  \n");
	ub.append(" <urn:s2> a <urn:C> .  \n");
	ub.append(" <urn:s3> a <urn:C> .  \n");
	ub.append(" <urn:s4> a <urn:C> .  \n");
	ub.append(" <urn:s5> a <urn:C> .  \n");
	ub.append(" <urn:s6> a <urn:C> .  \n");
	ub.append(" <urn:s7> a <urn:C> .  \n");
	ub.append(" <urn:s8> a <urn:C> .  \n");
	ub.append(" <urn:s9> a <urn:C> .  \n");
	ub.append(" <urn:s10> a <urn:C> .  \n");
	ub.append(" <urn:s11> a <urn:C> .  \n");
	ub.append(" <urn:s12> a <urn:C> .  \n");

	ub.append(" <urn:s1> <urn:p> \"01\" .  \n");
	ub.append(" <urn:s2> <urn:p> \"02\" .  \n");
	ub.append(" <urn:s3> <urn:p> \"03\" .  \n");
	ub.append(" <urn:s4> <urn:p> \"04\" .  \n");
	ub.append(" <urn:s5> <urn:p> \"05\" .  \n");
	ub.append(" <urn:s6> <urn:p> \"06\" .  \n");
	ub.append(" <urn:s7> <urn:p> \"07\" .  \n");
	ub.append(" <urn:s8> <urn:p> \"08\" .  \n");
	ub.append(" <urn:s9> <urn:p> \"09\" .  \n");
	ub.append(" <urn:s10> <urn:p> \"10\" .  \n");
	ub.append(" <urn:s11> <urn:p> \"11\" .  \n");
	ub.append(" <urn:s12> <urn:p> \"12\" .  \n");
	ub.append("} \n");

	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	StringBuilder qb = new StringBuilder();
	qb.append("SELECT ?s ?label\n");
	qb.append("WHERE { \n");
	qb.append(" 	  ?s a <urn:C> \n .\n");
	qb.append(" 	  OPTIONAL  { {SELECT ?label  WHERE { \n");
	qb.append("                     ?s <urn:p> ?label . \n");
	qb.append("   	      } ORDER BY ?label LIMIT 2 \n");
	qb.append("		    }\n");
	qb.append("       }\n");
	qb.append("}\n");
	qb.append("ORDER BY ?s\n");
	qb.append("LIMIT 10 \n");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb.toString());
	try (TupleQueryResult evaluate = tq.evaluate();) {
		assertTrue("The query should return a result", evaluate.hasNext());

		List<BindingSet> result = QueryResults.asList(evaluate);
		assertEquals(10, result.size());
		for (BindingSet bs : result) {
			Literal label = (Literal) bs.getValue("label");
			assertTrue("wrong label value (expected '01' or '02', but got '" + label.stringValue() + "')",
					label.stringValue().equals("01") || label.stringValue().equals("02"));
		}
	}
}
 
Example 14
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testSES1121VarNamesInOptionals() throws Exception {
	// Verifying that variable names have no influence on order of optionals
	// in query. See SES-1121.

	loadTestData("/testdata-query/dataset-ses1121.trig");

	StringBuilder query1 = new StringBuilder();
	query1.append(getNamespaceDeclarations());
	query1.append(" SELECT DISTINCT *\n");
	query1.append(" WHERE { GRAPH ?g { \n");
	query1.append("          OPTIONAL { ?var35 ex:p ?b . } \n ");
	query1.append("          OPTIONAL { ?b ex:q ?c . } \n ");
	query1.append("       } \n");
	query1.append(" } \n");

	StringBuilder query2 = new StringBuilder();
	query2.append(getNamespaceDeclarations());
	query2.append(" SELECT DISTINCT *\n");
	query2.append(" WHERE { GRAPH ?g { \n");
	query2.append("          OPTIONAL { ?var35 ex:p ?b . } \n ");
	query2.append("          OPTIONAL { ?b ex:q ?var2 . } \n ");
	query2.append("       } \n");
	query2.append(" } \n");

	TupleQuery tq1 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query1.toString());
	TupleQuery tq2 = conn.prepareTupleQuery(QueryLanguage.SPARQL, query2.toString());

	try (TupleQueryResult result1 = tq1.evaluate(); TupleQueryResult result2 = tq2.evaluate();) {
		assertNotNull(result1);
		assertNotNull(result2);

		List<BindingSet> qr1 = QueryResults.asList(result1);
		List<BindingSet> qr2 = QueryResults.asList(result2);

		// System.out.println(qr1);
		// System.out.println(qr2);

		// if optionals are not kept in same order, query results will be
		// different size.
		assertEquals(qr1.size(), qr2.size());

	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 15
Source File: StrictEvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testEvaluateRegexFlags() throws Exception {

	String query = "SELECT ?a WHERE { "
			+ "VALUES ?a { \"foo.bar\" \"foo bar\" } \n"
			+ "FILTER REGEX(str(?a), \"foo.bar\")}";

	ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	CloseableIteration<BindingSet, QueryEvaluationException> result = strategy.evaluate(pq.getTupleExpr(),
			new EmptyBindingSet());

	List<BindingSet> bindingSets = QueryResults.asList(result);
	assertThat(bindingSets).hasSize(2);

	// match with q flag
	query = "SELECT ?a WHERE { "
			+ "VALUES ?a { \"foo.bar\" \"foo bar\" } \n"
			+ "FILTER REGEX(str(?a), \"foo.bar\", \"q\")}";

	pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	result = strategy.evaluate(pq.getTupleExpr(),
			new EmptyBindingSet());

	bindingSets = QueryResults.asList(result);
	assertThat(bindingSets).hasSize(1);
	assertThat(bindingSets.get(0).getValue("a").stringValue()).isEqualTo("foo.bar");

	// match with i and q flag
	query = "SELECT ?a WHERE { "
			+ "VALUES ?a { \"foo.bar\" \"FOO.BAR\" \"foo bar\" } \n"
			+ "FILTER REGEX(str(?a), \"foo.bar\", \"iq\")}";

	pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	result = strategy.evaluate(pq.getTupleExpr(),
			new EmptyBindingSet());

	bindingSets = QueryResults.asList(result);
	assertThat(bindingSets).hasSize(2);

	List<String> values = bindingSets.stream().map(v -> v.getValue("a").stringValue()).collect(Collectors.toList());
	assertThat(values).containsExactlyInAnyOrder("foo.bar", "FOO.BAR");
}