Java Code Examples for org.openrdf.query.GraphQueryResult#next()

The following examples show how to use org.openrdf.query.GraphQueryResult#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: SampleBlazegraphRDR.java    From blazegraph-samples with GNU General Public License v2.0 6 votes vote down vote up
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 2
Source File: SampleBlazegraphSesameRemote.java    From blazegraph-samples with GNU General Public License v2.0 6 votes vote down vote up
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 3
Source File: Test_Ticket_789.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 4
Source File: SparqlEvaluator.java    From anno4j with Apache License 2.0 5 votes vote down vote up
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 5
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 6
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 7
Source File: DemoSesameServer.java    From database with GNU General Public License v2.0 4 votes vote down vote up
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);
            }
            
        }
        
        
    }
 
Example 8
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
   * 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 9
Source File: GlobalSecurityValidator.java    From blazegraph-samples with GNU General Public License v2.0 2 votes vote down vote up
public GlobalSecurityValidator(final RemoteRepositoryManager m_repo) throws Exception {
	
		GraphQueryResult repoDescription = m_repo.getRepositoryDescriptions();
		Set<String> namespaces = new HashSet<String>();
		while (repoDescription.hasNext()) {
			Statement stmt = repoDescription.next();
			if (stmt.getPredicate()
					.toString()
					.equals(SD.KB_NAMESPACE.stringValue())) {
				
				namespaces.add(stmt.getObject().stringValue());
			}
	
		}

		TupleQueryResult result;
		
		for (String namespace : namespaces) {
			
			try {
				RemoteRepository repo = m_repo.getRepositoryForNamespace(namespace);
				
				result = repo.prepareTupleQuery(GRANTED_DOCUMENTS).evaluate();
				
				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 (Exception e) {
				log.error("Security info was not collected", e);
			}
			
		}
		
}
 
Example 10
Source File: TestQuery.java    From database with GNU General Public License v2.0 2 votes vote down vote up
/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		
        final String serviceURL = "http://localhost:" + Config.BLAZEGRAPH_HTTP_PORT
                + BigdataStatics.getContextPath() + "/sparql";

		final HttpClient httpClient = 
			new DefaultHttpClient(DefaultClientConnectionManagerFactory.getInstance().newInstance());
		
		final Executor executor = Executors.newCachedThreadPool();
		
		final RemoteRepository repo = new RemoteRepository(serviceURL, httpClient, executor);

		long total = 0;
		
		for (int i = 0; i < 10; i++) {

			final long start = System.currentTimeMillis();
			
//			final IPreparedTupleQuery tq = repo.prepareTupleQuery(query2);
//			
//			final TupleQueryResult result = tq.evaluate();
			
			final IPreparedGraphQuery gq = repo.prepareGraphQuery(query2);
			
			final GraphQueryResult result = gq.evaluate();
			
			int j = 0;
			while (result.hasNext()) {
				j++;
				result.next();
			}
			
			result.close();
			
			final long duration = System.currentTimeMillis() - start;
			
			total += duration;
			
			System.err.println("run " + i + ", " + duration + " millis, " + j + " results");
			
		}
		
		final long average = total / 10;
		
		System.err.println("average time: " + average + " millis");
			
		httpClient.getConnectionManager().shutdown();

		System.exit(0);
			
	}