Java Code Examples for org.openrdf.query.TupleQueryResult#next()
The following examples show how to use
org.openrdf.query.TupleQueryResult#next() .
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_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 2
Source File: TestNanoSparqlClient.java From database with GNU General Public License v2.0 | 6 votes |
public void testServiceNodeBindings() throws Exception { final BigdataSailRemoteRepository repo = m_repo.getBigdataSailRemoteRepository(); final BigdataSailRemoteRepositoryConnection cxn = (BigdataSailRemoteRepositoryConnection) repo.getConnection(); try { String queryStr = "select * where {SERVICE <http://DBpedia.org/sparql> { <http://dbpedia.org/resource/Tonga_(Nyasa)_language> rdfs:label ?langLabel. }}"; // String queryStr = "SELECT * WHERE { BIND (<http://dbpedia.org/resource/Tonga_(Nyasa)_language> AS ?ref) . SERVICE <http://DBpedia.org/sparql> { ?ref rdfs:label ?langLabel. } }"; final org.openrdf.query.TupleQuery tq = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr); final TupleQueryResult tqr = tq.evaluate(); try { int cnt = 0; while (tqr.hasNext()) { tqr.next(); cnt++; } assertEquals(cnt, 2); } finally { tqr.close(); } } finally { cxn.close(); } }
Example 3
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 6 votes |
private int size(URI defaultGraph) throws RepositoryException, MalformedQueryException, QueryEvaluationException { TupleQuery qry = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { ?s ?p ?o }"); DatasetImpl dataset = new DatasetImpl(); dataset.addDefaultGraph(defaultGraph); qry.setDataset(dataset); TupleQueryResult result = qry.evaluate(); try { int count = 0; while (result.hasNext()) { result.next(); count++; } return count; } finally { result.close(); } }
Example 4
Source File: SPARQLUpdateTestv2.java From database with GNU General Public License v2.0 | 6 votes |
protected long debugPrintSolutions(final String query) throws QueryEvaluationException, RepositoryException, MalformedQueryException { TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); try { long n = 0; while (result.hasNext()) { System.err.println("==> NEXT SOLUTION"); final BindingSet bset = result.next(); for (final String bindingName : bset.getBindingNames()) { final Binding b = bset.getBinding(bindingName); System.err.println(bindingName + " -> " + b); } n++; } return n; } finally { result.close(); } }
Example 5
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testSES1073InverseSymmetricPattern() throws Exception { URI a = f.createURI("http://example.org/a"); URI b1 = f.createURI("http://example.org/b1"); URI b2 = f.createURI("http://example.org/b2"); URI c1 = f.createURI("http://example.org/c1"); URI c2 = f.createURI("http://example.org/c2"); URI a2b = f.createURI("http://example.org/a2b"); URI b2c = f.createURI("http://example.org/b2c"); conn.add(a, a2b, b1); conn.add(a, a2b, b2); conn.add(b1, b2c, c1); conn.add(b2, b2c, c2); String query = "select * "; query += "where{ "; query += "?c1 ^<http://example.org/b2c>/^<http://example.org/a2b>/<http://example.org/a2b>/<http://example.org/b2c> ?c2 . "; query += " } "; TupleQueryResult qRes = conn.prepareTupleQuery(QueryLanguage.SPARQL, query).evaluate(); try { assertTrue(qRes.hasNext()); int count = 0; while (qRes.hasNext()) { BindingSet r = qRes.next(); System.out.println(r); count++; } assertEquals(4, count); } finally { qRes.close(); } }
Example 6
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPreparedTupleQuery() 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(); queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">"); queryBuilder.append(" select ?name ?mbox "); queryBuilder.append(" where { ?s foaf:name ?name . ?s foaf:mbox ?mbox . }"); TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding(NAME, nameBob); TupleQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding(NAME), is(equalTo(true))); assertThat(solution.hasBinding(MBOX), is(equalTo(true))); Value nameResult = solution.getValue(NAME); Value mboxResult = solution.getValue(MBOX); assertEquals("unexpected value for name: " + nameResult, nameBob, nameResult); assertEquals("unexpected value for mbox: " + mboxResult, mboxBob, mboxResult); } } finally { result.close(); } }
Example 7
Source File: TestServiceWhiteList.java From database with GNU General Public License v2.0 | 5 votes |
public void testServiceWhiteList() throws Exception { TupleQueryResult res = m_repo.getRepositoryForNamespace(namespace). // prepareTupleQuery("SELECT ?b { ?b <http://purl.org/dc/elements/1.1/title> ?title . " + "SERVICE <" + SOME_SERVICE_ENDPOINT + "> { } }").evaluate(); int resCount = 0;; while(res.hasNext()){ res.next(); resCount++; } assertEquals(0, resCount); boolean exceptionThrown = false; try { res = m_repo.getRepositoryForNamespace(namespace). // prepareTupleQuery("SELECT ?b { ?b <http://purl.org/dc/elements/1.1/title> ?title . " + "SERVICE <" + SOME_SERVICE_ENDPOINT + "1> { } }").evaluate(); } catch(Exception e) { exceptionThrown = e.toString().contains("Service URI http://someService.com/test1 is not allowed"); } assertTrue(exceptionThrown); }
Example 8
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 9
Source File: RDFSContainer.java From anno4j with Apache License 2.0 | 5 votes |
private Object[] loadBlock(int b) throws RepositoryException, QueryEvaluationException { TupleQuery query = createBlockQuery(b); TupleQueryResult result = query.evaluate(); BindingSet bindings = result.next(); ObjectConnection con = getObjectConnection(); Object[] list = new Object[BSIZE]; while (bindings != null) { URI pred = (URI) bindings.getValue("pred"); int idx = getIndex(pred); Value value = bindings.getValue("value"); Set<URI> types = new HashSet<URI>(4); do { Value c = bindings.getValue("value_class"); if (c instanceof URI) { types.add((URI) c); } bindings = result.hasNext() ? result.next() : null; } while (bindings != null && pred.equals(bindings.getValue("pred"))); int i = idx % BSIZE; if (value instanceof Literal) { list[i] = con.getObject((Literal) value); } else { list[i] = con.getObject(types, (Resource) value); } } return list; }
Example 10
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 11
Source File: SampleBlazegraphCustomFunctionEmbedded.java From blazegraph-samples with GNU General Public License v2.0 | 5 votes |
public static void main(String[] args) throws OpenRDFException, IOException { final Repository repo = createRepository(); registerCustomFunction(repo); try{ repo.initialize(); /* * Load data from resources * src/main/resources/data.n3 */ Utils.loadDataFromResources(repo, "data.n3", ""); final TupleQueryResult result = Utils.executeSelectQuery(repo, QUERY, QueryLanguage.SPARQL); try { while(result.hasNext()){ BindingSet bs = result.next(); log.info(bs); } } finally { result.close(); } } finally { repo.shutDown(); } }
Example 12
Source File: ComplexSPARQLQueryTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testSES1970CountDistinctWildcard() throws Exception { loadTestData("/testdata-query/dataset-ses1970.trig"); String query = "SELECT (COUNT(DISTINCT *) AS ?c) {?s ?p ?o }"; TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); try { TupleQueryResult result = tq.evaluate(); assertNotNull(result); assertTrue(result.hasNext()); BindingSet s = result.next(); Literal count = (Literal)s.getValue("c"); assertNotNull(count); assertEquals(3, count.intValue()); result.close(); } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 13
Source File: RepositoryConnectionTest.java From database with GNU General Public License v2.0 | 5 votes |
@Test public void testPreparedTupleQuery2() 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(); queryBuilder.append(" prefix foaf: <" + FOAF_NS + ">"); queryBuilder.append(" SELECT ?name ?mbox"); queryBuilder.append(" where { ?VAR foaf:name ?name . ?VAR foaf:mbox ?mbox . }"); TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()); query.setBinding("VAR", bob); TupleQueryResult result = query.evaluate(); try { assertThat(result, is(notNullValue())); assertThat(result.hasNext(), is(equalTo(true))); while (result.hasNext()) { BindingSet solution = result.next(); assertThat(solution.hasBinding(NAME), is(equalTo(true))); assertThat(solution.hasBinding(MBOX), is(equalTo(true))); Value nameResult = solution.getValue(NAME); Value mboxResult = solution.getValue(MBOX); assertEquals("unexpected value for name: " + nameResult, nameBob, nameResult); assertEquals("unexpected value for mbox: " + mboxResult, mboxBob, mboxResult); } } finally { result.close(); } }
Example 14
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 15
Source File: HelloBlazegraph.java From blazegraph-samples with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws OpenRDFException { final Properties props = new Properties(); /* * For more configuration parameters see * http://www.blazegraph.com/docs/api/index.html?com/bigdata/journal/BufferMode.html */ props.put(Options.BUFFER_MODE, BufferMode.DiskRW); // persistent file system located journal props.put(Options.FILE, "/tmp/blazegraph/test.jnl"); // journal file location final BigdataSail sail = new BigdataSail(props); // instantiate a sail final Repository repo = new BigdataSailRepository(sail); // create a Sesame repository repo.initialize(); try { // prepare a statement final URIImpl subject = new URIImpl("http://blazegraph.com/Blazegraph"); final URIImpl predicate = new URIImpl("http://blazegraph.com/says"); final Literal object = new LiteralImpl("hello"); final Statement stmt = new StatementImpl(subject, predicate, object); // open repository connection RepositoryConnection cxn = repo.getConnection(); // upload data to repository try { cxn.begin(); cxn.add(stmt); cxn.commit(); } catch (OpenRDFException ex) { cxn.rollback(); throw ex; } finally { // close the repository connection cxn.close(); } // open connection if (repo instanceof BigdataSailRepository) { cxn = ((BigdataSailRepository) repo).getReadOnlyConnection(); } else { cxn = repo.getConnection(); } // evaluate sparql query try { final TupleQuery tupleQuery = cxn .prepareTupleQuery(QueryLanguage.SPARQL, "select ?p ?o where { <http://blazegraph.com/Blazegraph> ?p ?o . }"); final TupleQueryResult result = tupleQuery.evaluate(); try { while (result.hasNext()) { final BindingSet bindingSet = result.next(); System.err.println(bindingSet); } } finally { result.close(); } } finally { // close the repository connection cxn.close(); } } finally { repo.shutDown(); } }
Example 16
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 17
Source File: StressTest_ClosedByInterrupt_RW.java From database with GNU General Public License v2.0 | 4 votes |
@Override public void run() { RepositoryConnection conn = null; TupleQueryResult result = null; int loop = 0; while (stopRequested == false) { try { System.out.println("[Read ] snooze"); snooze(MILLIS_BETWEEN_QUERY_BURSTS); System.out.println("[Read ] enter loop " + loop); for (int invocation = 0; invocation < NUM_SELECTS; ++invocation) { conn = repo.getReadOnlyConnection(); conn.setAutoCommit(false); final String sparql = "SELECT ?s WHERE { ?s ?p ?o } LIMIT " + NUM_STATEMENTS_PER_SELECT; final TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, sparql); result = query.evaluate(); final List<String> duds = new ArrayList<String>(); while (result.hasNext()) { final BindingSet bindingSet = result.next(); for (final Iterator<Binding> i = bindingSet.iterator(); i.hasNext();) { final Binding b = i.next(); if (b.getValue() != null) { duds.add(b.getValue().stringValue()); } } } result.close(); result = null; conn.close(); conn = null; } } catch (Throwable t) { printError("Read Only threw in loop " + loop, t); } finally { closeNoException(result); closeNoException(conn); } System.out.println("[Read ] leave loop " + loop); ++loop; } }
Example 18
Source File: TestDataLoaderServlet.java From database with GNU General Public License v2.0 | 4 votes |
public void test_load01() throws Exception { final String kbPropsURL = this.getClass() .getResource("dataloader.props").getFile(); final String dataURL = this.getClass().getResource("sample-data.ttl") .getFile(); final PropertiesFormat format = PropertiesFormat.XML; final PropertiesParserFactory parserFactory = PropertiesParserRegistry .getInstance().get(format); final Properties loaderProps = parserFactory.getParser().parse( this.getClass().getResourceAsStream("dataloader.xml")); final String randomNS = "kb" + UUID.randomUUID(); { // verify does not exist. try { m_mgr.getRepositoryProperties(randomNS); fail("Should not exist: " + randomNS); } catch (HttpException ex) { // Expected status code. assertEquals(404, ex.getStatusCode()); } } // Set the random namespace and the correct resource paths loaderProps.setProperty("namespace", randomNS); loaderProps.setProperty("quiet", "true"); loaderProps.setProperty("verbose", "0"); loaderProps.setProperty("propertyFile", kbPropsURL); loaderProps.setProperty("fileOrDirs", dataURL); m_mgr.doDataLoader(loaderProps); RemoteRepository repo = m_mgr.getRepositoryForNamespace(randomNS); { // verify it was created by the data loader. final Properties p = m_mgr.getRepositoryProperties(randomNS); assertNotNull(p); log.warn("Found properties for namespace " + randomNS); } final BigdataSailRemoteRepositoryConnection cxn = (BigdataSailRemoteRepositoryConnection) repo .getBigdataSailRemoteRepository().getConnection(); try { String queryStr = "select * where { ?s ?p ?o }"; final org.openrdf.query.TupleQuery tq = cxn.prepareTupleQuery( QueryLanguage.SPARQL, queryStr); final TupleQueryResult tqr = tq.evaluate(); try { int cnt = 0; while (tqr.hasNext()) { tqr.next(); cnt++; } if (cnt == 0) { fail("DataLoaderServlet did not add any statements."); } assertTrue(cnt > 0); } finally { tqr.close(); } } finally { cxn.close(); } }
Example 19
Source File: SampleBlazegraphCustomFunctionRemote.java From blazegraph-samples with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { final String namespace = "test"; final Properties journalProperties = new Properties(); { journalProperties.setProperty(Journal.Options.BUFFER_MODE, BufferMode.MemStore.name()); } final RemoteRepositoryManager repo = new RemoteRepositoryManager( serviceURL , false /* useLBS */); repo.createRepository(namespace, journalProperties); try { /* * 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(QUERY) .evaluate(); //result processing try { while (result.hasNext()) { final BindingSet bs = result.next(); log.info(bs); } } finally { result.close(); } } finally { repo.close(); } }
Example 20
Source File: GlobalSecurityValidator.java From blazegraph-samples with GNU General Public License v2.0 | 3 votes |
public GlobalSecurityValidator(final Repository repo) { final TupleQueryResult result; try { result = Utils.executeSelectQuery(repo, GRANTED_DOCUMENTS, QueryLanguage.SPARQL); while(result.hasNext()){ BindingSet bs = result.next(); Binding user = bs.getBinding("user"); Binding document = bs.getBinding("doc"); if(securityInfo.containsKey(user)){ securityInfo.get(user).add(document.getValue()); }else{ List<Value> docs = new LinkedList<Value>(); docs.add(document.getValue()); securityInfo.put(user.getValue(), docs); } } } catch (OpenRDFException e) { log.error("Security info was not collected", e); } }