Java Code Examples for org.eclipse.rdf4j.query.TupleQuery#setBinding()

The following examples show how to use org.eclipse.rdf4j.query.TupleQuery#setBinding() . 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: AbstractLuceneSailGeoSPARQLTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testIntersectionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	try (RepositoryConnection connection = repository.getConnection()) {
		String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
				+ "select ?matchUri ?match where { ?matchUri geo:asWKT ?match. filter(geof:sfIntersects(?pattern, ?match)) }";
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("pattern", TEST_POLY);

		try (TupleQueryResult result = query.evaluate()) {

			// check the results
			Map<IRI, Literal> expected = new HashMap<>();
			expected.put(SUBJECT_4, POLY1);
			expected.put(SUBJECT_5, POLY2);

			while (result.hasNext()) {
				BindingSet bindings = result.next();
				IRI subj = (IRI) bindings.getValue("matchUri");

				Literal location = expected.remove(subj);
				assertNotNull(location);
				assertEquals(location, bindings.getValue("match"));
			}
			assertTrue(expected.isEmpty());
		}
	}
}
 
Example 2
Source File: AbstractLuceneSailTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testUnionQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	String queryStr = "";
	queryStr += "PREFIX search: <http://www.openrdf.org/contrib/lucenesail#> ";
	queryStr += "PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> ";
	queryStr += "SELECT DISTINCT ?result { ";
	queryStr += "{ ?result search:matches ?match1 . ";
	queryStr += "  ?match1 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate1> . }";
	queryStr += " UNION ";
	queryStr += "{ ?result search:matches ?match2 . ";
	queryStr += "  ?match2 search:query 'one' ; ";
	queryStr += "          search:property <urn:predicate2> . } ";
	queryStr += "} ";

	try (RepositoryConnection connection = repository.getConnection()) {
		// fire a query with the subject pre-specified
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("result", SUBJECT_1);
		try (TupleQueryResult result = query.evaluate()) {
			// check that this subject and only this subject is returned
			BindingSet bs = result.next();
			assertEquals(SUBJECT_1, bs.getValue("result"));
		}
	}
}
 
Example 3
Source File: LuceneSailTupleFunctionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testDistanceFunction() throws Exception {
	String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
			+ "select ?toUri ?fromUri ?dist where {?toUri a <urn:geo/Landmark>; geo:asWKT ?to. ?fromUri geo:asWKT ?from; <urn:geo/maxDistance> ?range."
			+ " bind(geof:distance(?from, ?to, ?units) as ?dist)" + " filter(?dist < ?range)" + " }";
	try {
		connection.begin();
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("units", GEOF.UOM_METRE);

		printTupleResult(query);
		try (TupleQueryResult result = query.evaluate()) {
			int count = countTupleResults(result);
			assertThat(count).isEqualTo(2);
		}
	} catch (Exception e) {
		connection.rollback();
		throw e;
	} finally {
		connection.commit();
	}
}
 
Example 4
Source File: SAILFederatedService.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> select(Service service, Set<String> projectionVars, BindingSet bindings, String baseUri) throws QueryEvaluationException {
	RepositoryConnection conn = endpoint.getConn();
	try {
		TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, service.getSelectQueryString(projectionVars), baseUri);
		Iterator<Binding> bIter = bindings.iterator();
		while (bIter.hasNext()) {
			Binding b = bIter.next();
			if (service.getServiceVars().contains(b.getName()))
				query.setBinding(b.getName(), b.getValue());
		}
		TupleQueryResult qRes = query.evaluate();
		return new InsertBindingsIteration(qRes, bindings);
	} catch(Throwable e) {
		throw new QueryEvaluationException(e);
	} finally {
		conn.close();
	}
}
 
Example 5
Source File: AbstractGenericLuceneTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testQueryWithSpecifiedSubject()
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	// fire a query with the subject pre-specified
	TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SERQL, QUERY_STRING);
	query.setBinding("Subject", SUBJECT_1);
	query.setBinding("Query", vf.createLiteral("one"));
	// check that this subject and only this subject is returned
	try (TupleQueryResult result = query.evaluate()) {
		// check that this subject and only this subject is returned
		assertTrue(result.hasNext());
		BindingSet bindings = result.next();
		assertEquals(SUBJECT_1, (IRI) bindings.getValue("Subject"));
		assertNotNull(bindings.getValue("Score"));
		assertFalse(result.hasNext());
	}
}
 
Example 6
Source File: SPARQLUpdateConformanceTest.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 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: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testPreparedTupleQueryUnicode() throws Exception {
	testCon.add(alexander, name, Александър);

	StringBuilder queryBuilder = new StringBuilder();
	queryBuilder.append(" SELECT person");
	queryBuilder.append(" FROM {person} foaf:name {name}");
	queryBuilder.append(" USING NAMESPACE foaf = <" + FOAF_NS + ">");

	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SERQL, queryBuilder.toString());
	query.setBinding(NAME, Александър);

	try (TupleQueryResult result = query.evaluate();) {
		assertThat(result).isNotNull();
		assertThat(result.hasNext()).isTrue();

		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertThat(solution.hasBinding(PERSON)).isTrue();
			assertThat(solution.getValue(PERSON)).isEqualTo(alexander);
		}
	}
}
 
Example 9
Source File: BasicTests.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testSingleSource_SetBinding() throws Exception {

	/* test a single source select query where we set a binding */
	prepareTest(Arrays.asList("/tests/basic/data01endpoint1.ttl", "/tests/basic/data01endpoint2.ttl"));

	try (RepositoryConnection conn = fedxRule.getRepository().getConnection()) {

		// SELECT query
		TupleQuery tq = conn
				.prepareTupleQuery("SELECT ?person WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		tq.setBinding("name", l("Alan"));
		TupleQueryResult tqr = tq.evaluate();
		List<BindingSet> res = Iterations.asList(tqr);
		assertContainsAll(res, "person", Sets.newHashSet(iri("http://example.org/", "a")));

		// CONSTRUCT query
		GraphQuery gq = conn.prepareGraphQuery(
				"CONSTRUCT { ?person <http://xmlns.com/foaf/0.1/name> ?name } WHERE { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		gq.setBinding("name", l("Alan"));
		GraphQueryResult gqr = gq.evaluate();
		List<Statement> stmts = Iterations.asList(gqr);
		Assertions.assertEquals(1, stmts.size());
		Assertions.assertEquals(iri("http://example.org/", "a"), stmts.get(0).getSubject());

		// BOOLEAN query
		BooleanQuery bq = conn.prepareBooleanQuery("ASK { ?person <http://xmlns.com/foaf/0.1/name> ?name }");
		bq.setBinding("name", l("non-existing-name"));
		Assertions.assertEquals(false, bq.evaluate());

	}

}
 
Example 10
Source File: AbstractLuceneSailGeoSPARQLTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testDistanceQuery() throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	try (RepositoryConnection connection = repository.getConnection()) {
		String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
				+ "select ?toUri ?to where { ?toUri geo:asWKT ?to. filter(geof:distance(?from, ?to, ?units) < ?range) }";
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("from", TEST_POINT);
		query.setBinding("units", GEOF.UOM_METRE);
		query.setBinding("range", sail.getValueFactory().createLiteral(1500.0));

		try (TupleQueryResult result = query.evaluate()) {

			// check the results
			Map<IRI, Literal> expected = new LinkedHashMap<>();
			expected.put(SUBJECT_1, EIFFEL_TOWER);
			expected.put(SUBJECT_2, ARC_TRIOMPHE);

			while (result.hasNext()) {
				BindingSet bindings = result.next();
				IRI subj = (IRI) bindings.getValue("toUri");
				// check ordering
				IRI expectedUri = expected.keySet().iterator().next();
				assertEquals(expectedUri, subj);

				Literal location = expected.remove(subj);
				assertNotNull(location);
				assertEquals(location, bindings.getValue("to"));
			}
			assertTrue(expected.isEmpty());
		}
	}
}
 
Example 11
Source File: CbSailProducer.java    From rya with Apache License 2.0 5 votes vote down vote up
protected Object performSelect(final String query, final String auth, final Boolean infer) throws RepositoryException, MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException {
    final TupleQuery tupleQuery = connection.prepareTupleQuery(
            QueryLanguage.SPARQL, query);
    if (auth != null && auth.length() > 0) {
        tupleQuery.setBinding(CONF_QUERY_AUTH, VALUE_FACTORY.createLiteral(auth));
    }
    if (infer != null) {
        tupleQuery.setBinding(CONF_INFER, VALUE_FACTORY.createLiteral(infer));
    }
    if (CbSailEndpoint.CbSailOutput.BINARY.equals(queryOutput)) {
        final List listOutput = new ArrayList();
        final AbstractTupleQueryResultHandler handler = new AbstractTupleQueryResultHandler() {
            @Override
            public void handleSolution(final BindingSet bindingSet) throws TupleQueryResultHandlerException {
                final Map<String, String> map = new HashMap<String, String>();
                for (final String s : bindingSet.getBindingNames()) {
                    map.put(s, bindingSet.getBinding(s).getValue().stringValue());
                }
                listOutput.add(map);
            }
        };
        tupleQuery.evaluate(handler);
        return listOutput;
    } else if (CbSailEndpoint.CbSailOutput.XML.equals(queryOutput)) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final SPARQLResultsXMLWriter sparqlWriter = new SPARQLResultsXMLWriter(baos);
        tupleQuery.evaluate(sparqlWriter);
        return new String(baos.toByteArray(), StandardCharsets.UTF_8);
    } else {
        throw new IllegalArgumentException("Query Output[" + queryOutput + "] is not recognized");
    }
}
 
Example 12
Source File: AbstractLuceneSailGeoSPARQLTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testComplexIntersectionQuery()
		throws RepositoryException, MalformedQueryException, QueryEvaluationException {
	try (RepositoryConnection connection = repository.getConnection()) {

		String queryStr = "prefix geo:  <" + GEO.NAMESPACE + ">" + "prefix geof: <" + GEOF.NAMESPACE + ">"
				+ "select ?matchUri ?intersects ?g where { graph ?g {?matchUri geo:asWKT ?match.}"
				+ " bind(geof:sfIntersects(?pattern, ?match) as ?intersects)" + " filter(?intersects)" + " }";
		TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, queryStr);
		query.setBinding("pattern", TEST_POLY);

		try (TupleQueryResult result = query.evaluate()) {

			// check the results
			Map<IRI, Literal> expected = new HashMap<>();
			expected.put(SUBJECT_5, sail.getValueFactory().createLiteral(true));

			while (result.hasNext()) {
				BindingSet bindings = result.next();
				IRI subj = (IRI) bindings.getValue("matchUri");

				Literal location = expected.remove(subj);
				assertNotNull("Expected subject: " + subj, location);
				assertEquals(location.booleanValue(), ((Literal) bindings.getValue("intersects")).booleanValue());

				assertNotNull(bindings.getValue("g"));
			}
			assertTrue(expected.isEmpty());
		}
	}
}
 
Example 13
Source File: RepositoryConnectionTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
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(" SELECT name, mbox");
	queryBuilder.append(" FROM {} foaf:name {name};");
	queryBuilder.append("         foaf:mbox {mbox}");
	queryBuilder.append(" USING NAMESPACE foaf = <" + FOAF_NS + ">");
	TupleQuery query = testCon.prepareTupleQuery(QueryLanguage.SERQL, queryBuilder.toString());
	query.setBinding(NAME, nameBob);

	try (TupleQueryResult result = query.evaluate();) {
		assertThat(result).isNotNull();
		assertThat(result.hasNext()).isTrue();
		while (result.hasNext()) {
			BindingSet solution = result.next();
			assertThat(solution.hasBinding(NAME)).isTrue();
			assertThat(solution.hasBinding(MBOX)).isTrue();
			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 14
Source File: SparqlRegexTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testBindingFlags() throws Exception {
	TupleQuery query = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryBindingFlags);
	query.setBinding("pattern", vf.createLiteral("@Work.example"));
	query.setBinding("flags", vf.createLiteral("i"));
	TupleQueryResult result = query.evaluate();
	assertEquals(hunt, result.next().getValue("name"));
	assertFalse(result.hasNext());
	result.close();
}
 
Example 15
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 16
Source File: SPARQLBuilderTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void test() throws RDF4JException { // NOPMD
	// Thrown exceptions are the only failure path.

	for (int i = 0; i < 100; i++) {
		TupleQuery tupleQuery = con.prepareTupleQuery(SPARQL, pattern);
		if (!(prefix.isEmpty() || namespace.isEmpty())) {
			tupleQuery.setBinding(prefix, valueFactory.createIRI(namespace));
		}
		tupleQuery.evaluate().close();
	}
}
 
Example 17
Source File: FedXWithLocalRepositoryManagerTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testWithLocalRepositoryManager_CustomFederatedServiceResolver() throws Exception {

	addMemoryStore("repo1");
	addMemoryStore("repo2");
	addMemoryStore("serviceRepo");

	// register custom federated service resolver
	AbstractFederatedServiceResolver serviceResolver = new SPARQLServiceResolver() {
		@Override
		protected FederatedService createService(String serviceUrl) throws QueryEvaluationException {
			if (serviceUrl.equals("http://serviceRepo")) {
				Repository serviceRepo = repoManager.getRepository("serviceRepo");
				return new RepositoryFederatedService(serviceRepo, false);
			}
			throw new IllegalArgumentException("Service url cannot be resolved: " + serviceUrl);
		}
	};
	repoManager.externalResolver = serviceResolver;

	ValueFactory vf = SimpleValueFactory.getInstance();
	addData("repo1", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p1"), RDF.TYPE, FOAF.PERSON)));
	addData("repo2", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p2"), RDF.TYPE, FOAF.PERSON)));

	addData("serviceRepo", Lists.newArrayList(
			vf.createStatement(vf.createIRI("http://ex.org/p1"), FOAF.NAME, vf.createLiteral("Person 1")),
			vf.createStatement(vf.createIRI("http://ex.org/p2"), FOAF.NAME, vf.createLiteral("Person 2"))));

	FedXRepositoryConfig fedXRepoConfig = FedXRepositoryConfigBuilder.create()
			.withResolvableEndpoint(Arrays.asList("repo1", "repo2"))
			.build();
	repoManager.addRepositoryConfig(new RepositoryConfig("federation", fedXRepoConfig));

	Repository repo = repoManager.getRepository("federation");

	try (RepositoryConnection conn = repo.getConnection()) {

		TupleQuery tq = conn.prepareTupleQuery(
				"SELECT * WHERE { ?person a ?PERSON . { SERVICE <http://serviceRepo> { ?person ?NAME ?name} } }");
		tq.setBinding("PERSON", FOAF.PERSON);
		tq.setBinding("NAME", FOAF.NAME);

		List<BindingSet> bindings = Iterations.asList(tq.evaluate());
		Assertions.assertEquals(2, bindings.size()); // two persons

		BindingSet b1 = bindings.get(0);
		BindingSet b2 = bindings.get(1);

		if (b1.getValue("person").equals(vf.createIRI("http://ex.org/p1"))) {
			Assertions.assertEquals(vf.createLiteral("Person 1"), b1.getValue("name"));
			Assertions.assertEquals(vf.createLiteral("Person 2"), b2.getValue("name"));
		} else {
			Assertions.assertEquals(vf.createLiteral("Person 2"), b1.getValue("name"));
			Assertions.assertEquals(vf.createLiteral("Person 1"), b2.getValue("name"));
		}

	}

}
 
Example 18
Source File: ComplexSPARQLQueryTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Test
public void testSameTermRepeatInUnion() throws Exception {
	loadTestData("/testdata-query/dataset-query.trig");
	StringBuilder query = new StringBuilder();
	query.append("PREFIX foaf:<http://xmlns.com/foaf/0.1/>\n");
	query.append("SELECT * {\n");
	query.append("    {\n");
	query.append("        ?sameTerm foaf:mbox ?mbox\n");
	query.append("        FILTER sameTerm(?sameTerm,$william)\n");
	query.append("    } UNION {\n");
	query.append("        ?x foaf:knows ?sameTerm\n");
	query.append("        FILTER sameTerm(?sameTerm,$william)\n");
	query.append("    }\n");
	query.append("}");

	TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString());
	tq.setBinding("william", conn.getValueFactory().createIRI("http://example.org/william"));

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

		int count = 0;
		while (result.hasNext()) {
			BindingSet bs = result.next();
			count++;
			assertNotNull(bs);

			// System.out.println(bs);

			Value mbox = bs.getValue("mbox");
			Value x = bs.getValue("x");

			assertTrue(mbox instanceof Literal || x instanceof IRI);
		}
		assertEquals(3, count);
	} catch (QueryEvaluationException e) {
		e.printStackTrace();
		fail(e.getMessage());
	}

}
 
Example 19
Source File: RdfCloudTripleStoreConnectionTest.java    From rya with Apache License 2.0 4 votes vote down vote up
public void testUpdateWAuthOnConfig() throws Exception {
        String sparqlUpdate = getSparqlUpdate();

        RdfCloudTripleStore tstore = new MockRdfCloudStore();
        NamespaceManager nm = new NamespaceManager(tstore.getRyaDAO(), tstore.getConf());
        tstore.setNamespaceManager(nm);
        SailRepository repo = new SailRepository(tstore);
        tstore.getRyaDAO().getConf().setCv("1|2");
        repo.initialize();

        RepositoryConnection conn = repo.getConnection();
        Update u = conn.prepareUpdate(QueryLanguage.SPARQL, sparqlUpdate);
        u.execute();

        String query =
                "PREFIX  ex:  <http://www.example.org/exampleDocument#>\n" +
                "PREFIX  voc:  <http://www.example.org/vocabulary#>\n" +
                "PREFIX  foaf:  <http://xmlns.com/foaf/0.1/>\n" +
                "PREFIX  rdfs:  <http://www.w3.org/2000/01/rdf-schema#>\n" +
                "\n" +
                "SELECT * \n" +
//              "FROM NAMED <http://www.example.org/exampleDocument#G1>\n" +
                "WHERE\n" +
                "{\n" +
                "  GRAPH ex:G1\n" +
                "  {\n" +
                "    ?m voc:name ?name ;\n" +
                "           voc:homepage ?hp .\n" +
                "  } .\n" +
                " GRAPH ex:G2\n" +
                "  {\n" +
                "    ?m voc:hasSkill ?skill .\n" +
                "  } .\n" +
                "}";
        TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query);
        tupleQuery.setBinding(RdfCloudTripleStoreConfiguration.CONF_QUERY_AUTH, VF.createLiteral("2"));
        CountTupleHandler tupleHandler = new CountTupleHandler();
        tupleQuery.evaluate(tupleHandler);
        assertEquals(1, tupleHandler.getCount());

        tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, query); //no auth
        tupleHandler = new CountTupleHandler();
        tupleQuery.evaluate(tupleHandler);
        assertEquals(0, tupleHandler.getCount());

        conn.close();

        repo.shutDown();
    }
 
Example 20
Source File: WikiDataReification.java    From inception with Apache License 2.0 4 votes vote down vote up
private List<Statement> getStatementsById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String
        .join("\n",
            "SELECT DISTINCT ?s ?p ?ps ?o WHERE {",
            "  ?s  ?p  ?id .",
            "  ?id ?ps ?o .",
            "  FILTER(STRSTARTS(STR(?ps), STR(?ps_ns)))",
            "}",
            "LIMIT 10");
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);
    tupleQuery.setBinding("ps_ns", vf.createIRI(PREDICATE_NAMESPACE));

    tupleQuery.setIncludeInferred(false);
    TupleQueryResult result;

    try {
        result = tupleQuery.evaluate();
    }
    catch (QueryEvaluationException e) {
        log.warn("No such statementId in knowledge base", e);
        return null;
    }

    List<Statement> statements = new ArrayList<>();
    while (result.hasNext()) {
        BindingSet bindings = result.next();
        Binding s = bindings.getBinding("s");
        Binding p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");
        Binding ps = bindings.getBinding("ps");

        IRI instance = vf.createIRI(s.getValue().stringValue());
        IRI predicate = vf.createIRI(p.getValue().stringValue());
        Statement root = vf.createStatement(instance, predicate, id);

        IRI valuePredicate = vf.createIRI(ps.getValue().stringValue());
        Value object = o.getValue();
        Statement valueStatement = vf.createStatement(id, valuePredicate, object);
        statements.add(root);
        statements.add(valueStatement);
    }
    return statements;
}