Java Code Examples for org.eclipse.rdf4j.query.BindingSet#hasBinding()

The following examples show how to use org.eclipse.rdf4j.query.BindingSet#hasBinding() . 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: QueryStringUtil.java    From CostFed with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Construct the statement string, i.e. "s p ?o_varID FILTER ?o_N=o ". This kind of statement
 * pattern is necessary to later on identify available results.
 * 
 * @param stmt
 * @param varID
 * @param varNames
 * @param bindings
 * @return
 */
protected static String constructStatementCheckId(StatementPattern stmt, int varID, Set<String> varNames, BindingSet bindings) {
	StringBuilder sb = new StringBuilder();
	
	String _varID = Integer.toString(varID);
	sb = appendVarId(sb, stmt.getSubjectVar(), _varID, varNames, bindings).append(" ");
	sb = appendVarId(sb, stmt.getPredicateVar(), _varID, varNames, bindings).append(" ");
	
	sb.append("?o_").append(_varID);
	varNames.add("o_" + _varID);
	
	String objValue;
	if (stmt.getObjectVar().hasValue()) {
		objValue = getValueString(stmt.getObjectVar().getValue());
	} else if (bindings.hasBinding(stmt.getObjectVar().getName())){
		objValue = getValueString(bindings.getBinding(stmt.getObjectVar().getName()).getValue());
	} else {
		// just to make sure that we see an error, will be deleted soon
		throw new RuntimeException("Unexpected.");
	}
	
	sb.append(" FILTER (?o_").append(_varID).append(" = ").append(objValue).append(" )");
			
	return sb.toString();
}
 
Example 2
Source File: PathIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public PathIteration(StrictEvaluationStrategy evaluationStrategyImpl, Scope scope, Var startVar,
		TupleExpr pathExpression, Var endVar, Var contextVar, long minLength, BindingSet bindings)
		throws QueryEvaluationException {
	this.evaluationStrategyImpl = evaluationStrategyImpl;
	this.scope = scope;
	this.startVar = startVar;
	this.endVar = endVar;

	this.startVarFixed = startVar.hasValue() || bindings.hasBinding(startVar.getName());
	this.endVarFixed = endVar.hasValue() || bindings.hasBinding(endVar.getName());

	this.pathExpression = pathExpression;
	this.contextVar = contextVar;

	this.currentLength = minLength;
	this.bindings = bindings;

	this.reportedValues = makeSet();
	this.unreportedValues = makeSet();
	this.valueQueue = makeQueue();

	createIteration();
}
 
Example 3
Source File: BindingSetStringConverter.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public String convert(final BindingSet bindingSet, final VariableOrder varOrder) {
    requireNonNull(bindingSet);
    requireNonNull(varOrder);

    // Convert each Binding to a String.
    final List<String> bindingStrings = new ArrayList<>();
    for(final String varName : varOrder) {
        if(bindingSet.hasBinding(varName)) {
            // Add a value to the binding set.
            final Value value = bindingSet.getBinding(varName).getValue();
            final RyaType ryaValue = RdfToRyaConversions.convertValue(value);
            final String bindingString = ryaValue.getData() + TYPE_DELIM + ryaValue.getDataType();
            bindingStrings.add(bindingString);
        } else {
            // Add a null value to the binding set.
            bindingStrings.add(NULL_VALUE_STRING);
        }
    }

    // Join the bindings using the binding delim.
    return Joiner.on(BINDING_DELIM).join(bindingStrings);
}
 
Example 4
Source File: StatisticsUtil.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static Value toValue(Var var, BindingSet bindings) {
	if (var.hasValue())
		return var.getValue();
	
	if (bindings.hasBinding(var.getName()))	
		return bindings.getValue(var.getName());
	
	return null;			
}
 
Example 5
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Append the variable to the provided StringBuilder, however change name of variable by appending "_varId" to it.
 *
 * Cases: 1) unbound: check provided bindingset for possible match a) match found: append matching value b) no
 * match: append ?varName_varId and add to varNames 2) bound: append value
 *
 * @param sb
 * @param var
 * @param varNames
 * @param bindings
 *
 * @return the complemented string builder
 */
protected static StringBuilder appendVarId(StringBuilder sb, Var var, String varID, Set<String> varNames,
		BindingSet bindings) {
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName())) {
			return appendValue(sb, bindings.getValue(var.getName()));
		}
		String newName = var.getName() + "_" + varID;
		varNames.add(newName);
		return sb.append("?").append(newName);
	} else {
		return appendValue(sb, var.getValue());
	}
}
 
Example 6
Source File: StrictEvaluationStrategy.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected boolean isUnbound(Var var, BindingSet bindings) {
	if (var == null) {
		return false;
	} else {
		return bindings.hasBinding(var.getName()) && bindings.getValue(var.getName()) == null;
	}
}
 
Example 7
Source File: QueryStringUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * returns true iff there is at least one free variable, i.e. there is no binding for any variable
 *
 * @param stmt
 * @param bindings
 * @return whether free vars are available
 */
public static boolean hasFreeVars(StatementPattern stmt, BindingSet bindings) {
	for (Var var : stmt.getVarList()) {
		if (!var.hasValue() && !bindings.hasBinding(var.getName())) {
			return true; // there is at least one free var
		}
	}
	return false;
}
 
Example 8
Source File: ExclusiveGroup.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public boolean hasFreeVarsFor(BindingSet bindings) {
	for (String var : freeVars) {
		if (!bindings.hasBinding(var)) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source File: AccumuloPcjSerializer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] convert(BindingSet bindingSet, VariableOrder varOrder) throws BindingSetConversionException {
    checkNotNull(bindingSet);
    checkNotNull(varOrder);

    // A list that holds all of the byte segments that will be concatenated at the end.
    // This minimizes byte[] construction.
    final List<byte[]> byteSegments = new LinkedList<>();

    try {
        for(final String varName: varOrder) {
            // Only write information for a variable name if the binding set contains it.
            if(bindingSet.hasBinding(varName)) {
                final RyaType rt = RdfToRyaConversions.convertValue(bindingSet.getBinding(varName).getValue());
                final byte[][] serializedVal = RyaContext.getInstance().serializeType(rt);
                byteSegments.add(serializedVal[0]);
                byteSegments.add(serializedVal[1]);
            }

            // But always write the value delimiter. If a value is missing, you'll see two delimiters next to each-other.
            byteSegments.add(DELIM_BYTES);
        }

        return concat(byteSegments);
    } catch (RyaTypeResolverException e) {
        throw new BindingSetConversionException("Could not convert the BindingSet into a byte[].", e);
    }
}
 
Example 10
Source File: BindingSetUtil.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a subset of vars with the variable names that appear in bindings.
 * @param vars
 * @param bindings
 * @return
 */

public static Collection<String> projectNames(Collection<String> vars, BindingSet bindings) {
    Set<String> names = new HashSet<String>();

    for (String varName : vars) {
        if (bindings.hasBinding(varName))
            names.add(varName);
    }
    return names;
}
 
Example 11
Source File: SPARQLComplianceTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected static final void printBindingSet(BindingSet bs, StringBuilder appendable) {
	List<String> names = new ArrayList<>(bs.getBindingNames());
	Collections.sort(names);

	for (String name : names) {
		if (bs.hasBinding(name)) {
			appendable.append(bs.getBinding(name));
			appendable.append(' ');
		}
	}
	appendable.append("\n");
}
 
Example 12
Source File: PathIteration.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
protected boolean isUnbound(Var var, BindingSet bindings) {
	if (var == null) {
		return false;
	} else {
		return bindings.hasBinding(var.getName()) && bindings.getValue(var.getName()) == null;
	}
}
 
Example 13
Source File: FedXStatementPattern.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean hasFreeVarsFor(BindingSet bindings) {
	for (String var : freeVars)
		if (!bindings.hasBinding(var))
			return true;
	return false;		
}
 
Example 14
Source File: BindingSetUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link BindingSet} that only includes the bindings whose names appear within the {@code variableOrder}.
 * If no binding is found for a variable, then that binding is just omitted from the resulting object.
 *
 * @param variableOrder - Defines which bindings will be kept. (not null)
 * @param bindingSet - Contains the source {@link Binding}s. (not null)
 * @return A new {@link BindingSet} containing only the specified bindings.
 */
public static BindingSet keepBindings(final VariableOrder variableOrder, final BindingSet bindingSet) {
    requireNonNull(variableOrder);
    requireNonNull(bindingSet);

    final MapBindingSet result = new MapBindingSet();
    for(final String bindingName : variableOrder) {
        if(bindingSet.hasBinding(bindingName)) {
            final Binding binding = bindingSet.getBinding(bindingName);
            result.addBinding(binding);
        }
    }
    return result;
}
 
Example 15
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Clone the specified variable and attach bindings.
 *
 * @param var
 * @param varNames
 * @param bindings
 *
 * @return the variable
 *
 */
protected static Var appendVar(Var var, Set<String> varNames, BindingSet bindings) {
	Var res = var.clone();
	if (!var.hasValue()) {
		if (bindings.hasBinding(var.getName())) {
			res.setValue(bindings.getValue(var.getName()));
		} else {
			varNames.add(var.getName());
		}
	}
	return res;
}
 
Example 16
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 17
Source File: QueryAlgebraUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Construct the statement string, i.e. "s p ?o_varID FILTER ?o_N=o ". This kind of statement pattern is necessary
 * to later on identify available results.
 *
 * @param stmt
 * @param varID
 * @param varNames
 * @param bindings
 * @return the expression
 */
protected static TupleExpr constructStatementCheckId(StatementPattern stmt, int varID, Set<String> varNames,
		BindingSet bindings) {

	String _varID = Integer.toString(varID);
	Var subj = appendVarId(stmt.getSubjectVar(), _varID, varNames, bindings);
	Var pred = appendVarId(stmt.getPredicateVar(), _varID, varNames, bindings);

	Var obj = new Var("o_" + _varID);
	varNames.add("o_" + _varID);

	Value objValue;
	if (stmt.getObjectVar().hasValue()) {
		objValue = stmt.getObjectVar().getValue();
	} else if (bindings.hasBinding(stmt.getObjectVar().getName())) {
		objValue = bindings.getBinding(stmt.getObjectVar().getName()).getValue();
	} else {
		// just to make sure that we see an error, will be deleted soon
		throw new RuntimeException("Unexpected.");
	}

	Compare cmp = new Compare(obj, new ValueConstant(objValue));
	cmp.setOperator(CompareOp.EQ);
	Filter filter = new Filter(new StatementPattern(subj, pred, obj), cmp);

	return filter;
}
 
Example 18
Source File: ExclusiveGroup.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public boolean hasFreeVarsFor(BindingSet bindings) {
	for (String var : freeVars)
		if (!bindings.hasBinding(var))
			return true;
	return false;		
}
 
Example 19
Source File: EventQueryNode.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
public CloseableIteration<BindingSet, QueryEvaluationException> evaluate(final BindingSet bindings) throws QueryEvaluationException {
    final List<BindingSet> list = new ArrayList<>();
    try {
        final Collection<Event> searchEvents;
        final String subj;
        //if the provided binding set has the subject already, set it to the constant subject.
        if(!subjectConstant.isPresent() && bindings.hasBinding(subjectVar.get())) {
            subjectConstant = Optional.of(bindings.getValue(subjectVar.get()).stringValue());
        } else if(bindings.size() != 0) {
            list.add(bindings);
        }

        // If the subject needs to be filled in, check if the subject variable is in the binding set.
        if(subjectConstant.isPresent()) {
            // if it is, fetch that value and then fetch the entity for the subject.
            subj = subjectConstant.get();
            searchEvents = eventStore.search(Optional.of(new RyaIRI(subj)), Optional.of(geoFilters), Optional.of(temporalFilters));
        } else {
            searchEvents = eventStore.search(Optional.empty(), Optional.of(geoFilters), Optional.of(temporalFilters));
        }

        for(final Event event : searchEvents) {
            final MapBindingSet resultSet = new MapBindingSet();
            if(event.getGeometry().isPresent()) {
                final Geometry geo = event.getGeometry().get();
                final Value geoValue = VF.createLiteral(geo.toText());
                final Var geoObj = geoPattern.getObjectVar();
                resultSet.addBinding(geoObj.getName(), geoValue);
            }

            final Value temporalValue;
            if(event.isInstant() && event.getInstant().isPresent()) {
                final Optional<TemporalInstant> opt = event.getInstant();
                DateTime dt = opt.get().getAsDateTime();
                dt = dt.toDateTime(DateTimeZone.UTC);
                final String str = dt.toString(TemporalInstantRfc3339.FORMATTER);
                temporalValue = VF.createLiteral(str);
            } else if(event.getInterval().isPresent()) {
                temporalValue = VF.createLiteral(event.getInterval().get().getAsPair());
            } else {
                temporalValue = null;
            }

            if(temporalValue != null) {
                final Var temporalObj = temporalPattern.getObjectVar();
                resultSet.addBinding(temporalObj.getName(), temporalValue);
            }
            list.add(resultSet);
        }
    } catch (final ObjectStorageException e) {
        throw new QueryEvaluationException("Failed to evaluate the binding set", e);
    }
    return new CollectionIteration<>(list);
}
 
Example 20
Source File: QueryAlgebraUtil.java    From CostFed with GNU Affero General Public License v3.0 3 votes vote down vote up
/**
 * returns true iff there is at least one free variable, i.e. there is no binding
 * for any variable
 * 
 * @param stmt
 * @param bindings
 * @return
 */
public static boolean hasFreeVars(StatementPattern stmt, BindingSet bindings) {
	for (Var var : stmt.getVarList()) {
		if(!var.hasValue() && !bindings.hasBinding(var.getName()))
			return true;	// there is at least one free var				
	}
	return false;
}