org.eclipse.rdf4j.query.QueryResults Java Examples

The following examples show how to use org.eclipse.rdf4j.query.QueryResults. 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: QueryResultIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Writes a query result document in a specific query result format to an output stream.
 *
 * @param tqr    The query result to write.
 * @param format The file format of the document to write.
 * @param out    An OutputStream to write the document to.
 * @throws IOException                           If an I/O error occurred while writing the query result document to
 *                                               the stream.
 * @throws TupleQueryResultHandlerException      If such an exception is thrown by the used query result writer.
 * @throws UnsupportedQueryResultFormatException
 * @throws QueryEvaluationException              If an unsupported query result file format was specified.
 */
public static void writeTuple(TupleQueryResult tqr, QueryResultFormat format, OutputStream out) throws IOException,
		TupleQueryResultHandlerException, UnsupportedQueryResultFormatException, QueryEvaluationException {
	TupleQueryResultWriter writer = createTupleWriter(format, out);
	try {
		writer.startDocument();
		writer.startHeader();
		QueryResults.report(tqr, writer);
	} catch (QueryResultHandlerException e) {
		if (e.getCause() instanceof IOException) {
			throw (IOException) e.getCause();
		} else if (e instanceof TupleQueryResultHandlerException) {
			throw (TupleQueryResultHandlerException) e;
		} else {
			throw new TupleQueryResultHandlerException(e);
		}
	}
}
 
Example #2
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDescribeMultipleB() throws Exception {
	String update = "insert data { <urn:1> <urn:p1> <urn:v> . <urn:1> <urn:blank> [] . <urn:2> <urn:p2> <urn:3> . } ";
	conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE <urn:1> <urn:2> ");

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

	ValueFactory vf = conn.getValueFactory();
	IRI urn1 = vf.createIRI("urn:1");
	IRI p1 = vf.createIRI("urn:p1");
	IRI p2 = vf.createIRI("urn:p2");
	IRI urn2 = vf.createIRI("urn:2");
	IRI blank = vf.createIRI("urn:blank");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(evaluate);

		assertTrue(result.contains(urn1, p1, null));
		assertTrue(result.contains(urn1, blank, null));
		assertTrue(result.contains(urn2, p2, null));
	}
}
 
Example #3
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDescribeMultipleC() throws Exception {
	String update = "insert data { <urn:1> <urn:p1> <urn:v> . [] <urn:blank> <urn:1>. <urn:1> <urn:blank> [] . <urn:2> <urn:p2> <urn:3> . } ";
	conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE <urn:1> <urn:2> ");

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

	ValueFactory vf = conn.getValueFactory();
	IRI urn1 = vf.createIRI("urn:1");
	IRI p1 = vf.createIRI("urn:p1");
	IRI p2 = vf.createIRI("urn:p2");
	IRI urn2 = vf.createIRI("urn:2");
	IRI blank = vf.createIRI("urn:blank");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(evaluate);

		assertTrue(result.contains(urn1, p1, null));
		assertTrue(result.contains(urn1, blank, null));
		assertTrue(result.contains(null, blank, urn1));
		assertTrue(result.contains(urn2, p2, null));
	}
}
 
Example #4
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 #5
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2104ConstructBGPSameURI() throws Exception {
	final String queryStr = "PREFIX : <urn:> CONSTRUCT {:x :p :x } WHERE {} ";

	conn.add(new StringReader("@prefix : <urn:> . :a :p :b . "), "", RDFFormat.TURTLE);

	final IRI x = conn.getValueFactory().createIRI("urn:x");
	final IRI p = conn.getValueFactory().createIRI("urn:p");

	GraphQuery query = conn.prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
	try (GraphQueryResult evaluate = query.evaluate();) {
		Model result = QueryResults.asModel(evaluate);

		assertNotNull(result);
		assertFalse(result.isEmpty());
		assertTrue(result.contains(x, p, x));
	}
}
 
Example #6
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDescribeMultipleA() throws Exception {
	String update = "insert data { <urn:1> <urn:p1> <urn:v> . [] <urn:blank> <urn:1> . <urn:2> <urn:p2> <urn:3> . } ";
	conn.prepareUpdate(QueryLanguage.SPARQL, update).execute();

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE <urn:1> <urn:2> ");

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

	ValueFactory vf = conn.getValueFactory();
	IRI urn1 = vf.createIRI("urn:1");
	IRI p1 = vf.createIRI("urn:p1");
	IRI p2 = vf.createIRI("urn:p2");
	IRI urn2 = vf.createIRI("urn:2");
	IRI blank = vf.createIRI("urn:blank");

	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(evaluate);
		assertTrue(result.contains(urn1, p1, null));
		assertTrue(result.contains(null, blank, urn1));
		assertTrue(result.contains(urn2, p2, null));
	}
}
 
Example #7
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 #8
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 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();
	IRI b = f.createIRI("http://example.org/b");
	IRI p = f.createIRI("http://example.org/p");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(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 #9
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 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();
	IRI a = f.createIRI("http://example.org/a");
	IRI p = f.createIRI("http://example.org/p");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(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 #10
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 #11
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 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();
	IRI a = f.createIRI("http://example.org/a");
	IRI p = f.createIRI("http://example.org/p");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
Source File: AbstractQueryResultIOTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void doTupleLinks(TupleQueryResultFormat format, TupleQueryResult input, TupleQueryResult expected,
		List<String> links) throws QueryResultHandlerException, QueryEvaluationException, QueryResultParseException,
		UnsupportedQueryResultFormatException, IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.startHeader();
	writer.handleLinks(links);
	QueryResults.report(input, writer);

	// System.out.println("output: " + out.toString("UTF-8"));

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	TupleQueryResult output = parseTupleInternal(format, in);

	assertQueryResultsEqual(expected, output);
}
 
Example #18
Source File: AbstractQueryResultIOTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void doTupleLinksAndStylesheet(TupleQueryResultFormat format, TupleQueryResult input,
		TupleQueryResult expected, List<String> links, String stylesheetUrl) throws QueryResultHandlerException,
		QueryEvaluationException, QueryResultParseException, UnsupportedQueryResultFormatException, IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.handleStylesheet(stylesheetUrl);
	writer.startHeader();
	writer.handleLinks(links);
	QueryResults.report(input, writer);

	// System.out.println("output: " + out.toString("UTF-8"));

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	TupleQueryResult output = parseTupleInternal(format, in);

	assertQueryResultsEqual(expected, output);
}
 
Example #19
Source File: AbstractQueryResultIOTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void doTupleLinksAndStylesheetAndNamespaces(TupleQueryResultFormat format, TupleQueryResult input,
		TupleQueryResult expected, List<String> links, String stylesheetUrl, Map<String, String> namespaces)
		throws QueryResultHandlerException, QueryEvaluationException, QueryResultParseException,
		UnsupportedQueryResultFormatException, IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	for (String nextPrefix : namespaces.keySet()) {
		writer.handleNamespace(nextPrefix, namespaces.get(nextPrefix));
	}
	writer.startDocument();
	writer.handleStylesheet(stylesheetUrl);
	writer.startHeader();
	writer.handleLinks(links);
	QueryResults.report(input, writer);

	// System.out.println("output: " + out.toString("UTF-8"));

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	TupleQueryResult output = parseTupleInternal(format, in);

	assertQueryResultsEqual(expected, output);
}
 
Example #20
Source File: AbstractQueryResultIOTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void doTupleLinksAndStylesheetNoStarts(TupleQueryResultFormat format, TupleQueryResult input,
		TupleQueryResult expected, List<String> links, String stylesheetUrl) throws QueryResultHandlerException,
		QueryEvaluationException, QueryResultParseException, UnsupportedQueryResultFormatException, IOException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	// Test for handling when startDocument and startHeader are not called
	writer.handleStylesheet(stylesheetUrl);
	writer.handleLinks(links);
	QueryResults.report(input, writer);

	// System.out.println("output: " + out.toString("UTF-8"));

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	TupleQueryResult output = parseTupleInternal(format, in);

	assertQueryResultsEqual(expected, output);
}
 
Example #21
Source File: SPARQLCSVTupleTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testmultipleVarResults() throws Exception {
	TupleQueryResultFormat format = getTupleFormat();
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.startHeader();
	writer.handleLinks(Arrays.<String>asList());
	QueryResults.report(createTupleMultipleBindingSets(), writer);

	assertRegex("a,b,c\r\n" + "foo:bar,_:bnode,baz\r\n" + "1,,Hello World!\r\n"
			+ "http://example.org/test/ns/bindingA,http://example.com/other/ns/bindingB,\"http://example.com/other/ns/binding,C\"\r\n"
			+ "\"string with newline at the end       \n\",string with space at the end         ,    \r\n"
			+ "''single-quoted string,\"\"\"\"\"double-quoted string\",\t\tunencoded tab characters followed by encoded \t\t(\r\n)?",
			out.toString("UTF-8"));
}
 
Example #22
Source File: RemoveIsolationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testRemoveOptimisticIsolation() throws Exception {
	con.begin(level);

	con.add(f.createIRI("http://example.org/people/alice"), f.createIRI("http://example.org/ontology/name"),
			f.createLiteral("Alice"));

	try (RepositoryResult<Statement> stats = con.getStatements(null, null, null, true);) {
		con.remove(stats);
	}

	try (RepositoryResult<Statement> stats = con.getStatements(null, null, null, true);) {
		assertEquals(Collections.emptyList(), QueryResults.asList(stats));
	}
	con.rollback();
}
 
Example #23
Source File: SPARQLCSVTupleTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSingleVarResults() throws Exception {
	TupleQueryResultFormat format = getTupleFormat();
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.startHeader();
	writer.handleLinks(Arrays.<String>asList());
	QueryResults.report(createTupleSingleVarMultipleBindingSets(), writer);

	System.out.println(out.toString("UTF-8"));
	assertRegex("a\r\n" + "foo:bar\r\n" + "2.0(E0)?\r\n" + "_:bnode3\r\n" + "''single-quoted string\r\n"
			+ "\"\"\"\"\"double-quoted string\"\r\n" + "space at the end         \r\n"
			+ "space at the end         \r\n" + "\"\"\"\"\"double-quoted string with no datatype\"\r\n"
			+ "\"newline at the end \n\"(\r\n)?"
			+ "urn:rdf4j:triple:PDw8dXJuOmE-IDxodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjdHlwZT4gPHVybjpiPj4-(\r\n)?",
			out.toString("UTF-8"));
}
 
Example #24
Source File: GettingStartedDemoMinimal.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) {

		FedXRepository repository = FedXFactory.newFederation()
				.withSparqlEndpoint("http://dbpedia.org/sparql")
				.withSparqlEndpoint("https://query.wikidata.org/sparql")
				.create();

		String query = "PREFIX wd: <http://www.wikidata.org/entity/> "
				+ "PREFIX wdt: <http://www.wikidata.org/prop/direct/> "
				+ "SELECT * WHERE { "
				+ " ?country a <http://dbpedia.org/class/yago/WikicatMemberStatesOfTheEuropeanUnion> ."
				+ " ?country <http://www.w3.org/2002/07/owl#sameAs> ?countrySameAs . "
				+ " ?countrySameAs wdt:P2131 ?gdp ."
				+ "}";

		List<BindingSet> res = Repositories.tupleQuery(repository, query, it -> QueryResults.asList(it));
		res.forEach(bs -> System.out.println(bs));

		repository.shutDown();
	}
 
Example #25
Source File: SPARQLCSVTupleBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testmultipleVarResults() throws Exception {
	TupleQueryResultFormat format = getTupleFormat();
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.startHeader();
	writer.handleLinks(Arrays.<String>asList());
	QueryResults.report(createTupleMultipleBindingSets(), writer);

	assertRegex("a,b,c\r\n" + "foo:bar,_:bnode,baz\r\n" + "1,,Hello World!\r\n"
			+ "http://example.org/test/ns/bindingA,http://example.com/other/ns/bindingB,\"http://example.com/other/ns/binding,C\"\r\n"
			+ "\"string with newline at the end       \n\",string with space at the end         ,    \r\n"
			+ "''single-quoted string,\"\"\"\"\"double-quoted string\",\t\tunencoded tab characters followed by encoded \t\t(\r\n)?",
			out.toString("UTF-8"));
}
 
Example #26
Source File: SPARQLCSVTupleBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSingleVarResults() throws Exception {
	TupleQueryResultFormat format = getTupleFormat();
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	TupleQueryResultWriter writer = QueryResultIO.createTupleWriter(format, out);
	writer.startDocument();
	writer.startHeader();
	writer.handleLinks(Arrays.<String>asList());
	QueryResults.report(createTupleSingleVarMultipleBindingSets(), writer);

	System.out.println(out.toString("UTF-8"));
	assertRegex("a\r\n" + "foo:bar\r\n" + "2.0(E0)?\r\n" + "_:bnode3\r\n" + "''single-quoted string\r\n"
			+ "\"\"\"\"\"double-quoted string\"\r\n" + "space at the end         \r\n"
			+ "space at the end         \r\n" + "\"\"\"\"\"double-quoted string with no datatype\"\r\n"
			+ "\"newline at the end \n\"(\r\n)?"
			+ "urn:rdf4j:triple:PDw8dXJuOmE-IDxodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjdHlwZT4gPHVybjpiPj4-(\r\n)?",
			out.toString("UTF-8"));
}
 
Example #27
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 #28
Source File: QueryResultIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Writes a graph query result document in a specific RDF format to an output stream.
 *
 * @param gqr    The query result to write.
 * @param format The file format of the document to write.
 * @param out    An OutputStream to write the document to.
 * @throws IOException                  If an I/O error occurred while writing the query result document to the
 *                                      stream.
 * @throws RDFHandlerException          If such an exception is thrown by the used RDF writer.
 * @throws QueryEvaluationException
 * @throws UnsupportedRDFormatException If an unsupported query result file format was specified.
 */
public static void writeGraph(GraphQueryResult gqr, RDFFormat format, OutputStream out)
		throws IOException, RDFHandlerException, UnsupportedRDFormatException, QueryEvaluationException {
	RDFWriter writer = Rio.createWriter(format, out);
	try {
		QueryResults.report(gqr, writer);
	} catch (RDFHandlerException e) {
		if (e.getCause() instanceof IOException) {
			throw (IOException) e.getCause();
		} else {
			throw e;
		}
	}
}
 
Example #29
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 #30
Source File: TripleStoreRDF4J.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
private void write(DataSource ds, RepositoryConnection conn, Resource context) {
    LOGGER.info("Writing context {}", context);

    RepositoryResult<Statement> statements;
    statements = conn.getStatements(null, null, null, context);
    Model model = QueryResults.asModel(statements);
    copyNamespacesToModel(conn, model);

    String outname = context.toString();
    write(model, outputStream(ds, outname));
}