Java Code Examples for org.eclipse.rdf4j.query.Binding#getValue()

The following examples show how to use org.eclipse.rdf4j.query.Binding#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: SPARQLCSVTupleBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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: SPARQLCSVTupleTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 3
Source File: TimeAwareHBaseSail.java    From Halyard with Apache License 2.0 6 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(TupleExpr tupleExpr, Dataset dataset, BindingSet bindings, boolean includeInferred) throws SailException {
    Binding b = bindings.getBinding(TIMESTAMP_CALLBACK_BINDING_NAME);
    final TimestampCallbackBinding timestampBinding = (b instanceof TimestampCallbackBinding) ? (TimestampCallbackBinding) b : null;
    CloseableIteration<BindingSet, QueryEvaluationException> iter = super.evaluate(tupleExpr, dataset, bindings, includeInferred);
    //push back the actual timestamp binding to the callback binding if requested
    if (timestampBinding != null) {
        iter = new FilterIteration<BindingSet, QueryEvaluationException>(iter) {
            @Override
            protected boolean accept(BindingSet bindings) throws QueryEvaluationException {
                Binding b = bindings.getBinding(TIMESTAMP_BINDING_NAME);
                //push back actual time if the timestamp binding is not provided
                timestampBinding.v = b == null ? SimpleValueFactory.getInstance().createLiteral(System.currentTimeMillis()) : b.getValue();
                return true;
            }
        };
    }
    return iter;
}
 
Example 4
Source File: WikiDataReification.java    From inception with Apache License 2.0 5 votes vote down vote up
private List<Statement> getQualifiersById(RepositoryConnection aConnection, KnowledgeBase kb,
        String aStatementId)
{
    ValueFactory vf = aConnection.getValueFactory();
    
    String QUERY = String.join("\n",
            "SELECT DISTINCT ?p ?o WHERE {",
            "  ?id ?p ?o .",
            "}",
            "LIMIT " + kb.getMaxResults());
    Resource id = vf.createBNode(aStatementId);
    TupleQuery tupleQuery = aConnection.prepareTupleQuery(QueryLanguage.SPARQL, QUERY);
    tupleQuery.setBinding("id", id);

    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 p = bindings.getBinding("p");
        Binding o = bindings.getBinding("o");

        if (!p.getValue().stringValue().contains(PREDICATE_NAMESPACE)) {
            IRI predicate = vf.createIRI(p.getValue().stringValue());
            Value object = o.getValue();
            Statement qualifierStatement = vf.createStatement(id, predicate, object);
            statements.add(qualifierStatement);
        }
    }
    return statements;
}
 
Example 5
Source File: SPARQLCSVTupleBackgroundTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean matchBindingSets(List<? extends BindingSet> queryResult1,
		Iterable<? extends BindingSet> queryResult2, Map<BNode, BNode> bNodeMapping, int idx) {
	boolean result = false;

	if (idx < queryResult1.size()) {
		BindingSet bs1 = queryResult1.get(idx);

		List<BindingSet> matchingBindingSets = findMatchingBindingSets(bs1, queryResult2, bNodeMapping);

		for (BindingSet bs2 : matchingBindingSets) {
			// Map bNodes in bs1 to bNodes in bs2
			Map<BNode, BNode> newBNodeMapping = new HashMap<>(bNodeMapping);

			for (Binding binding : bs1) {
				if (binding.getValue() instanceof BNode) {
					newBNodeMapping.put((BNode) binding.getValue(), (BNode) bs2.getValue(binding.getName()));
				}
			}

			// FIXME: this recursive implementation has a high risk of
			// triggering a stack overflow

			// Enter recursion
			result = matchBindingSets(queryResult1, queryResult2, newBNodeMapping, idx + 1);

			if (result == true) {
				// models match, look no further
				break;
			}
		}
	} else {
		// All statements have been mapped successfully
		result = true;
	}

	return result;
}
 
Example 6
Source File: SPARQLCSVTupleTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private boolean matchBindingSets(List<? extends BindingSet> queryResult1,
		Iterable<? extends BindingSet> queryResult2, Map<BNode, BNode> bNodeMapping, int idx) {
	boolean result = false;

	if (idx < queryResult1.size()) {
		BindingSet bs1 = queryResult1.get(idx);

		List<BindingSet> matchingBindingSets = findMatchingBindingSets(bs1, queryResult2, bNodeMapping);

		for (BindingSet bs2 : matchingBindingSets) {
			// Map bNodes in bs1 to bNodes in bs2
			Map<BNode, BNode> newBNodeMapping = new HashMap<>(bNodeMapping);

			for (Binding binding : bs1) {
				if (binding.getValue() instanceof BNode) {
					newBNodeMapping.put((BNode) binding.getValue(), (BNode) bs2.getValue(binding.getName()));
				}
			}

			// FIXME: this recursive implementation has a high risk of
			// triggering a stack overflow

			// Enter recursion
			result = matchBindingSets(queryResult1, queryResult2, newBNodeMapping, idx + 1);

			if (result == true) {
				// models match, look no further
				break;
			}
		}
	} else {
		// All statements have been mapped successfully
		result = true;
	}

	return result;
}
 
Example 7
Source File: MapBindingSet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Value getValue(String bindingName) {
	Binding binding = getBinding(bindingName);

	if (binding != null) {
		return binding.getValue();
	}

	return null;
}
 
Example 8
Source File: DAWGTestResultSetWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void handleSolution(BindingSet bindingSet) throws TupleQueryResultHandlerException {
	try {
		BNode solutionNode = vf.createBNode();

		reportStatement(resultSetNode, SOLUTION, solutionNode);

		for (Binding binding : bindingSet) {
			BNode bindingNode = vf.createBNode();

			reportStatement(solutionNode, BINDING, bindingNode);
			reportStatement(bindingNode, VARIABLE, vf.createLiteral(binding.getName()));

			Value value = binding.getValue();

			// Map bnodes to new bnodes to prevent collisions with the bnodes
			// generated for the result format
			if (value instanceof BNode) {
				BNode mappedBNode = bnodeMap.get(value);

				if (mappedBNode == null) {
					mappedBNode = vf.createBNode();
					bnodeMap.put((BNode) value, mappedBNode);
				}

				value = mappedBNode;
			}

			reportStatement(bindingNode, VALUE, value);
		}
	} catch (RDFHandlerException e) {
		throw new TupleQueryResultHandlerException(e);
	}
}
 
Example 9
Source File: OneOfVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
private static void assertBindingSet(final Iterator<BindingSet> bindingSetIter, final Iterator<Resource> expectedValues) {
    while (expectedValues.hasNext()) {
        final Resource expectedValue = expectedValues.next();
        assertTrue(bindingSetIter.hasNext());
        final BindingSet bindingSet = bindingSetIter.next();
        assertTrue(bindingSet instanceof QueryBindingSet);
        assertEquals(1, bindingSet.getBindingNames().size());
        final Binding binding = bindingSet.getBinding("s");
        assertNotNull(binding);
        final Value actualValue = binding.getValue();
        assertEquals(expectedValue, actualValue);
    }
}
 
Example 10
Source File: StatementMetadataNode.java    From rya with Apache License 2.0 5 votes vote down vote up
private boolean canJoinBindingSets(final BindingSet bs1, final BindingSet bs2) {
    for (final Binding b : bs1) {
        final String name = b.getName();
        final Value val = b.getValue();
        if (bs2.hasBinding(name) && (!bs2.getValue(name).equals(val))) {
            return false;
        }
    }
    return true;
}
 
Example 11
Source File: BindingSetUtil.java    From semagrow with Apache License 2.0 5 votes vote down vote up
public static boolean hasBNode(BindingSet bindings) {

        for (Binding b : bindings) {
            if (b.getValue() instanceof BNode) {
                return true;
            }
        }
        return false;
    }
 
Example 12
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;
}
 
Example 13
Source File: TransactionWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void serialize(SPARQLUpdateOperation op, XMLWriter xmlWriter) throws IOException {
	String baseURI = op.getBaseURI();
	if (baseURI != null) {
		xmlWriter.setAttribute(TransactionXMLConstants.BASE_URI_ATT, baseURI);
	}
	xmlWriter.setAttribute(TransactionXMLConstants.INCLUDE_INFERRED_ATT, op.isIncludeInferred());
	xmlWriter.startTag(TransactionXMLConstants.SPARQL_UPDATE_TAG);

	// serialize update string
	String updateString = op.getUpdateString();
	xmlWriter.textElement(TransactionXMLConstants.UPDATE_STRING_TAG, updateString);

	// serialize dataset definition (if any)
	Dataset dataset = op.getDataset();
	if (dataset != null) {
		xmlWriter.startTag(TransactionXMLConstants.DATASET_TAG);

		xmlWriter.startTag(TransactionXMLConstants.DEFAULT_GRAPHS_TAG);
		for (IRI defaultGraph : dataset.getDefaultGraphs()) {
			xmlWriter.textElement(TransactionXMLConstants.GRAPH_TAG, defaultGraph.stringValue());
		}
		xmlWriter.endTag(TransactionXMLConstants.DEFAULT_GRAPHS_TAG);

		xmlWriter.startTag(TransactionXMLConstants.NAMED_GRAPHS_TAG);
		for (IRI namedGraph : dataset.getNamedGraphs()) {
			xmlWriter.textElement(TransactionXMLConstants.GRAPH_TAG, namedGraph.stringValue());
		}
		xmlWriter.endTag(TransactionXMLConstants.NAMED_GRAPHS_TAG);

		xmlWriter.startTag(TransactionXMLConstants.DEFAULT_REMOVE_GRAPHS_TAG);
		for (IRI defaultRemoveGraph : dataset.getDefaultRemoveGraphs()) {
			xmlWriter.textElement(TransactionXMLConstants.GRAPH_TAG, defaultRemoveGraph.stringValue());
		}
		xmlWriter.endTag(TransactionXMLConstants.DEFAULT_REMOVE_GRAPHS_TAG);

		if (dataset.getDefaultInsertGraph() != null) {
			xmlWriter.textElement(TransactionXMLConstants.DEFAULT_INSERT_GRAPH,
					dataset.getDefaultInsertGraph().stringValue());
		}
		xmlWriter.endTag(TransactionXMLConstants.DATASET_TAG);
	}

	if (op.getBindings() != null && op.getBindings().length > 0) {
		xmlWriter.startTag(TransactionXMLConstants.BINDINGS);

		for (Binding binding : op.getBindings()) {
			if (binding.getName() != null && binding.getValue() != null
					&& binding.getValue().stringValue() != null) {
				if (binding.getValue() instanceof IRI) {
					xmlWriter.setAttribute(TransactionXMLConstants.NAME_ATT, binding.getName());
					xmlWriter.textElement(TransactionXMLConstants.BINDING_URI, binding.getValue().stringValue());
				}

				if (binding.getValue() instanceof BNode) {
					xmlWriter.setAttribute(TransactionXMLConstants.NAME_ATT, binding.getName());
					xmlWriter.textElement(TransactionXMLConstants.BINDING_BNODE, binding.getValue().stringValue());
				}

				if (binding.getValue() instanceof Literal) {
					xmlWriter.setAttribute(TransactionXMLConstants.NAME_ATT, binding.getName());

					Literal literal = (Literal) binding.getValue();
					if (Literals.isLanguageLiteral(literal)) {
						xmlWriter.setAttribute(TransactionXMLConstants.LANGUAGE_ATT, literal.getLanguage().get());
					} else {
						xmlWriter.setAttribute(TransactionXMLConstants.DATA_TYPE_ATT,
								literal.getDatatype().stringValue());
					}

					xmlWriter.textElement(TransactionXMLConstants.BINDING_LITERAL,
							binding.getValue().stringValue());
				}
			}
		}

		xmlWriter.endTag(TransactionXMLConstants.BINDINGS);
	}

	xmlWriter.endTag(TransactionXMLConstants.SPARQL_UPDATE_TAG);

}