org.openrdf.query.TupleQueryResult Java Examples

The following examples show how to use org.openrdf.query.TupleQueryResult. 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: TestTicket4249.java    From database with 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 #2
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #3
Source File: BlazeGraphEmbedded.java    From tinkerpop3 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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 #4
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #5
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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 #6
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 #7
Source File: Test_Ticket_2091.java    From database with 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 #8
Source File: SesameDriver.java    From trainbenchmark with 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 File: Test_Ticket_1893.java    From database with 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 File: TestTicket967.java    From database with 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 File: Test_Ticket_789.java    From database with 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 File: SPARQLQueryTest.java    From database with 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
Source File: BigdataSailRemoteRepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: BigdataSailRemoteRepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@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 File: SPARQLQueryTest.java    From database with 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 File: SPARQLUpdateTestv2.java    From database with 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
Source File: TestNanoSparqlClient.java    From database with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: AbstractDataDrivenSPARQLTestCase.java    From database with GNU General Public License v2.0 5 votes vote down vote up
private void compareTupleQueryResults(
		final TupleQueryResult queryResult,
		final TupleQueryResult expectedResult)
		throws QueryEvaluationException {

	compareTupleQueryResults(queryResult, expectedResult, checkOrder);

}
 
Example #19
Source File: BigdataRemoteTupleQuery.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public void evaluate(TupleQueryResultHandler handler)
		throws QueryEvaluationException, TupleQueryResultHandlerException {
	TupleQueryResult tqr = evaluate();
	try {
		handler.startQueryResult(tqr.getBindingNames());
		while (tqr.hasNext()) {
			handler.handleSolution(tqr.next());
		}
		handler.endQueryResult();
	} finally {
		tqr.close();
	}
}
 
Example #20
Source File: BigdataSailRemoteRepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testTupleQueryBaseURI() throws Exception {
    final String baseURI = ":baseURI";
    final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}", baseURI);
    final TupleQueryResult tqr = tq.evaluate();
	try {
		assertEquals(baseURI, remote.data.opts.getRequestParam(RemoteRepositoryDecls.BASE_URI));
		assertEquals(baseURI,remote.data.opts.getRequestParam(RemoteRepositoryDecls.BASE_URI));
	} finally {
		tqr.close();
	}
}
 
Example #21
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 #22
Source File: AbstractInlineSELECTTestCase.java    From database with GNU General Public License v2.0 5 votes vote down vote up
public void expectResultSet(String vars, String ... bindings) throws Exception {
          final TupleQueryResult expectedResult = expectedTupleQueryResult(vars, bindings);

          loadData(trigData());
          
          final TupleQueryResult queryResult = executeSelect(queryStr);
          compareTupleQueryResults(queryResult, expectedResult, false);
}
 
Example #23
Source File: AbstractDataAndSPARQLTestCase.java    From database with GNU General Public License v2.0 5 votes vote down vote up
protected void compareTupleQueryResults(
        final TupleQueryResult queryResult,
        final TupleQueryResult expectedResult, final boolean checkOrder)
        throws QueryEvaluationException {

    AbstractQueryEngineTestCase.compareTupleQueryResults(getName(), "",
            store, astContainer, queryResult, expectedResult, false,
            checkOrder);
    
}
 
Example #24
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testSES1991UUIDEvaluation()
	throws Exception
{
	loadTestData("/testdata-query/defaultgraph.ttl");
	String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(UUID() as ?uid) } LIMIT 2";

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

	try {
		TupleQueryResult result = tq.evaluate();
		assertNotNull(result);

		URI uuid1 = (URI)result.next().getValue("uid");
		URI uuid2 = (URI)result.next().getValue("uid");

		assertNotNull(uuid1);
		assertNotNull(uuid2);
		assertFalse(uuid1.equals(uuid2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #25
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 #26
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 #27
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@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 #28
Source File: ObjectArrayCursor.java    From anno4j with 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;
}
 
Example #29
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testNullContext2()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append(" SELECT * ");
	query.append(" FROM sesame:nil ");
	query.append(" WHERE { ?s ?p ?o } ");

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

	try {
		TupleQueryResult result = tq.evaluate();
		assertNotNull(result);

		while (result.hasNext()) {
			BindingSet bs = result.next();
			assertNotNull(bs);

			Resource s = (Resource)bs.getValue("s");

			assertNotNull(s);
			assertFalse(bob.equals(s)); // should not be present in default
													// graph
			assertFalse(alice.equals(s)); // should not be present in default
													// graph
		}
		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #30
Source File: TestTicket275.java    From database with 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();
	}
}