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

The following examples show how to use org.openrdf.query.GraphQueryResult#close() . 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: BigdataRemoteGraphQuery.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 6
Source File: BigdataSailRemoteRepositoryConnection.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 7
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 8
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 9
Source File: LearningSparql_UPDATE_ITCase.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * 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 10
Source File: IntegrationTestSupertypeLayer.java    From cumulusrdf with Apache License 2.0 5 votes vote down vote up
/**
 * 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 11
Source File: NamedQueryTest.java    From anno4j with Apache License 2.0 4 votes vote down vote up
public void testConstruct() throws Exception {
	GraphQueryResult result = me.loadAllPeople();
	assertTrue(result.hasNext());
	result.close();
}
 
Example 12
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 13
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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 14
Source File: AbstractTestNanoSparqlClient.java    From database with GNU General Public License v2.0 4 votes vote down vote up
/**
 * @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 15
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);
			
	}