Java Code Examples for org.openrdf.query.TupleQueryResult#hasNext()
The following examples show how to use
org.openrdf.query.TupleQueryResult#hasNext() .
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: Test_Ticket_2091.java From database with GNU General Public License v2.0 | 6 votes |
/** * Execute a query including constants in projection expression. * The test succeeeds if the query successfully evaluates with * QUERY_ENGINE_CHUNK_HANDLER set to NativeHeapStandloneChunkHandler, * as it requires results to be encoded in respect to namespace of value factory, * which fails if constant has not been resolved against target DB value factory. * @throws Exception */ public void test_simple() throws Exception { setMethodisPostUrlEncodedData(); BigdataSailRemoteRepositoryConnection conn = m_repo.getBigdataSailRemoteRepository().getConnection(); conn.prepareUpdate(QueryLanguage.SPARQL, "prefix wd: <http://wd/> \n" + "prefix wdt: <http://wdt/> " + "INSERT DATA { wd:Q2 wdt:P31 wd:Q3917681 } ").execute(); final TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, QUERY).evaluate(); Collection<Value> subjects = new ArrayList<>(); try { while(result.hasNext()) { BindingSet bs = result.next(); subjects.add(bs.getBinding("s").getValue()); } } finally { result.close(); } if(log.isInfoEnabled()) log.info(subjects); assertEquals(1, subjects.size()); }
Example 2
Source File: Test_Ticket_789.java From database with GNU General Public License v2.0 | 6 votes |
public void test_ticket_1326_dataset() throws Exception { populate(); BigdataSailRemoteRepository sailRepo = m_repo.getBigdataSailRemoteRepository(); BigdataSailRemoteRepositoryConnection con = sailRepo.getConnection(); final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}"); final DatasetImpl dataset = new DatasetImpl(); dataset.addDefaultGraph(defaultGraph1); tq.setDataset(dataset); { TupleQueryResult tqr = tq.evaluate(); try { int count = 0; while (tqr.hasNext()) { tqr.next(); count++; } // there is only 1 statement in defaultGraph1 assertEquals(1, count); } finally { tqr.close(); } } }
Example 3
Source File: Concurrency.java From database with GNU General Public License v2.0 | 6 votes |
/** * Issue the query. * * @throws Exception */ private void doQuery() throws Exception { RepositoryConnection cxn = repo.getReadOnlyConnection(); try { final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); tupleQuery.setIncludeInferred(true /* includeInferred */); TupleQueryResult result = tupleQuery.evaluate(); // do something with the results int resultCount = 0; while (result.hasNext()) { BindingSet bindingSet = result.next(); // log.info(bindingSet); resultCount++; } log.info(resultCount + " results"); } finally { // close the repository connection cxn.close(); } }
Example 4
Source File: SPARQLQueryTest.java From database with GNU General Public License v2.0 | 6 votes |
protected static String getManifestName(Repository manifestRep, RepositoryConnection con, String manifestFileURL) throws QueryEvaluationException, RepositoryException, MalformedQueryException { // Try to extract suite name from manifest file TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL, "SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}"); manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL)); TupleQueryResult manifestNames = manifestNameQuery.evaluate(); try { if (manifestNames.hasNext()) { return manifestNames.next().getValue("ManifestName").stringValue(); } } finally { manifestNames.close(); } // Derive name from manifest URL int lastSlashIdx = manifestFileURL.lastIndexOf('/'); int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1); return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx); }
Example 5
Source File: SPARQLUpdateTestv2.java From database with GNU General Public License v2.0 | 6 votes |
protected long countSolutions(final String query) throws QueryEvaluationException, RepositoryException, MalformedQueryException { TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); try { long n = 0; while (result.hasNext()) { final BindingSet bset = result.next(); n++; if (logger.isInfoEnabled()) logger.info(bset.toString()); } return n; } finally { result.close(); } }
Example 6
Source File: TestTicket967.java From database with GNU General Public License v2.0 | 6 votes |
private void addDuringQueryExec(final RepositoryConnection conn, final Resource subj, final URI pred, final Value obj, final Resource... ctx) throws RepositoryException, MalformedQueryException, QueryEvaluationException { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }" ); tq.setBinding("s", subj); tq.setBinding("p", pred); tq.setBinding("o", obj); final TupleQueryResult tqr = tq.evaluate(); try { if (!tqr.hasNext()) { conn.add(subj, pred, obj, ctx); } } finally { tqr.close(); } }
Example 7
Source File: BigdataSPARQLUpdateTest.java From database with GNU General Public License v2.0 | 6 votes |
/** * Count solutions for a TupleQuery. * * @param query * The SPARQL query. * @return The #of solutions. * @throws QueryEvaluationException * @throws RepositoryException * @throws MalformedQueryException */ protected long countSolutions(final String query) throws QueryEvaluationException, RepositoryException, MalformedQueryException { TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); try { long n = 0; while (result.hasNext()) { final BindingSet bset = result.next(); n++; if (logger.isInfoEnabled()) logger.info(bset.toString()); } return n; } finally { result.close(); } }
Example 8
Source File: CustomSesameDataset.java From GeoTriples with Apache License 2.0 | 5 votes |
/** * Execute a SELECT SPARQL query against the graphs * * @param qs * SELECT SPARQL query * @return list of solutions, each containing a hashmap of bindings */ public List<HashMap<String, Value>> runSPARQL(String qs) { try { RepositoryConnection con = currentRepository.getConnection(); try { TupleQuery query = con.prepareTupleQuery( org.openrdf.query.QueryLanguage.SPARQL, qs); //System.exit(0); TupleQueryResult qres = query.evaluate(); ArrayList<HashMap<String, Value>> reslist = new ArrayList<HashMap<String, Value>>(); while (qres.hasNext()) { BindingSet b = qres.next(); Set<String> names = b.getBindingNames(); HashMap<String, Value> hm = new HashMap<String, Value>(); for (String n : names) { hm.put(n, b.getValue(n)); } reslist.add(hm); } return reslist; } finally { con.close(); } } catch (Exception e) { e.printStackTrace(); } return null; }
Example 9
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test /** * @see http://www.openrdf.org/issues/browse/SES-1091 * @throws Exception */ public void testArbitraryLengthPathWithFilter3() throws Exception { loadTestData("/testdata-query/alp-testdata.ttl"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("SELECT ?parent ?child "); query.append("WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?child = <http://example.org/C>) }"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); int count = 0; while (result.hasNext()) { count++; BindingSet bs = result.next(); assertTrue(bs.hasBinding("child")); assertTrue(bs.hasBinding("parent")); } assertEquals(2, count); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 10
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testOrderByQueriesAreInterruptable() throws Exception { testCon.begin(); for (int index = 0; index < 512; index++) { testCon.add(RDFS.CLASS, RDFS.COMMENT, testCon.getValueFactory().createBNode()); } testCon.commit(); final TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * WHERE { ?s ?p ?o . ?s1 ?p1 ?o1 . ?s2 ?p2 ?o2 . ?s3 ?p3 ?o3 } ORDER BY ?s1 ?p1 ?o1 LIMIT 1000"); query.setMaxQueryTime(2); final TupleQueryResult result = query.evaluate(); final long startTime = System.currentTimeMillis(); try { result.hasNext(); fail("Query should have been interrupted"); } catch (QueryInterruptedException e) { // Expected final long duration = System.currentTimeMillis() - startTime; assertTrue("Query not interrupted quickly enough, should have been ~2s, but was " + (duration / 1000) + "s", duration < 5000); } }
Example 11
Source File: SparqlServiceIntegrationTest.java From sparql-playground with GNU General Public License v2.0 | 5 votes |
private long countResults(TupleQueryResult results) { try { long counter = 0; while (results.hasNext()) { results.next(); counter++; } return counter; } catch (QueryEvaluationException e) { e.printStackTrace(); return 0; } }
Example 12
Source File: TestTicket1788.java From database with GNU General Public License v2.0 | 5 votes |
private void executeQuery(final BigdataSailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException { try { repo.initialize(); final BigdataSailRepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { conn.add(getClass().getResourceAsStream("TestTicket1788.n3"), "", RDFFormat.TURTLE); conn.commit(); final String query = "SELECT * {\r\n" + " ?s <http://p> ?o .\r\n" + " values ?o { \"A\"^^xsd:string \"B\"^^xsd:string \"D\"^^xsd:string }\r\n" + "}"; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult tqr = q.evaluate(); int cnt = 0; while (tqr.hasNext()) { BindingSet bindings = tqr.next(); cnt++; if(log.isInfoEnabled()) log.info("bindings="+bindings); } tqr.close(); assertEquals(2, cnt); } finally { conn.close(); } } finally { repo.shutDown(); } }
Example 13
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPropertyPathInTree() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append(" SELECT ?node ?name "); query.append(" FROM ex:tree-graph "); query.append(" WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); while (result.hasNext()) { BindingSet bs = result.next(); assertNotNull(bs); System.out.println(bs); } result.close(); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 14
Source File: TestTicket2083.java From database with GNU General Public License v2.0 | 4 votes |
private void executeQuery(final BigdataSailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException { try { repo.initialize(); final BigdataSailRepositoryConnection conn = repo.getConnection(); conn.setAutoCommit(false); try { conn.add(getClass().getResourceAsStream("TestTicket2083.n3"), "", RDFFormat.TURTLE); conn.commit(); final String query = "PREFIX wd: <http://wd/>\n" + "PREFIX wdt: <http://wdt/>\n" + "SELECT ?id\r\n" + "(SAMPLE(?img) as ?pic)\r\n" + "(str(?pic) as ?description)\r\n" + "WHERE {\r\n" + " ?id wdt:P31 wd:Q35657 .\r\n" + " ?id wdt:P6 ?head .\r\n" + " OPTIONAL {\r\n" + " ?head wdt:P18 ?img\r\n" + " }\r\n" + "} GROUP BY ?id ?head ?description "; final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult tqr = q.evaluate(); int cnt = 0; while (tqr.hasNext()) { BindingSet bindings = tqr.next(); cnt++; // if(log.isInfoEnabled()) System.out.println("bindings="+bindings); } tqr.close(); assertEquals(1, cnt); } finally { conn.close(); } } finally { repo.shutDown(); } }
Example 15
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 4 votes |
@Test public void testGroupConcatDistinct() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append(getNamespaceDeclarations()); query.append("SELECT (GROUP_CONCAT(DISTINCT ?l) AS ?concat)"); query.append("WHERE { ex:groupconcat-test ?p ?l . }"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); while (result.hasNext()) { BindingSet bs = result.next(); assertNotNull(bs); Value concat = bs.getValue("concat"); assertTrue(concat instanceof Literal); String lexValue = ((Literal)concat).getLabel(); int occ = countCharOccurrences(lexValue, 'a'); assertEquals(1, occ); occ = countCharOccurrences(lexValue, 'b'); assertEquals(1, occ); occ = countCharOccurrences(lexValue, 'c'); assertEquals(1, occ); occ = countCharOccurrences(lexValue, 'd'); assertEquals(1, occ); } result.close(); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 16
Source File: SampleBlazegraphSesameRemote.java From blazegraph-samples with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { final RemoteRepositoryManager repo = new RemoteRepositoryManager( serviceURL, false /* useLBS */); try { JettyResponseListener response = getStatus(repo); log.info(response.getResponseBody()); // create a new namespace if not exists final String namespace = "newNamespace"; final Properties properties = new Properties(); properties.setProperty("com.bigdata.rdf.sail.namespace", namespace); if (!namespaceExists(repo, namespace)) { log.info(String.format("Create namespace %s...", namespace)); repo.createRepository(namespace, properties); log.info(String.format("Create namespace %s done", namespace)); } else { log.info(String.format("Namespace %s already exists", namespace)); } //get properties for namespace log.info(String.format("Property list for namespace %s", namespace)); response = getNamespaceProperties(repo, namespace); log.info(response.getResponseBody()); /* * Load data from file located in the resource folder * src/main/resources/data.n3 */ final String resource = "/data.n3"; loadDataFromResource(repo, namespace, resource); // execute query final TupleQueryResult result = repo.getRepositoryForNamespace(namespace) .prepareTupleQuery("SELECT * {?s ?p ?o} LIMIT 100") .evaluate(); //result processing try { while (result.hasNext()) { final BindingSet bs = result.next(); log.info(bs); } } finally { result.close(); } } finally { repo.close(); } }
Example 17
Source File: TestFederatedQuery.java From database with GNU General Public License v2.0 | 4 votes |
public void testSimpleServiceQuery() throws Exception { // test setup final String EX_NS = "http://example.org/"; final ValueFactory f = new ValueFactoryImpl(); final URI bob = f.createURI(EX_NS, "bob"); final URI alice = f.createURI(EX_NS, "alice"); final URI william = f.createURI(EX_NS, "william"); // clears the repository and adds new data prepareTest("simple-default-graph.ttl", Arrays.asList("simple.ttl")); final StringBuilder qb = new StringBuilder(); qb.append(" SELECT * \n"); qb.append(" WHERE { \n"); qb.append(" SERVICE <" + getRepositoryUrl(1) + "> { \n"); qb.append(" ?X <" + FOAF.NAME + "> ?Y \n "); qb.append(" } \n "); qb.append(" ?X a <" + FOAF.PERSON + "> . \n"); qb.append(" } \n"); final BigdataSailRemoteRepositoryConnection conn = m_repo.getBigdataSailRemoteRepository().getConnection(); try { final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb.toString()); final TupleQueryResult tqr = tq.evaluate(); assertNotNull(tqr); assertTrue("No solutions.", tqr.hasNext()); int count = 0; while (tqr.hasNext()) { final BindingSet bs = tqr.next(); count++; final Value x = bs.getValue("X"); final Value y = bs.getValue("Y"); assertFalse(william.equals(x)); assertTrue(bob.equals(x) || alice.equals(x)); if (bob.equals(x)) { f.createLiteral("Bob").equals(y); } else if (alice.equals(x)) { f.createLiteral("Alice").equals(y); } } assertEquals(2, count); } finally { conn.close(); } }
Example 18
Source File: TestBOpUtility.java From database with GNU General Public License v2.0 | 4 votes |
public void testOpenWorldEq() throws Exception { final Sail sail = new MemoryStore(); final Repository repo = new SailRepository(sail); repo.initialize(); final RepositoryConnection cxn = repo.getConnection(); try { final ValueFactory vf = sail.getValueFactory(); final URI mike = vf.createURI(BD.NAMESPACE + "mike"); final URI age = vf.createURI(BD.NAMESPACE + "age"); final Literal mikeAge = vf.createLiteral(34); cxn.add(vf.createStatement(mike, RDF.TYPE, RDFS.RESOURCE)); cxn.add(vf.createStatement(mike, age, mikeAge)); final String query = "select * " + "where { " + " ?s ?p ?o . " + " filter (?o < 40) " + "}"; final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query); final TupleQueryResult result = tupleQuery.evaluate(); while (result.hasNext()) { final BindingSet tmp = result.next(); if(log.isInfoEnabled()) log.info(tmp.toString()); } } finally { cxn.close(); repo.shutDown(); } }
Example 19
Source File: StressTestConcurrentRestApiRequests.java From database with GNU General Public License v2.0 | 4 votes |
@Override protected void doApplyToNamespace(final RemoteRepository repo, final UUID uuid) throws Exception { /* * Setup data to be deleted. * * Note: This uses SELECT rather than CONSTRUCT since we need to get * the graph as well when addressing a QUADS mode namespace. */ final ValueFactory vf = ValueFactoryImpl.getInstance(); final Collection<Statement> stmts = new ArrayList<>(batchSize); TupleQueryResult result = null; try { if (quads) { result = repo.prepareTupleQuery( "SELECT * WHERE {GRAPH ?g {?s ?p ?o} }") .evaluate(); } else { result = repo.prepareTupleQuery( "SELECT * WHERE {?s ?p ?o}").evaluate(); } while (result.hasNext() && stmts.size() < batchSize) { final BindingSet bset = result.next(); final Resource s = (Resource) bset.getBinding("s") .getValue(); final URI p = (URI) bset.getBinding("p").getValue(); final Value o = (Value) bset.getBinding("o").getValue(); final Resource g = (Resource) (quads ? bset.getBinding("g") .getValue() : null); final Statement stmt = quads ? vf.createStatement(s, p, o, g) : vf.createStatement(s, p, o); stmts.add(stmt); } } finally { if (result != null) result.close(); } // do mutation. repo.remove(new RemoteRepository.RemoveOp(stmts), uuid); }
Example 20
Source File: RepositoryListHandler.java From cumulusrdf with Apache License 2.0 | 4 votes |
@Override public ModelAndView serve(final Repository repository, final HttpServletRequest request, final HttpServletResponse response) throws Exception { Map<String, Object> model = new HashMap<String, Object>(); if (METHOD_GET.equals(request.getMethod())) { Repository systemRepository = _repositoryManager.getSystemRepository(); ValueFactory vf = systemRepository.getValueFactory(); try { RepositoryConnection con = systemRepository.getConnection(); try { // connection before returning. Would be much better to stream the query result directly to the client. List<String> bindingNames = new ArrayList<String>(); List<BindingSet> bindingSets = new ArrayList<BindingSet>(); TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SERQL, REPOSITORY_LIST_QUERY).evaluate(); try { // Determine the repository's URI StringBuffer requestURL = request.getRequestURL(); if (requestURL.charAt(requestURL.length() - 1) != '/') { requestURL.append('/'); } String namespace = requestURL.toString(); while (queryResult.hasNext()) { QueryBindingSet bindings = new QueryBindingSet(queryResult.next()); String id = bindings.getValue("id").stringValue(); bindings.addBinding("uri", vf.createURI(namespace, id)); bindingSets.add(bindings); } bindingNames.add("uri"); bindingNames.addAll(queryResult.getBindingNames()); } finally { queryResult.close(); } model.put(QueryResultView.QUERY_RESULT_KEY, new TupleQueryResultImpl(bindingNames, bindingSets)); } finally { con.close(); } } catch (RepositoryException e) { throw new ServerHTTPException(e.getMessage(), e); } } TupleQueryResultWriterFactory factory = ProtocolUtil.getAcceptableService(request, response, TupleQueryResultWriterRegistry.getInstance()); model.put(QueryResultView.FILENAME_HINT_KEY, "repositories"); model.put(QueryResultView.FACTORY_KEY, factory); model.put(QueryResultView.HEADERS_ONLY, METHOD_HEAD.equals(request.getMethod())); return new ModelAndView(TupleQueryResultView.getInstance(), model); }