org.eclipse.rdf4j.query.QueryLanguage Java Examples

The following examples show how to use org.eclipse.rdf4j.query.QueryLanguage. 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: AbstractLuceneSailSpinTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDistanceFunction() throws Exception {
	RepositoryConnection connection = getConnection();
	String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
			+ "prefix search: <" + LuceneSailSchema.NAMESPACE + ">"
			+ "select ?toUri ?fromUri ?dist where {(?from ?range ?units geo:asWKT search:distance)"
			+ "search:withinDistance (?toUri ?to ?dist) ."
			+ "?toUri a <urn:geo/Landmark>. ?fromUri geo:asWKT ?from; <urn:geo/maxDistance> ?range.}";
	try {
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("units", GEOF.UOM_METRE);

		printTupleResult(query);
		try (TupleQueryResult result = query.evaluate()) {
			int count = countTupleResults(result);
			Assert.assertEquals(2, count);
		}
	} catch (Exception e) {
		connection.rollback();
		throw e;
	} finally {
		connection.commit();
	}
}
 
Example #2
Source File: HBaseSailTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testCardinalityCalculator() throws Exception {
    HBaseSail sail = new HBaseSail(HBaseServerTestInstance.getInstanceConfig(), "cardinalitytable", true, 0, true, 0, null, null);
    sail.initialize();
    SimpleValueFactory f = SimpleValueFactory.getInstance();
    TupleExpr q1 = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "select * where {?s a ?o}", "http://whatever/").getTupleExpr();
    TupleExpr q2 = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "select * where {graph <http://whatevercontext> {?s a ?o}}", "http://whatever/").getTupleExpr();
    TupleExpr q3 = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "select * where {?s <http://whatever/> ?o}", "http://whatever/").getTupleExpr();
    TupleExpr q4 = QueryParserUtil.parseTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p \"whatever\"^^<" + HALYARD.SEARCH_TYPE.stringValue() + ">}", "http://whatever/").getTupleExpr();
    assertEquals(100.0, sail.statistics.getCardinality(q1), 0.01);
    assertEquals(100.0, sail.statistics.getCardinality(q2), 0.01);
    assertEquals(100.0, sail.statistics.getCardinality(q3), 0.01);
    assertEquals(0.0001, sail.statistics.getCardinality(q4), 0.00001);
    sail.addStatement(HALYARD.STATS_ROOT_NODE, VOID.TRIPLES, f.createLiteral(10000l), HALYARD.STATS_GRAPH_CONTEXT);
    sail.addStatement(f.createIRI(HALYARD.STATS_ROOT_NODE.stringValue() + "_property_" + HalyardTableUtils.encode(HalyardTableUtils.hashKey(RDF.TYPE))), VOID.TRIPLES, f.createLiteral(5000l), HALYARD.STATS_GRAPH_CONTEXT);
    sail.addStatement(f.createIRI("http://whatevercontext"), VOID.TRIPLES, f.createLiteral(10000l), HALYARD.STATS_GRAPH_CONTEXT);
    sail.addStatement(f.createIRI("http://whatevercontext_property_" + HalyardTableUtils.encode(HalyardTableUtils.hashKey(RDF.TYPE))), VOID.TRIPLES, f.createLiteral(20l), HALYARD.STATS_GRAPH_CONTEXT);
    sail.commit();
    assertEquals(5000.0, sail.statistics.getCardinality(q1), 0.01);
    assertEquals(20.0, sail.statistics.getCardinality(q2), 0.01);
    assertEquals(100.0, sail.statistics.getCardinality(q3), 0.01);
    assertEquals(0.0001, sail.statistics.getCardinality(q4), 0.00001);
    sail.shutDown();
}
 
Example #3
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUpdateSequenceInsertDelete() throws Exception {
	logger.debug("executing testUpdateSequenceInsertDelete");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT {?x foaf:name \"foo\" } WHERE {?y ex:containsPerson ?x}; ");
	update.append(getNamespaceDeclarations());
	update.append("DELETE {?y foaf:name ?n } WHERE {?x ex:containsPerson ?y. ?y foaf:name ?n . } ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertTrue(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	operation.execute();

	String msg = "foaf:name properties should have been deleted";
	assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	msg = "foaf:name properties with value 'foo' should not have been added";
	assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true));
	assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true));
}
 
Example #4
Source File: StrictEvaluationStrategyTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Verifies if only those input bindings that actually occur in the query are returned in the result. See SES-2373.
 */
@Test
public void testBindings() throws Exception {
	String query = "SELECT ?a ?b WHERE {}";
	ParsedQuery pq = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);

	final ValueFactory vf = SimpleValueFactory.getInstance();
	QueryBindingSet constants = new QueryBindingSet();
	constants.addBinding("a", vf.createLiteral("foo"));
	constants.addBinding("b", vf.createLiteral("bar"));
	constants.addBinding("x", vf.createLiteral("X"));
	constants.addBinding("y", vf.createLiteral("Y"));

	CloseableIteration<BindingSet, QueryEvaluationException> result = strategy.evaluate(pq.getTupleExpr(),
			constants);
	assertNotNull(result);
	assertTrue(result.hasNext());
	BindingSet bs = result.next();
	assertTrue(bs.hasBinding("a"));
	assertTrue(bs.hasBinding("b"));
	assertFalse(bs.hasBinding("x"));
	assertFalse(bs.hasBinding("y"));
}
 
Example #5
Source File: AbstractGenericLuceneTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUnionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	String queryStr = "";
	queryStr += "PREFIX search: <http://www.openrdf.org/contrib/lucenesail#> ";
	queryStr += "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
	queryStr += "SELECT DISTINCT ?result { ";
	queryStr += "{ ?result search:matches ?match1 . ";
	queryStr += "  ?match1 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate1> . }";
	queryStr += " UNION ";
	queryStr += "{ ?result search:matches ?match2 . ";
	queryStr += "  ?match2 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate2> . } ";
	queryStr += "} ";

	// fire a query with the subject pre-specified
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	try (TupleQueryResult result = query.evaluate()) {
		while (result.hasNext()) {
			System.out.println(result.next());
		}
	}
}
 
Example #6
Source File: SnapshotTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_safeInsert() throws Exception {
	b.add(REMBRANDT, RDF.TYPE, PAINTER);
	b.add(REMBRANDT, PAINTS, NIGHTWATCH);
	b.add(REMBRANDT, PAINTS, ARTEMISIA);
	b.add(REMBRANDT, PAINTS, DANAE);
	a.begin(level);
	b.begin(level);
	// PICASSO is *not* a known PAINTER
	a.add(PICASSO, PAINTS, GUERNICA);
	a.add(PICASSO, PAINTS, JACQUELINE);
	b.prepareUpdate(QueryLanguage.SPARQL,
			"INSERT { ?painting a <Painting> }\n" + "WHERE { [a <Painter>] <paints> ?painting }", NS).execute();
	a.commit();
	b.commit();
	assertEquals(9, size(a, null, null, null, false));
	assertEquals(9, size(b, null, null, null, false));
}
 
Example #7
Source File: SnapshotTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test_mergeOptionalInsert() throws Exception {
	a.add(PICASSO, RDF.TYPE, PAINTER);
	b.add(REMBRANDT, RDF.TYPE, PAINTER);
	b.add(REMBRANDT, PAINTS, NIGHTWATCH);
	b.add(REMBRANDT, PAINTS, ARTEMISIA);
	b.add(REMBRANDT, PAINTS, DANAE);
	a.begin(level);
	b.begin(level);
	// PICASSO *is* a known PAINTER
	a.add(PICASSO, PAINTS, GUERNICA);
	a.add(PICASSO, PAINTS, JACQUELINE);
	b.prepareUpdate(QueryLanguage.SPARQL, "INSERT { ?painting a <Painting> }\n" + "WHERE { ?painter a <Painter> "
			+ "OPTIONAL { ?painter <paints> ?painting } }", NS).execute();
	a.commit();
	assertEquals(3, size(b, REMBRANDT, PAINTS, null, false));
	b.commit();
	assertEquals(10, size(a, null, null, null, false));
}
 
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 testSimpleTupleQueryUnicode() throws Exception {
	testCon.add(alexander, name, Александър);
	StringBuilder queryBuilder = new StringBuilder(128);
	queryBuilder.append(" SELECT person");
	queryBuilder.append(" FROM {person} foaf:name {").append(Александър.getLabel()).append("}");
	queryBuilder.append(" USING NAMESPACE foaf = <" + FOAF_NS + ">");

	try (TupleQueryResult result = testCon.prepareTupleQuery(QueryLanguage.SERQL, queryBuilder.toString())
			.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: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInsertWhereUsing() throws Exception {

	logger.debug("executing testInsertWhereUsing");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT {?x rdfs:label ?y . } USING ex:graph1 WHERE {?x foaf:name ?y }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	operation.execute();

	String message = "label should have been inserted in default graph, for ex:bob only";
	assertTrue(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));
	assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph1));
	assertFalse(message, con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true, graph2));
	assertFalse(message, con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true));
}
 
Example #10
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testInsertDataGraph2() throws Exception {
	logger.debug("executing testInsertDataGraph2");

	StringBuilder update = new StringBuilder();
	update.append("INSERT DATA { \n");
	update.append("<urn:s1> a <urn:C1> . \n");
	update.append("GRAPH <urn:g1> { <urn:s1> <urn:p1> <urn:o1> . } \n");
	update.append("}");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());
	assertFalse(con.hasStatement(f.createIRI("urn:s1"), RDF.TYPE, null, true, (Resource) null));
	assertFalse(con.hasStatement(f.createIRI("urn:s1"), f.createIRI("urn:p1"), f.createIRI("urn:o1"), true,
			f.createIRI("urn:g1")));
	operation.execute();
	assertTrue(con.hasStatement(f.createIRI("urn:s1"), RDF.TYPE, null, true, (Resource) null));
	assertTrue(con.hasStatement(f.createIRI("urn:s1"), f.createIRI("urn:p1"), f.createIRI("urn:o1"), true,
			f.createIRI("urn:g1")));
}
 
Example #11
Source File: AbstractLuceneSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUnionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	String queryStr = "";
	queryStr += "PREFIX search: <http://www.openrdf.org/contrib/lucenesail#> ";
	queryStr += "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
	queryStr += "SELECT DISTINCT ?result { ";
	queryStr += "{ ?result search:matches ?match1 . ";
	queryStr += "  ?match1 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate1> . }";
	queryStr += " UNION ";
	queryStr += "{ ?result search:matches ?match2 . ";
	queryStr += "  ?match2 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate2> . } ";
	queryStr += "} ";

	try (RepositoryConnection connection = repository.getConnection()) {
		// fire a query with the subject pre-specified
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("result", SUBJECT_1);
		try (TupleQueryResult result = query.evaluate()) {
			// check that this subject and only this subject is returned
			BindingSet bs = result.next();
			assertEquals(SUBJECT_1, bs.getValue("result"));
		}
	}
}
 
Example #12
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDeleteFromDefaultGraphUsingWith() throws Exception {

	con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST);
	con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST, RDF.ALT);
	con.add(RDF.FIRST, RDF.FIRST, RDF.FIRST, RDF.BAG);

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("WITH sesame:nil DELETE { ?s ?p ?o  } WHERE { ?s ?p ?o }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());
	operation.execute();

	assertTrue(con.hasStatement(RDF.FIRST, RDF.FIRST, RDF.FIRST, true, RDF.ALT));
	assertTrue(con.hasStatement(RDF.FIRST, RDF.FIRST, RDF.FIRST, true, RDF.BAG));
	assertFalse(con.hasStatement(RDF.FIRST, RDF.FIRST, RDF.FIRST, true, SESAME.NIL));
	assertFalse(con.hasStatement(RDF.FIRST, RDF.FIRST, RDF.FIRST, true, (Resource) null));
}
 
Example #13
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDeleteInsertWhere() throws Exception {
	logger.debug("executing test DeleteInsertWhere");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE { ?x foaf:name ?y } INSERT {?x rdfs:label ?y . } WHERE {?x foaf:name ?y }");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertFalse(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));
	assertFalse(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true));

	operation.execute();

	assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));
	assertTrue(con.hasStatement(alice, RDFS.LABEL, f.createLiteral("Alice"), true));

	assertFalse(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertFalse(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

}
 
Example #14
Source File: RepositoryPerformance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private int runQuery(RepositoryConnection conn, IRI instance) throws Exception {

			long start = System.currentTimeMillis();
			TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL,
					"SELECT * WHERE { <" + instance.stringValue() + "> ?p ?o }");

			TupleQueryResult res = null;
			try {
				res = query.evaluate();
				int count = 0;
				while (res.hasNext()) {
					res.next();
					count++;
				}
				System.out.println("Instance " + instance.stringValue() + " has " + count + " results. Duration: "
						+ (System.currentTimeMillis() - start) + "ms");
				return count;
			} finally {
				if (res != null) {
					res.close();
				}
			}
		}
 
Example #15
Source File: RepositoryModel.java    From semweb4j with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public ClosableIterable<Statement> queryConstruct(String query, String querylanguage)
		throws QueryLanguageNotSupportedException {
	assertModel();
	if (querylanguage.equalsIgnoreCase("SPARQL"))
		return sparqlConstruct(query);
	else {
		QueryLanguage ql = QueryLanguage.valueOf(querylanguage);
		if (ql == null) {
			throw new QueryLanguageNotSupportedException("Unsupported query language: '"
					+ querylanguage + "'");
		}
		try {
			GraphQuery prepared = this.connection.prepareGraphQuery(ql, query);
			GraphQueryResult graphQueryResult = prepared.evaluate();
			return new GraphIterable(graphQueryResult, this);
		} catch (MalformedQueryException | RepositoryException |
				UnsupportedQueryLanguageException | QueryEvaluationException e) {
			throw new ModelRuntimeException(e);
		}
	}
}
 
Example #16
Source File: HBaseSailTest.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Test
public void testEvaluate() 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");
    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);
    sail.commit();
    TupleQuery q = rep.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, "select ?s ?p ?o where {<http://whatever/subj/> <http://whatever/pred/> \"whatever\"}");
    TupleQueryResult res = q.evaluate();
    assertTrue(res.hasNext());
    rep.shutDown();
}
 
Example #17
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 #18
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testIterator() throws Exception {
	TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SERQL, multipleResultQuery).evaluate();

	try {
		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}

		assertTrue("query should have multiple results.", count > 1);
	} finally {
		result.close();
	}
}
 
Example #19
Source File: WriteTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testSimpleUpdateQuery_insertData() throws Exception {

	prepareTest(Arrays.asList("/tests/basic/data_emptyStore.ttl", "/tests/basic/data_emptyStore.ttl"));

	Iterator<Endpoint> iter = federationContext().getEndpointManager().getAvailableEndpoints().iterator();
	EndpointBase ep1 = (EndpointBase) iter.next();
	ep1.setWritable(true);

	try (RepositoryConnection conn = fedxRule.getRepository().getConnection()) {
		Update update = conn.prepareUpdate(QueryLanguage.SPARQL,
				"PREFIX ex: <http://example.org/> INSERT DATA { ex:subject a ex:Person } ");
		update.execute();

		// test that statement is returned from federation
		List<Statement> stmts = Iterations.asList(conn.getStatements(null, null, null, true));
		Assertions.assertEquals(1, stmts.size());
		Assertions.assertEquals(RDF.TYPE, stmts.get(0).getPredicate());
	}
}
 
Example #20
Source File: SPARQLUpdateTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUpdateSequenceDeleteInsert() throws Exception {
	logger.debug("executing testUpdateSequenceDeleteInsert");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE {?y foaf:name ?n } WHERE {?x ex:containsPerson ?y. ?y foaf:name ?n . }; ");
	update.append(getNamespaceDeclarations());
	update.append("INSERT {?x foaf:name \"foo\" } WHERE {?y ex:containsPerson ?x} ");

	Update operation = con.prepareUpdate(QueryLanguage.SPARQL, update.toString());

	assertTrue(con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertTrue(con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	operation.execute();

	String msg = "foaf:name properties should have been deleted";
	assertFalse(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("Bob"), true));
	assertFalse(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("Alice"), true));

	msg = "foaf:name properties with value 'foo' should have been added";
	assertTrue(msg, con.hasStatement(bob, FOAF.NAME, f.createLiteral("foo"), true));
	assertTrue(msg, con.hasStatement(alice, FOAF.NAME, f.createLiteral("foo"), true));
}
 
Example #21
Source File: HibiscusSourceSelection.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
 * @throws RepositoryException Repository Exception
 * @throws MalformedQueryException Memory Exception
 * @throws QueryEvaluationException Query Exception
 */

public ArrayList<String> FedSumD_getMatchingSbjAuthorities(StatementPattern stmt, StatementSource src) throws RepositoryException, MalformedQueryException, QueryEvaluationException 
{
	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 #22
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPreparedBooleanQuery() 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(ASK);
	queryBuilder.append("{ ?p foaf:name ?name }");

	BooleanQuery query = testCon.prepareBooleanQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding(NAME, nameBob);

	assertThat(query.evaluate()).isTrue();
}
 
Example #23
Source File: LinearTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<Value> eval(String var, RepositoryConnection con, String qry) throws Exception {
	TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, qry, NS);
	try (TupleQueryResult result = tq.evaluate();) {
		List<Value> list = new ArrayList<>();
		while (result.hasNext()) {
			list.add(result.next().getValue(var));
		}
		return list;
	}
}
 
Example #24
Source File: SpifSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testCanInvoke() throws Exception {
	loadRDF("/schema/spif.ttl");
	BooleanQuery bq = conn.prepareBooleanQuery(QueryLanguage.SPARQL, "prefix spif: <http://spinrdf.org/spif#> "
			+ "ask where {filter(spif:canInvoke(spif:indexOf, 'foobar', 'b'))}");
	assertTrue(bq.evaluate());
}
 
Example #25
Source File: SailRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public SailTupleQuery prepareTupleQuery(QueryLanguage ql, String queryString, String baseURI)
		throws MalformedQueryException {
	Optional<TupleExpr> sailTupleExpr = sailConnection.prepareQuery(ql, Query.QueryType.TUPLE, queryString,
			baseURI);

	ParsedTupleQuery parsedQuery = sailTupleExpr
			.map(expr -> new ParsedTupleQuery(queryString, expr))
			.orElse(QueryParserUtil.parseTupleQuery(ql, queryString, baseURI));
	return new SailTupleQuery(parsedQuery, this);
}
 
Example #26
Source File: ConfigurableSailRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Update prepareUpdate(QueryLanguage ql, String update,
		String baseURI) throws RepositoryException,
		MalformedQueryException {
	checkOperations(true);
	return super.prepareUpdate(ql, update, baseURI);
}
 
Example #27
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testInComparison2() 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/0)) } ");

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

	try (TupleQueryResult result = tq.evaluate();) {
		assertNotNull(result);
		assertFalse(result.hasNext());
	}
}
 
Example #28
Source File: PcjTables.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Scan Rya for results that solve the PCJ's query and store them in the PCJ table.
 * <p>
 * This method assumes the PCJ table has already been created.
 *
 * @param accumuloConn - A connection to the Accumulo that hosts the PCJ table. (not null)
 * @param pcjTableName - The name of the PCJ table that will receive the results. (not null)
 * @param ryaConn - A connection to the Rya store that will be queried to find results. (not null)
 * @throws PCJStorageException If results could not be written to the PCJ table,
 *   the PCJ table does not exist, or the query that is being execute
 *   was malformed.
 */
public void populatePcj(
        final Connector accumuloConn,
        final String pcjTableName,
        final RepositoryConnection ryaConn) throws PCJStorageException {
    checkNotNull(accumuloConn);
    checkNotNull(pcjTableName);
    checkNotNull(ryaConn);

    try {
        // Fetch the query that needs to be executed from the PCJ table.
        final PcjMetadata pcjMetadata = getPcjMetadata(accumuloConn, pcjTableName);
        final String sparql = pcjMetadata.getSparql();

        // Query Rya for results to the SPARQL query.
        final TupleQuery query = ryaConn.prepareTupleQuery(QueryLanguage.SPARQL, sparql);
        final TupleQueryResult results = query.evaluate();

        // Load batches of 1000 of them at a time into the PCJ table
        final Set<VisibilityBindingSet> batch = new HashSet<>(1000);
        while(results.hasNext()) {
            batch.add( new VisibilityBindingSet(results.next()) );

            if(batch.size() == 1000) {
                addResults(accumuloConn, pcjTableName, batch);
                batch.clear();
            }
        }

        if(!batch.isEmpty()) {
            addResults(accumuloConn, pcjTableName, batch);
        }

    } catch (RepositoryException | MalformedQueryException | QueryEvaluationException e) {
        throw new PCJStorageException("Could not populate a PCJ table with Rya results for the table named: " + pcjTableName, e);
    }
}
 
Example #29
Source File: HibiscusSourceSelection.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Search HiBISCuS index for the given triple pattern p with sbj authority and obj authority.
 * Note: sa, oa can be null i.e. for unbound tuple 
 * @param stmt Statement pattern	
 * @param sa Subject authority
 * @param p Predicate
 * @param oa Object authority
 * @throws QueryEvaluationException Query Error
 * @throws MalformedQueryException  Memory Error
 * @throws RepositoryException  Repository Erro
 */
public void FedSumLookup(StatementPattern stmt, String sa, String p, String oa) throws QueryEvaluationException, RepositoryException, MalformedQueryException {
	    String  queryString = getFedSumLookupQuery(sa,p,oa) ;
	    TupleQuery tupleQuery = getSummaryConnection().prepareTupleQuery(QueryLanguage.SPARQL, queryString);
		 TupleQueryResult result = tupleQuery.evaluate();
		   while(result.hasNext())
		   {
			  String endpoint = result.next().getValue("url").stringValue();
				String id = "sparql_" + endpoint.replace("http://", "").replace("/", "_");
				addSource(stmt, new StatementSource(id, StatementSourceType.REMOTE));
		   }
	}
 
Example #30
Source File: TriplestoreProvenanceCollectorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testCollect() throws ProvenanceCollectionException, RepositoryException, MalformedQueryException, QueryEvaluationException {
	Sail ms = new MemoryStore();
	SailRepository repo = new SailRepository(ms);
	repo.initialize();
	TriplestoreProvenanceCollector coll = new TriplestoreProvenanceCollector(repo, "fakeUser", "SPARQL");
	coll.recordQuery("fakeQuery");
	String queryString = "SELECT ?x ?y WHERE { ?x ?p ?y } ";
	TupleQuery tupleQuery = repo.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	TupleQueryResult result = tupleQuery.evaluate();
	// TODO not asserting on the results.
	assertTrue(result.hasNext());
}