Java Code Examples for org.eclipse.rdf4j.query.BindingSet#getValue()
The following examples show how to use
org.eclipse.rdf4j.query.BindingSet#getValue() .
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: SPARQLCSVTupleTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private static boolean bindingSetsMatch(BindingSet bs1, BindingSet bs2, Map<BNode, BNode> bNodeMapping) { if (bs1.size() != bs2.size()) { return false; } for (Binding binding1 : bs1) { Value value1 = binding1.getValue(); Value value2 = bs2.getValue(binding1.getName()); if (value1 == null && value2 != null) { return false; } else if (value1 != null && value2 == null) { return false; } else if (value1 != null && value2 != null) { if (!CSVQueryResultsComparisons.equals(value1, value2) && !value1.stringValue().equals(value2.stringValue())) { return false; } } } return true; }
Example 2
Source File: DirectTypeHierarchyInferencer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 6 votes |
private void evaluateIntoStatements(ParsedGraphQuery query, Collection<Statement> statements) throws SailException, RDFHandlerException, QueryEvaluationException { try (CloseableIteration<? extends BindingSet, QueryEvaluationException> bindingsIter = getWrappedConnection() .evaluate(query.getTupleExpr(), null, EmptyBindingSet.getInstance(), true)) { ValueFactory vf = getValueFactory(); while (bindingsIter.hasNext()) { BindingSet bindings = bindingsIter.next(); Value subj = bindings.getValue("subject"); Value pred = bindings.getValue("predicate"); Value obj = bindings.getValue("object"); if (subj instanceof Resource && pred instanceof IRI && obj != null) { statements.add(vf.createStatement((Resource) subj, (IRI) pred, obj)); } } } }
Example 3
Source File: HalyardStatementPatternEvaluation.java From Halyard with Apache License 2.0 | 5 votes |
protected boolean isUnbound(Var var, BindingSet bindings) { if (var == null) { return false; } else { return bindings.hasBinding(var.getName()) && bindings.getValue(var.getName()) == null; } }
Example 4
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testSES2052If2() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append("SELECT ?p \n"); query.append("WHERE { \n"); query.append(" ?s ?p ?o . \n"); query.append( " FILTER(IF(!BOUND(?p), false , ?p = <http://www.w3.org/1999/02/22-rdf-syntax-ns#type>)) \n"); query.append("}"); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try (TupleQueryResult result = tq.evaluate();) { assertNotNull(result); while (result.hasNext()) { BindingSet bs = result.next(); IRI p = (IRI) bs.getValue("p"); assertNotNull(p); assertEquals(RDF.TYPE, p); } } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 5
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testValuesInOptional() throws Exception { loadTestData("/testdata-query/dataset-ses1692.trig"); StringBuilder query = new StringBuilder(); query.append(" PREFIX : <http://example.org/>\n"); query.append( " SELECT DISTINCT ?a ?name ?isX WHERE { ?b :p1 ?a . ?a :name ?name. OPTIONAL { ?a a :X . VALUES(?isX) { (:X) } } } "); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try (TupleQueryResult result = tq.evaluate();) { assertNotNull(result); assertTrue(result.hasNext()); int count = 0; while (result.hasNext()) { count++; BindingSet bs = result.next(); // System.out.println(bs); IRI a = (IRI) bs.getValue("a"); assertNotNull(a); Value isX = bs.getValue("isX"); Literal name = (Literal) bs.getValue("name"); assertNotNull(name); if (a.stringValue().endsWith("a1")) { assertNotNull(isX); } else if (a.stringValue().endsWith(("a2"))) { assertNull(isX); } } assertEquals(2, count); } }
Example 6
Source File: TurtleParserTestCase.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void parseNegativeTurtleEvalTests(TestSuite suite, String fileBasePath, String testBaseUrl, String manifestBaseUrl, RepositoryConnection con) throws Exception { StringBuilder negativeEvalQuery = new StringBuilder(); negativeEvalQuery.append(" PREFIX mf: <http://www.w3.org/2001/sw/DataAccess/tests/test-manifest#>\n"); negativeEvalQuery.append(" PREFIX qt: <http://www.w3.org/2001/sw/DataAccess/tests/test-query#>\n"); negativeEvalQuery.append(" PREFIX rdft: <http://www.w3.org/ns/rdftest#>\n"); negativeEvalQuery.append(" SELECT ?test ?testName ?inputURL ?outputURL \n"); negativeEvalQuery.append(" WHERE { \n"); negativeEvalQuery.append(" ?test a rdft:TestTurtleNegativeEval . "); negativeEvalQuery.append(" ?test mf:name ?testName . "); negativeEvalQuery.append(" ?test mf:action ?inputURL . "); negativeEvalQuery.append(" }"); TupleQueryResult queryResult = con.prepareTupleQuery(QueryLanguage.SPARQL, negativeEvalQuery.toString()) .evaluate(); // Add all negative eval 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 7
Source File: BindingSetUtil.java From semagrow with Apache License 2.0 | 5 votes |
/** * Returns true if the value of every binding name on first agrees with * the value of the binding name (if exists) on the second bindingset * @param first * @param second * @return true or false */ public static boolean agreesOn(BindingSet first, BindingSet second) { for (Binding b : first) { Value v = second.getValue(b.getName()); if (v != null && !v.equals(b.getValue())) return false; } return true; }
Example 8
Source File: StrictEvaluationStrategy.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public Value evaluate(Var var, BindingSet bindings) throws QueryEvaluationException { Value value = var.getValue(); if (value == null) { value = bindings.getValue(var.getName()); } if (value == null) { throw new ValueExprEvaluationException(); } return value; }
Example 9
Source File: AbstractLuceneSailTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testPropertyVar() throws MalformedQueryException, RepositoryException, QueryEvaluationException { StringBuilder buffer = new StringBuilder(); buffer.append("SELECT \n"); buffer.append(" Resource, Property \n"); buffer.append("FROM \n"); buffer.append(" {Resource} <" + MATCHES + "> {} "); buffer.append(" <" + QUERY + "> {\"one\"}; "); buffer.append(" <" + PROPERTY + "> {Property} "); String q = buffer.toString(); try (RepositoryConnection connection = repository.getConnection()) { // fire the query TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SERQL, q); try (TupleQueryResult result = query.evaluate()) { int results = 0; Map<IRI, IRI> expectedSubject = new HashMap<>(); expectedSubject.put(SUBJECT_1, PREDICATE_1); expectedSubject.put(SUBJECT_2, PREDICATE_1); expectedSubject.put(SUBJECT_3, PREDICATE_2); while (result.hasNext()) { results++; BindingSet bindings = result.next(); // the resource should be among the set of expected subjects, if so, // remove it from the set Value subject = bindings.getValue("Resource"); IRI expectedProperty = expectedSubject.remove(subject); assertEquals("For subject " + subject, expectedProperty, bindings.getValue("Property")); } // there should have been 3 results assertEquals(3, results); } } }
Example 10
Source File: HalyardValueExprEvaluation.java From Halyard with Apache License 2.0 | 5 votes |
/** * Evaluate a {@link Var} query model node. * @param var * @param bindings the set of named value bindings * @return the result of {@link Var#getValue()} from either {@code var}, or if {@code null}, from the {@ bindings} * @throws ValueExprEvaluationException * @throws QueryEvaluationException */ private Value evaluate(Var var, BindingSet bindings) throws ValueExprEvaluationException, QueryEvaluationException { Value value = var.getValue(); if (value == null) { value = bindings.getValue(var.getName()); } if (value == null) { throw new ValueExprEvaluationException(); } return value; }
Example 11
Source File: AbstractLuceneSailGeoSPARQLTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 12
Source File: Tuple.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
public Tuple(BindingSet bindingset, String[] bindingnames) { for (String bindingname : bindingnames) { Value value; if (bindingname.startsWith("?")) { value = bindingset.getValue(bindingname.substring(1)); } else { value = bindingset.getValue(bindingname); } if (value != null) { line.add(value); } } }
Example 13
Source File: TriGParserTestCase.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 14
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testNullContext1() throws Exception { loadTestData("/testdata-query/dataset-query.trig"); StringBuilder query = new StringBuilder(); query.append(" SELECT * "); query.append(" FROM DEFAULT "); query.append(" WHERE { ?s ?p ?o } "); TupleQuery tq = conn.prepareTupleQuery(QueryLanguage.SPARQL, query.toString()); try (TupleQueryResult result = tq.evaluate();) { assertNotNull(result); while (result.hasNext()) { BindingSet bs = result.next(); assertNotNull(bs); Resource s = (Resource) bs.getValue("s"); assertNotNull(s); assertFalse(bob.equals(s)); // should not be present in default // graph assertFalse(alice.equals(s)); // should not be present in // default // graph } } catch (QueryEvaluationException e) { e.printStackTrace(); fail(e.getMessage()); } }
Example 15
Source File: AbstractNQuadsParserTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private void parsePositiveNQuadsSyntaxTests(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:TestNQuadsPositiveSyntax . "); 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 16
Source File: ConstantOptimizer.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Applies generally applicable optimizations to the supplied query: variable assignments are inlined. */ @Override public void optimize(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings) { ConstantVisitor visitor = new ConstantVisitor(); tupleExpr.visit(visitor); Set<String> varsBefore = visitor.varNames; VarNameCollector varCollector = new VarNameCollector(); tupleExpr.visit(varCollector); Set<String> varsAfter = varCollector.varNames; if (varsAfter.size() < varsBefore.size()) { varsBefore.removeAll(varsAfter); for (ProjectionElemList projElems : visitor.projElemLists) { for (ProjectionElem projElem : projElems.getElements()) { String name = projElem.getSourceName(); if (varsBefore.contains(name)) { UnaryTupleOperator proj = (UnaryTupleOperator) projElems.getParentNode(); Extension ext = new Extension(proj.getArg()); proj.setArg(ext); Var lostVar = new Var(name); Value value = bindings.getValue(name); if (value != null) { lostVar.setValue(value); } ext.addElement(new ExtensionElem(lostVar, name)); } } } } }
Example 17
Source File: FedXConnection.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
private static String getOriginalQueryString(BindingSet b) { if (b == null) { return null; } Value q = b.getValue(FedXRepositoryConnection.BINDING_ORIGINAL_QUERY); if (q != null) { return q.stringValue(); } return null; }
Example 18
Source File: StrictEvaluationStrategy.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(Service service, BindingSet bindings) throws QueryEvaluationException { Var serviceRef = service.getServiceRef(); String serviceUri; if (serviceRef.hasValue()) { serviceUri = serviceRef.getValue().stringValue(); } else { if (bindings != null && bindings.getValue(serviceRef.getName()) != null) { serviceUri = bindings.getBinding(serviceRef.getName()).getValue().stringValue(); } else { throw new QueryEvaluationException("SERVICE variables must be bound at evaluation time."); } } try { FederatedService fs = serviceResolver.getService(serviceUri); // create a copy of the free variables, and remove those for which // bindings are available (we can set them as constraints!) Set<String> freeVars = new HashSet<>(service.getServiceVars()); freeVars.removeAll(bindings.getBindingNames()); // Get bindings from values pre-bound into variables. MapBindingSet allBindings = new MapBindingSet(); for (Binding binding : bindings) { allBindings.addBinding(binding.getName(), binding.getValue()); } Set<Var> boundVars = getBoundVariables(service); for (Var boundVar : boundVars) { freeVars.remove(boundVar.getName()); allBindings.addBinding(boundVar.getName(), boundVar.getValue()); } bindings = allBindings; String baseUri = service.getBaseURI(); // special case: no free variables => perform ASK query if (freeVars.isEmpty()) { boolean exists = fs.ask(service, bindings, baseUri); // check if triples are available (with inserted bindings) if (exists) { return new SingletonIteration<>(bindings); } else { return new EmptyIteration<>(); } } // otherwise: perform a SELECT query return fs.select(service, freeVars, bindings, baseUri); } catch (RuntimeException e) { // suppress exceptions if silent if (service.isSilent()) { return new SingletonIteration<>(bindings); } else { throw e; } } }
Example 19
Source File: AbstractLuceneSailTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
private void evaluate(String[] queries, ArrayList<List<Map<String, String>>> expectedResults) throws MalformedQueryException, RepositoryException, QueryEvaluationException { try (RepositoryConnection connection = repository.getConnection()) { for (int queryID = 0; queryID < queries.length; queryID++) { String serql = queries[queryID]; List<Map<String, String>> expectedResultSet = expectedResults.get(queryID); // fire the query TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SERQL, serql); try (TupleQueryResult tqr = query.evaluate()) { // check the results int actualResults = 0; Set<Integer> matched = new HashSet<>(); while (tqr.hasNext()) { BindingSet bs = tqr.next(); actualResults++; boolean matches; for (int resultSetID = 0; resultSetID < expectedResultSet.size(); resultSetID++) { // ignore results that matched before if (matched.contains(resultSetID)) { continue; } // assume it matches matches = true; // get the result we compare with now Map<String, String> expectedResult = new HashMap<>(expectedResultSet.get(resultSetID)); // get all var names Collection<String> vars = new ArrayList<>(expectedResult.keySet()); // check if all actual results are expected for (String var : vars) { String expectedVal = expectedResult.get(var); Value actualVal = bs.getValue(var); if (expectedVal == null) { // don't care about the actual value, as long as there is // one if (actualVal == null) { matches = false; break; } } else { // compare the values if ((actualVal == null) || (expectedVal.compareTo(actualVal.stringValue()) != 0)) { matches = false; break; } } // remove the matched result so that we do not match it twice expectedResult.remove(var); } // check if expected results were existing if (!expectedResult.isEmpty()) { matches = false; } if (matches) { matched.add(resultSetID); break; } } } // the number of matched expected results must be equal to the number // of actual results assertEquals("How many expected results were retrieved for query #" + queryID + "?", expectedResultSet.size(), matched.size()); assertEquals("How many actual results were retrieved for query #" + queryID + "?", expectedResultSet.size(), actualResults); } } } }
Example 20
Source File: ComplexSPARQLQueryTest.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 4 votes |
@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()); } }