org.eclipse.rdf4j.query.TupleQuery Java Examples

The following examples show how to use org.eclipse.rdf4j.query.TupleQuery. 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: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testEvaluate() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI uri1 = VF.createIRI(litdupsNS, "uri1");
    conn.add(cpu, loadPerc, uri1);
    conn.commit();

    String query = "select * where {" +
            "?x <" + loadPerc.stringValue() + "> ?o1." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    assertEquals(cth.getCount(), 1);
    conn.close();
}
 
Example #2
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testRegexFilter() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    IRI testClass = VF.createIRI(litdupsNS, "test");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc, sev);
    conn.add(cpu, loadPerc, ten);
    conn.add(cpu, RDF.TYPE, testClass);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            String.format("<%s> ?p ?o.\n", cpu.stringValue()) +
            "FILTER(regex(?o, '^1'))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 1);
}
 
Example #3
Source File: ContextAwareConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testTupleQuery() throws Exception {
	RepositoryConnection stub = new RepositoryConnectionStub() {

		@Override
		public TupleQuery prepareTupleQuery(QueryLanguage ql, String query, String baseURI)
				throws MalformedQueryException, RepositoryException {
			assertEquals(SPARQL, ql);
			assertEquals(queryString, query);
			return new TupleQueryStub() {

				@Override
				public void setDataset(Dataset dataset) {
					Set<IRI> contexts = Collections.singleton(context);
					assertEquals(contexts, dataset.getDefaultGraphs());
					super.setDataset(dataset);
				}
			};
		}
	};
	Repository repo = stub.getRepository();
	ContextAwareConnection con = new ContextAwareConnection(repo, stub);
	con.setReadContexts(context);
	con.setQueryLanguage(SERQL);
	con.prepareTupleQuery(SPARQL, queryString, null);
}
 
Example #4
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2250BindErrorsInPath() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data { <urn:test:subj> <urn:test:pred> _:blank }");

	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	StringBuilder qb = new StringBuilder();
	qb.append("SELECT * {\n" + "    ?s1 ?p1 ?blank . " + "    FILTER(isBlank(?blank))"
			+ "    BIND (iri(?blank) as ?biri)" + "    ?biri <urn:test:pred>* ?o2 ." + "}");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, qb.toString());
	try (TupleQueryResult evaluate = tq.evaluate();) {
		assertFalse("The query should not return a result", evaluate.hasNext());
	}
}
 
Example #5
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testSPOSubjRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI cpu2 = VF.createIRI(litdupsNS, "cpu2");
    IRI cpu3 = VF.createIRI(litdupsNS, "cpu3");
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu2, loadPerc, sev);
    conn.add(cpu3, loadPerc, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?s ?p ?o.\n" +
            "FILTER(org.apache:range(?s, <" + cpu.stringValue() + ">, <" + cpu2.stringValue() + ">))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example #6
Source File: HBaseSailTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluateWithContext() throws Exception {
    ValueFactory vf = SimpleValueFactory.getInstance();
    Resource subj = vf.createIRI("http://whatever/subj/");
    IRI pred = vf.createIRI("http://whatever/pred/");
    Value obj = vf.createLiteral("whatever");
    IRI context = vf.createIRI("http://whatever/context/");
    CloseableIteration<? extends Statement, SailException> iter;
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "whatevertable", true, 0, true, 0, null, null);
    SailRepository rep = new SailRepository(sail);
    rep.initialize();
    sail.addStatement(subj, pred, obj, context);
    sail.commit();
    TupleQuery q = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, "select ?s ?p ?o from named <http://whatever/context/> where {<http://whatever/subj/> <http://whatever/pred/> \"whatever\"}");
    TupleQueryResult res = q.evaluate();
    assertFalse(res.hasNext());
    rep.shutDown();
}
 
Example #7
Source File: LimitedSizeNativeStoreConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testLimit() throws Exception {
	((LimitedSizeNativeStoreConnection) ((SailRepositoryConnection) testCon).getSailConnection())
			.setMaxCollectionsSize(2);
	testCon.begin();
	ValueFactory vf = testCon.getValueFactory();
	IRI context1 = vf.createIRI("http://my.context.1");
	IRI predicate = vf.createIRI("http://my.predicate");
	IRI object = vf.createIRI("http://my.object");

	for (int j = 0; j < 100; j++) {
		testCon.add(vf.createIRI("http://my.subject" + j), predicate, object, context1);
	}
	testCon.commit();
	String queryString = "SELECT DISTINCT ?s WHERE {?s ?p ?o}";
	TupleQuery q = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	QueryEvaluationException shouldThrow = runQuery(q);
	assertNotNull(shouldThrow);

	// There is just one object therefore we should not throw a new
	// exception
	queryString = "SELECT DISTINCT ?o WHERE {?s ?p ?o}";
	q = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	shouldThrow = runQuery(q);
	assertNull(shouldThrow);
}
 
Example #8
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPreparedTupleQueryUnicode() throws Exception {
	testCon.add(alexander, name, Александър);

	StringBuilder queryBuilder = new StringBuilder();
	queryBuilder.append(" SELECT person");
	queryBuilder.append(" FROM {person} foaf:name {name}");
	queryBuilder.append(" USING NAMESPACE foaf = <" + FOAF_NS + ">");

	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SERQL, queryBuilder.toString());
	query.setBinding(NAME, Александър);

	try (TupleQueryResult result = query.evaluate();) {
		assertThat(result).isNotNull();
		assertThat(result.hasNext()).isTrue();

		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertThat(solution.hasBinding(PERSON)).isTrue();
			assertThat(solution.getValue(PERSON)).isEqualTo(alexander);
		}
	}
}
 
Example #9
Source File: SAILFederatedService.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> select(Service service, Set<String> projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException {
	RepositoryConnection conn = endpoint.getConn();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, service.getSelectQueryString(projectionVars), baseUri);
		Iterator<Binding> bIter = bindings.iterator();
		while (bIter.hasNext()) {
			Binding b = bIter.next();
			if (service.getServiceVars().contains(b.getName()))
				query.setBinding(b.getName(), b.getValue());
		}
		TupleQueryResult qRes = query.evaluate();
		return new InsertBindingsIteration(qRes, bindings);
	} catch(Throwable e) {
		throw new QueryEvaluationException(e);
	} finally {
		conn.close();
	}
}
 
Example #10
Source File: SplSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void runTests() throws Exception {
	ValueFactory vf = conn.getValueFactory();
	loadRDF("/schema/owl.ttl");
	conn.add(vf.createStatement(vf.createURI("test:run"), RDF.TYPE, vf.createURI(SPL.NAMESPACE, "RunTestCases")));
	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, "prefix spin: <http://spinrdf.org/spin#> "
			+ "prefix spl: <http://spinrdf.org/spl#> "
			+ "select ?testCase ?expected ?actual where {(<test:run>) spin:select (?testCase ?expected ?actual)}");
	try ( // returns failed tests
			TupleQueryResult tqr = tq.evaluate()) {
		while (tqr.hasNext()) {
			BindingSet bs = tqr.next();
			Value testCase = bs.getValue("testCase");
			Value expected = bs.getValue("expected");
			Value actual = bs.getValue("actual");
			assertEquals(testCase.stringValue(), expected, actual);
		}
	}
}
 
Example #11
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testPOPredRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc1");
    IRI loadPerc2 = VF.createIRI(litdupsNS, "loadPerc2");
    IRI loadPerc3 = VF.createIRI(litdupsNS, "loadPerc3");
    IRI loadPerc4 = VF.createIRI(litdupsNS, "loadPerc4");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc2, sev);
    conn.add(cpu, loadPerc4, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "?x ?p ?o.\n" +
            "FILTER(org.apache:range(?p, <" + loadPerc.stringValue() + ">, <" + loadPerc3.stringValue() + ">))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example #12
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * https://github.com/eclipse/rdf4j/issues/1026
 */
@Test
public void testFilterExistsExternalValuesClause() throws Exception {
	StringBuilder ub = new StringBuilder();
	ub.append("insert data {\n");
	ub.append("  <http://subj1> a <http://type> .\n");
	ub.append("  <http://subj2> a <http://type> .\n");
	ub.append("  <http://subj1> <http://predicate> <http://obj1> .\n");
	ub.append("  <http://subj2> <http://predicate> <http://obj2> .\n");
	ub.append("}");
	conn.prepareUpdate(QueryLanguage.SPARQL, ub.toString()).execute();

	String query = "select ?s  {\n" + "    ?s a* <http://type> .\n"
			+ "    FILTER EXISTS {?s <http://predicate> ?o}\n"
			+ "} limit 100 values ?o {<http://obj1>}";

	TupleQuery tq = conn.prepareTupleQuery(query);

	List<BindingSet> result = QueryResults.asList(tq.evaluate());
	assertEquals("single result expected", 1, result.size());
	assertEquals("http://subj1", result.get(0).getValue("s").stringValue());
}
 
Example #13
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSES2052If1() throws Exception {
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append("SELECT ?p \n");
	query.append("WHERE { \n");
	query.append("         ?s ?p ?o . \n");
	query.append("        FILTER(IF(BOUND(?p), ?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>, false)) \n");
	query.append("}");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());
	try (TupleQueryResult result = tq.evaluate();) {
		assertNotNull(result);
		while (result.hasNext()) {
			BindingSet bs = result.next();

			IRI p = (IRI) bs.getValue("p");
			assertNotNull(p);
			assertEquals(RDF.TYPE, p);
		}
	} catch (Exception e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example #14
Source File: ResultGenerator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Create the result files for queryFile (without extensions)
 *
 * Resources are located on classpath.
 *
 * e.g. createResult("/tests/medium/", "query01");
 *
 * @param queryFile
 */
protected void createResult(String baseDir, String queryFile) throws Exception {

	String q = readQueryString(baseDir + queryFile + ".rq");

	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, q);
	TupleQueryResult res = query.evaluate();

	OutputStream out = new FileOutputStream(new File("test" + baseDir, queryFile + ".srx"));
	TupleQueryResultWriter qrWriter = new SPARQLResultsXMLWriter(out);
	QueryResults.report(res, qrWriter);
	out.close();
}
 
Example #15
Source File: TBSSSourceSelectionOriginal.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 *  Get matching Subject authorities from a specific source for a triple pattern 
 * @param stmt Triple pattern
 * @param src Capable source 
 * @return List of authorities
 */

public ArrayList<String> getFedSumDMatchingSbjAuthorities(StatementPattern stmt, StatementSource src)
{
	String endPointUrl = "http://" + src.getEndpointID().replace("sparql_", "");
	endPointUrl = endPointUrl.replace("_", "/");
	ArrayList<String> sbjAuthorities = new ArrayList<String>();

	String  queryString = getFedSumSbjAuthLookupQuery(stmt, endPointUrl) ;

	TupleQuery tupleQuery = getSummaryConnection().prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	TupleQueryResult result = tupleQuery.evaluate();
	while (result.hasNext())
		sbjAuthorities.add(result.next().getValue("sbjAuth").stringValue());

	return sbjAuthorities;
}
 
Example #16
Source File: TBSSSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Long getDistinctObjectCount(String endpoint) {
	String strQuery = "SELECT  (COUNT(distinct ?o) AS ?triples) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
			"FILTER isIRI(?o)" +
       		"} " ;
	SPARQLRepository repo = createSPARQLRepository(endpoint);
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		String v = rs.next().getValue("triples").stringValue();
		rs.close();
		return Long.parseLong(v);
	} finally {
		conn.close();
	}
}
 
Example #17
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) {
	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 #18
Source File: TBSSSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get total number of triple for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static Long getTripleCount(String pred, String endpoint) {
	String strQuery = "SELECT  (COUNT(*) AS ?triples) " + // 
			"WHERE " +
			"{" +
       		"?s <"+pred+"> ?o " +
       		"} " ;
	SPARQLRepository repo = createSPARQLRepository(endpoint);
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		String v = rs.next().getValue("triples").stringValue();
		rs.close();
		return Long.parseLong(v);
	} finally {
		conn.close();
	}
}
 
Example #19
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) {
	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 #20
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) {
	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 #21
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 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);

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

		assertNotNull(uuid1);
		assertNotNull(uuid2);
		assertFalse(uuid1.equals(uuid2));
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #22
Source File: ArbitraryLengthQueryTest.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * This test works. The expected result is 6 rows ranging from "Model1Class 1" through "Model1Class 6".
 *
 * @throws RepositoryException
 * @throws QueryEvaluationException
 * @throws TupleQueryResultHandlerException
 *
 * @throws MalformedQueryException
 */
public void testWithoutSubquery() throws RepositoryException, QueryEvaluationException, TupleQueryResultHandlerException, MalformedQueryException {
    final String query = "SELECT ?i ?i_label ?i_class ?i_v1"
            + "WHERE {"
            + "?i <http://www.w3.org/2000/01/rdf-schema#label> ?i_label ."
            + "?i a ?i_class ."
            + "?i_class <http://www.w3.org/2000/01/rdf-schema#subClassOf>* <http://dragon-research.com/cham/model/model1#Model1Class> ."
            + "OPTIONAL { ?i <http://dragon-research.com/cham/model/model1#name> ?i_v1 } ."
            + "}"
            + "ORDER BY ?i_label";

    final RepositoryConnection conn = repository.getConnection();
    final TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    RdfCloudTripleStoreConnectionTest.CountTupleHandler countTupleHandler = new RdfCloudTripleStoreConnectionTest.CountTupleHandler();
    tupleQuery.evaluate(countTupleHandler);
    assertEquals(6, countTupleHandler.getCount());
    conn.close();
}
 
Example #23
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testOptionalFilter() throws Exception {
	String optional = "{ ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } }";
	IRI s = vf.createIRI("urn:test:s");
	IRI p1 = vf.createIRI(URN_TEST_P1);
	IRI p2 = vf.createIRI(URN_TEST_P2);
	Value v1 = vf.createLiteral(1);
	Value v2 = vf.createLiteral(2);
	Value v3 = vf.createLiteral(3);
	testCon.add(s, p1, v1);
	testCon.add(s, p2, v2);
	testCon.add(s, p1, v3);
	String qry = "PREFIX :<urn:test:> SELECT ?s ?v1 ?v2 WHERE " + optional;
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, qry);
	try (TupleQueryResult result = query.evaluate();) {
		Set<List<Value>> set = new HashSet<>();
		while (result.hasNext()) {
			BindingSet bindings = result.next();
			set.add(Arrays.asList(bindings.getValue("v1"), bindings.getValue("v2")));
		}
		assertThat(set).contains(Arrays.asList(v1, v2));
		assertThat(set).contains(Arrays.asList(v3, null));
	}
}
 
Example #24
Source File: LuceneSailExample.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private static void tupleQuery(String queryString, RepositoryConnection connection)
		throws QueryEvaluationException, RepositoryException, MalformedQueryException {
	System.out.println("Running query: \n" + queryString);
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	try (TupleQueryResult result = query.evaluate()) {
		// print the results
		System.out.println("Query results:");
		while (result.hasNext()) {
			BindingSet bindings = result.next();
			System.out.println("found match: ");
			for (Binding binding : bindings) {
				System.out.println("\t" + binding.getName() + ": " + binding.getValue());
			}
		}
	}
}
 
Example #25
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 6 votes vote down vote up
public void testSPOObjRange() throws Exception {
    RepositoryConnection conn = repository.getConnection();
    IRI loadPerc = VF.createIRI(litdupsNS, "loadPerc");
    Literal six = VF.createLiteral("6");
    Literal sev = VF.createLiteral("7");
    Literal ten = VF.createLiteral("10");
    conn.add(cpu, loadPerc, six);
    conn.add(cpu, loadPerc, sev);
    conn.add(cpu, loadPerc, ten);
    conn.commit();

    String query = "PREFIX org.apache: <" + NAMESPACE + ">\n" +
            "select * where {" +
            "<" + cpu.stringValue() + "> <" + loadPerc.stringValue() + "> ?o.\n" +
            "FILTER(org.apache:range(?o, '6', '8'))." +
            "}";
    TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    CountTupleHandler cth = new CountTupleHandler();
    tupleQuery.evaluate(cth);
    conn.close();
    assertEquals(cth.getCount(), 2);
}
 
Example #26
Source File: AccumuloRyaSailFactoryLoadFilesIT.java    From rya with Apache License 2.0 5 votes vote down vote up
private static int performTupleQuery(final String query, final RepositoryConnection conn) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException {
    final TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
    tupleQuery.setMaxExecutionTime(10);
    final CountingResultHandler handler = new CountingResultHandler();
    tupleQuery.evaluate(handler);
    return handler.getCount();
}
 
Example #27
Source File: QueryEvaluator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Evaluates the query submitted with the given request.
 *
 * @param builder   used to build the response
 * @param resp      the response object
 * @param out       the output writer
 * @param xslPath   style sheet path
 * @param con       connection to repository
 * @param queryText the query text, having been pulled using
 *                  {@link org.eclipse.rdf4j.workbench.commands.QueryServlet} from one of three request parameters:
 *                  "query", "queryhash" or "saved"
 * @param req       the request object
 * @param cookies   used to deal with browser cookies
 * @throws BadRequestException if there's a problem getting request parameters or issuing the repository query
 * @throws RDF4JException      if there's a problem preparing the query
 */
public void extractQueryAndEvaluate(final TupleResultBuilder builder, final HttpServletResponse resp,
		final OutputStream out, final String xslPath, final RepositoryConnection con, String queryText,
		final WorkbenchRequest req, final CookieHandler cookies) throws BadRequestException, RDF4JException {
	final QueryLanguage queryLn = QueryLanguage.valueOf(req.getParameter("queryLn"));
	Query query = QueryFactory.prepareQuery(con, queryLn, queryText);
	boolean evaluateCookie = false;
	int offset = req.getInt("offset");
	int limit = req.getInt("limit_query");
	boolean paged = limit > 0;
	if (query instanceof GraphQuery || query instanceof TupleQuery) {
		final int know_total = req.getInt("know_total");
		evaluateCookie = know_total <= 0;
		if (!evaluateCookie) {
			cookies.addTotalResultCountCookie(req, resp, know_total);
		}
		if (paged) {
			PagedQuery pagedQuery = new PagedQuery(queryText, queryLn, limit, offset);
			if (pagedQuery.isPaged()) {
				offset = pagedQuery.getOffset();
				limit = pagedQuery.getLimit();
			}
			if (!evaluateCookie) {
				query = QueryFactory.prepareQuery(con, queryLn, pagedQuery.toString());
			}
		}
	}
	if (req.isParameterPresent("infer")) {
		final boolean infer = Boolean.parseBoolean(req.getParameter("infer"));
		query.setIncludeInferred(infer);
	}
	this.evaluate(builder, out, xslPath, req, resp, cookies, query, evaluateCookie, paged, offset, limit);
}
 
Example #28
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testNullContext1() throws Exception {
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append(" SELECT * ");
	query.append(" FROM DEFAULT ");
	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
		}
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #29
Source File: SPARQLBuilderTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test() throws RDF4JException { // NOPMD
	// Thrown exceptions are the only failure path.

	for (int i = 0; i < 100; i++) {
		TupleQuery tupleQuery = con.prepareTupleQuery(SPARQL, pattern);
		if (!(prefix.isEmpty() || namespace.isEmpty())) {
			tupleQuery.setBinding(prefix, valueFactory.createIRI(namespace));
		}
		tupleQuery.evaluate().close();
	}
}
 
Example #30
Source File: Demo3.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) throws Exception {

		List<Endpoint> endpoints = new ArrayList<>();
		endpoints.add(EndpointFactory.loadSPARQLEndpoint("http://dbpedia", "http://dbpedia.org/sparql"));
		endpoints.add(EndpointFactory.loadSPARQLEndpoint("http://swdf", "http://data.semanticweb.org/sparql"));

		FedXRepository repo = FedXFactory.createFederation(endpoints);
		repo.init();

		String q = "PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\n"
				+ "PREFIX dbpedia-owl: <http://dbpedia.org/ontology/>\n"
				+ "SELECT ?President ?Party WHERE {\n"
				+ "?President rdf:type dbpedia-owl:President .\n"
				+ "?President dbpedia-owl:party ?Party . }";

		TupleQuery query = repo.getQueryManager().prepareTupleQuery(q);
		try (TupleQueryResult res = query.evaluate()) {

			while (res.hasNext()) {
				System.out.println(res.next());
			}
		}

		repo.shutDown();
		System.out.println("Done.");
		System.exit(0);

	}