org.eclipse.rdf4j.query.GraphQuery Java Examples

The following examples show how to use org.eclipse.rdf4j.query.GraphQuery. 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: ContextAwareConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testGraphQuery() throws Exception {
	RepositoryConnection stub = new RepositoryConnectionStub() {

		@Override
		public GraphQuery prepareGraphQuery(QueryLanguage ql, String query, String baseURI)
				throws MalformedQueryException, RepositoryException {
			assertEquals(SPARQL, ql);
			assertEquals(queryString, query);
			return new GraphQueryStub() {

				@Override
				public void setDataset(Dataset dataset) {
					Set<IRI> contexts = Collections.singleton(context);
					assertEquals(contexts, dataset.getDefaultGraphs());
					super.setDataset(dataset);
				}
			};
		}
	};
	Repository repo = stub.getRepository();
	ContextAwareConnection con = new ContextAwareConnection(repo, stub);
	con.setReadContexts(context);
	con.setQueryLanguage(SERQL);
	con.prepareGraphQuery(SPARQL, queryString, null);
}
 
Example #2
Source File: QueryEvaluator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/***
 * Evaluate a graph query, and create an XML results document.
 *
 * @param builder     response builder helper for generating the XML response to the client, which <em>must not</em>
 *                    have had start() called on it
 * @param xslPath     needed to begin writing response body after writing result count cookie
 * @param req         needed to write result count cookie
 * @param resp        needed to write result count cookie
 * @param cookies     needed to write result count cookie
 * @param query       the query to be evaluated
 * @param writeCookie whether to write the total result count cookie
 * @throws QueryResultHandlerException
 */
private void evaluateGraphQuery(final TupleResultBuilder builder, String xslPath, WorkbenchRequest req,
		HttpServletResponse resp, CookieHandler cookies, final GraphQuery query, boolean writeCookie, boolean paged,
		int offset, int limit) throws QueryEvaluationException, QueryResultHandlerException {
	List<Statement> statements = Iterations.asList(query.evaluate());
	if (writeCookie) {
		cookies.addTotalResultCountCookie(req, resp, statements.size());
	}
	builder.transform(xslPath, "graph.xsl");
	builder.start();
	builder.variables("subject", "predicate", "object");
	builder.link(Arrays.asList(INFO));
	if (paged && writeCookie) {
		// Only in this case do we have paged results, but were given the full
		// query. Just-in-case parameter massaging below to avoid array index
		// issues.
		int fromIndex = Math.min(0, offset);
		statements = statements.subList(fromIndex,
				Math.max(fromIndex, Math.min(offset + limit, statements.size())));
	}
	for (Statement statement : statements) {
		builder.result(statement.getSubject(), statement.getPredicate(), statement.getObject(),
				statement.getContext());
	}
	builder.end();
}
 
Example #3
Source File: PropertyShape.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String describe(SailRepositoryConnection connection, Resource resource) {
	GraphQuery graphQuery = connection.prepareGraphQuery("describe ?a where {BIND(?resource as ?a)}");
	graphQuery.setBinding("resource", resource);

	try (Stream<Statement> stream = graphQuery.evaluate().stream()) {

		LinkedHashModel statements = stream.collect(Collectors.toCollection(LinkedHashModel::new));
		statements.setNamespace(SHACL.PREFIX, SHACL.NAMESPACE);

		WriterConfig config = new WriterConfig();
		config.set(BasicWriterSettings.PRETTY_PRINT, true);
		config.set(BasicWriterSettings.INLINE_BLANK_NODES, true);

		StringWriter stringWriter = new StringWriter();

		Rio.write(statements, stringWriter, RDFFormat.TURTLE, config);

		return stringWriter.toString();
	}
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
Source File: AbstractLuceneSailSpinTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Reproduce #235 with following query: <code>
 * construct {
 *   ?pred a <urn:ontology/Phrase> . ?pred <urn:ontology/label> ?label2 .
 * ?pred <urn:ontology/score> ?score } where { bind(str("ornare") as ?query)
 * . (?query search:allMatches search:score) search:search (?pred ?score) .
 * ?pred rdfs:label ?label . bind(fn:upper-case(?label) as ?label2) , }
 * </code>
 *
 * @throws Exception
 */
@Test
@Ignore("Regression due to GH-1642 - no appetite pending deprecation of LuceneSpinSail")
public void test235Issue() throws Exception {
	StringBuilder buffer = new StringBuilder();
	buffer.append(" construct {\n");
	buffer.append("  ?pred a <urn:ontology/Phrase> .\n");
	buffer.append("  ?pred <urn:ontology/label> ?label2 .\n");
	buffer.append("  ?pred <urn:ontology/score> ?score .\n");
	buffer.append(" } where {\n");
	buffer.append("  bind(str(\"ornare\") as ?query) .\n");
	buffer.append("  (?query <" + ALL_MATCHES + "> <" + SCORE + ">) <" + SEARCH + "> (?pred ?score) . \n");
	buffer.append("  ?pred rdfs:label ?label .\n");
	buffer.append("  bind(fn:upper-case(?label) as ?label2)\n");
	buffer.append(" }");
	log.info("Request query: \n====================\n{}\n======================\n", buffer.toString());

	GraphQuery query = getConnection().prepareGraphQuery(QueryLanguage.SPARQL, buffer.toString());
	printGraphResult(query);
	try (GraphQueryResult res = query.evaluate()) {
		int cnt = countGraphResults(res);
		Assert.assertTrue(String.format("count triples: ", cnt), cnt > 2);
	}
}
 
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 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 #10
Source File: FedXRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public SailQuery prepareQuery(QueryLanguage ql, String queryString,
		String baseURI) throws MalformedQueryException {
	SailQuery q = super.prepareQuery(ql, queryString, baseURI);
	if (q instanceof SailTupleQuery) {
		insertOriginalQueryString(q, queryString, baseURI, QueryType.SELECT);
		q = new FedXTupleQuery((SailTupleQuery) q);
	} else if (q instanceof GraphQuery) {
		insertOriginalQueryString(q, queryString, baseURI, QueryType.CONSTRUCT);
		q = new FedXGraphQuery((SailGraphQuery) q);
	} else if (q instanceof SailBooleanQuery) {
		insertOriginalQueryString(q, queryString, baseURI, QueryType.ASK);
		q = new FedXBooleanQuery((SailBooleanQuery) q);
	}
	setIncludeInferredDefault(q);
	return q;
}
 
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 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 #13
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String query, String querylanguage)
		throws QueryLanguageNotSupportedException {
	assertModel();
	if (querylanguage.equalsIgnoreCase("SPARQL"))
		return sparqlConstruct(query);
	else {
		QueryLanguage ql = QueryLanguage.valueOf(querylanguage);
		if (ql == null) {
			throw new QueryLanguageNotSupportedException("Unsupported query language: '"
					+ querylanguage + "'");
		}
		try {
			GraphQuery prepared = this.connection.prepareGraphQuery(ql, query);
			GraphQueryResult graphQueryResult = prepared.evaluate();
			return new GraphIterable(graphQueryResult, this);
		} catch (MalformedQueryException | RepositoryException |
				UnsupportedQueryLanguageException | QueryEvaluationException e) {
			throw new ModelRuntimeException(e);
		}
	}
}
 
Example #14
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.toRDF4JQueryLanguage(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(RDF4JException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #15
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public GraphQuery prepareGraphQuery(QueryLanguage ql, String query, String base)
		throws RepositoryException, MalformedQueryException {
	if (SPARQL.equals(ql)) {
		return new SPARQLGraphQuery(client, base, query);
	}
	throw new UnsupportedQueryLanguageException("Unsupported query language " + ql);
}
 
Example #16
Source File: SpinInferencing.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static int executeRule(Resource subj, Resource rule, QueryPreparer queryPreparer, SpinParser parser,
		InferencerConnection conn) throws OpenRDFException {
	int nofInferred;
	TripleSource tripleSource = queryPreparer.getTripleSource();
	ParsedOperation parsedOp = parser.parse(rule, tripleSource);
	if (parsedOp instanceof ParsedGraphQuery) {
		ParsedGraphQuery graphQuery = (ParsedGraphQuery) parsedOp;
		GraphQuery queryOp = queryPreparer.prepare(graphQuery);
		addBindings(subj, rule, graphQuery, queryOp, tripleSource, parser);
		CountingRDFInferencerInserter handler = new CountingRDFInferencerInserter(conn,
				tripleSource.getValueFactory());
		queryOp.evaluate(handler);
		nofInferred = handler.getStatementCount();
	} else if (parsedOp instanceof ParsedUpdate) {
		ParsedUpdate graphUpdate = (ParsedUpdate) parsedOp;
		Update updateOp = queryPreparer.prepare(graphUpdate);
		addBindings(subj, rule, graphUpdate, updateOp, tripleSource, parser);
		UpdateCountListener listener = new UpdateCountListener();
		conn.addConnectionListener(listener);
		updateOp.execute();
		conn.removeConnectionListener(listener);
		// number of statement changes
		nofInferred = listener.getAddedStatementCount() + listener.getRemovedStatementCount();
	} else {
		throw new MalformedSpinException("Invalid rule: " + rule);
	}
	return nofInferred;
}
 
Example #17
Source File: LuceneSailExample.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static void graphQuery(String queryString, RepositoryConnection connection)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	System.out.println("Running query: \n" + queryString);
	GraphQuery query = connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
	try (GraphQueryResult result = query.evaluate()) {
		// print the results
		while (result.hasNext()) {
			Statement stmt = result.next();
			System.out.println("found match: " + stmt.getSubject().stringValue() + "\t"
					+ stmt.getPredicate().stringValue() + "\t" + stmt.getObject().stringValue());
		}
	}

}
 
Example #18
Source File: BasicTests.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSingleSource_SetBinding() throws Exception {

	/* test a single source select query where we set a binding */
	prepareTest(Arrays.asList("/tests/basic/data01endpoint1.ttl", "/tests/basic/data01endpoint2.ttl"));

	try (RepositoryConnection conn = fedxRule.getRepository().getConnection()) {

		// SELECT query
		TupleQuery tq = conn
				.prepareTupleQuery("SELECT ?person WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		tq.setBinding("name", l("Alan"));
		TupleQueryResult tqr = tq.evaluate();
		List<BindingSet> res = Iterations.asList(tqr);
		assertContainsAll(res, "person", Sets.newHashSet(iri("http://example.org/", "a")));

		// CONSTRUCT query
		GraphQuery gq = conn.prepareGraphQuery(
				"CONSTRUCT { ?person <http://xmlns.com/foaf/0.1/name> ?name } WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		gq.setBinding("name", l("Alan"));
		GraphQueryResult gqr = gq.evaluate();
		List<Statement> stmts = Iterations.asList(gqr);
		Assertions.assertEquals(1, stmts.size());
		Assertions.assertEquals(iri("http://example.org/", "a"), stmts.get(0).getSubject());

		// BOOLEAN query
		BooleanQuery bq = conn.prepareBooleanQuery("ASK { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		bq.setBinding("name", l("non-existing-name"));
		Assertions.assertEquals(false, bq.evaluate());

	}

}
 
Example #19
Source File: SailRepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testPrepareQuery_bypassed() throws Exception {
	TupleExpr expr = mock(TupleExpr.class);
	Optional<TupleExpr> response = Optional.of(expr);
	when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response);
	when(sailConnection.evaluate(eq(expr), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>());

	GraphQuery query = (GraphQuery) subject.prepareQuery("CONSTRUCT WHERE { ?s ?p ?o }");
	query.evaluate();
	// check that the TupleExpr implementation created by the underlying sail was passed to the evaluation
	verify(sailConnection).evaluate(eq(expr), any(), any(), anyBoolean());
}
 
Example #20
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDescribeD() throws Exception {
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:d");

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

	ValueFactory f = conn.getValueFactory();
	IRI d = f.createIRI("http://example.org/d");
	IRI p = f.createIRI("http://example.org/p");
	IRI e = f.createIRI("http://example.org/e");
	try (GraphQueryResult evaluate = gq.evaluate();) {
		Model result = QueryResults.asModel(evaluate);

		assertNotNull(result);
		assertTrue(result.contains(null, p, e));
		assertFalse(result.contains(e, null, null));
		Set<Value> objects = result.filter(d, p, null).objects();
		assertNotNull(objects);
		for (Value object : objects) {
			if (object instanceof BNode) {
				Set<Value> childObjects = result.filter((BNode) object, null, null).objects();
				assertNotNull(childObjects);
				for (Value childObject : childObjects) {
					if (childObject instanceof BNode) {
						assertTrue(result.contains((BNode) childObject, null, null));
					}
				}
			}
		}
	}
}
 
Example #21
Source File: SailRepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testPrepareGraphQuery_not_bypassed() throws Exception {
	Optional<TupleExpr> response = Optional.empty();
	when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response);
	when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>());

	GraphQuery query = subject.prepareGraphQuery("CONSTRUCT WHERE { ?s ?p ?o }");
	query.evaluate();
	// check that evaluation is still called, and not with an empty TupleExpr
	verify(sailConnection).evaluate(any(TupleExpr.class), any(), any(), anyBoolean());
}
 
Example #22
Source File: SailRepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testPrepareGraphQuery_bypassed() throws Exception {
	TupleExpr expr = mock(TupleExpr.class);
	Optional<TupleExpr> response = Optional.of(expr);
	when(sailConnection.prepareQuery(any(), eq(Query.QueryType.GRAPH), any(), any())).thenReturn(response);
	when(sailConnection.evaluate(eq(expr), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>());

	GraphQuery query = subject.prepareGraphQuery("CONSTRUCT WHERE { ?s ?p ?o }");
	query.evaluate();
	// check that the TupleExpr implementation created by the underlying sail was passed to the evaluation
	verify(sailConnection).evaluate(eq(expr), any(), any(), anyBoolean());
}
 
Example #23
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void exportStatements(Resource subj, IRI pred, Value obj, boolean includeInferred, RDFHandler handler,
		Resource... contexts) throws RepositoryException, RDFHandlerException {
	try {
		GraphQuery query = prepareGraphQuery(SPARQL, EVERYTHING, "");
		setBindings(query, subj, pred, obj, contexts);
		query.evaluate(handler);
	} catch (MalformedQueryException | QueryEvaluationException e) {
		throw new RepositoryException(e);
	}
}
 
Example #24
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private RepositoryResult<Statement> getStatementGeneral(Resource subj, IRI pred, Value obj, boolean includeInferred,
		Resource... contexts) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	GraphQueryResult gRes = null;
	RepositoryResult<Statement> result = null;

	boolean allGood = false;
	try {
		GraphQuery query = prepareGraphQuery(SPARQL, EVERYTHING, "");
		query.setIncludeInferred(includeInferred);
		setBindings(query, subj, pred, obj, contexts);
		gRes = query.evaluate();
		result = new RepositoryResult<>(
				new ExceptionConvertingIteration<Statement, RepositoryException>(gRes) {

					@Override
					protected RepositoryException convert(Exception e) {
						return new RepositoryException(e);
					}
				});
		allGood = true;
		return result;
	} finally {
		if (!allGood) {
			try {
				if (result != null) {
					result.close();
				}
			} finally {
				if (gRes != null) {
					gRes.close();
				}
			}
		}
	}
}
 
Example #25
Source File: TripleSourceBase.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> getStatements(
		String preparedQuery, RepositoryConnection conn, QueryType queryType)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException
{
	switch (queryType)
	{
	case SELECT:
		monitorRemoteRequest();
		TupleQuery tQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(tQuery);
		return tQuery.evaluate();
	case CONSTRUCT:
		monitorRemoteRequest();
		GraphQuery gQuery = conn.prepareGraphQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(gQuery);
		return new GraphToBindingSetConversionIteration(gQuery.evaluate());
	case ASK:
		monitorRemoteRequest();
		BooleanQuery bQuery = conn.prepareBooleanQuery(QueryLanguage.SPARQL, preparedQuery);
		disableInference(bQuery);
		return booleanToBindingSetIteration(bQuery.evaluate());
	default:
		throw new UnsupportedOperationException(
				"Operation not supported for query type " + queryType);
	}
}
 
Example #26
Source File: ContextAwareConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public GraphQuery prepareGraphQuery(QueryLanguage ql, String query, String baseURI)
		throws MalformedQueryException, RepositoryException {
	if (baseURI == null) {
		baseURI = getBaseURI();
	}
	return initQuery(super.prepareGraphQuery(ql, query, baseURI));
}
 
Example #27
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String query) throws ModelRuntimeException {
	assertModel();
	try {
		GraphQuery prepared = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, query);
		GraphQueryResult graphQueryResult = prepared.evaluate();
		return new GraphIterable(graphQueryResult, this);
	} catch (MalformedQueryException | RepositoryException |
			UnsupportedQueryLanguageException | QueryEvaluationException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #28
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String query) throws ModelRuntimeException {
	assertModel();
	try {
		GraphQuery prepared = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, query);
		GraphQueryResult graphQueryResult = prepared.evaluate();
		return new GraphIterable(graphQueryResult, this);
	} catch (MalformedQueryException | RepositoryException |
			UnsupportedQueryLanguageException | QueryEvaluationException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #29
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlConstruct(String queryString)
        throws ModelRuntimeException {
	this.assertModel();
	GraphQuery query;
	try {
		query = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		GraphQueryResult graphQueryResult = query.evaluate();
		return new StatementIterable(graphQueryResult, null);
	} catch(RDF4JException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example #30
Source File: RepositoryModelSet.java    From semweb4j with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public ClosableIterable<Statement> sparqlDescribe(String queryString)
        throws ModelRuntimeException {
	this.assertModel();
	GraphQuery query;
	try {
		query = this.connection.prepareGraphQuery(QueryLanguage.SPARQL, queryString);
		GraphQueryResult graphQueryResult = query.evaluate();
		return new StatementIterable(graphQueryResult, null);
	} catch(RDF4JException e) {
		throw new ModelRuntimeException(e);
	}
}