Java Code Examples for org.openrdf.query.QueryLanguage

The following examples show how to use org.openrdf.query.QueryLanguage. These examples are extracted from open source projects. 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 Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testClearGraph()
	throws Exception
{
	logger.debug("executing testClearGraph");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("CLEAR GRAPH <" + graph1.stringValue() + "> ");

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

	operation.execute();
	assertFalse(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	assertTrue(con.hasStatement(null, null, null, false));
}
 
Example 2
@Test
public void testIdenticalVariablesInStatementPattern()
	throws Exception
{
	conn.add(alice, f.createURI("http://purl.org/dc/elements/1.1/publisher"), bob);

	StringBuilder queryBuilder = new StringBuilder();
	queryBuilder.append("SELECT ?publisher ");
	queryBuilder.append("{ ?publisher <http://purl.org/dc/elements/1.1/publisher> ?publisher }");

	conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBuilder.toString()).evaluate(
			new TupleQueryResultHandlerBase() {

				public void handleSolution(BindingSet bindingSet) {
					fail("nobody is self published");
				}
			});
}
 
Example 3
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCreateNewGraph()
	throws Exception
{
	logger.debug("executing testCreateNewGraph");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());

	URI newGraph = f.createURI(EX_NS, "new-graph");

	update.append("CREATE GRAPH <" + newGraph + "> ");

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

	operation.execute();
	assertTrue(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	assertFalse(con.hasStatement(null, null, null, false, newGraph));
	assertTrue(con.hasStatement(null, null, null, false));
}
 
Example 4
/**
 * 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 5
@Test
public void testInComparison1()
	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 , 1)) } ");

	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 6
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteDataFromGraph()
	throws Exception
{
	logger.debug("executing testDeleteDataFromGraph");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DELETE DATA { GRAPH ex:graph1 {ex:alice foaf:knows ex:bob. } } ");

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

	assertTrue(con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1));
	operation.execute();

	String msg = "statement should have been deleted from graph1";
	assertFalse(msg, con.hasStatement(alice, FOAF.KNOWS, bob, true, graph1));
}
 
Example 7
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDeleteTransformedWhere()
	throws Exception
{
	logger.debug("executing testDeleteTransformedWhere");

	StringBuilder update = new StringBuilder();
	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 = "ex:containsPerson properties should not have been deleted";
	assertTrue(msg, con.hasStatement(graph1, f.createURI(EX_NS, "containsPerson"), bob, true));
	assertTrue(msg, con.hasStatement(graph2, f.createURI(EX_NS, "containsPerson"), alice, true));

}
 
Example 8
/**
 * {@inheritDoc}
 * 
 * Logs the query at INFO and logs the optimized AST at TRACE.
 */
@Override
protected Stream<Statement> _project( 
        final String queryStr, final String extQueryId) {
    
    logQuery(queryStr);
    return Code.wrapThrow(() -> {
        final BigdataSailGraphQuery query = (BigdataSailGraphQuery) 
                cxn().prepareGraphQuery(QueryLanguage.SPARQL, queryStr);
        setMaxQueryTime(query);
        final UUID queryId = setupQuery(query.getASTContainer(), 
                                        QueryType.CONSTRUCT, extQueryId);
    
        sparqlLog.trace(() -> "optimized AST:\n"+query.optimize());
    
        /*
         * Result is closed automatically by GraphStreamer.
         */
        final GraphQueryResult result = query.evaluate();
        final Optional<Runnable> onClose = 
                Optional.of(() -> finalizeQuery(queryId));
        return new GraphStreamer<>(result, onClose).stream();
    });
    
}
 
Example 9
@Test
public void testDescribeA()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ex:a");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI a = f.createURI("http://example.org/a");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Value> objects = result.filter(a, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			assertTrue(result.contains((Resource)object, null, null));
			assertEquals(2, result.filter((Resource)object, null, null).size());
		}
	}
}
 
Example 10
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 11
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInsertEmptyWhere()
	throws Exception
{
	logger.debug("executing test testInsertEmptyWhere");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT { <" + bob + "> rdfs:label \"Bob\" . } WHERE { }");

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

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

	operation.execute();

	assertTrue(con.hasStatement(bob, RDFS.LABEL, f.createLiteral("Bob"), true));
}
 
Example 12
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDropGraph()
	throws Exception
{
	logger.debug("executing testDropGraph");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("DROP GRAPH <" + graph1.stringValue() + "> ");

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

	operation.execute();
	assertFalse(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	assertTrue(con.hasStatement(null, null, null, false));
}
 
Example 13
Source Project: trainbenchmark   Source File: SesameDriver.java    License: 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 14
Source Project: anno4j   Source File: ClazzBuildingSupport.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean hasPropertyTransitive(RDFSProperty property) throws RepositoryException {
    try {
        BooleanQuery query = getObjectConnection().prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   {" +
                        "       <" + property.getResourceAsString() + "> rdfs:domain <" + getResourceAsString() + "> . " +
                        "   }" +
                        "   UNION" +
                        "   {" +
                        "       <" + getResourceAsString() + "> rdfs:subClassOf+ ?s ." +
                        "       <" + property.getResourceAsString() + "> rdfs:domain ?s ." +
                        "   }" +
                        "}"
        );

        return query.evaluate();
    } catch (QueryEvaluationException | MalformedQueryException e) {
        throw new RepositoryException(e);
    }
}
 
Example 15
Source Project: anno4j   Source File: ClazzBuildingSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Whether the mapping for the given property needs to be redefined in this class.
 * This is the case if the class has a (direct) {@code owl:Restriction} on the property
 * for this class.
 * @param property The property to check for.
 * @return Returns true if the property mapping needs a redefinition in the Java class generated
 * for this class.
 * @throws RepositoryException Thrown if an error occurs while querying the repository.
 */
 boolean needsRedefinition(RDFSProperty property) throws RepositoryException {
    try {
        BooleanQuery query = getObjectConnection().prepareBooleanQuery(QueryLanguage.SPARQL,
                "ASK {" +
                        "   ?r a owl:Restriction . " +
                        "   <" + getResourceAsString() + "> rdfs:subClassOf ?r . " +
                        "   ?r owl:onProperty <" + property.getResourceAsString() + "> . " +
                        "}"
        );

        return query.evaluate();

    } catch (MalformedQueryException | QueryEvaluationException e) {
        throw new RepositoryException(e);
    }
}
 
Example 16
Source Project: anno4j   Source File: SchemaSanitizingObjectSupport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Complements transitive edges for transitive properties ({@code owl:TransitiveProperty}).
 * @throws RepositoryException Thrown if an error occurs while updating the repository.
 */
private void sanitizeTransitivity() throws RepositoryException {
    ObjectConnection connection = getObjectConnection();
    try {
        connection.prepareUpdate(QueryLanguage.SPARQL,
                "INSERT {" +
                        "   <" + getResourceAsString() + "> ?p ?z . " +
                        "} WHERE {" +
                        "   <" + getResourceAsString() + "> ?p ?y . " +
                        "   ?y ?p ?z . " +
                        "   ?p a owl:TransitiveProperty . " +
                        "}"
        ).execute();

    } catch (MalformedQueryException | UpdateExecutionException e) {
        throw new RepositoryException(e);
    }
}
 
Example 17
Source Project: database   Source File: TestTicket4249.java    License: 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 18
Source Project: anno4j   Source File: SchemaSanitizingObjectSupportTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEquivalenceSubpropertySanitizing() throws Exception {
    // Prepare the resources used in the test:
    SanitizingTestResource resource = anno4j.createObject(SanitizingTestResource.class);
    SanitizingTestResource x1 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x1"));
    SanitizingTestResource x2 = anno4j.createObject(SanitizingTestResource.class, (Resource) new URIImpl("urn:anno4j:x2"));

    // Declare x1,x2 equivalent:
    anno4j.getObjectRepository().getConnection().prepareUpdate(QueryLanguage.SPARQL,
            "INSERT DATA {" +
                    "   <" + x1 + "> owl:sameAs <" + x2 + "> . " +
                    "}"
    ).execute();

    // Setup values:
    resource.setObjectSubproperty(Sets.newHashSet(x2));
    assertEquals(Sets.newHashSet(x2), resource.getObjectSuperproperty());
    assertEquals(Sets.newHashSet(x2), resource.getObjectSubproperty());

    // Setting superproperty to equivalent value:
    resource.setObjectSuperproperty(Sets.newHashSet(x1));
    assertEquals(Sets.newHashSet(x1), resource.getObjectSuperproperty());
    assertEquals(Sets.newHashSet(x2), resource.getObjectSubproperty());
}
 
Example 19
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testDropDefault()
	throws Exception
{
	logger.debug("executing testDropDefault");

	String update = "DROP DEFAULT";

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

	// Verify statements exist in the named graphs.
	assertTrue(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	// Verify statements exist in the default graph.
	assertTrue(con.hasStatement(null, null, null, false, new Resource[] { null }));

	operation.execute();
	assertTrue(con.hasStatement(null, null, null, false, graph1));
	assertTrue(con.hasStatement(null, null, null, false, graph2));
	// Verify that no statements remain in the 'default' graph.
	assertFalse(con.hasStatement(null, null, null, false, new Resource[] { null }));

}
 
Example 20
public void testServiceNodeBindings() throws Exception {
        final BigdataSailRemoteRepository repo = m_repo.getBigdataSailRemoteRepository();
        final BigdataSailRemoteRepositoryConnection cxn = 
            (BigdataSailRemoteRepositoryConnection) repo.getConnection();
        
        try {
          String queryStr = "select * where {SERVICE <http://DBpedia.org/sparql> { <http://dbpedia.org/resource/Tonga_(Nyasa)_language> rdfs:label ?langLabel. }}";
//                String queryStr = "SELECT * WHERE { BIND (<http://dbpedia.org/resource/Tonga_(Nyasa)_language> AS ?ref) . SERVICE <http://DBpedia.org/sparql> { ?ref rdfs:label ?langLabel. } }";
            final org.openrdf.query.TupleQuery tq = cxn.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
            final TupleQueryResult tqr = tq.evaluate();
            try {
                int cnt = 0;
                while (tqr.hasNext()) {
                    tqr.next();
                    cnt++;
                }
                assertEquals(cnt, 2);
            } finally {
                tqr.close();
            }
        } finally {
            cxn.close();
        }
    }
 
Example 21
@Test
public void testSES2024PropertyPathAnonVarSharing() throws Exception {
	loadTestData("/testdata-query/dataset-ses2024.trig");
	String query = "PREFIX : <http://example.org/> SELECT * WHERE { ?x1 :p/:lit ?l1 . ?x1 :diff ?x2 . ?x2 :p/:lit ?l2 . }" ;

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

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

		BindingSet bs = result.next();
		Literal l1 = (Literal)bs.getValue("l1");
		Literal l2 = (Literal)bs.getValue("l2");

		assertNotNull(l1);
		assertFalse(l1.equals(l2));

		result.close();
	}
	catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}
}
 
Example 22
Source Project: database   Source File: Test_Ticket_1893.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void checkResults(final BigdataSailRemoteRepositoryConnection conn, final int count)
		throws QueryEvaluationException, RepositoryException,
		MalformedQueryException {
	final TupleQueryResult result = conn.prepareTupleQuery(QueryLanguage.SPARQL, QUERY).evaluate();
	
	Collection<Value> subjects = new ArrayList<>();
	try {
		while(result.hasNext()) {
			BindingSet bs = result.next();
			subjects.add(bs.getBinding("s").getValue());
		}
	} finally {
		result.close();
	}
	if(log.isInfoEnabled()) log.info(subjects);
	assertEquals(count, subjects.size());
}
 
Example 23
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testAddToDefault()
	throws Exception
{
	logger.debug("executing testAddToDefault");

	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("ADD GRAPH <" + graph1.stringValue() + "> TO DEFAULT");

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

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, graph1));
}
 
Example 24
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testCopyToDefault()
	throws Exception
{
	logger.debug("executing testCopyToDefault");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("COPY GRAPH <" + graph1.stringValue() + "> TO DEFAULT");

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

	assertTrue(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	operation.execute();
	assertFalse(con.hasStatement(graph1, DC.PUBLISHER, null, false, (Resource)null));
	assertFalse(con.hasStatement(graph2, DC.PUBLISHER, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, (Resource)null));
	assertTrue(con.hasStatement(bob, FOAF.NAME, null, false, graph1));
}
 
Example 25
@Test
public void testDescribeAWhere()
	throws Exception
{
	loadTestData("/testdata-query/dataset-describe.trig");
	StringBuilder query = new StringBuilder();
	query.append(getNamespaceDeclarations());
	query.append("DESCRIBE ?x WHERE {?x rdfs:label \"a\". } ");

	GraphQuery gq = conn.prepareGraphQuery(QueryLanguage.SPARQL, query.toString());

	ValueFactory f = conn.getValueFactory();
	URI a = f.createURI("http://example.org/a");
	URI p = f.createURI("http://example.org/p");
	Model result = QueryResults.asModel(gq.evaluate());
	Set<Value> objects = result.filter(a, p, null).objects();
	assertNotNull(objects);
	for (Value object : objects) {
		if (object instanceof BNode) {
			assertTrue(result.contains((Resource)object, null, null));
			assertEquals(2, result.filter((Resource)object, null, null).size());
		}
	}
}
 
Example 26
@Override
public ClosableIterable<Statement> queryConstruct(String queryString, String queryLanguage)
        throws QueryLanguageNotSupportedException, ModelRuntimeException {
	this.assertModel();
	// resolve the query language String to a QueryLanguage
	QueryLanguage language = ConversionUtil.toOpenRDFQueryLanguage(queryLanguage);
	
	try {
		// determine query result
		GraphQuery query = this.connection.prepareGraphQuery(language, queryString);
		GraphQueryResult queryResult = query.evaluate();
		
		// wrap it in a GraphIterable
		return new GraphIterable(queryResult, null);
	} catch(OpenRDFException e) {
		throw new ModelRuntimeException(e);
	}
}
 
Example 27
Source Project: database   Source File: LoadPdb.java    License: 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 28
Source Project: database   Source File: Test_Ticket_2091.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Execute a query including constants in projection expression.
 * The test succeeeds if the query successfully evaluates with 
 * QUERY_ENGINE_CHUNK_HANDLER set to NativeHeapStandloneChunkHandler,
 * as it requires results to be encoded in respect to namespace of value factory,
 * which fails if constant has not been resolved against target DB value factory.
 * @throws Exception
 */
public void test_simple() throws Exception {

	setMethodisPostUrlEncodedData();
	BigdataSailRemoteRepositoryConnection conn = m_repo.getBigdataSailRemoteRepository().getConnection();
	conn.prepareUpdate(QueryLanguage.SPARQL, "prefix wd: <http://wd/> \n" + 
			"prefix wdt: <http://wdt/> " +
			"INSERT DATA { wd:Q2 wdt:P31 wd:Q3917681 } ").execute();

	final TupleQueryResult result = 
			conn.prepareTupleQuery(QueryLanguage.SPARQL, QUERY).evaluate();
	
	Collection<Value> subjects = new ArrayList<>();
	try {
		while(result.hasNext()) {
			BindingSet bs = result.next();
			subjects.add(bs.getBinding("s").getValue());
		}
	} finally {
		result.close();
	}
	if(log.isInfoEnabled()) log.info(subjects);
	assertEquals(1, subjects.size());

}
 
Example 29
Source Project: database   Source File: SPARQLUpdateTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Test
public void testInsertNonMatchingWhere()
	throws Exception
{
	logger.debug("executing test testInsertNonMatchingWhere");
	StringBuilder update = new StringBuilder();
	update.append(getNamespaceDeclarations());
	update.append("INSERT { ?x rdfs:label ?y . } WHERE { ?x rdfs:comment ?y }");

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

	assertFalse(con.hasStatement(bob, RDFS.LABEL, null, true));

	operation.execute();

	assertFalse(con.hasStatement(bob, RDFS.LABEL, null, true));
}
 
Example 30
Source Project: database   Source File: Test_Ticket_1717.java    License: 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();
       }
   }
}