org.openrdf.query.GraphQueryResult Java Examples
The following examples show how to use
org.openrdf.query.GraphQueryResult.
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: BlazeGraphEmbedded.java From tinkerpop3 with GNU General Public License v2.0 | 6 votes |
/** * {@inheritDoc} * * Logs the query at INFO and logs the optimized AST at TRACE. */ @Override protected Stream<Statement> _project( final String queryStr, final String extQueryId) { logQuery(queryStr); return Code.wrapThrow(() -> { final BigdataSailGraphQuery query = (BigdataSailGraphQuery) cxn().prepareGraphQuery(QueryLanguage.SPARQL, queryStr); setMaxQueryTime(query); final UUID queryId = setupQuery(query.getASTContainer(), QueryType.CONSTRUCT, extQueryId); sparqlLog.trace(() -> "optimized AST:\n"+query.optimize()); /* * Result is closed automatically by GraphStreamer. */ final GraphQueryResult result = query.evaluate(); final Optional<Runnable> onClose = Optional.of(() -> finalizeQuery(queryId)); return new GraphStreamer<>(result, onClose).stream(); }); }
Example #2
Source File: SampleBlazegraphRDR.java From blazegraph-samples with GNU General Public License v2.0 | 6 votes |
private static boolean namespaceExists(final String namespace, final RemoteRepositoryManager repo) throws Exception{ final GraphQueryResult res = repo.getRepositoryDescriptions(); try{ while(res.hasNext()){ final Statement stmt = res.next(); if (stmt.getPredicate().toString().equals(SD.KB_NAMESPACE.stringValue())) { if(namespace.equals(stmt.getObject().stringValue())){ log.info(String.format("Namespace %s already exists", namespace)); return true; } } } } finally { res.close(); } return false; }
Example #3
Source File: SampleBlazegraphSesameRemote.java From blazegraph-samples with GNU General Public License v2.0 | 6 votes |
private static boolean namespaceExists(final RemoteRepositoryManager repo, final String namespace) throws Exception { final GraphQueryResult res = repo.getRepositoryDescriptions(); try { while (res.hasNext()) { final Statement stmt = res.next(); if (stmt.getPredicate() .toString() .equals(SD.KB_NAMESPACE.stringValue())) { if (namespace.equals(stmt.getObject().stringValue())) { return true; } } } } finally { res.close(); } return false; }
Example #4
Source File: RepositoryModelSet.java From semweb4j with BSD 2-Clause "Simplified" License | 6 votes |
@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.toOpenRDFQueryLanguage(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(OpenRDFException e) { throw new ModelRuntimeException(e); } }
Example #5
Source File: Test_Ticket_789.java From database with GNU General Public License v2.0 | 6 votes |
/** * Test supposed to check if remote call for getStatements properly handle * contexts */ public void test_ticket_753_getStatements() throws Exception { populate(); final GraphQueryResult resultIncludeInferred = m_repo.getStatements(s, p, o, true, c); try { int count = 0; while (resultIncludeInferred.hasNext()) { resultIncludeInferred.next(); count++; } // check that only one of the (s,p,o) triple returned for the specified context c, // as the other one belongs to different context namedGraph1 assertEquals(1, count); } finally { resultIncludeInferred.close(); } }
Example #6
Source File: BigdataGraph.java From database with GNU General Public License v2.0 | 6 votes |
/** * Find vertices based on the supplied from and to vertices and the edge * labels. One or the other (from and to) must be null (wildcard), but not * both. Use getEdges() for wildcards on both the from and to. The edge * labels can be null to include all labels. * * @param from * the from vertex (null for wildcard) * @param to * the to vertex (null for wildcard) * @param labels * the edge labels to consider (optional) * @return * the vertices matching the supplied criteria */ Iterable<Vertex> getVertices(final URI from, final URI to, final String... labels) throws Exception { if (from != null && to != null) { throw new IllegalArgumentException(); } if (from == null && to == null) { throw new IllegalArgumentException(); } final GraphQueryResult stmts = getElements(from, to, labels); /* * VertexIterable will close the connection if necessary. */ return new VertexIterable(stmts, from == null); }
Example #7
Source File: BigdataSailRemoteRepositoryConnection.java From database with GNU General Public License v2.0 | 5 votes |
@Override public void exportStatements(final Resource s, final URI p, final Value o, final boolean includeInferred, final RDFHandler handler, final Resource... c) throws RepositoryException, RDFHandlerException { try { final RemoteRepository remote = repo.getRemoteRepository(); final GraphQueryResult src = remote.getStatements(s, p, o, includeInferred, c); try { handler.startRDF(); while (src.hasNext()) { handler.handleStatement(src.next()); } handler.endRDF(); } finally { src.close(); } } catch (Exception ex) { throw new RepositoryException(ex); } }
Example #8
Source File: BigdataRemoteGraphQuery.java From database with GNU General Public License v2.0 | 5 votes |
@Override public void evaluate(RDFHandler handler) throws QueryEvaluationException, RDFHandlerException { GraphQueryResult gqr = evaluate(); try { handler.startRDF(); while (gqr.hasNext()) { handler.handleStatement(gqr.next()); } handler.endRDF();; } finally { gqr.close(); } }
Example #9
Source File: BigdataRemoteGraphQuery.java From database with GNU General Public License v2.0 | 5 votes |
@Override public GraphQueryResult evaluate() throws QueryEvaluationException { try { configureConnectOptions(q); return q.evaluate(); } catch (Exception ex) { throw new QueryEvaluationException(ex); } }
Example #10
Source File: BigdataGraph.java From database with GNU General Public License v2.0 | 5 votes |
/** * Translates the request to a high-performance SPARQL query: * * construct { * ?from ?edge ?to . * } where { * ?edge rdf:type <Edge> . * * ?from ?edge ?to . * * # filter by edge label * ?edge rdfs:label ?label . * filter(?label in ("label1", "label2", ...)) . * } */ protected GraphQueryResult getElements(final URI from, final URI to, final String... labels) throws Exception { final StringBuilder sb = new StringBuilder(); sb.append("construct { ?from ?edge ?to . } where {\n"); sb.append(" ?edge <"+TYPE+"> <"+EDGE+"> .\n"); sb.append(" ?from ?edge ?to .\n"); if (labels != null && labels.length > 0) { if (labels.length == 1) { sb.append(" ?edge <"+LABEL+"> \"").append(labels[0]).append("\" .\n"); } else { sb.append(" ?edge <"+LABEL+"> ?label .\n"); sb.append(" filter(?label in ("); for (String label : labels) { sb.append("\""+label+"\", "); } sb.setLength(sb.length()-2); sb.append(")) .\n"); } } sb.append("}"); // bind the from and/or to final String queryStr = sb.toString() .replace("?from", from != null ? "<"+from+">" : "?from") .replace("?to", to != null ? "<"+to+">" : "?to"); final org.openrdf.query.GraphQuery query = cxn().prepareGraphQuery(QueryLanguage.SPARQL, queryStr); final GraphQueryResult stmts = query.evaluate(); return stmts; }
Example #11
Source File: BigdataGraph.java From database with GNU General Public License v2.0 | 5 votes |
/** * Find edges based on a SPARQL construct query. The query MUST construct * edge statements: * <p> * construct { ?from ?edge ?to } where { ... } * * @see {@link BigdataGraphQuery} */ Iterable<Edge> getEdges(final String queryStr) throws Exception { final org.openrdf.query.GraphQuery query = cxn().prepareGraphQuery(QueryLanguage.SPARQL, queryStr); final GraphQueryResult stmts = query.evaluate(); /* * EdgeIterable will close the connection if necessary. */ return new EdgeIterable(stmts); }
Example #12
Source File: BigdataGraph.java From database with GNU General Public License v2.0 | 5 votes |
/** * Find vertices based on a SPARQL construct query. If the subject parameter * is true, the vertices will be taken from the subject position of the * constructed statements, otherwise they will be taken from the object * position. * * @see {@link BigdataGraphQuery} */ Iterable<Vertex> getVertices(final String queryStr, final boolean subject) throws Exception { final org.openrdf.query.GraphQuery query = cxn().prepareGraphQuery(QueryLanguage.SPARQL, queryStr); final GraphQueryResult stmts = query.evaluate(); /* * VertexIterable will close the connection if necessary. */ return new VertexIterable(stmts, subject); }
Example #13
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testSimpleGraphQuery() throws Exception { testCon.add(alice, name, nameAlice, context2); testCon.add(alice, mbox, mboxAlice, context2); testCon.add(context2, publisher, nameAlice); testCon.add(bob, name, nameBob, context1); testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">"); queryBuilder.append(" construct "); queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }"); GraphQueryResult result = testCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()).evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); if (name.equals(st.getPredicate())) { assertThat(st.getObject(), anyOf(is(equalTo((Value)nameAlice)), is(equalTo((Value)nameBob)))); } else { assertThat(st.getPredicate(), is(equalTo(mbox))); assertThat(st.getObject(), anyOf(is(equalTo((Value)mboxAlice)), is(equalTo((Value)mboxBob)))); } } } finally { result.close(); } }
Example #14
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPreparedGraphQuery() throws Exception { testCon.add(alice, name, nameAlice, context2); testCon.add(alice, mbox, mboxAlice, context2); testCon.add(context2, publisher, nameAlice); testCon.add(bob, name, nameBob, context1); testCon.add(bob, mbox, mboxBob, context1); testCon.add(context1, publisher, nameBob); StringBuilder queryBuilder = new StringBuilder(128); queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">"); queryBuilder.append(" construct "); queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }"); GraphQuery query = testCon.prepareGraphQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding(NAME, nameBob); GraphQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { Statement st = result.next(); URI predicate = st.getPredicate(); assertThat(predicate, anyOf(is(equalTo(name)), is(equalTo(mbox)))); Value object = st.getObject(); if (name.equals(predicate)) { assertEquals("unexpected value for name: " + object, nameBob, object); } else { assertThat(predicate, is(equalTo(mbox))); assertEquals("unexpected value for mbox: " + object, mboxBob, object); } } } finally { result.close(); } }
Example #15
Source File: LearningSparql_UPDATE_ITCase.java From cumulusrdf with Apache License 2.0 | 5 votes |
/** * Executes a given update command both on remote and local model. * * @param data the object holding test data (i.e. commands, queries, datafiles). * @throws Exception hopefully never otherwise the corresponding test fails. */ @SuppressWarnings("deprecation") void executeUpdate(final MisteryGuest data) throws Exception { load(data); final String updateCommand = readFile(data.query); final Update localUpdate = localConnection.prepareUpdate(QueryLanguage.SPARQL, updateCommand); final Update cumulusUpdate = cumulusConnection.prepareUpdate(QueryLanguage.SPARQL, updateCommand); localUpdate.execute(); cumulusUpdate.execute(); try { assertTrue(ModelUtil.equals( statements(localConnection.getStatements(null, null, null, false).asList()), statements(cumulusConnection.getStatements(null, null, null, false).asList()))); } catch (final AssertionError exception) { final String queryString = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}"; final GraphQuery localQuery = localConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); final GraphQuery cumulusQuery = cumulusConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); final GraphQueryResult debugLocalResult = localQuery.evaluate(); final GraphQueryResult debugCumulusResult = cumulusQuery.evaluate(); System.err.println("***** LOCAL ******"); QueryResultIO.write(debugLocalResult, RDFFormat.NTRIPLES, System.err); System.err.println("***** CRDF ******"); QueryResultIO.write(debugCumulusResult, RDFFormat.NTRIPLES, System.err); debugCumulusResult.close(); debugLocalResult.close(); throw exception; } }
Example #16
Source File: IntegrationTestSupertypeLayer.java From cumulusrdf with Apache License 2.0 | 5 votes |
/** * Executes a given CONSTRUCT query against a given dataset. * * @param data the mistery guest containing test data (query and dataset) * @throws Exception never, otherwise the test fails. */ protected void constructTest(final MisteryGuest data) throws Exception { load(data); final String queryString = queryString(data.query); final GraphQuery localQuery = localConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); final GraphQuery cumulusQuery = cumulusConnection.prepareGraphQuery(QueryLanguage.SPARQL, queryString); GraphQueryResult localResult = localQuery.evaluate(); GraphQueryResult cumulusResult = cumulusQuery.evaluate(); try { assertTrue( ModelUtil.equals( statements(Iterations.asSet(localResult)), statements(Iterations.asSet(cumulusResult)))); } catch (final AssertionError exception) { final GraphQueryResult debugLocalResult = localQuery.evaluate(); final GraphQueryResult debugCumulusResult = cumulusQuery.evaluate(); System.err.println("***** LOCAL ******"); QueryResultIO.write(debugLocalResult, RDFFormat.NTRIPLES, System.err); System.err.println("***** CRDF ******"); QueryResultIO.write(debugCumulusResult, RDFFormat.NTRIPLES, System.err); debugCumulusResult.close(); debugLocalResult.close(); throw exception; } cumulusResult.close(); localResult.close(); }
Example #17
Source File: RepositoryModelSet.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@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(OpenRDFException e) { throw new ModelRuntimeException(e); } }
Example #18
Source File: RepositoryModelSet.java From semweb4j with BSD 2-Clause "Simplified" License | 5 votes |
@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(OpenRDFException e) { throw new ModelRuntimeException(e); } }
Example #19
Source File: SparqlEvaluator.java From anno4j with Apache License 2.0 | 5 votes |
public Statement asStatement() throws OpenRDFException { GraphQueryResult result = asGraphQueryResult(); try { if (result.hasNext()) { Statement stmt = result.next(); if (result.hasNext()) throw new MultipleResultException(); return stmt; } return null; } finally { result.close(); } }
Example #20
Source File: AbstractTestNanoSparqlClient.java From database with GNU General Public License v2.0 | 4 votes |
/** * Preferred version executes the {@link IPreparedGraphQuery} and ensures * that the {@link GraphQueryResult} is closed. * * @param preparedQuery * The prepared query. * * @return The resulting graph. * * @throws Exception */ static protected Graph asGraph(final IPreparedGraphQuery preparedQuery) throws Exception { final GraphQueryResult result = preparedQuery.evaluate(); try { final Graph g = new LinkedHashModel(); while (result.hasNext()) { g.add(result.next()); } return g; } finally { result.close(); } }
Example #21
Source File: AbstractTestNanoSparqlClient.java From database with GNU General Public License v2.0 | 4 votes |
/** * Counts the #of results in a SPARQL result set. * * @param result * The connection from which to read the results. * * @return The #of results. * * @throws Exception * If anything goes wrong. */ static protected long countResults(final GraphQueryResult result) throws Exception { try { long count = 0; while (result.hasNext()) { result.next(); count++; } return count; } finally { result.close(); } }
Example #22
Source File: AbstractTestNanoSparqlClient.java From database with GNU General Public License v2.0 | 4 votes |
/** * @deprecated by {@link #asGraph(IPreparedGraphQuery)} which can ensure that * the {@link GraphQueryResult} is closed. */ static protected Graph asGraph(final GraphQueryResult result) throws Exception { try { final Graph g = new LinkedHashModel(); while (result.hasNext()) { g.add(result.next()); } return g; } finally { result.close(); } }
Example #23
Source File: BigdataSailGraphQuery.java From database with GNU General Public License v2.0 | 4 votes |
public GraphQueryResult evaluate(final BindingsClause bc) throws QueryEvaluationException { final QueryRoot originalQuery = astContainer.getOriginalAST(); if (bc != null) originalQuery.setBindingsClause(bc); if (getMaxQueryTime() > 0) originalQuery.setTimeout(TimeUnit.SECONDS .toMillis(getMaxQueryTime())); originalQuery.setIncludeInferred(getIncludeInferred()); final GraphQueryResult queryResult = ASTEvalHelper.evaluateGraphQuery( getTripleStore(), astContainer, new QueryBindingSet( getBindings()), getDataset()); return queryResult; }
Example #24
Source File: NanoSparqlObjectManager.java From database with GNU General Public License v2.0 | 4 votes |
@Override public ICloseableIterator<Statement> evaluateGraph(final String query) { try { // Setup the query. final IPreparedGraphQuery q = m_repo.prepareGraphQuery(query); // Note: evaluate() runs asynchronously and must be closed(). final GraphQueryResult res = q.evaluate(); // Will close the GraphQueryResult. return new Sesame2BigdataIterator<Statement, QueryEvaluationException>( res); } catch (Exception ex) { throw new RuntimeException("query=" + query, ex); } }
Example #25
Source File: GraphIterable.java From semweb4j with BSD 2-Clause "Simplified" License | 4 votes |
public GraphIterable(GraphQueryResult graphQueryResult, RepositoryModel model) { this.queryResult = graphQueryResult; this.model = model; }
Example #26
Source File: SparqlEvaluator.java From anno4j with Apache License 2.0 | 4 votes |
public GraphQueryResult asGraphQueryResult() throws OpenRDFException { return prepareGraphQuery().evaluate(); }
Example #27
Source File: SparqlAdvice.java From anno4j with Apache License 2.0 | 4 votes |
private Object cast(SparqlBuilder result, Class<?> rclass, Class<?> componentClass) throws OpenRDFException, TransformerException, IOException, ParserConfigurationException, SAXException, XMLStreamException { if (TupleQueryResult.class.equals(rclass)) { return result.asTupleQueryResult(); } else if (GraphQueryResult.class.equals(rclass)) { return result.asGraphQueryResult(); } else if (Result.class.equals(rclass)) { return result.asResult(componentClass); } else if (Set.class.equals(rclass)) { return result.asSet(componentClass); } else if (List.class.equals(rclass)) { return result.asList(componentClass); } else if (byte[].class.equals(rclass)) { return result.asByteArray(); } else if (CharSequence.class.equals(rclass)) { return result.asCharSequence(); } else if (Readable.class.equals(rclass)) { return result.asReadable(); } else if (String.class.equals(rclass)) { return result.asString(); } else if (Void.class.equals(rclass) || Void.TYPE.equals(rclass)) { result.asUpdate(); return null; } else if (Boolean.class.equals(rclass) || Boolean.TYPE.equals(rclass)) { return result.asBoolean(); } else if (Byte.class.equals(rclass) || Byte.TYPE.equals(rclass)) { return result.asByte(); } else if (Character.class.equals(rclass) || Character.TYPE.equals(rclass)) { return result.asChar(); } else if (Double.class.equals(rclass) || Double.TYPE.equals(rclass)) { return result.asDouble(); } else if (Float.class.equals(rclass) || Float.TYPE.equals(rclass)) { return result.asFloat(); } else if (Integer.class.equals(rclass) || Integer.TYPE.equals(rclass)) { return result.asInt(); } else if (Long.class.equals(rclass) || Long.TYPE.equals(rclass)) { return result.asLong(); } else if (Short.class.equals(rclass) || Short.TYPE.equals(rclass)) { return result.asShort(); } else if (Model.class.equals(rclass)) { return result.asModel(); } else if (Statement.class.equals(rclass)) { return result.asStatement(); } else if (BindingSet.class.equals(rclass)) { return result.asBindingSet(); } else if (URI.class.equals(rclass)) { return result.asURI(); } else if (BNode.class.equals(rclass)) { return result.asBNode(); } else if (Literal.class.equals(rclass)) { return result.asLiteral(); } else if (Resource.class.equals(rclass)) { return result.asResource(); } else if (Value.class.equals(rclass)) { return result.asValue(); } else if (Document.class.equals(rclass)) { return result.asDocument(); } else if (DocumentFragment.class.equals(rclass)) { return result.asDocumentFragment(); } else if (Element.class.equals(rclass)) { return result.asElement(); } else if (Node.class.equals(rclass)) { return result.asNode(); } else if (Reader.class.equals(rclass)) { return result.asReader(); } else if (CharArrayWriter.class.equals(rclass)) { return result.asCharArrayWriter(); } else if (ByteArrayOutputStream.class.equals(rclass)) { return result.asByteArrayOutputStream(); } else if (ReadableByteChannel.class.equals(rclass)) { return result.asReadableByteChannel(); } else if (InputStream.class.equals(rclass)) { return result.asInputStream(); } else if (XMLEventReader.class.equals(rclass)) { return result.asXMLEventReader(); } else { return result.as(rclass); } }
Example #28
Source File: NamedQueryTest.java From anno4j with Apache License 2.0 | 4 votes |
@Sparql(PREFIX + "CONSTRUCT { ?person a :Person; :name ?name } " + "WHERE { ?person :name ?name } ORDER BY ?name") GraphQueryResult loadAllPeople();
Example #29
Source File: NamedQueryTest.java From anno4j with Apache License 2.0 | 4 votes |
public void testConstruct() throws Exception { GraphQueryResult result = me.loadAllPeople(); assertTrue(result.hasNext()); result.close(); }
Example #30
Source File: DemoSesameServer.java From database with GNU General Public License v2.0 | 4 votes |
public static void _main(String[] args) throws Exception { String sesameURL, repoID; if (args != null && args.length == 2) { sesameURL = args[0]; repoID = args[1]; } else { sesameURL = DemoSesameServer.sesameURL; repoID = DemoSesameServer.repoID; } Repository repo = new HTTPRepository(sesameURL, repoID); repo.initialize(); RepositoryConnection cxn = repo.getConnection(); cxn.setAutoCommit(false); try { // load some statements built up programmatically URI mike = new URIImpl(BD.NAMESPACE + "Mike"); URI bryan = new URIImpl(BD.NAMESPACE + "Bryan"); URI loves = new URIImpl(BD.NAMESPACE + "loves"); URI rdf = new URIImpl(BD.NAMESPACE + "RDF"); Graph graph = new GraphImpl(); graph.add(mike, loves, rdf); graph.add(bryan, loves, rdf); cxn.add(graph); cxn.commit(); } finally { cxn.close(); } { // show the entire contents of the repository SparqlBuilder sparql = new SparqlBuilder(); sparql.addTriplePattern("?s", "?p", "?o"); GraphQuery query = cxn.prepareGraphQuery( QueryLanguage.SPARQL, sparql.toString()); GraphQueryResult result = query.evaluate(); while (result.hasNext()) { Statement stmt = result.next(); System.err.println(stmt); } } }