org.eclipse.rdf4j.query.algebra.ValueConstant Java Examples

The following examples show how to use org.eclipse.rdf4j.query.algebra.ValueConstant. 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: GeoParseUtils.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Extracts the arguments used in a {@link FunctionCall}.
 * @param matchName - The variable name to match to arguments used in the {@link FunctionCall}.
 * @param call - The {@link FunctionCall} to match against.
 * @return - The {@link Value}s matched.
 */
public static Object[] extractArguments(final String matchName, final FunctionCall call) {
    final Object[] args = new Object[call.getArgs().size() - 1];
    int argI = 0;
    for (int i = 0; i != call.getArgs().size(); ++i) {
        final ValueExpr arg = call.getArgs().get(i);
        if (argI == i && arg instanceof Var && matchName.equals(((Var)arg).getName())) {
            continue;
        }
        if (arg instanceof ValueConstant) {
            args[argI] = ((ValueConstant)arg).getValue();
        } else if (arg instanceof Var && ((Var)arg).hasValue()) {
            args[argI] = ((Var)arg).getValue();
        } else {
            args[argI] = arg;
        }
        ++argI;
    }
    return args;
}
 
Example #2
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ValueConstant visit(ASTRDFLiteral node, Object data) throws VisitorException {
	String label = (String) node.getLabel().jjtAccept(this, null);
	String lang = node.getLang();
	ASTIRI datatypeNode = node.getDatatype();

	Literal literal;
	if (datatypeNode != null) {
		IRI datatype;
		try {
			datatype = valueFactory.createIRI(datatypeNode.getValue());
		} catch (IllegalArgumentException e) {
			// invalid URI
			throw new VisitorException(e.getMessage());
		}
		literal = valueFactory.createLiteral(label, datatype);
	} else if (lang != null) {
		literal = valueFactory.createLiteral(label, lang);
	} else {
		literal = valueFactory.createLiteral(label);
	}

	return new ValueConstant(literal);
}
 
Example #3
Source File: RegexAsStringFunctionOptimizer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(Regex node) {
	final ValueExpr flagsArg = node.getFlagsArg();
	if (flagsArg == null || flagsArg.toString().isEmpty()) {
		// if we have no flags then we can not be in case insensitive mode
		if (node.getPatternArg() instanceof ValueConstant) {
			ValueConstant vc = (ValueConstant) node.getPatternArg();
			String regex = vc.getValue().stringValue();
			final boolean anchoredAtStart = regex.startsWith("^");
			final boolean anchoredAtEnd = regex.endsWith("$");

			if (anchoredAtStart && anchoredAtEnd) {
				equalsCandidate(node, regex);
			} else if (anchoredAtStart) {
				strstartsCandidate(node, regex);
			} else if (anchoredAtEnd) {
				strendsCandidate(node, regex);
			} else {
				containsCandidate(node, regex);
			}
		}
	}
	super.meet(node);
}
 
Example #4
Source File: EventQueryNode2IT.java    From rya with Apache License 2.0 6 votes vote down vote up
private static Value[] extractArguments(final String matchName, final FunctionCall call) {
    final Value args[] = new Value[call.getArgs().size() - 1];
    int argI = 0;
    for (int i = 0; i != call.getArgs().size(); ++i) {
        final ValueExpr arg = call.getArgs().get(i);
        if (argI == i && arg instanceof Var && matchName.equals(((Var)arg).getName())) {
            continue;
        }
        if (arg instanceof ValueConstant) {
            args[argI] = ((ValueConstant)arg).getValue();
        } else if (arg instanceof Var && ((Var)arg).hasValue()) {
            args[argI] = ((Var)arg).getValue();
        } else {
            throw new IllegalArgumentException("Query error: Found " + arg + ", expected a Literal, BNode or URI");
        }
        ++argI;
    }
    return args;
}
 
Example #5
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Add visit(ASTAdd node, Object data) throws VisitorException {
	Add add = new Add();
	add.setSilent(node.isSilent());

	ASTGraphOrDefault sourceNode = (ASTGraphOrDefault) node.jjtGetChild(0);
	if (sourceNode.jjtGetNumChildren() > 0) {
		ValueConstant sourceGraph = (ValueConstant) sourceNode.jjtGetChild(0).jjtAccept(this, data);
		add.setSourceGraph(sourceGraph);
	}

	ASTGraphOrDefault destinationNode = (ASTGraphOrDefault) node.jjtGetChild(1);
	if (destinationNode.jjtGetNumChildren() > 0) {
		ValueConstant destinationGraph = (ValueConstant) destinationNode.jjtGetChild(0).jjtAccept(this, data);
		add.setDestinationGraph(destinationGraph);
	}
	return add;
}
 
Example #6
Source File: QueryModelBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public ValueConstant visit(ASTLiteral litNode, Object data) throws VisitorException {
	IRI datatype = null;

	// Get datatype URI from child URI node, if present
	ASTValueExpr dtNode = litNode.getDatatypeNode();
	if (dtNode instanceof ASTURI) {
		datatype = valueFactory.createIRI(((ASTURI) dtNode).getValue());
	} else if (dtNode != null) {
		throw new IllegalArgumentException("Unexpected datatype type: " + dtNode.getClass());
	}

	Literal literal;
	if (datatype != null) {
		literal = valueFactory.createLiteral(litNode.getLabel(), datatype);
	} else if (litNode.hasLang()) {
		literal = valueFactory.createLiteral(litNode.getLabel(), litNode.getLang());
	} else {
		literal = valueFactory.createLiteral(litNode.getLabel());
	}

	return new ValueConstant(literal);
}
 
Example #7
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Move visit(ASTMove node, Object data) throws VisitorException {
	Move move = new Move();
	move.setSilent(node.isSilent());

	ASTGraphOrDefault sourceNode = (ASTGraphOrDefault) node.jjtGetChild(0);
	if (sourceNode.jjtGetNumChildren() > 0) {
		ValueConstant sourceGraph = (ValueConstant) sourceNode.jjtGetChild(0).jjtAccept(this, data);
		move.setSourceGraph(sourceGraph);
	}

	ASTGraphOrDefault destinationNode = (ASTGraphOrDefault) node.jjtGetChild(1);
	if (destinationNode.jjtGetNumChildren() > 0) {
		ValueConstant destinationGraph = (ValueConstant) destinationNode.jjtGetChild(0).jjtAccept(this, data);
		move.setDestinationGraph(destinationGraph);
	}
	return move;
}
 
Example #8
Source File: FilterRangeVisitor.java    From rya with Apache License 2.0 6 votes vote down vote up
@Override
public void meet(final Filter node) throws Exception {
    super.meet(node);

    final ValueExpr arg = node.getCondition();
    if (arg instanceof FunctionCall) {
        final FunctionCall fc = (FunctionCall) arg;
        if (RANGE.stringValue().equals(fc.getURI())) {
            //range(?var, start, end)
            final List<ValueExpr> valueExprs = fc.getArgs();
            if (valueExprs.size() != 3) {
                throw new QueryEvaluationException("org.apache:range must have 3 parameters: variable, start, end");
            }
            final Var var = (Var) valueExprs.get(0);
            final ValueConstant startVc = (ValueConstant) valueExprs.get(1);
            final ValueConstant endVc = (ValueConstant) valueExprs.get(2);
            final Value start = startVc.getValue();
            final Value end = endVc.getValue();
            rangeValues.put(var, new RangeValue(start, end));
            node.setCondition(new ValueConstant(BooleanLiteral.TRUE));
        }
    }
}
 
Example #9
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Clear visit(ASTDrop node, Object data) throws VisitorException {
	// implementing drop as a synonym of clear, in Sesame this is really the
	// same thing, as empty
	// graphs are not recorded.

	Clear clear = new Clear();
	clear.setSilent(node.isSilent());

	ASTGraphRefAll graphRef = node.jjtGetChild(ASTGraphRefAll.class);

	if (graphRef.jjtGetNumChildren() > 0) {
		ValueConstant graph = (ValueConstant) graphRef.jjtGetChild(0).jjtAccept(this, data);
		clear.setGraph(graph);
	} else {
		if (graphRef.isDefault()) {
			clear.setScope(Scope.DEFAULT_CONTEXTS);
		} else if (graphRef.isNamed()) {
			clear.setScope(Scope.NAMED_CONTEXTS);
		}
	}
	return clear;
}
 
Example #10
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnsupportedExtension() throws Exception {
    StatementPattern sp = new StatementPattern(new Var("x"), constant(TAKES), new Var("c"));
    List<ExtensionElem> elements = Arrays.asList(new ExtensionElem(new Var("x"), "renamed"),
            new ExtensionElem(new Not(new ValueConstant(VF.createLiteral(true))), "notTrue"),
            new ExtensionElem(new ValueConstant(TAKES), "constant"));
    Extension extensionNode = new Extension(sp, elements);
    QueryRoot queryTree = new QueryRoot(extensionNode);
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof Extension);
    Assert.assertEquals(elements, ((Extension) queryTree.getArg()).getElements());
    TupleExpr innerQuery = ((Extension) queryTree.getArg()).getArg();
    Assert.assertTrue(innerQuery instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) innerQuery;
    Assert.assertEquals(Sets.newHashSet("x", "c"), pipelineNode.getAssuredBindingNames());
}
 
Example #11
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Clear visit(ASTClear node, Object data) throws VisitorException {
	Clear clear = new Clear();
	clear.setSilent(node.isSilent());

	ASTGraphRefAll graphRef = node.jjtGetChild(ASTGraphRefAll.class);

	if (graphRef.jjtGetNumChildren() > 0) {
		ValueConstant graph = (ValueConstant) graphRef.jjtGetChild(0).jjtAccept(this, data);
		clear.setGraph(graph);
	} else {
		if (graphRef.isDefault()) {
			clear.setScope(Scope.DEFAULT_CONTEXTS);
		} else if (graphRef.isNamed()) {
			clear.setScope(Scope.NAMED_CONTEXTS);
		}
	}
	return clear;
}
 
Example #12
Source File: SpinRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(ProjectionElem node) throws RDFHandlerException {
	if (isSubQuery) {
		super.meet(node);
	} else {
		String varName = node.getSourceName();
		ValueExpr valueExpr = inlineBindings.getValueExpr(varName);
		Value value = (valueExpr instanceof ValueConstant) ? ((ValueConstant) valueExpr).getValue()
				: getVar(varName);
		String targetName = node.getTargetName();
		IRI pred;
		if ("subject".equals(targetName)) {
			pred = SP.SUBJECT_PROPERTY;
		} else if ("predicate".equals(targetName)) {
			pred = SP.PREDICATE_PROPERTY;
		} else if ("object".equals(targetName)) {
			pred = SP.OBJECT_PROPERTY;
		} else {
			throw new AssertionError("Unexpected ProjectionElem: " + node);
		}
		handler.handleStatement(valueFactory.createStatement(subject, pred, value));
	}
}
 
Example #13
Source File: PeriodicQueryUtil.java    From rya with Apache License 2.0 6 votes vote down vote up
private static TimeUnit getTimeUnit(ValueConstant val) {
    Preconditions.checkArgument(val.getValue() instanceof IRI);
    IRI uri = (IRI) val.getValue();
    Preconditions.checkArgument(uri.getNamespace().equals(temporalNameSpace));

    switch (uri.getLocalName()) {
    case "days":
        return TimeUnit.DAYS;
    case "hours":
        return TimeUnit.HOURS;
    case "minutes":
        return TimeUnit.MINUTES;
    default:
        throw new IllegalArgumentException("Invalid time unit for Periodic Function.");
    }
}
 
Example #14
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 #15
Source File: GeoTemporalMongoDBStorageStrategyTest.java    From rya with Apache License 2.0 6 votes vote down vote up
private static Value[] extractArguments(final String matchName, final FunctionCall call) {
    final Value args[] = new Value[call.getArgs().size() - 1];
    int argI = 0;
    for (int i = 0; i != call.getArgs().size(); ++i) {
        final ValueExpr arg = call.getArgs().get(i);
        if (argI == i && arg instanceof Var && matchName.equals(((Var)arg).getName())) {
            continue;
        }
        if (arg instanceof ValueConstant) {
            args[argI] = ((ValueConstant)arg).getValue();
        } else if (arg instanceof Var && ((Var)arg).hasValue()) {
            args[argI] = ((Var)arg).getValue();
        } else {
            throw new IllegalArgumentException("Query error: Found " + arg + ", expected a Literal, BNode or URI");
        }
        ++argI;
    }
    return args;
}
 
Example #16
Source File: QueryModelBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Var visit(ASTEdge node, Object data) throws VisitorException {
	ValueExpr arg = (ValueExpr) node.getValueExpr().jjtAccept(this, null);

	if (arg instanceof Var) {
		return (Var) arg;
	} else if (arg instanceof ValueConstant) {
		ValueConstant vc = (ValueConstant) arg;
		return createConstantVar(vc.getValue());
	} else {
		throw new IllegalArgumentException("Unexpected edge argument type: " + arg.getClass());
	}
}
 
Example #17
Source File: SPARQLValueExprRenderer.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(ValueConstant theVal)
        throws Exception
{
    mBuffer.append(SPARQLQueryStringUtil.toSPARQL(theVal.getValue()));
}
 
Example #18
Source File: ConstructConsequentVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultiProjection() {
    Extension extension = new Extension(new SingletonSet(),
            new ExtensionElem(new ValueConstant(RDF.TYPE), "rdftype"),
            new ExtensionElem(new ValueConstant(OWL.OBJECTPROPERTY), "owlprop"),
            new ExtensionElem(new ValueConstant(OWL.EQUIVALENTCLASS), "owleqcls"),
            new ExtensionElem(new ValueConstant(OWL.CLASS), "owlclass"));
    MultiProjection projection = new MultiProjection(extension, Arrays.asList(
            new ProjectionElemList(
                    new ProjectionElem("cls", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlclass", "object")),
            new ProjectionElemList(
                    new ProjectionElem("prop", "subject"),
                    new ProjectionElem("rdftype", "predicate"),
                    new ProjectionElem("owlprop", "object")),
            new ProjectionElemList(
                    new ProjectionElem("owleqcls", "predicate"),
                    new ProjectionElem("cls", "object"))));
    ConstructConsequentVisitor visitor = new ConstructConsequentVisitor();
    projection.visit(visitor);
    Set<StatementPattern> expected = Sets.newHashSet(
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.CLASS)),
            new StatementPattern(s(null), p(RDF.TYPE), o(OWL.OBJECTPROPERTY)),
            new StatementPattern(s(null), p(OWL.EQUIVALENTCLASS), o(null)));
    Assert.assertEquals(expected, visitor.getConsequents());
}
 
Example #19
Source File: SparqlToPipelineTransformVisitorTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtension() throws Exception {
    QueryRoot queryTree = new QueryRoot(new Extension(
            new StatementPattern(new Var("x"), constant(TAKES), new Var("c")),
            new ExtensionElem(new Var("x"), "renamed"),
            new ExtensionElem(new ValueConstant(TAKES), "constant")));
    SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(collection);
    queryTree.visit(visitor);
    Assert.assertTrue(queryTree.getArg() instanceof AggregationPipelineQueryNode);
    AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) queryTree.getArg();
    Assert.assertEquals(Sets.newHashSet("x", "c", "renamed", "constant"), pipelineNode.getAssuredBindingNames());
}
 
Example #20
Source File: PeriodicQueryUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param values - Values extracted from FunctionCall representing the PeriodicQuery Filter
 * @param arg - Argument of the PeriodicQueryNode that will be created (PeriodicQueryNode is a UnaryTupleOperator)
 * @return - PeriodicQueryNode to be inserted in place of the original FunctionCall
 * @throws Exception
 */
private static PeriodicQueryNode parseAndSetValues(List<ValueExpr> values, TupleExpr arg) throws Exception {
    // general validation of input
    Preconditions.checkArgument(values.size() == 4);
    Preconditions.checkArgument(values.get(0) instanceof Var);
    Preconditions.checkArgument(values.get(1) instanceof ValueConstant);
    Preconditions.checkArgument(values.get(2) instanceof ValueConstant);
    Preconditions.checkArgument(values.get(3) instanceof ValueConstant);

    // get temporal variable
    Var var = (Var) values.get(0);
    Preconditions.checkArgument(var.getValue() == null);
    String tempVar = var.getName();

    // get TimeUnit
    TimeUnit unit = getTimeUnit((ValueConstant) values.get(3));

    // get window and period durations
    double windowDuration = parseTemporalDuration((ValueConstant) values.get(1));
    double periodDuration = parseTemporalDuration((ValueConstant) values.get(2));
    long windowMillis = convertToMillis(windowDuration, unit);
    long periodMillis = convertToMillis(periodDuration, unit);
    // period must evenly divide window at least once
    Preconditions.checkArgument(windowMillis > periodMillis);
    Preconditions.checkArgument(windowMillis % periodMillis == 0, "Period duration does not evenly divide window duration.");

    // create PeriodicMetadata.Builder
    return new PeriodicQueryNode(windowMillis, periodMillis, TimeUnit.MILLISECONDS, tempVar, arg);
}
 
Example #21
Source File: PeriodicQueryUtil.java    From rya with Apache License 2.0 5 votes vote down vote up
private static double parseTemporalDuration(ValueConstant valConst) {
    Value val = valConst.getValue();
    Preconditions.checkArgument(val instanceof Literal);
    Literal literal = (Literal) val;
    String stringVal = literal.getLabel();
    IRI dataType = literal.getDatatype();
    Preconditions.checkArgument(dataType.equals(XMLSchema.DECIMAL) || dataType.equals(XMLSchema.DOUBLE)
            || dataType.equals(XMLSchema.FLOAT) || dataType.equals(XMLSchema.INTEGER) || dataType.equals(XMLSchema.INT));
    return Double.parseDouble(stringVal);
}
 
Example #22
Source File: QueryVariableNormalizer.java    From rya with Apache License 2.0 5 votes vote down vote up
private static List<List<String>> filterCommonVars(List<QueryModelNode> vars1, List<QueryModelNode> vars2) {
    
    
    List<List<String>> varList = Lists.newArrayList();
    List<String> varList1 = Lists.newArrayList();
    List<String> varList2 = Lists.newArrayList();
    

    
    for (int i = 0; i < vars1.size(); i++) {

        if ((vars1.get(i) instanceof ValueConstant) && (vars2.get(i) instanceof Var)) {
            
            ValueConstant vc = (ValueConstant) vars1.get(i);
            final String s = VarNameUtils.createUniqueConstVarName(vc.getValue());
            varList1.add(s);
            varList2.add(((Var)vars2.get(i)).getName());
        } else if(!(vars1.get(i) instanceof ValueConstant)){
            if (!((Var) vars1.get(i)).isConstant() && (vars2.get(i) instanceof Var)
                    && !((Var) vars2.get(i)).isConstant()) {
                varList1.add(((Var) vars1.get(i)).getName());
                varList2.add(((Var) vars2.get(i)).getName());
            } else if (((Var) vars1.get(i)).isConstant() && (vars2.get(i) instanceof Var)
                    && !((Var) vars2.get(i)).isConstant()) {
                varList1.add(((Var) vars1.get(i)).getName());
                varList2.add(((Var) vars2.get(i)).getName());
            }
        }

    }
    
    varList.add(varList1);
    varList.add(varList2);

    return varList;
}
 
Example #23
Source File: PeriodicQueryUtilTest.java    From rya with Apache License 2.0 5 votes vote down vote up
@Test
public void periodicNodePresentTest() throws Exception {
    
    List<ValueExpr> values = Arrays.asList(new Var("time"), new ValueConstant(VF.createLiteral(12.0)), new ValueConstant(VF.createLiteral(6.0)), new ValueConstant(VF.createIRI(PeriodicQueryUtil.temporalNameSpace + "hours")));
    FunctionCall func = new FunctionCall(PeriodicQueryUtil.PeriodicQueryURI, values);
    Optional<PeriodicQueryNode> node1 = PeriodicQueryUtil.getPeriodicQueryNode(func, new Join());
    Assert.assertEquals(true, node1.isPresent());
    
    PeriodicQueryNode node2 = new PeriodicQueryNode(12*60*60*1000L, 6*3600*1000L, TimeUnit.MILLISECONDS, "time", new Join());
    
    Assert.assertEquals(true, periodicNodesEqualIgnoreArg(node1.get(), node2));
}
 
Example #24
Source File: AggregationPipelineQueryNode.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Get an object representing the value field of some value expression, or
 * return null if the expression isn't supported.
 */
private Object valueFieldExpr(final ValueExpr expr) {
    if (expr instanceof Var) {
        return valueFieldExpr(((Var) expr).getName());
    }
    else if (expr instanceof ValueConstant) {
        return new Document("$literal", ((ValueConstant) expr).getValue().stringValue());
    }
    else {
        return null;
    }
}
 
Example #25
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public PropertySetElem visit(ASTPathOneInPropertySet node, Object data) throws VisitorException {

	PropertySetElem result = new PropertySetElem();
	result.setInverse(node.isInverse());
	ValueConstant predicate = (ValueConstant) node.jjtGetChild(0).jjtAccept(this, data);
	result.setPredicate(predicate);

	return result;
}
 
Example #26
Source File: SparqlTupleExprRenderer.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(final Filter theFilter) throws Exception {
	ctxOpen(theFilter);

	if (theFilter.getArg() != null) {
		theFilter.getArg().visit(this);
	}

	// try and reverse engineer the original scoping intent of the query
	final boolean aNeedsNewScope = theFilter.getParentNode() != null
			&& (theFilter.getParentNode() instanceof Join || theFilter.getParentNode() instanceof LeftJoin);

	String aFilter = renderValueExpr(theFilter.getCondition());
	if (theFilter.getCondition() instanceof ValueConstant || theFilter.getCondition() instanceof Var) {
		// means the filter is something like "filter (true)" or "filter (?v)"
		// so we'll need to wrap it in parens since they can't live
		// in the query w/o them, but we can't always wrap them in parens in
		// the normal renderer

		aFilter = "(" + aFilter + ")";
	}

	mJoinBuffer.append(indent());

	// if (aNeedsNewScope) {
	// mJoinBuffer.append("{ ");
	// }

	mJoinBuffer.append("filter ").append(aFilter).append(".");

	// if (aNeedsNewScope) {
	// mJoinBuffer.append("}.");
	// }

	mJoinBuffer.append("\n");

	ctxClose(theFilter);
}
 
Example #27
Source File: FilterUtils.java    From CostFed with GNU Affero General Public License v3.0 5 votes vote down vote up
protected static void append(ValueExpr expr, StringBuilder sb) throws FilterConversionException {
	if (expr instanceof Compare) {
		append((Compare)expr, sb);
	} else if (expr instanceof Var) {
		append((Var)expr, sb);
	} else if (expr instanceof ValueConstant) {
		append((ValueConstant)expr, sb);
	} else if (expr instanceof Regex) {
	    append((Regex)expr, sb);
	} else {
		// TODO add more!
		throw new FilterConversionException("Expression type not supported, fallback to sesame evaluation: " + expr.getClass().getCanonicalName());
	}
}
 
Example #28
Source File: TupleExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Maps the given valueExpr to a Var. If the supplied ValueExpr is a Var, the object itself will be returned. If it
 * is a ValueConstant, this method will check if an existing variable mapping exists and return that mapped
 * variable, otherwise it will create and store a new mapping.
 *
 * @param valueExpr
 * @return a Var for the given valueExpr.
 * @throws IllegalArgumentException if the supplied ValueExpr is null or of an unexpected type.
 */
protected Var mapValueExprToVar(Object valueExpr) {
	if (valueExpr instanceof Var) {
		return (Var) valueExpr;
	} else if (valueExpr instanceof ValueConstant) {
		Var v = TupleExprs.createConstVar(((ValueConstant) valueExpr).getValue());
		return v;
	} else if (valueExpr instanceof TripleRef) {
		return ((TripleRef) valueExpr).getExprVar();
	} else if (valueExpr == null) {
		throw new IllegalArgumentException("valueExpr is null");
	} else {
		throw new IllegalArgumentException("valueExpr is a: " + valueExpr.getClass());
	}
}
 
Example #29
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Load visit(ASTLoad node, Object data) throws VisitorException {

	ValueConstant source = (ValueConstant) node.jjtGetChild(0).jjtAccept(this, data);

	Load load = new Load(source);
	load.setSilent(node.isSilent());
	if (node.jjtGetNumChildren() > 1) {
		ValueConstant graph = (ValueConstant) node.jjtGetChild(1).jjtAccept(this, data);
		load.setGraph(graph);
	}

	return load;
}
 
Example #30
Source File: UpdateExprBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Create visit(ASTCreate node, Object data) throws VisitorException {
	ValueConstant graph = (ValueConstant) node.jjtGetChild(0).jjtAccept(this, data);

	Create create = new Create(graph);
	create.setSilent(node.isSilent());
	return create;
}