Java Code Examples for org.eclipse.rdf4j.query.algebra.Var#isConstant()

The following examples show how to use org.eclipse.rdf4j.query.algebra.Var#isConstant() . 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: StatementPatternMatcher.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * The following table describes how a Subject, Predicate, and Object Var may be handled for a Statement and a
 * Statement Pattern:
 * <table border=1>
 *     <tr> <th>Pattern's var is constant</th> <th>Effect on resulting BS</th> </tr>
 *     <try> <td>yes</td> <td>Emit a BS if they match, no Context binding</td> </tr>
 *     <try> <td>no</td>  <td>Emit a BS with a binding for the variable</td> </tr>
 * </table>
 *
 * @param var - The statement pattern variable that is being matched. (not null)
 * @param stmtValue - The statement's value for the variable. (not null)
 * @param bs - The binding set that may be updated to include a binding for the variable. (not null)
 * @return {@code true} if he variable and the statement value match, otherwise {@code false},
 */
private boolean matchesValue(final Var var, final Value stmtValue, final QueryBindingSet bs) {
    requireNonNull(var);
    requireNonNull(stmtValue);
    requireNonNull(bs);

    // If the var is a constant, statement's value must match the var's value.
    if(var.isConstant()) {
        if(!stmtValue.equals(var.getValue())) {
            return false;
        }
    } else {
        // Otherwise it is a variable to be filled in.
        bs.addBinding(var.getName(), stmtValue);
    }

    // Either the value matched the constant or the binding set was updated.
    return true;
}
 
Example 2
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meetNAryValueOperator(NAryValueOperator node) {

    List<ValueExpr> oldValues = node.getArguments();
    List<ValueExpr> newValues = Lists.newArrayList();

    for (ValueExpr v : oldValues) {
        if (v instanceof Var) {
            Var var = (Var) v;
            if (!(var.isConstant() && hMap.containsKey(var.getName()))) {
                String val = hMap.get(var.getName());
                if (VarNameUtils.isConstant(val)) {
                    newValues.add(new ValueConstant(valMap.get(val)));
                } else {
                    var.setName(val);
                    newValues.add(var);
                }
            }
        } else {
            newValues.add(v);
        }
    }
    
    node.setArguments(newValues);

}
 
Example 3
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(Var node) throws Exception {

    int count = 1;

    if (!node.isConstant()) {
        if (varMap.containsKey(node.getName())) {
            count = varMap.get(node.getName());
            count++;
            varMap.put(node.getName(), count);
        } else
            varMap.put(node.getName(), 1);

        if (!emptyVarMap.containsKey(node.getName()))
            emptyVarMap.put(node.getName(), 0);

    }
    super.meet(node);
}
 
Example 4
Source File: EventQueryNode.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs an instance of {@link EventQueryNode}.
 * @param usedFilters
 *
 * @param type - The type of {@link Event} this node matches. (not null)
 * @param patterns - The query StatementPatterns that are solved using an
 *   Event of the Type. (not null)
 * @param entities - The {@link EventStorage} that will be searched to match
 *   {@link BindingSet}s when evaluating a query. (not null)
 */
private EventQueryNode(final EventStorage eventStore, final StatementPattern geoPattern, final StatementPattern temporalPattern, final Collection<IndexingExpr> geoFilters, final Collection<IndexingExpr> temporalFilters, final Collection<FunctionCall> usedFilters) throws IllegalStateException {
    this.geoPattern = requireNonNull(geoPattern);
    this.temporalPattern = requireNonNull(temporalPattern);
    this.geoFilters = requireNonNull(geoFilters);
    this.temporalFilters = requireNonNull(temporalFilters);
    this.eventStore = requireNonNull(eventStore);
    this.usedFilters = requireNonNull(usedFilters);
    bindingNames = new HashSet<>();

    // Subject based preconditions.
    verifySameSubjects(getPatterns());
    // Predicate based preconditions.
    verifyAllPredicatesAreConstants(getPatterns());

    // The Subject may either be constant or a variable.
    final Var subject = patterns.iterator().next().getSubjectVar();
    subjectIsConstant = subject.isConstant();
    if(subjectIsConstant) {
        subjectConstant = Optional.of( subject.getValue().toString() );
        subjectVar = Optional.empty();
    } else {
        subjectConstant = Optional.empty();
        subjectVar = Optional.of( subject.getName() );
    }
}
 
Example 5
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(Var node) throws RDFHandlerException {
	Value value;
	if (node.isConstant()) {
		value = node.getValue();
	} else {
		value = getVar(node.getName());
	}
	handler.handleStatement(valueFactory.createStatement(subject, predicate, value));
}
 
Example 6
Source File: DistanceQuerySpec.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
static String getVarName(ValueExpr v) {
	if (v instanceof Var) {
		Var var = (Var) v;
		if (!var.isConstant()) {
			return var.getName();
		}
	}
	return null;
}
 
Example 7
Source File: GeoRelationQuerySpecBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static String getVarName(ValueExpr v) {
	if (v instanceof Var) {
		Var var = (Var) v;
		if (!var.isConstant()) {
			return var.getName();
		}
	}
	return null;
}
 
Example 8
Source File: VarConstantIndexListPruner.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(Var node) throws RuntimeException {

    if (node.isConstant()) {
        String key = node.getValue().toString();
        if(constantMap.containsKey(key)){
            int count = constantMap.get(key);
            count += 1;
            constantMap.put(key, count);
        } else {
            constantMap.put(key, 1);
        }
    }

}
 
Example 9
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 5 votes vote down vote up
public void meet(Var var) {
    if (!var.isConstant() && hMap.containsKey(var.getName())) {
        String val = hMap.get(var.getName());
        if (VarNameUtils.isConstant(val)) {
           var.setName(val);
           var.setValue(valMap.get(val));
           var.setAnonymous(true); //TODO this might be a hack -- when are Vars not anonymous?
        } else {
            var.setName(val);
        }
    }
}
 
Example 10
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
public void meet(Var var) {
    
    if (!(var.getParentNode() instanceof NAryValueOperator)) {
        if (!var.isConstant() && hMap.containsKey(var.getName())) {
            String val = hMap.get(var.getName());
            if (VarNameUtils.isConstant(val)) {
                var.replaceWith(new ValueConstant(valMap.get(val)));
            } else {
                var.setName(val);
            }
        }
    }
}
 
Example 11
Source File: IndexingExpr.java    From rya with Apache License 2.0 5 votes vote down vote up
public Set<String> getBindingNames() {
    //resource and match variable for search are already included as standard result-bindings
    Set<String> bindings = Sets.newHashSet();

    for(Var v: spConstraint.getVarList()) {
        if(!v.isConstant()) {
            bindings.add(v.getName());
        }
    }
    return bindings;
}
 
Example 12
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public Object visit(ASTBind node, Object data) throws VisitorException {
	// bind expression
	Object child0 = node.jjtGetChild(0).jjtAccept(this, data);
	ValueExpr ve = child0 instanceof ValueExpr ? (ValueExpr) child0
			: (child0 instanceof TripleRef) ? ((TripleRef) child0).getExprVar() : null;
	if (ve == null) {
		throw new IllegalArgumentException("Unexpected expressin on bind");
	}

	// name to bind the expression outcome to
	Node aliasNode = node.jjtGetChild(1);
	String alias = ((ASTVar) aliasNode).getName();

	Extension extension = new Extension();
	extension.addElement(new ExtensionElem(ve, alias));

	TupleExpr result = null;
	TupleExpr arg = graphPattern.buildTupleExpr();

	// check if alias is not previously used.
	if (arg.getBindingNames().contains(alias)) {
		// SES-2314 we need to doublecheck that the reused varname is not
		// just
		// for an anonymous var or a constant.
		VarCollector collector = new VarCollector();
		arg.visit(collector);
		for (Var v : collector.getCollectedVars()) {
			if (alias.equals(v.getName())) {
				if (!v.isConstant() && !v.isAnonymous()) {
					throw new VisitorException(String.format("BIND clause alias '%s' was previously used", alias));
				}
				break;
			}
		}
	}

	if (arg instanceof Filter) {
		result = arg;
		// we need to push down the extension so that filters can operate on
		// the BIND expression.
		while (((Filter) arg).getArg() instanceof Filter) {
			arg = ((Filter) arg).getArg();
		}

		extension.setArg(((Filter) arg).getArg());
		((Filter) arg).setArg(extension);
	} else {
		extension.setArg(arg);
		result = extension;
	}

	GraphPattern replacementGP = new GraphPattern(graphPattern);
	replacementGP.addRequiredTE(result);

	graphPattern = replacementGP;

	return result;
}
 
Example 13
Source File: EntityQueryNode.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Constructs an instance of {@link EntityQueryNode}.
 *
 * @param type - The type of {@link Entity} this node matches. (not null)
 * @param patterns - The query StatementPatterns that are solved using an
 *   Entity of the Type. (not null)
 * @param entities - The {@link EntityStorage} that will be searched to match
 *   {@link BindingSet}s when evaluating a query. (not null)
 */
public EntityQueryNode(final Type type, final Collection<StatementPattern> patterns, final EntityStorage entities) throws IllegalStateException {
    this.type = requireNonNull(type);
    this.patterns = requireNonNull(patterns);
    this.entities = requireNonNull(entities);

    bindingNames = new HashSet<>();
    properties = new HashSet<>();
    // Subject based preconditions.
    verifySameSubjects(patterns);

    // Predicate based preconditions.
    verifyAllPredicatesAreConstants(patterns);
    verifyHasCorrectTypePattern(type, patterns);
    verifyAllPredicatesPartOfType(type, patterns);

    // The Subject may either be constant or a variable.
    final Var subject = patterns.iterator().next().getSubjectVar();
    subjectIsConstant = subject.isConstant();
    if(subjectIsConstant) {
        subjectConstant = Optional.of( subject.getValue().toString() );
        subjectVar = Optional.empty();
    } else {
        subjectConstant = Optional.empty();
        subjectVar = Optional.of( subject.getName() );
    }

    // Any constant that appears in the Object portion of the SP will be used to make sure they match.
    final Builder<RyaIRI, Var> builder = ImmutableMap.builder();
    for(final StatementPattern sp : patterns) {
        final Var object = sp.getObjectVar();
        final Var pred = sp.getPredicateVar();
        final RyaIRI predIRI = new RyaIRI(pred.getValue().stringValue());
        bindingNames.addAll(sp.getBindingNames());
        if(object.isConstant() && !pred.getValue().equals(RDF.TYPE)) {
            final RyaType propertyType = RdfToRyaConversions.convertValue(object.getValue());
            properties.add(new Property(predIRI, propertyType));
        }
        builder.put(predIRI, object);
    }
    objectVariables = builder.build();
}
 
Example 14
Source File: StarQuery.java    From rya with Apache License 2.0 4 votes vote down vote up
private Var getCommonVar(final List<StatementPattern> nodes) {

        Set<Var> vars = null;
        final List<Var> tempVar;
        Set<Var> tempSet;

        int i = 0;
        for (final StatementPattern sp : nodes) {

            if (vars == null) {
                vars = Sets.newHashSet();
                vars.add(sp.getSubjectVar());
                vars.add(sp.getObjectVar());
            } else {
                tempSet = Sets.newHashSet();
                tempSet.add(sp.getSubjectVar());
                tempSet.add(sp.getObjectVar());
                vars = Sets.intersection(vars, tempSet);
            }

        }
        if (vars == null) {
            throw new NullPointerException("vars is null so the list of statement pattern nodes must be empty: nodes.size()= " + nodes.size());
        }
        if (vars.size() == 1) {
            return vars.iterator().next();
        } else if (vars.size() > 1) {
            Var first = null;

            i = 0;

            for (final Var v : vars) {
                i++;

                if (i == 1) {
                    first = v;
                } else {
                    if (v.isConstant()) {
                        return v;
                    }
                }
            }

            return first;

        } else {
            throw new IllegalStateException("No common Var!");
        }

    }
 
Example 15
Source File: StarQuery.java    From rya with Apache License 2.0 4 votes vote down vote up
public static boolean isValidStarQuery(final Collection<StatementPattern> nodes) {

        Set<String> bindings = null;
        boolean contextSet = false;
        Var context = null;

        if(nodes.size() < 2) {
            return false;
        }

        for(final StatementPattern sp: nodes) {

            final Var tempContext = sp.getContextVar();
            final Var predVar = sp.getPredicateVar();

            //does not support variable context
            if(tempContext != null && !tempContext.isConstant()) {
               return false;
            }
            if(!contextSet) {
                context = tempContext;
                contextSet = true;
            } else {

                if(context == null && tempContext != null) {
                    return false;
                } else if (context != null && !context.equals(tempContext)) {
                    return false;
                }
            }

            if(!predVar.isConstant()) {
                return false;
            }

            if(bindings == null ) {
                bindings = sp.getBindingNames();
                if(bindings.size() == 0) {
                    return false;
                }
            } else {
                bindings = Sets.intersection(bindings, sp.getBindingNames());
                if(bindings.size() == 0) {
                    return false;
                }
            }

        }


        return isBindingsetValid(bindings);
    }
 
Example 16
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 3 votes vote down vote up
public void meet(Var var) {
    if (var.isConstant()) {
        valMap.put(var.getName(),var.getValue());
    }
    
    
}