org.eclipse.rdf4j.query.Query Java Examples
The following examples show how to use
org.eclipse.rdf4j.query.Query.
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: SPARQLConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void setBindings(Query query, Resource subj, IRI pred, Value obj, Resource... contexts) throws RepositoryException { if (subj != null) { query.setBinding("s", subj); } if (pred != null) { query.setBinding("p", pred); } if (obj != null) { query.setBinding("o", obj); } if (contexts != null && contexts.length > 0) { SimpleDataset dataset = new SimpleDataset(); for (Resource ctx : contexts) { if (ctx == null || ctx instanceof IRI) { dataset.addDefaultGraph((IRI) ctx); } else { throw new RepositoryException("Contexts must be URIs"); } } query.setDataset(dataset); } }
Example #2
Source File: ExplainQueryController.java From semagrow with Apache License 2.0 | 6 votes |
@Override protected ModelAndView handleQuery(Query query, boolean headersOnly, HttpServletRequest request, HttpServletResponse response) throws HTTPException { if (query instanceof SemagrowTupleQuery) { SemagrowTupleQuery stQuery = (SemagrowTupleQuery) query; TupleExpr decomposedQuery = stQuery.getDecomposedQuery(); Map<String, Object> model = new HashMap<String, Object>(); model.put(ExplainView.DECOMPOSED,decomposedQuery); model.put(ExplainView.HEADERS_ONLY, headersOnly); return new ModelAndView(ExplainView.getInstance(), model); } else throw new ClientHTTPException(SC_BAD_REQUEST, "Unsupported query type: " + query.getClass().getName()); }
Example #3
Source File: QueryManager.java From CostFed with GNU Affero General Public License v3.0 | 6 votes |
/** * Prepare a {@link Query} which uses the underlying federation to evaluate the SPARQL query.<p> * * The queryString is modified to use the declared PREFIX declarations, see * {@link Config#getPrefixDeclarations()} for details. * * @param queryString * @return * @throws MalformedQueryException */ public Query prepareQuery(String queryString) { if (prefixDeclarations.size() > 0) { /* we have to check for prefixes in the query to not add * duplicate entries. In case duplicates are present * Sesame throws a MalformedQueryException */ if (prefixCheck.matcher(queryString).matches()) { queryString = getPrefixDeclarationsCheck(queryString) + queryString; } else { queryString = getPrefixDeclarations() + queryString; } } Query q = conn.prepareQuery(QueryLanguage.SPARQL, queryString); // TODO set query time return q; }
Example #4
Source File: ContextAwareConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test public void testQuery() throws Exception { RepositoryConnection stub = new RepositoryConnectionStub() { @Override public Query prepareQuery(QueryLanguage ql, String query, String baseURI) throws MalformedQueryException, RepositoryException { assertEquals(SPARQL, ql); assertEquals(queryString, query); return new QueryStub() { @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.prepareQuery(SPARQL, queryString, null); }
Example #5
Source File: QueryTimeoutTests.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test @Disabled // local test only public void testLocalTimeout2() throws Exception { assumeSparqlEndpoint(); prepareTest(Arrays.asList("/tests/medium/data1.ttl", "/tests/medium/data2.ttl", "/tests/medium/data3.ttl", "/tests/medium/data4.ttl")); fedxRule.enableDebug(); repoSettings(1).setLatencySimulator(latencySimulator(2000)); repoSettings(2).setLatencySimulator(latencySimulator(2500)); Query query = queryManager().prepareQuery(readQueryString("/tests/medium/query01.rq")); query.setMaxExecutionTime(5); Assertions.assertThrows(QueryInterruptedException.class, () -> { try (TupleQueryResult tq = ((TupleQuery) query).evaluate()) { Iterations.asList(tq); } }); }
Example #6
Source File: QueryTimeoutTests.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Test @Disabled // local test only public void testLocalTimeout() throws Exception { assumeSparqlEndpoint(); prepareTest(Arrays.asList("/tests/medium/data1.ttl", "/tests/medium/data2.ttl", "/tests/medium/data3.ttl", "/tests/medium/data4.ttl")); fedxRule.enableDebug(); repoSettings(1).setLatencySimulator(latencySimulator(2000)); repoSettings(2).setLatencySimulator(latencySimulator(2000)); repoSettings(3).setLatencySimulator(latencySimulator(4000)); Query query = queryManager().prepareQuery(readQueryString("/tests/medium/query05.rq")); query.setMaxExecutionTime(10); Assertions.assertThrows(QueryInterruptedException.class, () -> { try (TupleQueryResult tq = ((TupleQuery) query).evaluate()) { Iterations.asList(tq); } }); }
Example #7
Source File: TripleSourceBase.java From CostFed with GNU Affero General Public License v3.0 | 5 votes |
/** * Set includeInference to disabled explicitly. * * @param query */ protected void disableInference(Query query) { // set includeInferred to false explicitly try { query.setIncludeInferred(false); } catch (Exception e) { } }
Example #8
Source File: SPARQLConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Query prepareQuery(QueryLanguage ql, String query, String base) throws RepositoryException, MalformedQueryException { if (SPARQL.equals(ql)) { String strippedQuery = QueryParserUtil.removeSPARQLQueryProlog(query).toUpperCase(); if (strippedQuery.startsWith("SELECT")) { return prepareTupleQuery(ql, query, base); } else if (strippedQuery.startsWith("ASK")) { return prepareBooleanQuery(ql, query, base); } else { return prepareGraphQuery(ql, query, base); } } throw new UnsupportedOperationException("Unsupported query language " + ql); }
Example #9
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareBooleanQuery_bypassed() throws Exception { TupleExpr expr = mock(TupleExpr.class); Optional<TupleExpr> response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.BOOLEAN), any(), any())).thenReturn(response); when(sailConnection.evaluate(eq(expr), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); BooleanQuery query = subject.prepareBooleanQuery("ASK 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 #10
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareBooleanQuery_not_bypassed() throws Exception { Optional<TupleExpr> response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.BOOLEAN), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); BooleanQuery query = subject.prepareBooleanQuery("ASK 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 #11
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@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 #12
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@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 #13
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareTupleQuery_bypassed() throws Exception { TupleExpr expr = mock(TupleExpr.class); Optional<TupleExpr> response = Optional.of(expr); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); when(sailConnection.evaluate(eq(expr), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); TupleQuery query = subject.prepareTupleQuery("SELECT * 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 #14
Source File: QueryPlanRetrievalTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testTimeout() { SailRepository sailRepository = new SailRepository(new MemoryStore()); try (SailRepositoryConnection connection = sailRepository.getConnection()) { connection.begin(); for (int i = 0; i < 1000; i++) { connection.add(vf.createBNode(i + ""), RDF.TYPE, vf.createBNode((i + 1) + "")); connection.add(vf.createBNode(i + ""), RDF.TYPE, vf.createBNode((i - 1) + "")); connection.add(vf.createBNode(i + ""), RDF.TYPE, vf.createBNode((i + 2) + "")); connection.add(vf.createBNode(i + ""), RDF.TYPE, vf.createBNode((i - 2) + "")); } connection.commit(); } try (SailRepositoryConnection connection = sailRepository.getConnection()) { Query query = connection.prepareTupleQuery(String.join("\n", "", "select * where {", " ?a (a|^a)* ?type. ", " FILTER NOT EXISTS{?a (a|^a)* ?type} ", " FILTER NOT EXISTS{?a (a|^a)* ?type} ", " FILTER NOT EXISTS{?a (a|^a)* ?type} ", " FILTER NOT EXISTS{?a (a|^a)* ?type}", " FILTER NOT EXISTS{?a (a|^a)* ?type}", " FILTER NOT EXISTS{?a (a|^a)* ?type}", " FILTER NOT EXISTS{?a (a|^a)* ?type}", " FILTER NOT EXISTS{?a (a|^a)* ?type}", "}")); query.setMaxExecutionTime(1); String actual = query.explain(Explanation.Level.Timed).toString(); Assert.assertThat(actual, containsString("Timed out")); } sailRepository.shutDown(); }
Example #15
Source File: LoggingUtil.java From semagrow with Apache License 2.0 | 5 votes |
public static void logRemote(Logger logger, RepositoryConnection conn, String sparqlQuery, java.net.URL endpoint, TupleExpr expr, Query query) { logger.info("rc {} - rq {} - sq {} - Sending to [{}] query [{}] with {}", conn.hashCode(), Math.abs((sparqlQuery+endpoint).hashCode()), Math.abs(expr.getParentNode().getParentNode().hashCode()), endpoint, sparqlQuery.replace('\n', ' '), query.getBindings()); }
Example #16
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareTupleQuery_not_bypassed() throws Exception { Optional<TupleExpr> response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); TupleQuery query = subject.prepareTupleQuery("SELECT * 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 #17
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@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 #18
Source File: DatasetRepositoryConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private Query wrap(SailQuery q) { if (q instanceof SailBooleanQuery) { return wrap((SailBooleanQuery) q); } if (q instanceof SailGraphQuery) { return wrap((SailGraphQuery) q); } if (q instanceof SailTupleQuery) { return wrap((SailTupleQuery) q); } throw new IllegalArgumentException(q.getClass().getSimpleName() + " not supported on DatasetRepository"); }
Example #19
Source File: SailRepositoryConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public SailTupleQuery prepareTupleQuery(QueryLanguage ql, String queryString, String baseURI) throws MalformedQueryException { Optional<TupleExpr> sailTupleExpr = sailConnection.prepareQuery(ql, Query.QueryType.TUPLE, queryString, baseURI); ParsedTupleQuery parsedQuery = sailTupleExpr .map(expr -> new ParsedTupleQuery(queryString, expr)) .orElse(QueryParserUtil.parseTupleQuery(ql, queryString, baseURI)); return new SailTupleQuery(parsedQuery, this); }
Example #20
Source File: SailRepositoryConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public SailGraphQuery prepareGraphQuery(QueryLanguage ql, String queryString, String baseURI) throws MalformedQueryException { Optional<TupleExpr> sailTupleExpr = sailConnection.prepareQuery(ql, Query.QueryType.GRAPH, queryString, baseURI); ParsedGraphQuery parsedQuery = sailTupleExpr .map(expr -> new ParsedGraphQuery(queryString, expr)) .orElse(QueryParserUtil.parseGraphQuery(ql, queryString, baseURI)); return new SailGraphQuery(parsedQuery, this); }
Example #21
Source File: SailRepositoryConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public SailBooleanQuery prepareBooleanQuery(QueryLanguage ql, String queryString, String baseURI) throws MalformedQueryException { Optional<TupleExpr> sailTupleExpr = sailConnection.prepareQuery(ql, Query.QueryType.BOOLEAN, queryString, baseURI); ParsedBooleanQuery parsedQuery = sailTupleExpr .map(expr -> new ParsedBooleanQuery(queryString, expr)) .orElse(QueryParserUtil.parseBooleanQuery(ql, queryString, baseURI)); return new SailBooleanQuery(parsedQuery, this); }
Example #22
Source File: SailRepositoryConnectionTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPrepareQuery_not_bypassed() throws Exception { Optional<TupleExpr> response = Optional.empty(); when(sailConnection.prepareQuery(any(), eq(Query.QueryType.TUPLE), any(), any())).thenReturn(response); when(sailConnection.evaluate(any(), any(), any(), anyBoolean())).thenReturn(new EmptyIteration<>()); TupleQuery query = (TupleQuery) subject.prepareQuery("SELECT * 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 #23
Source File: EvalFunction.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected static void addArguments(Query query, Value... args) throws ValueExprEvaluationException { for (int i = 1; i < args.length; i += 2) { if (!(args[i] instanceof URI)) { throw new ValueExprEvaluationException("Argument " + i + " must be a URI"); } query.setBinding(((URI) args[i]).getLocalName(), args[i + 1]); } }
Example #24
Source File: AbstractSpinFunction.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected static void addBindings(Query query, Value... args) throws ValueExprEvaluationException { for (int i = 1; i < args.length; i += 2) { if (!(args[i] instanceof Literal)) { throw new ValueExprEvaluationException("Argument " + i + " must be a literal"); } query.setBinding(((Literal) args[i]).getLabel(), args[i + 1]); } }
Example #25
Source File: FedXBaseTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected TupleQueryResult runSelectQueryFile(String queryFile) throws Exception { String queryString = readQueryString(queryFile); Query query = queryManager().prepareQuery(queryString); if (query instanceof TupleQuery) { return ((TupleQuery) query).evaluate(); } throw new Exception("unexpected query: " + queryString); }
Example #26
Source File: QueryManager.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Prepare a {@link Query} which uses the underlying federation to evaluate the SPARQL query. * <p> * * The queryString is modified to use the declared PREFIX declarations, see * {@link FedXConfig#getPrefixDeclarations()} for details. * * @param queryString * @return the prepared {@link Query} * @throws MalformedQueryException */ public Query prepareQuery(String queryString) throws MalformedQueryException { if (prefixDeclarations.size() > 0) { /* * we have to check for prefixes in the query to not add duplicate entries. In case duplicates are present * RDF4J throws a MalformedQueryException */ if (prefixCheck.matcher(queryString).matches()) { queryString = getPrefixDeclarationsCheck(queryString) + queryString; } else { queryString = getPrefixDeclarations() + queryString; } } Query q; try { q = getOrCreateConn().prepareQuery(QueryLanguage.SPARQL, queryString); } catch (RepositoryException e) { throw new FedXRuntimeException(e); // cannot occur } // TODO set query time return q; }
Example #27
Source File: ContextAwareConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Override public Query prepareQuery(QueryLanguage ql, String query, String baseURI) throws MalformedQueryException, RepositoryException { if (baseURI == null) { baseURI = getBaseURI(); } return initQuery(super.prepareQuery(ql, query, baseURI)); }
Example #28
Source File: TripleSourceBase.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Set includeInferred depending on {@link QueryInfo#getIncludeInferred()} * * @param query * @param queryInfo */ protected void configureInference(Query query, QueryInfo queryInfo) { try { query.setIncludeInferred(queryInfo.getIncludeInferred()); } catch (Exception e) { log.debug("Failed to set include inferred: " + e.getMessage()); log.trace("Details:", e); } }
Example #29
Source File: QueryFactory.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public static Query prepareQuery(final RepositoryConnection con, final QueryLanguage queryLn, final String query) throws RDF4JException { Query rval = null; try { rval = con.prepareQuery(queryLn, query); } catch (UnsupportedOperationException exc) { // TODO must be an HTTP repository try { con.prepareTupleQuery(queryLn, query).evaluate().close(); rval = con.prepareTupleQuery(queryLn, query); } catch (Exception e1) { // guess its not a tuple query try { con.prepareGraphQuery(queryLn, query).evaluate().close(); rval = con.prepareGraphQuery(queryLn, query); } catch (Exception e2) { // guess its not a graph query try { con.prepareBooleanQuery(queryLn, query).evaluate(); rval = con.prepareBooleanQuery(queryLn, query); } catch (Exception e3) { // guess its not a boolean query // let's assume it is an malformed tuple query rval = con.prepareTupleQuery(queryLn, query); } } } } return rval; }
Example #30
Source File: QueryEvaluator.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void evaluate(final TupleResultBuilder builder, final OutputStream out, final String xslPath, final WorkbenchRequest req, HttpServletResponse resp, CookieHandler cookies, final Query query, boolean writeCookie, boolean paged, int offset, int limit) throws RDF4JException, BadRequestException { if (query instanceof TupleQuery) { this.evaluateTupleQuery(builder, xslPath, req, resp, cookies, (TupleQuery) query, writeCookie, paged, offset, limit); } else { final RDFFormat format = req.isParameterPresent(ACCEPT) ? Rio.getWriterFormatForMIMEType(req.getParameter(ACCEPT)).orElse(null) : null; if (query instanceof GraphQuery) { GraphQuery graphQuery = (GraphQuery) query; if (null == format) { this.evaluateGraphQuery(builder, xslPath, req, resp, cookies, graphQuery, writeCookie, paged, offset, limit); } else { this.evaluateGraphQuery(Rio.createWriter(format, out), graphQuery); } } else if (query instanceof BooleanQuery) { builder.transform(xslPath, "boolean.xsl"); builder.startBoolean(); this.evaluateBooleanQuery(builder, (BooleanQuery) query); builder.endBoolean(); } else { throw new BadRequestException("Unknown query type: " + query.getClass().getSimpleName()); } } }