org.eclipse.rdf4j.query.TupleQueryResult Java Examples

The following examples show how to use org.eclipse.rdf4j.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: 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 #2
Source File: SPARQLStoreConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void testSimpleTupleQueryUnicode() throws Exception {
	testCon.add(alexander, name, Александър);

	StringBuilder queryBuilder = new StringBuilder();
	queryBuilder.append(" PREFIX foaf: <" + FOAF_NS + ">");
	queryBuilder.append(" SELECT ?person");
	queryBuilder.append(" WHERE { ?person foaf:name \"").append(Александър.getLabel()).append("\" . } ");

	try (TupleQueryResult result = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString())
			.evaluate()) {
		assertNotNull(result);
		assertTrue(result.hasNext());

		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertTrue(solution.hasBinding("person"));
			assertEquals(alexander, solution.getValue("person"));
		}
	}
}
 
Example #3
Source File: StatsGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
private static Set<String> getCurrentResult(TupleQueryResult res) throws QueryEvaluationException 
{
	List<String> bindingNames = res.getBindingNames();
	Set<String> curResults = new HashSet<String>() ;
	while (res.hasNext()) {
		BindingSet result = res.next();
		String recordLine ="";
		for(int i = 0 ; i < bindingNames.size(); i++)
		{
			String bindingName = bindingNames.get(i);
			String bindingVal = result.getBinding(bindingName).getValue().toString().replaceAll("\n", " ").replace("]", "").replace("[", "");
			if(i< bindingNames.size()-1)					
			recordLine = recordLine+bindingName+"="+bindingVal+";";
			else
				recordLine = recordLine+bindingName+"="+bindingVal;	
			
		}
		curResults.add("["+recordLine+"]");
		}

	return curResults;
}
 
Example #4
Source File: StatsGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
public static String getFscores(String queryNo,TupleQueryResult res) throws QueryEvaluationException, RepositoryException, MalformedQueryException 
{
	
	String Fscores = "" ;
	double precision, recall,F1;
	Set<String> curResults =  getCurrentResult(res) ;
	//System.out.println("current:"+ curResults);
	Set<String> actualResults = getActualResults(queryNo) ;
	//System.out.println("actual:" +actualResults);
	Set<String> diffSet = Sets.difference(actualResults, curResults);
	//System.out.println(diffSet);
	//System.out.println(Sets.difference( curResults,actualResults));
	double correctResults = actualResults.size()-diffSet.size();
	precision = (correctResults/curResults.size());
	recall = correctResults/actualResults.size();
	F1 = 2*(precision*recall)/(precision+recall);
	Fscores = "Precision: "+precision+", Recall: " + recall +", F1: "+F1;
	return Fscores;
	
}
 
Example #5
Source File: SPARQLServiceEvaluationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read the expected tuple query result from the specified resource
 *
 * @param queryResource
 * @return
 * @throws RepositoryException
 * @throws IOException
 */
private TupleQueryResult readExpectedTupleQueryResult(String resultFile) throws Exception {
	Optional<QueryResultFormat> tqrFormat = QueryResultIO.getParserFormatForFileName(resultFile);

	if (tqrFormat.isPresent()) {
		InputStream in = SPARQLServiceEvaluationTest.class.getResourceAsStream(resultFile);
		try {
			TupleQueryResultParser parser = QueryResultIO.createTupleParser(tqrFormat.get());
			parser.setValueFactory(SimpleValueFactory.getInstance());

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

			parser.parseQueryResult(in);
			return qrBuilder.getQueryResult();
		} finally {
			in.close();
		}
	} else {
		Set<Statement> resultGraph = readExpectedGraphQueryResult(resultFile);
		return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph);
	}
}
 
Example #6
Source File: AbstractLuceneSailSpinTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Valid search query. SPRQL query: <code>
 * select ?pred ?score ?subject where {
 *    ("ornare" search:allMatches search:score) search:search  (?pred ?score) .
 *    ?pred <urn:test.org/onto#number> ?subject . }
 * </code>
 *
 * @throws Exception
 */
@Test
public void simpleSearchTest() throws Exception {
	StringBuilder buffer = new StringBuilder();
	buffer.append("select ?predicate ?score ?subject where {\n");
	buffer.append("(\"ornare\" <" + ALL_MATCHES + "> <" + SCORE + ">) <" + SEARCH + ">  (?pred ?score) . \n");
	buffer.append("  ?pred <urn:test.org/onto#number> ?subject .\n");
	buffer.append("}\n");
	log.info("Request query: \n====================\n{}\n======================\n", buffer.toString());

	TupleQuery query = getConnection().prepareTupleQuery(QueryLanguage.SPARQL, buffer.toString());
	log.debug("query class: {}", query.getClass());
	// log.debug("query representation: \n{}", query);
	// printTupleResult(query);
	try (TupleQueryResult res = query.evaluate()) {
		int count = countTupleResults(res);
		log.info("count statements: {}", count);
		Assert.assertTrue("count statements: " + count, count > 0);
	}

}
 
Example #7
Source File: NoReification.java    From inception with Apache License 2.0 6 votes vote down vote up
@Override
public boolean exists(RepositoryConnection aConnection, KnowledgeBase akb,
        KBStatement mockStatement)
{
    ValueFactory vf = aConnection.getValueFactory();
    String QUERY = "SELECT * WHERE { ?s ?p ?o . }";
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("s", vf.createIRI(mockStatement.getInstance().getIdentifier()));
    tupleQuery.setBinding("p", vf.createIRI(mockStatement.getProperty().getIdentifier()));

    InceptionValueMapper mapper = new InceptionValueMapper();
    tupleQuery.setBinding("o", mapper.mapStatementValue(mockStatement, vf));

    try (TupleQueryResult result = tupleQuery.evaluate()) {
        return result.hasNext();
    }
}
 
Example #8
Source File: BasicTests.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testQueryWithLimit() throws Exception {

	final QueryManager qm = federationContext().getQueryManager();

	prepareTest(Arrays.asList("/tests/medium/data1.ttl", "/tests/medium/data2.ttl", "/tests/medium/data3.ttl",
			"/tests/medium/data4.ttl"));

	String queryString = readQueryString("/tests/basic/query_limit01.rq");

	evaluateQueryPlan("/tests/basic/query_limit01.rq", "/tests/basic/query_limit01.qp");

	TupleQuery query = qm.prepareTupleQuery(queryString);

	try (TupleQueryResult actual = query.evaluate()) {
		if (actual.hasNext()) {
			@SuppressWarnings("unused")
			BindingSet firstResult = actual.next();
		}
		if (actual.hasNext()) {
			throw new Exception("Expected single result due to LIMIT 1");
		}
	}
}
 
Example #9
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 #10
Source File: DAWGTestResultSetUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static TupleQueryResult toTupleQueryResult(Iterable<? extends Statement> dawgGraph)
		throws DAWGTestResultSetParseException {
	TupleQueryResultBuilder tqrBuilder = new TupleQueryResultBuilder();
	DAWGTestResultSetParser parser = new DAWGTestResultSetParser(tqrBuilder);

	try {
		parser.startRDF();
		for (Statement st : dawgGraph) {
			parser.handleStatement(st);
		}
		parser.endRDF();

		return tqrBuilder.getQueryResult();
	} catch (RDFHandlerException e) {
		throw new DAWGTestResultSetParseException(e.getMessage(), e);
	}
}
 
Example #11
Source File: PropertyPathTests.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
	public void testPropertyPath_ExclusivePath() throws Exception {

		prepareTest(Arrays.asList("/tests/propertypath/data1.ttl", "/tests/propertypath/data2.ttl"));

		String query = "SELECT * WHERE { ?x rdf:type/rdfs:subClassOf* foaf:Agent . ?x rdfs:label ?label}";

		String actualQueryPlan = federationContext().getQueryManager().getQueryPlan(query);

		// Note: we currently cannot compare the query plan, because the queryplan contains generated
		// variable name identifiers for anonymous nodes.
//		assertQueryPlanEquals(readResourceAsString("/tests/propertypath/query_path_exclusivePath.qp"),
//				actualQueryPlan);
		Assertions.assertTrue(actualQueryPlan.contains("ExclusiveArbitraryLengthPath"));

		try (TupleQueryResult tqr = federationContext().getQueryManager().prepareTupleQuery(query).evaluate()) {

			List<BindingSet> res = Iterations.asList(tqr);

			assertContainsAll(res, "label",
					Sets.newHashSet(l("Person 1"), l("Person 2")));
		}
	}
 
Example #12
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 #13
Source File: HTTPRepositoryConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public RepositoryResult<Resource> getContextIDs() throws RepositoryException {
	try {
		List<Resource> contextList = new ArrayList<>();

		try (TupleQueryResult contextIDs = client.getContextIDs()) {
			while (contextIDs.hasNext()) {
				BindingSet bindingSet = contextIDs.next();
				Value context = bindingSet.getValue("contextID");

				if (context instanceof Resource) {
					contextList.add((Resource) context);
				}
			}
		}

		return createRepositoryResult(contextList);
	} catch (QueryEvaluationException | IOException e) {
		throw new RepositoryException(e);
	}
}
 
Example #14
Source File: SPARQLConnection.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Converts a {@link TupleQueryResult} resulting from the {@link #EVERYTHING_WITH_GRAPH} to a statement by using the
 * respective values from the {@link BindingSet} or (if provided) the ones from the arguments.
 *
 * @param iter the {@link TupleQueryResult}
 * @param subj the subject {@link Resource} used as input or <code>null</code> if wildcard was used
 * @param pred the predicate {@link IRI} used as input or <code>null</code> if wildcard was used
 * @param obj  the object {@link Value} used as input or <code>null</code> if wildcard was used
 * @return the converted iteration
 */
protected Iteration<Statement, QueryEvaluationException> toStatementIteration(TupleQueryResult iter,
		final Resource subj, final IRI pred, final Value obj) {

	return new ConvertingIteration<BindingSet, Statement, QueryEvaluationException>(iter) {

		@Override
		protected Statement convert(BindingSet b) throws QueryEvaluationException {

			Resource s = subj == null ? (Resource) b.getValue("s") : subj;
			IRI p = pred == null ? (IRI) b.getValue("p") : pred;
			Value o = obj == null ? b.getValue("o") : obj;
			Resource ctx = (Resource) b.getValue("ctx");

			return SimpleValueFactory.getInstance().createStatement(s, p, o, ctx);
		}

	};
}
 
Example #15
Source File: SemagrowSummariesGenerator.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(?s) AS ?triples) " + // 
			"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("triples").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example #16
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get Predicate List
 * @param endPointUrl SPARQL endPoint Url
 * @param graph Named graph
 * @return  predLst Predicates List
 */
private static List<String> getPredicates(String endPointUrl, String graph)
{
	List<String>  predLst = new ArrayList<String>();
	String strQuery = getPredQuery(graph);
	SPARQLRepository repo = new SPARQLRepository(endPointUrl);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult res = query.evaluate();
		while (res.hasNext()) 
		{
			String pred = res.next().getValue("p").toString();
			predLst.add(pred);	  		
		}
	} finally {
		conn.close();
		repo.shutDown();
	}
	return predLst;
}
 
Example #17
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 #18
Source File: DAWGTestResultSetUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static Model toGraph(TupleQueryResult tqr) throws QueryEvaluationException {
	Model graph = new TreeModel();
	DAWGTestResultSetWriter writer = new DAWGTestResultSetWriter(new StatementCollector(graph));

	try {
		writer.startQueryResult(tqr.getBindingNames());
		while (tqr.hasNext()) {
			writer.handleSolution(tqr.next());
		}
		writer.endQueryResult();
	} catch (TupleQueryResultHandlerException e) {
		// No exceptions expected from DAWGTestResultSetWriter or
		// StatementCollector, foud a bug?
		throw new RuntimeException(e);
	}

	return graph;
}
 
Example #19
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 #20
Source File: TBSSSummariesGenerator.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
 * @throws RepositoryException 
 * @throws MalformedQueryException 
 * @throws QueryEvaluationException 
 */
public static Long getObjectsCount(String endpoint) throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	long count = 0;
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objts) " + // 
			"WHERE " +
			"{" +

       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = createSPARQLRepository(endpoint);
	TupleQuery query = repo.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
	TupleQueryResult rs = query.evaluate();
	while( rs.hasNext() ) 
	{
		count = Long.parseLong(rs.next().getValue("objts").stringValue());

	}
	rs.close();
	return count;
}
 
Example #21
Source File: LuceneSailTupleFunctionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Positive control test: ie valid SPARQL query.
 *
 * @throws Exception
 */
@Test
public void simpleTest() throws Exception {
	StringBuilder buffer = new StringBuilder();
	buffer.append("select ?s ?p ?o where { ?s ?p ?o } limit 10");
	try {
		connection.begin();

		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, buffer.toString());
		try (TupleQueryResult res = query.evaluate()) {
			int count = countTupleResults(res);
			log.info("count statements: {}", count);
			Assert.assertTrue(count > 0);
		}
	} catch (Exception e) {
		connection.rollback();
		throw e;
	} finally {
		connection.commit();
	}
}
 
Example #22
Source File: FedXBaseTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Read the expected tuple query result from the specified resource
 *
 * @param queryResource
 * @return
 * @throws RepositoryException
 * @throws IOException
 */
protected TupleQueryResult readExpectedTupleQueryResult(String resultFile) throws Exception {
	QueryResultFormat tqrFormat = QueryResultIO.getParserFormatForFileName(resultFile).get();

	if (tqrFormat != null) {
		InputStream in = SPARQLBaseTest.class.getResourceAsStream(resultFile);
		if (in == null) {
			throw new IOException("File could not be opened: " + resultFile);
		}

		try {
			TupleQueryResultParser parser = QueryResultIO.createTupleParser(tqrFormat);

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

			parser.parseQueryResult(in);
			return qrBuilder.getQueryResult();
		} finally {
			in.close();
		}
	} else {
		Set<Statement> resultGraph = readExpectedGraphQueryResult(resultFile);
		return DAWGTestResultSetUtil.toTupleQueryResult(resultGraph);
	}
}
 
Example #23
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testFilterRegexBoolean() throws Exception {
	loadTestData("/testdata-query/dataset-query.trig");

	// test case for issue SES-1050
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append(" SELECT *");
	query.append(" WHERE { ");
	query.append("       ?x foaf:name ?name ; ");
	query.append("          foaf:mbox ?mbox . ");
	query.append("       FILTER(EXISTS { ");
	query.append("            FILTER(REGEX(?name, \"Bo\") && REGEX(?mbox, \"bob\")) ");
	// query.append(" FILTER(REGEX(?mbox, \"bob\")) ");
	query.append("            } )");
	query.append(" } ");

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

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

		assertTrue(result.hasNext());
		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			// System.out.println(bs);
		}
		assertEquals(1, count);
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #24
Source File: SPARQLStoreConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
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 { [] foaf:name ?name;");
	queryBuilder.append("            foaf:mbox ?mbox. }");

	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString());
	query.setBinding("name", nameBob);

	try (TupleQueryResult result = query.evaluate()) {
		assertTrue(result != null);
		assertTrue(result.hasNext());

		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertTrue(solution.hasBinding("name"));
			assertTrue(solution.hasBinding("mbox"));

			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);
		}
	}
}
 
Example #25
Source File: CascadeValueExceptionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testValueExceptionGreaterThanPlain() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryStrGT);
	try (TupleQueryResult evaluate = query.evaluate()) {
		assertFalse(evaluate.hasNext());
	}
}
 
Example #26
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSES1073InverseSymmetricPattern() throws Exception {
	IRI a = f.createIRI("http://example.org/a");
	IRI b1 = f.createIRI("http://example.org/b1");
	IRI b2 = f.createIRI("http://example.org/b2");
	IRI c1 = f.createIRI("http://example.org/c1");
	IRI c2 = f.createIRI("http://example.org/c2");
	IRI a2b = f.createIRI("http://example.org/a2b");
	IRI b2c = f.createIRI("http://example.org/b2c");
	conn.add(a, a2b, b1);
	conn.add(a, a2b, b2);
	conn.add(b1, b2c, c1);
	conn.add(b2, b2c, c2);
	String query = "select * ";
	query += "where{ ";
	query += "?c1 ^<http://example.org/b2c>/^<http://example.org/a2b>/<http://example.org/a2b>/<http://example.org/b2c> ?c2 . ";
	query += " } ";
	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	try (TupleQueryResult result = tq.evaluate();) {
		assertTrue(result.hasNext());
		int count = 0;
		while (result.hasNext()) {
			BindingSet r = result.next();
			// System.out.println(r);
			count++;
		}
		assertEquals(4, count);
	}
}
 
Example #27
Source File: ProtocolTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private TupleQueryResult evaluateTupleQuery(String location, String query, QueryLanguage queryLn) throws Exception {
	location += "?query=" + URLEncoder.encode(query, "UTF-8") + "&queryLn=" + queryLn.getName();

	URL url = new URL(location);

	HttpURLConnection conn = (HttpURLConnection) url.openConnection();

	// Request SPARQL-XML formatted results:
	conn.setRequestProperty("Accept", TupleQueryResultFormat.SPARQL.getDefaultMIMEType());

	conn.connect();

	try {
		int responseCode = conn.getResponseCode();
		// HTTP 200
		if (responseCode == HttpURLConnection.HTTP_OK) {
			// Process query results
			return QueryResultIO.parseTuple(conn.getInputStream(), TupleQueryResultFormat.SPARQL);
		} else {
			String response = "location " + location + " responded: " + conn.getResponseMessage() + " ("
					+ responseCode + ")";
			fail(response);
			throw new RuntimeException(response);
		}
	} finally {
		conn.disconnect();
	}
}
 
Example #28
Source File: AbstractQueryResultIOTupleTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public final void testRDFStarCompatibility() throws IOException {
	ValueFactory vf = SimpleValueFactory.getInstance();

	List<String> bindingNames = Arrays.asList("a", "b", "c");
	List<BindingSet> bindings = new ArrayList<>();
	MapBindingSet bs1 = new MapBindingSet();
	// Note that the CSV format seems to ignore the datatype and assume it's xsd:integer
	// so no other datatype works with it properly.
	bs1.addBinding("a", vf.createLiteral("1984", XMLSchema.INTEGER));
	bs1.addBinding("b", vf.createIRI("urn:test"));
	bs1.addBinding("c", vf.createBNode("bnode1"));
	bindings.add(bs1);
	MapBindingSet bs2 = new MapBindingSet();
	bs2.addBinding("a", vf.createLiteral("foo"));
	bs2.addBinding("b", vf.createTriple(vf.createBNode("bnode2"), RDFS.LABEL,
			vf.createLiteral("\"literal with\tfunny\nchars")));
	bs2.addBinding("c", vf.createTriple(vf.createTriple(vf.createTriple(vf.createIRI("urn:a"), RDF.TYPE,
			vf.createIRI("urn:b")), vf.createIRI("urn:c"), vf.createIRI("urn:d")), vf.createIRI("urn:e"),
			vf.createIRI("urn:f")));
	bindings.add(bs2);

	try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
		QueryResultIO.writeTuple(new IteratingTupleQueryResult(bindingNames, bindings), getTupleFormat(), bos);
		System.out.println(bos.toString());
		try (ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray())) {
			TupleQueryResult parsedBindings = QueryResultIO.parseTuple(bis, getTupleFormat());
			assertEquals(bindingNames, parsedBindings.getBindingNames());
			List<BindingSet> actualBindings = new ArrayList<>();
			parsedBindings.forEach(actualBindings::add);
			assertEquals(bindings, actualBindings);
		}
	}
}
 
Example #29
Source File: RepositoryFederatedServiceIntegrationTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<BindingSet> evaluateQuery(String query) {
	try (RepositoryConnection conn = localRepo.getConnection()) {
		try (TupleQueryResult tqr = conn.prepareTupleQuery(query).evaluate()) {
			return Iterations.asList(tqr);
		}
	}
}
 
Example #30
Source File: QueryEvaluator.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/***
 * Evaluate a tuple query, and create an XML results document. This method completes writing of the response. !paged
 * means use all results.
 *
 * @param builder     response builder helper for generating the XML response to the client, which <em>must not</em>
 *                    have had start() called on it
 * @param xslPath     needed to begin writing response body after writing result count cookie
 * @param req         needed to write result count cookie
 * @param resp        needed to write result count cookie
 * @param cookies     needed to write result count cookie
 * @param query       the query to be evaluated
 * @param writeCookie whether to write the total result count cookie
 * @param paged       whether to display a limited subset
 * @throws QueryResultHandlerException
 */
public void evaluateTupleQuery(final TupleResultBuilder builder, String xslPath, WorkbenchRequest req,
		HttpServletResponse resp, CookieHandler cookies, final TupleQuery query, boolean writeCookie, boolean paged,
		int offset, int limit) throws QueryEvaluationException, QueryResultHandlerException {
	final TupleQueryResult result = query.evaluate();
	final String[] names = result.getBindingNames().toArray(new String[0]);
	List<BindingSet> bindings = Iterations.asList(result);
	if (writeCookie) {
		cookies.addTotalResultCountCookie(req, resp, bindings.size());
	}
	builder.transform(xslPath, "tuple.xsl");
	builder.start();
	builder.variables(names);
	builder.link(Arrays.asList(INFO));
	final List<Object> values = new ArrayList<>(names.length);
	if (paged && writeCookie) {
		// Only in this case do we have paged results, but were given the full
		// query. Just-in-case parameter massaging below to avoid array index
		// issues.
		int fromIndex = Math.min(0, offset);
		bindings = bindings.subList(fromIndex, Math.max(fromIndex, Math.min(offset + limit, bindings.size())));
	}
	for (BindingSet set : bindings) {
		addResult(builder, names, values, set);
	}
	builder.end();
}