Java Code Examples for org.eclipse.rdf4j.query.TupleQueryResult#close()

The following examples show how to use org.eclipse.rdf4j.query.TupleQueryResult#close() . 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: 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 2
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 3
Source File: TBSSSummariesGenerator.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 = getPredQury(graph);
	SPARQLRepository repo = createSPARQLRepository(endPointUrl);
	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);	  		
		}
		res.close();
	} finally {
		conn.close();
	}
	return predLst;
}
 
Example 4
Source File: SummaryGenerator.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 5
Source File: SPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 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().createIRI(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 6
Source File: TriGParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parseNegativeTriGSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl,
		String manifestBaseUrl, RepositoryConnection con) throws Exception {
	StringBuilder negativeQuery = new StringBuilder();
	negativeQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	negativeQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	negativeQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	negativeQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	negativeQuery.append(" WHERE { \n");
	negativeQuery.append("     ?test a rdft:TestTrigNegativeSyntax . ");
	negativeQuery.append("     ?test mf:name ?testName . ");
	negativeQuery.append("     ?test mf:action ?inputURL . ");
	negativeQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeQuery.toString()).evaluate();

	// Add all negative parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), manifestBaseUrl);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testBaseUrl + nextTestFile;

		suite.addTest(new NegativeParserTest(nextTestUri, nextTestName, nextInputURL, nextBaseUrl,
				createTriGParser(), FailureMode.DO_NOT_IGNORE_FAILURE));
	}

	queryResult.close();

}
 
Example 7
Source File: SparqlRegexTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBinding() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBinding);
	query.setBinding("pattern", vf.createLiteral("@work.example"));
	TupleQueryResult result = query.evaluate();
	assertEquals(hunt, result.next().getValue("name"));
	assertFalse(result.hasNext());
	result.close();
}
 
Example 8
Source File: SPARQLRepositoryPerformance.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param args
 */
public static void main(String[] args) throws Exception {

	SPARQLRepository repo = new SPARQLRepository("http://10.212.10.29:8081/openrdf-sesame/repositories/drugbank");
	repo.init();

	RepositoryConnection conn = null;
	TupleQueryResult qRes = null;
	try {

		conn = repo.getConnection();

		TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * WHERE { ?x ?y ?z } LIMIT 100");
		qRes = q.evaluate();

		while (qRes.hasNext()) {
			qRes.next();
		}
		System.out.println("Done.");
		;
	} finally {
		if (qRes != null) {
			qRes.close();
		}
		if (conn != null) {
			conn.close();
		}
	}
	repo.shutDown();

}
 
Example 9
Source File: AbstractNTriplesParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parsePositiveNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri,
		RepositoryConnection con) throws Exception {
	StringBuilder positiveQuery = new StringBuilder();
	positiveQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	positiveQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	positiveQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	positiveQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	positiveQuery.append(" WHERE { \n");
	positiveQuery.append("     ?test a rdft:TestNTriplesPositiveSyntax . ");
	positiveQuery.append("     ?test mf:name ?testName . ");
	positiveQuery.append("     ?test mf:action ?inputURL . ");
	positiveQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, positiveQuery.toString()).evaluate();

	// Add all positive parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), testLocationBaseUri);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testLocationBaseUri + nextTestFile;

		suite.addTest(new PositiveParserTest(nextTestUri, nextTestName, nextInputURL, null, nextBaseUrl,
				createRDFParser(), createRDFParser()));
	}

	queryResult.close();

}
 
Example 10
Source File: SparqlSetBindingTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBinding() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBinding);
	query.setBinding("name", ringo);
	TupleQueryResult result = query.evaluate();
	assertEquals(ringo, result.next().getValue("name"));
	assertFalse(result.hasNext());
	result.close();
}
 
Example 11
Source File: AbstractQueryResultIOTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected void doTupleNoLinks(TupleQueryResultFormat format, TupleQueryResult input, TupleQueryResult expected)
		throws IOException, QueryResultParseException, UnsupportedQueryResultFormatException,
		QueryEvaluationException, QueryResultHandlerException {
	ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
	QueryResultIO.writeTuple(input, format, out);
	input.close();

	// System.out.println("output: " + out.toString("UTF-8"));

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	TupleQueryResult output = parseTupleInternal(format, in);

	assertQueryResultsEqual(expected, output);
}
 
Example 12
Source File: TriGParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parsePositiveTriGSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl,
		String testLocationBaseUri, RepositoryConnection con) throws Exception {
	StringBuilder positiveQuery = new StringBuilder();
	positiveQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	positiveQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	positiveQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	positiveQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	positiveQuery.append(" WHERE { \n");
	positiveQuery.append("     ?test a rdft:TestTrigPositiveSyntax . ");
	positiveQuery.append("     ?test mf:name ?testName . ");
	positiveQuery.append("     ?test mf:action ?inputURL . ");
	positiveQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, positiveQuery.toString()).evaluate();

	// Add all positive parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), testLocationBaseUri);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testBaseUrl + nextTestFile;

		suite.addTest(new PositiveParserTest(nextTestUri, nextTestName, nextInputURL, null, nextBaseUrl,
				createTriGParser(), createNQuadsParser()));
	}

	queryResult.close();

}
 
Example 13
Source File: Cardinality.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
private static long executeQuery(RepositoryConnection conn, String queryString) {
	long results = 0;
	TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	//System.out.println(queryString);
	TupleQueryResult result = tupleQuery.evaluate();
	try {
		while(result.hasNext())
		{
			results = (long) Double.parseDouble(result.next().getValue("card").stringValue());
		}
	} finally {
		result.close();
	}
	return results;
}
 
Example 14
Source File: SparqlSetBindingTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBindingSubselect() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBindingSubselect);
	query.setBinding("x", ringoRes);
	TupleQueryResult result = query.evaluate();
	assertEquals(ringo, result.next().getValue("name"));
	assertFalse(result.hasNext());
	result.close();
}
 
Example 15
Source File: AbstractNTriplesParserTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parseNegativeNTriplesSyntaxTests(TestSuite suite, String fileBasePath, String testLocationBaseUri,
		RepositoryConnection con) throws Exception {
	StringBuilder negativeQuery = new StringBuilder();
	negativeQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	negativeQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	negativeQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	negativeQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	negativeQuery.append(" WHERE { \n");
	negativeQuery.append("     ?test a rdft:TestNTriplesNegativeSyntax . ");
	negativeQuery.append("     ?test mf:name ?testName . ");
	negativeQuery.append("     ?test mf:action ?inputURL . ");
	negativeQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeQuery.toString()).evaluate();

	// Add all negative parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).toString();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), testLocationBaseUri);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testLocationBaseUri + nextTestFile;

		suite.addTest(new NegativeParserTest(nextTestUri, nextTestName, nextInputURL, nextBaseUrl,
				createRDFParser(), FailureMode.DO_NOT_IGNORE_FAILURE));
	}

	queryResult.close();

}
 
Example 16
Source File: SparqlAggregatesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testConcat() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, concatMbox);
	TupleQueryResult result = query.evaluate();
	assertTrue(result.hasNext());
	assertNotNull(result.next().getValue("mbox"));
	assertNotNull(result.next().getValue("mbox"));
	assertFalse(result.hasNext());
	result.close();
}
 
Example 17
Source File: SparqlAggregatesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testConcatOptional() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, concatOptionalMbox);
	TupleQueryResult result = query.evaluate();
	assertTrue(result.hasNext());
	result.next();
	result.next();
	result.next();
	assertFalse(result.hasNext());
	result.close();
}
 
Example 18
Source File: TupleQueryResultTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetBindingNames() throws Exception {
	TupleQueryResult result = con.prepareTupleQuery(QueryLanguage.SERQL, multipleResultQuery).evaluate();
	try {
		List<String> headers = result.getBindingNames();

		assertThat(headers.get(0)).isEqualTo("P").as("first header element");
		assertThat(headers.get(1)).isEqualTo("D").as("second header element");
	} finally {
		result.close();
	}
}
 
Example 19
Source File: TurtleParserTestCase.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void parseNegativeTurtleSyntaxTests(TestSuite suite, String fileBasePath, String testBaseUrl,
		String manifestBaseUrl, RepositoryConnection con) throws Exception {
	StringBuilder negativeQuery = new StringBuilder();
	negativeQuery.append(" PREFIX mf:   <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n");
	negativeQuery.append(" PREFIX qt:   <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n");
	negativeQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n");
	negativeQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n");
	negativeQuery.append(" WHERE { \n");
	negativeQuery.append("     ?test a rdft:TestTurtleNegativeSyntax . ");
	negativeQuery.append("     ?test mf:name ?testName . ");
	negativeQuery.append("     ?test mf:action ?inputURL . ");
	negativeQuery.append(" }");

	TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeQuery.toString()).evaluate();

	// Add all negative parser tests to the test suite
	while (queryResult.hasNext()) {
		BindingSet bindingSet = queryResult.next();
		IRI nextTestUri = (IRI) bindingSet.getValue("test");
		String nextTestName = ((Literal) bindingSet.getValue("testName")).getLabel();
		String nextTestFile = removeBase(((IRI) bindingSet.getValue("inputURL")).toString(), manifestBaseUrl);
		String nextInputURL = fileBasePath + nextTestFile;

		String nextBaseUrl = testBaseUrl + nextTestFile;

		suite.addTest(new NegativeParserTest(nextTestUri, nextTestName, nextInputURL, nextBaseUrl,
				createTurtleParser(), FailureMode.DO_NOT_IGNORE_FAILURE));
	}

	queryResult.close();

}
 
Example 20
Source File: QueryEvaluation.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
public Map<String, List<List<Object>>> evaluate(String queries, String cfgName, List<String> endpoints) throws Exception {
	List<List<Object>> report = new ArrayList<List<Object>>();
	List<List<Object>> sstreport = new ArrayList<List<Object>>();
	Map<String, List<List<Object>>> result = new HashMap<String, List<List<Object>>>();
	result.put("report", report);
	result.put("sstreport", sstreport);
	
	List<String> qnames = Arrays.asList(queries.split(" "));
	for (String curQueryName : qnames)
	{
		List<Object> reportRow = new ArrayList<Object>();
		report.add(reportRow);
		String curQuery = qp.getQuery(curQueryName);
		reportRow.add(curQueryName);
		
		List<Object> sstReportRow = new ArrayList<Object>();
		sstreport.add(sstReportRow);
		sstReportRow.add(curQueryName);
		
		Config config = new Config(cfgName);
		SailRepository repo = null;
		TupleQueryResult res = null;
		
		try {
			repo = FedXFactory.initializeSparqlFederation(config, endpoints);
			TupleQuery query = repo.getConnection().prepareTupleQuery(QueryLanguage.SPARQL, curQuery);
			
		   	long startTime = System.currentTimeMillis();
		   	res = query.evaluate();
		    long count = 0;
		
		    while (res.hasNext()) {
		    	BindingSet row = res.next();
		    	System.out.println(count+": "+ row);
		    	count++;
		    }
		  
		    long runTime = System.currentTimeMillis() - startTime;
		    reportRow.add((Long)count); reportRow.add((Long)runTime);
		    sstReportRow.add((Long)count);
		    sstReportRow.add(QueryInfo.queryInfo.get().numSources.longValue());
		    sstReportRow.add(QueryInfo.queryInfo.get().totalSources.longValue());
		    log.info(curQueryName + ": Query exection time (msec): "+ runTime + ", Total Number of Records: " + count + ", Source count: " + QueryInfo.queryInfo.get().numSources.longValue());
		    //log.info(curQueryName + ": Query exection time (msec): "+ runTime + ", Total Number of Records: " + count + ", Source Selection Time: " + QueryInfo.queryInfo.get().getSourceSelection().time);
		} catch (Throwable e) {
			e.printStackTrace();
			log.error("", e);
			File f = new File("results/" + curQueryName + ".error.txt");
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			PrintStream ps = new PrintStream(os);
			e.printStackTrace(ps);
			ps.flush();
			FileUtils.write(f, os.toString("UTF8"));
			reportRow.add(null); reportRow.add(null);
		} finally {
			if (null != res) {
	    		res.close();
	    	}
			
	    	if (null != repo) {
	    	    repo.shutDown();
	    	}
        }
	}
	return result;
}