Java Code Examples for org.openrdf.query.TupleQueryResult

The following examples show how to use org.openrdf.query.TupleQueryResult. These examples are extracted from open source projects. 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
/**
 * Get total number of distinct objects for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static long getDistinctObj(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objs) " + // 
			"WHERE " +
			"{" +
       		"?s <" + pred + "> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("objs").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 2
/**
 * Get total number of distinct objects for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static long getDistinctSbj(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?subjs) " + // 
			"WHERE " +
			"{" +
       		"?s <" + pred + "> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("subjs").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 3
/**
 * Get total number of distinct objects of a dataset
 * @return count
 */
public static long getObjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("objts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example 4
@Test
public void testInComparison3()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } ");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	BindingSet bs = result.next();
	Value y = bs.getValue("y");
	assertNotNull(y);
	assertTrue(y instanceof Literal);
	assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
}
 
Example 5
/**
 * {@inheritDoc}
 * 
 * Logs the query at INFO and logs the optimized AST at TRACE.
 */
@Override
protected Stream<BindingSet> _select( 
        final String queryStr, final String extQueryId) {

    logQuery(queryStr);
    return Code.wrapThrow(() -> {
        final BigdataSailTupleQuery query = (BigdataSailTupleQuery) 
                cxn().prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
        setMaxQueryTime(query);
        final UUID queryId = setupQuery(query.getASTContainer(), 
                                        QueryType.SELECT, extQueryId);
        
        sparqlLog.trace(() -> "optimized AST:\n"+query.optimize());
        
        /*
         * Result is closed automatically by GraphStreamer.
         */
        final TupleQueryResult result = query.evaluate();
        final Optional<Runnable> onClose = 
                Optional.of(() -> finalizeQuery(queryId));
        return new GraphStreamer<>(result, onClose).stream();
    });
    
}
 
Example 6
Source Project: database   Source File: Test_Ticket_2091.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 7
Source Project: database   Source File: TestTicket4249.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final String string, final double start, final double length, final String expected)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException, VisitorException {

	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start, ?length) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", vf.createLiteral(string));
	q.setBinding("start", vf.createLiteral(start));
	q.setBinding("length", vf.createLiteral(length));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue().stringValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example 8
Source Project: trainbenchmark   Source File: SesameDriver.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public Collection<? extends SesameMatch> runQuery(final RailwayQuery query, final String queryDefinition)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final Collection<SesameMatch> results = new ArrayList<>();

	final TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryDefinition);
	final TupleQueryResult queryResults = tupleQuery.evaluate();
	try {
		while (queryResults.hasNext()) {
			final BindingSet bs = queryResults.next();
			final SesameMatch match = SesameMatch.createMatch(query, bs);
			results.add(match);
		}
	} finally {
		queryResults.close();
	}

	return results;
}
 
Example 9
Source Project: database   Source File: Test_Ticket_1893.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void checkResults(final BigdataSailRemoteRepositoryConnection conn, final int count)
		throws QueryEvaluationException, RepositoryException,
		MalformedQueryException {
	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(count, subjects.size());
}
 
Example 10
Source Project: database   Source File: TestTicket967.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 11
Source Project: database   Source File: Test_Ticket_789.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 12
Source Project: database   Source File: SPARQLQueryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 13
@Test
public void testTupleQueryIncludeInferred() throws Exception {
	final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}");
	tq.setIncludeInferred(false);
	tq.evaluate();
	assertEquals("false", remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED));
	assertEquals("false", remote.data.request.getParams().get(RemoteRepositoryDecls.INCLUDE_INFERRED).getValue());
	
	tq.setIncludeInferred(true);
	final TupleQueryResult tqr = tq.evaluate();
	try {
		assertEquals("true", remote.data.opts.getRequestParam(RemoteRepositoryDecls.INCLUDE_INFERRED));
		assertEquals("true", remote.data.request.getParams().get(RemoteRepositoryDecls.INCLUDE_INFERRED).getValue());
	} finally {
		tqr.close();
	}
}
 
Example 14
@Test
public void testTupleQueryDataset() throws Exception {
	final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}");
	tq.setDataset(dataset);
	final TupleQueryResult tqr = tq.evaluate();
	try {
		assertEquals(defaultGraphs,tq.getDataset().getDefaultGraphs());
		assertEquals(namedGraphs,tq.getDataset().getNamedGraphs());
		Collection<String> optsDefaultGraphs = Arrays.asList(remote.data.opts.requestParams.get(RemoteRepositoryDecls.DEFAULT_GRAPH_URI));
		assertTrue(optsDefaultGraphs.contains(defaultGraph1.stringValue()));
		assertTrue(optsDefaultGraphs.contains(defaultGraph2.stringValue()));
		List<String> requestDefaultGraphs = remote.data.request.getParams().get(RemoteRepositoryDecls.DEFAULT_GRAPH_URI).getValues();
		assertTrue(requestDefaultGraphs.contains(defaultGraph1.stringValue()));
		assertTrue(requestDefaultGraphs.contains(defaultGraph2.stringValue()));
		Collection<String> optsNamedGraphs = Arrays.asList(remote.data.opts.requestParams.get(RemoteRepositoryDecls.NAMED_GRAPH_URI));
		assertTrue(optsNamedGraphs.contains(namedGraph1.stringValue()));
		assertTrue(optsNamedGraphs.contains(namedGraph2.stringValue()));
		List<String> requestNamedGraphs = remote.data.request.getParams().get(RemoteRepositoryDecls.NAMED_GRAPH_URI).getValues();
		assertTrue(requestNamedGraphs.contains(namedGraph1.stringValue()));
		assertTrue(requestNamedGraphs.contains(namedGraph2.stringValue()));
	} finally {
		tqr.close();
	}
}
 
Example 15
Source Project: database   Source File: SPARQLQueryTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
protected final TupleQueryResult readExpectedTupleQueryResult()
	throws Exception
{
	TupleQueryResultFormat tqrFormat = QueryResultIO.getParserFormatForFileName(resultFileURL);

	if (tqrFormat != null) {
		InputStream in = new URL(resultFileURL).openStream();
		try {
			TupleQueryResultParser parser = QueryResultIO.createParser(tqrFormat);
			parser.setValueFactory(dataRep.getValueFactory());

			TupleQueryResultBuilder qrBuilder = new TupleQueryResultBuilder();
			parser.setQueryResultHandler(qrBuilder);

			parser.parseQueryResult(in);
			return qrBuilder.getQueryResult();
		}
		finally {
			in.close();
		}
	}
	else {
		Set<Statement> resultGraph = readExpectedGraphQueryResult();
		return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph);
	}
}
 
Example 16
Source Project: database   Source File: SPARQLUpdateTestv2.java    License: GNU General Public License v2.0 6 votes vote down vote up
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 17
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 18
@Test
/**
 * @see http://www.openrdf.org/issues/browse/SES-1091
 * @throws Exception
 */
public void testArbitraryLengthPathWithFilter1()
	throws Exception
{
	loadTestData("/testdata-query/alp-testdata.ttl");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT ?parent ?child ");
	query.append("WHERE { ?child a owl:Class . ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }");

	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(4, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 19
public static void main(String[] args) throws Exception  {

	final RemoteRepositoryManager repositoryManager = new RemoteRepositoryManager(serviceURL, false /*useLBS*/);

	try{	
	
		final String namespace = "namespaceRDR";
		final Properties properties = new Properties();
		properties.setProperty(Options.NAMESPACE, namespace);
		properties.setProperty(Options.STATEMENT_IDENTIFIERS, "true");
		
		if(!namespaceExists(namespace, repositoryManager)){
			log.info(String.format("Create namespace %s...", namespace));
			repositoryManager.createRepository(namespace, properties);
			log.info(String.format("Create namespace %s done", namespace));
		}
		
		final InputStream is = SampleBlazegraphRDR.class.getResourceAsStream("/rdr_test.ttl");
		try{
			repositoryManager.getRepositoryForNamespace(namespace).add(new AddOp(is, RDFFormat.forMIMEType("application/x-turtle-RDR")));
		} finally {
			is.close();
		}
		
		//execute query
		final RemoteRepository r = repositoryManager.getRepositoryForNamespace(namespace);
		final IPreparedTupleQuery query = r.prepareTupleQuery("SELECT ?age ?src WHERE {?bob foaf:name \"Bob\" . <<?bob foaf:age ?age>> dc:source ?src .}");
		final TupleQueryResult result = query.evaluate();
		try {
			while (result.hasNext()) {
				final BindingSet bs = result.next();
				log.info(bs);
			}
		} finally {
			result.close();
		}
	} finally {
		repositoryManager.close();
	}
}
 
Example 20
public static void main(String[] args) throws IOException, OpenRDFException {

		// load journal properties from resources
		final Properties props = loadProperties("/blazegraph.properties");

		// instantiate a sail
		final BigdataSail sail = new BigdataSail(props);
		final Repository repo = new BigdataSailRepository(sail);

		try{
			repo.initialize();
			
			/*
			 * Load data from resources 
			 * src/main/resources/data.n3
			 */
	
			loadDataFromResources(repo, "/data.n3", "");
			
			final String query = "select * {<http://blazegraph.com/blazegraph> ?p ?o}";
			final TupleQueryResult result = executeSelectQuery(repo, query, QueryLanguage.SPARQL);
			
			try {
				while(result.hasNext()){
					
					final BindingSet bs = result.next();
					log.info(bs);
					
				}
			} finally {
				result.close();
			}
		} finally {
			repo.shutDown();
		}
	}
 
Example 21
Source Project: database   Source File: TestTicket1681.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			conn.add(getClass().getResourceAsStream("TestTicket1681.nt"), "",
					RDFFormat.TURTLE);
			conn.commit();

			final String query = "SELECT * WHERE { ?s <http://p>  ?o . FILTER (?o IN (<http://o2>, <http://o3>) ) }";
			final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					query);
			final TupleQueryResult tqr = q.evaluate();
			int cnt = 0;
			while (tqr.hasNext()) {
			    final Set<String> bindingNames = tqr.next().getBindingNames();
			    cnt++;
			    if(log.isInfoEnabled())
			        log.info("bindingNames="+bindingNames);
			}
			tqr.close();
			assertEquals(1, cnt);
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 22
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 23
@Test
public void testQueryWithURI() throws Exception {
	String query = "select ?x where { ?x rdf:type <http://example.org/tuto/ontology#Cat> . }";
	TupleQueryResult result = (TupleQueryResult) sparqlService.evaluateQuery(query);
	Assert.assertEquals(countResults(result), 2);

}
 
Example 24
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 25
Source Project: anno4j   Source File: ObjectQuery.java    License: Apache License 2.0 5 votes vote down vote up
private CloseableIteration<?, QueryEvaluationException> createCursor(
		TupleQueryResult result, List<String> bindings)
		throws QueryEvaluationException {
	if (bindings.size() > 1)
		return new ObjectArrayCursor(manager, result, bindings);
	return new ObjectCursor(manager, result, bindings.get(0));
}
 
Example 26
Source Project: anno4j   Source File: RDFSContainer.java    License: Apache License 2.0 5 votes vote down vote up
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 27
Source Project: anno4j   Source File: SparqlEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
public BindingSet asBindingSet() throws OpenRDFException {
	TupleQueryResult result = asTupleQueryResult();
	try {
		if (result.hasNext()) {
			BindingSet bindings = result.next();
			if (result.hasNext())
				throw new MultipleResultException();
			return bindings;
		}
		return null;
	} finally {
		result.close();
	}
}
 
Example 28
Source Project: anno4j   Source File: SparqlEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
public Set<? extends Value> asSetOfValues() throws OpenRDFException {
	Set<Value> set = new LinkedHashSet<Value>();
	TupleQueryResult result = asTupleQueryResult();
	try {
		if (result.getBindingNames().isEmpty())
			return null;
		String name = result.getBindingNames().iterator().next();
		while (result.hasNext()) {
			set.add(result.next().getValue(name));
		}
		return set;
	} finally {
		result.close();
	}
}
 
Example 29
Source Project: database   Source File: TestTicket275.java    License: GNU General Public License v2.0 5 votes vote down vote up
private void executeQuery(final SailRepository repo)
		throws RepositoryException, MalformedQueryException,
		QueryEvaluationException, RDFParseException, IOException {
	try {
		repo.initialize();
		final RepositoryConnection conn = repo.getConnection();
		conn.setAutoCommit(false);
		try {
			conn.add(getClass().getResourceAsStream("TestTicket275.ttl"), "",
					RDFFormat.TURTLE);
			conn.commit();

			final String query = "SELECT ?lookup WHERE { ?lookup <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <os:class/Lookup> . ?lookup <os:prop/lookup/majorType> ?majorType . OPTIONAL{?lookup <os:prop/lookup/minorType> ?minorType}. FILTER(STR(?majorType) = ?argMajorType). FILTER(!bound(?minorType))}";
			final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					query);
			q.setBinding("argMajorType", conn.getValueFactory()
					.createLiteral("majoor"));
			final TupleQueryResult tqr = q.evaluate();
			while (tqr.hasNext()) {
			    final Set<String> bindingNames = tqr.next().getBindingNames();
			    if(log.isInfoEnabled())
			        log.info("bindingNames="+bindingNames);
			}
			tqr.close();
		} finally {
			conn.close();
		}
	} finally {
		repo.shutDown();
	}
}
 
Example 30
Source Project: anno4j   Source File: ObjectArrayCursor.java    License: Apache License 2.0 5 votes vote down vote up
public ObjectArrayCursor(ObjectConnection manager, TupleQueryResult result,
		List<String> bindings, Class<?> componentType) throws QueryEvaluationException {
	this.bindings = bindings;
	this.result = result;
	this.next = result.hasNext() ? result.next() : null;
	this.manager = manager;
	this.of = manager.getObjectFactory();
	this.componentType = componentType;
}