org.openrdf.query.TupleQuery Java Examples

The following examples show how to use org.openrdf.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: TestTicket632.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final URI serviceUri, final SailRepository repo) throws RepositoryException, MalformedQueryException, QueryEvaluationException, RDFParseException, IOException, RDFHandlerException {
    try {
        repo.initialize();
        final RepositoryConnection conn = repo.getConnection();
        final ValueFactory vf = conn.getValueFactory();
        conn.setAutoCommit(false);
        try {
            final String query = "SELECT ?x { SERVICE <" + serviceUri.stringValue() + "> { ?x <u:1> ?bool1 } }";
            final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
            q.setBinding("bool1", vf.createLiteral(true));
            final TupleQueryResult tqr = q.evaluate();
            try {
                tqr.hasNext();
            } finally {
                tqr.close();
            }
        } finally {
            conn.close();
        }
    } finally {
        repo.shutDown();
    }
}
 
Example #2
Source File: TestTicket967.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void addDuringQueryExec(final RepositoryConnection conn,
	final Resource subj, final URI pred, final Value obj,
	final Resource... ctx) throws RepositoryException,
	MalformedQueryException, QueryEvaluationException {
final TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL,
      		"select distinct ?s ?p ?o where{?s ?p ?t . ?t <http://www.w3.org/2000/01/rdf-schema#subClassOf> ?o }"
      		);
      tq.setBinding("s", subj);
      tq.setBinding("p", pred);
      tq.setBinding("o", obj);
      final TupleQueryResult tqr = tq.evaluate();
      try {
          if (!tqr.hasNext()) {
              conn.add(subj, pred, obj, ctx);
          }
      } finally {
          tqr.close();
      }
  }
 
Example #3
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private int size(URI defaultGraph)
	throws RepositoryException, MalformedQueryException, QueryEvaluationException
{
	TupleQuery qry = testCon.prepareTupleQuery(QueryLanguage.SPARQL, "SELECT * { ?s ?p ?o }");
	DatasetImpl dataset = new DatasetImpl();
	dataset.addDefaultGraph(defaultGraph);
	qry.setDataset(dataset);
	TupleQueryResult result = qry.evaluate();
	try {
		int count = 0;
		while (result.hasNext()) {
			result.next();
			count++;
		}
		return count;
	}
	finally {
		result.close();
	}
}
 
Example #4
Source File: SesameDriver.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public Collection<? extends SesameMatch> runQuery(final RailwayQuery query, final String queryDefinition)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final Collection<SesameMatch> results = new ArrayList<>();

	final TupleQuery tupleQuery = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryDefinition);
	final TupleQueryResult queryResults = tupleQuery.evaluate();
	try {
		while (queryResults.hasNext()) {
			final BindingSet bs = queryResults.next();
			final SesameMatch match = SesameMatch.createMatch(query, bs);
			results.add(match);
		}
	} finally {
		queryResults.close();
	}

	return results;
}
 
Example #5
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Override
  protected void doInsertWithBodyTest(final String method, final int ntriples,
          /*final String servlet,*/ final RDFFormat format) throws Exception {

      final Graph g = genNTRIPLES2(ntriples);
      cxn.add(g);
      assertEquals(ntriples, getExactSize());
      
// Verify the expected #of statements in the store.
{
	final String queryStr = "select * where {?s ?p ?o}";
	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
	assertEquals(ntriples, countResults(query.evaluate()));
}

  }
 
Example #6
Source File: TestBigdataSailRemoteRepository.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void test_INSERT_triples_with_BODY_and_defaultContext()
        throws Exception {

    if(TestMode.quads != getTestMode())
        return;

    final String resource = packagePath
            + "insert_triples_with_defaultContext.ttl";

    final Graph g = loadGraphFromResource(resource);

    // Load the resource into the KB.
    doInsertByBody("POST", RDFFormat.TURTLE, g, new URIImpl(
            "http://example.org"));
    
    // Verify that the data were inserted into the appropriate context.
    {
    	final String queryStr = "select * { GRAPH <http://example.org> {?s ?p ?p} }";
    	final TupleQuery query = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		assertEquals(7, countResults(query.evaluate()));
    }

}
 
Example #7
Source File: SampleBlazegraphSesameEmbedded.java    From blazegraph-samples with GNU General Public License v2.0 6 votes vote down vote up
public static TupleQueryResult executeSelectQuery(final Repository repo, final String query,
		final QueryLanguage ql) throws OpenRDFException  {

	RepositoryConnection cxn;
	if (repo instanceof BigdataSailRepository) {
		cxn = ((BigdataSailRepository) repo).getReadOnlyConnection();
	} else {
		cxn = repo.getConnection();
	}

	try {

		final TupleQuery tupleQuery = cxn.prepareTupleQuery(ql, query);
		tupleQuery.setIncludeInferred(true /* includeInferred */);
		return tupleQuery.evaluate();
		
	} finally {
		// close the repository connection
		cxn.close();
	}
}
 
Example #8
Source File: Test_Ticket_1717.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Test supposed to check if constants in BIND expressions will be resolved
 */
public void test_ticket_1717() throws Exception {

   {
     // Clear DB per task description (Executing the query over the empty database)
     m_repo.remove(new RemoveOp(null, null, null));
     String query = "SELECT ?z ?s1 {  ?s ?p ?o .   BIND(?o+1 AS ?z)  BIND(?z+1 AS ?z2) }";
     final TupleQuery tq = m_repo.getBigdataSailRemoteRepository().getConnection().prepareTupleQuery(QueryLanguage.SPARQL, query, null);
       final TupleQueryResult tqr = tq.evaluate();
       try {
           int count = 0;
           while (tqr.hasNext()) {
               System.out.println(tqr.next());
               count++;
            }
           assertEquals(0,count); // asserting successful execution of the query, as it was failing while parsing
       } finally {
            tqr.close();
       }
   }
}
 
Example #9
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) throws Exception
{
	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 #10
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) throws Exception {
	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 #11
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get total number of distinct objects of a dataset
 * @return count
 */
public static long getObjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?o) AS ?objts) " + // 
			"WHERE " +
			"{" +
       		"?s ?p ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("objts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example #12
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 subjects of a dataset
 * @return count 
 */
public static long getSubjectCount(String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?sbjts) " + // 
			"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("sbjts").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example #13
Source File: RDFSContainer.java    From anno4j with Apache License 2.0 6 votes vote down vote up
private TupleQuery createBlockQuery(int b) throws RepositoryException {
	StringBuilder sb = new StringBuilder();
	sb.append("SELECT ?pred ?value ?value_class\n");
	sb.append("WHERE { $self ?pred ?value\n");
	sb.append("OPTIONAL { ?value a ?value_class }\n");
	sb.append("FILTER (");
	for (int i = b * BSIZE, n = b * BSIZE + BSIZE; i < n; i++) {
		sb.append("?pred = <");
		sb.append(RDF.NAMESPACE);
		sb.append("_");
		sb.append((i + 1));
		sb.append(">");
		if (i + 1 < n) {
			sb.append(" || ");
		}
	}
	sb.append(")}\n");
	ObjectConnection con = getObjectConnection();
	try {
		TupleQuery query = con.prepareTupleQuery(SPARQL, sb.toString());
		query.setBinding("self", getResource());
		return query;
	} catch (MalformedQueryException e) {
		throw new RepositoryException(e);
	}
}
 
Example #14
Source File: ObjectQueryFactory.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public ObjectQuery createQuery(PropertySetFactory factory)
		throws RepositoryException {
	synchronized (queries) {
		ObjectQuery query = queries.remove(factory);
		if (query != null)
			return query;
	}
	Class<?> type = factory.getPropertyType();
	Map<String, String> properties = mapper.findEagerProperties(type);
	if (properties == null)
		return null;
	// TODO this should be a static string
	String sparql = buildQuery(properties, factory);
	try {
		TupleQuery tuples = connection.prepareTupleQuery(SPARQL, sparql);
		return new ObjectQuery(connection, tuples);
	} catch (MalformedQueryException e) {
		throw new RepositoryException(e);
	}
}
 
Example #15
Source File: FieldPredicateTest.java    From anno4j with Apache License 2.0 6 votes vote down vote up
public void testReadAccess() throws Exception {
	ValueFactory vf = con.getValueFactory();
	URI graph = vf.createURI("urn:test:graph");
	con.setAddContexts(graph);
	Company c = new Company();
	c = (Company) con.getObject(con.addObject(c));
	c.setName("My Company");
	assertEquals("My Company", c.getName());
	TupleQuery query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	TupleQueryResult results = query.evaluate();
	Value g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
	con.setAddContexts();
	assertEquals("My Company", c.getName());
	query = con.prepareTupleQuery("SELECT ?g WHERE {GRAPH ?g {?o <urn:test:name> ?name}}");
	query.setBinding("name", vf.createLiteral("My Company"));
	results = query.evaluate();
	g = results.next().getValue("g");
	results.close();
	assertEquals(graph, g);
}
 
Example #16
Source File: Test_Ticket_789.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void test_ticket_1326_dataset() throws Exception {
	populate();
	
	BigdataSailRemoteRepository sailRepo = m_repo.getBigdataSailRemoteRepository();
	BigdataSailRemoteRepositoryConnection con = sailRepo.getConnection();
	final TupleQuery tq = con.prepareTupleQuery(QueryLanguage.SPARQL, "select * where {?s ?p ?o}");

	final DatasetImpl dataset = new DatasetImpl();
	dataset.addDefaultGraph(defaultGraph1);

	tq.setDataset(dataset);
	{
		TupleQueryResult tqr = tq.evaluate();
		try {
			int count = 0;
			while (tqr.hasNext()) {
				tqr.next();
				count++;
			}
			// there is only 1 statement in defaultGraph1 
			assertEquals(1, count);
		} finally {
			tqr.close();
		}
	}
}
 
Example #17
Source File: Concurrency.java    From database with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Issue the query.
 * 
 * @throws Exception
 */
private void doQuery() throws Exception {
   
    RepositoryConnection cxn = repo.getReadOnlyConnection();
    try {

        final TupleQuery tupleQuery = 
            cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
        tupleQuery.setIncludeInferred(true /* includeInferred */);
        TupleQueryResult result = tupleQuery.evaluate();
        // do something with the results
        int resultCount = 0;
        while (result.hasNext()) {
            BindingSet bindingSet = result.next();
            // log.info(bindingSet);
            resultCount++;
        }
        log.info(resultCount + " results");
        
    } finally {
        // close the repository connection
        cxn.close();
    }
        
}
 
Example #18
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testOrPredicate()
	throws Exception
{
	String union = "{ :s ?p :o FILTER (?p = :p1 || ?p = :p2) }";
	URI s = vf.createURI("urn:test:s");
	URI p1 = vf.createURI(URN_TEST_P1);
	URI p2 = vf.createURI(URN_TEST_P2);
	URI o = vf.createURI("urn:test:o");
	testCon.add(s, p1, o);
	testCon.add(s, p2, o);
	String qry = "PREFIX :<urn:test:> SELECT ?p WHERE " + union;
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SPARQL, qry);
	TupleQueryResult result = query.evaluate();
	List<Value> list = new ArrayList<Value>();
	while (result.hasNext()) {
		BindingSet bindings = result.next();
		list.add(bindings.getValue("p"));
	}
	result.close();
	assertThat(list, hasItem(p1));
	assertThat(list, hasItem(p2));
}
 
Example #19
Source File: RepositoryConnectionTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testOptionalFilter()
	throws Exception
{
	String optional = "{ ?s :p1 ?v1 OPTIONAL {?s :p2 ?v2 FILTER(?v1<3) } }";
	URI s = vf.createURI("urn:test:s");
	URI p1 = vf.createURI(URN_TEST_P1);
	URI p2 = vf.createURI(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);
	TupleQueryResult result = query.evaluate();
	Set<List<Value>> set = new HashSet<List<Value>>();
	while (result.hasNext()) {
		BindingSet bindings = result.next();
		set.add(Arrays.asList(bindings.getValue("v1"), bindings.getValue("v2")));
	}
	result.close();
	assertThat(set, hasItem(Arrays.asList(v1, v2)));
	assertThat(set, hasItem(Arrays.asList(v3, null)));
}
 
Example #20
Source File: SPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
protected static String getManifestName(Repository manifestRep, RepositoryConnection con,
		String manifestFileURL)
	throws QueryEvaluationException, RepositoryException, MalformedQueryException
{
	// Try to extract suite name from manifest file
	TupleQuery manifestNameQuery = con.prepareTupleQuery(QueryLanguage.SERQL,
			"SELECT ManifestName FROM {ManifestURL} rdfs:label {ManifestName}");
	manifestNameQuery.setBinding("ManifestURL", manifestRep.getValueFactory().createURI(manifestFileURL));
	TupleQueryResult manifestNames = manifestNameQuery.evaluate();
	try {
		if (manifestNames.hasNext()) {
			return manifestNames.next().getValue("ManifestName").stringValue();
		}
	}
	finally {
		manifestNames.close();
	}

	// Derive name from manifest URL
	int lastSlashIdx = manifestFileURL.lastIndexOf('/');
	int secLastSlashIdx = manifestFileURL.lastIndexOf('/', lastSlashIdx - 1);
	return manifestFileURL.substring(secLastSlashIdx + 1, lastSlashIdx);
}
 
Example #21
Source File: LoadPdb.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public static void executeSelectQuery(Repository repo, String query) throws Exception {

		RepositoryConnection cxn = repo.getConnection();
		int counter = 0;
		try {

			final TupleQuery tupleQuery = cxn.prepareTupleQuery(QueryLanguage.SPARQL, query);
			tupleQuery.setIncludeInferred(true /* includeInferred */);
			TupleQueryResult result = tupleQuery.evaluate();
			// do something with the results
			while (result.hasNext()) {
				BindingSet bindingSet = result.next();
				LOG.info(bindingSet);
				counter++;
			}

		} finally {
			// close the repository connection
			cxn.close();
//			LOG.info
            System.err.println
            ("Number of results: " + counter);
		}

	}
 
Example #22
Source File: SPARQLInferenceTest.java    From neo4j-sparql-extension with GNU General Public License v3.0 6 votes vote down vote up
@Before
public void before()
		throws RepositoryException, IOException, RDFParseException,
		       MalformedQueryException, QueryResultParseException,
			   QueryResultHandlerException {
	repo = new SailRepository(new MemoryStore());
	repo.initialize();
	conn = repo.getConnection();
	vf = conn.getValueFactory();
	conn.add(getResource(data), "file://", RDFFormat.TURTLE);
	SPARQLResultsXMLParserFactory factory =
			new SPARQLResultsXMLParserFactory();
	parser = factory.getParser();
	parser.setValueFactory(vf);
	List<Rule> rules;
	rules = Rules.fromOntology(getResource(data));
	QueryRewriter rewriter = new QueryRewriter(conn, rules);
	query = (TupleQuery) rewriter.rewrite(QueryLanguage.SPARQL, queryString);
	nonInfQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString);
	System.out.println("== QUERY (" + this.name + ") ==");
	System.out.println(nonInfQuery);
	System.out.println("== REWRITTEN QUERY (" + this.name + ") ==");
	System.out.println(query);
}
 
Example #23
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testSES1991STRUUIDEvaluation()
	throws Exception
{
	loadTestData("/testdata-query/defaultgraph.ttl");
	String query = "SELECT ?uid WHERE {?s ?p ?o . BIND(STRUUID() as ?uid) } LIMIT 2";

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

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

		Literal uid1 = (Literal)result.next().getValue("uid");
		Literal uid2 = (Literal)result.next().getValue("uid");

		assertNotNull(uid1);
		assertFalse(uid1.equals(uid2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example #24
Source File: TestTicket1755.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
	private void testQuery(final BigdataSailRepositoryConnection conn,
			final String query, final int expectedIVs) throws MalformedQueryException, RepositoryException, QueryEvaluationException {
		TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
		TupleQueryResult tqr = tq.evaluate();
		try {
			int cnt = 0;
			while (tqr.hasNext()) {
				tqr.next();
				cnt++;
			}
//			assertEquals("Expected 1 row in resultset", 1, cnt);
			QueryRoot queryRoot = ((BigdataSailTupleQuery)tq).getASTContainer().getOriginalAST();
			cnt = 0;
			for (Object filterNode: queryRoot.getWhereClause().getChildren(FilterNode.class)) {
				cnt += checkNode((BOp)filterNode);
			}
			assertEquals("Expected inlined IV for date literal", expectedIVs, cnt);
		} finally {
			tqr.close();
		}
	}
 
Example #25
Source File: TestTicket4249.java    From database with GNU General Public License v2.0 6 votes vote down vote up
private void executeQuery(final RepositoryConnection conn, final Literal string, final int start, final Literal expected)
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	final ValueFactory vf = conn.getValueFactory();
	final String query = "select ?substring WHERE { BIND ( SUBSTR(?string, ?start) as ?substring ) . }";
	final TupleQuery q = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
	q.setBinding("string", string);
	q.setBinding("start", vf.createLiteral(start));
	final TupleQueryResult tqr = q.evaluate();
	try {
		while (tqr.hasNext()) {
			final BindingSet bindings = tqr.next();
			// assert expected value
			assertEquals(expected, bindings.getBinding("substring").getValue());
		}
	} finally {
		tqr.close();
	}
}
 
Example #26
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInComparison3()
	throws Exception
{
	loadTestData("/testdata-query/dataset-ses1913.trig");
	StringBuilder query = new StringBuilder();
	query.append(" PREFIX : <http://example.org/>\n");
	query.append(" SELECT ?y WHERE { :a :p ?y. FILTER(?y in (:c, :d, 1, 1/0)) } ");

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

	TupleQueryResult result = tq.evaluate();
	assertNotNull(result);
	assertTrue(result.hasNext());

	BindingSet bs = result.next();
	Value y = bs.getValue("y");
	assertNotNull(y);
	assertTrue(y instanceof Literal);
	assertEquals(f.createLiteral("1", XMLSchema.INTEGER), y);
}
 
Example #27
Source File: SemagrowSummariesGenerator.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Get total number of distinct objects for a predicate
 * @param pred Predicate
 * @param m model
 * @return triples
 */
public static long getDistinctSbj(String pred, String endpoint) throws Exception {
	String strQuery = "SELECT  (COUNT(DISTINCT ?s) AS ?subjs) " + // 
			"WHERE " +
			"{" +
       		"?s <" + pred + "> ?o " +
       		"} " ;
	SPARQLRepository repo = new SPARQLRepository(endpoint);
	repo.initialize();
	RepositoryConnection conn = repo.getConnection();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, strQuery); 
		TupleQueryResult rs = query.evaluate();
		return Long.parseLong(rs.next().getValue("subjs").stringValue());
	} finally {
		conn.close();
		repo.shutDown();
	}
}
 
Example #28
Source File: SPARQLTupleStreamingOutput.java    From neo4j-sparql-extension with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new sparql tuple streaming output that executes a SPARQL
 * SELECT query and streams the result.
 * @param query the SELECT query to execute
 * @param writerFactory a result writer factory used to serialise the
 * results
 * @param conn the connection to use for query execution
 */
public SPARQLTupleStreamingOutput(
	TupleQuery query,
	TupleQueryResultWriterFactory writerFactory,
	RepositoryConnection conn) {
	super(conn);
	this.query = query;
	this.factory = writerFactory;
}
 
Example #29
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testPropertyPathInTree()
	throws Exception
{
	loadTestData("/testdata-query/dataset-query.trig");

	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append(" SELECT ?node ?name ");
	query.append(" FROM ex:tree-graph ");
	query.append(" WHERE { ?node ex:hasParent+ ex:b . ?node ex:name ?name . }");

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

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

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

			System.out.println(bs);

		}
		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example #30
Source File: ComplexSPARQLQueryTest.java    From database with GNU General Public License v2.0 5 votes vote down vote up
@Test
/**
 * @see http://www.openrdf.org/issues/browse/SES-1091
 * @throws Exception
 */
public void testArbitraryLengthPathWithFilter2()
	throws Exception
{
	loadTestData("/testdata-query/alp-testdata.ttl");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("SELECT ?parent ?child ");
	query.append("WHERE { ?child rdfs:subClassOf+ ?parent . FILTER (?parent = owl:Thing) }");

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

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

		int count = 0;
		while (result.hasNext()) {
			count++;
			BindingSet bs = result.next();
			assertTrue(bs.hasBinding("child"));
			assertTrue(bs.hasBinding("parent"));
		}
		assertEquals(4, count);
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}