org.apache.jena.sparql.expr.Expr Java Examples

The following examples show how to use org.apache.jena.sparql.expr.Expr. 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: ExprNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * normalizes an expression, substituting every instance of NodeValueNode
 * whose node is a Node_Extended with the associated expression of that
 * Node_Extended.
 *
 * @param expr expression to normalize
 * @return
 */
public Expr normalize(Expr expr) {
    if (expr instanceof ExprFunction1) {
        return normalize((ExprFunction1) expr);
    } else if (expr instanceof ExprFunction2) {
        return normalize((ExprFunction2) expr);
    } else if (expr instanceof ExprFunction3) {
        return normalize((ExprFunction3) expr);
    } else if (expr instanceof ExprFunctionN) {
        return normalize((ExprFunctionN) expr);
    } else if (expr instanceof ExprFunctionOp) {
        return normalize((ExprFunctionOp) expr);
    } else if (expr instanceof NodeValueNode) {
        return normalize((NodeValueNode) expr);
    } else if (expr instanceof ExprAggregator) {
        return normalize((ExprAggregator) expr);
    }
    return expr;
}
 
Example #2
Source File: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private void addNamedGraph(Binding binding, Context context, DatasetGraph dsg, Expr sourceExpr) {
	String sourceURI = evalSourceURI(binding, context, sourceExpr);
	final String absURI = baseURI(sourceURI, baseURI);
	Dataset dataset = ContextUtils.getDataset(context);
	Node n = NodeFactory.createURI(absURI);
	Graph g = dsg.getGraph(n);
	if (g == null) {
		g = GraphFactory.createJenaDefaultGraph();
		dsg.addGraph(n, g);
	}
	// default: check the dataset
	if (dataset.containsNamedModel(absURI)) {
		Graph dg = dataset.getNamedModel(absURI).getGraph();
		GraphUtil.addInto(g, dg);
		return;
	}
	// fallback: load as RDF graph
	StreamRDF dest = StreamRDFLib.graph(g);
	ContextUtils.loadGraph(context, sourceURI, absURI, dest);
}
 
Example #3
Source File: QueryAggregatesNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitDatasetDecl(Query q) {
    SPARQLExtQuery query = asSPARQLExtQuery(q);
	final ExprNormalizer enzer = new ExprNormalizer(query);
    query.getFromClauses().replaceAll((fromClause) -> {
        if (fromClause.getGenerate() == null) {
            Expr nzed = enzer.normalize(fromClause.getName());
            return new FromClause(fromClause.isNamed(), nzed);
        } else {
            SPARQLExtQuery gnzed = fromClause.getGenerate();
            gnzed.normalizeXExpr();
            if (!fromClause.isNamed()) {
                return new FromClause(gnzed);
            }
            Expr nnzed = enzer.normalize(fromClause.getName());
            return new FromClause(gnzed, nnzed);
        }
    });
}
 
Example #4
Source File: labelSearch.java    From xcurator with Apache License 2.0 6 votes vote down vote up
private QueryIterator buildSyntax(QueryIterator input, Node nodeVar, String pattern, ExecutionContext execCxt)
{
    Var var2 = createNewVar() ; 
    // Triple patterns for   ?x rdfs:label ?hiddenVar
    ElementTriplesBlock elementBGP = new ElementTriplesBlock();
    Triple t = new Triple(nodeVar, RDFS.label.asNode(), var2) ;
    elementBGP.addTriple(t) ;
    
    // Regular expression for  regex(?hiddenVar, "pattern", "i") 
    Expr regex = new E_Regex(new ExprVar(var2.getName()), pattern, "i") ;
    
    ElementGroup elementGroup = new ElementGroup() ;
    elementGroup.addElement(elementBGP) ;
    elementGroup.addElement(new ElementFilter(regex)) ;
    // Compile it.
    // The better design is to build the Op structure programmatically,
    Op op = Algebra.compile(elementGroup) ;
    op = Algebra.optimize(op, execCxt.getContext()) ;
    return QC.execute(op, input, execCxt) ;
}
 
Example #5
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * normalizes an expression, substituting every instance of NodeValueNode
 * whose node is a Node_Extended with the associated expression of that
 * Node_Extended.
 *
 * @param expr expression to normalize
 * @return
 */
public Expr normalize(Expr expr) {
    if (expr instanceof ExprFunction1) {
        return normalize((ExprFunction1) expr);
    } else if (expr instanceof ExprFunction2) {
        return normalize((ExprFunction2) expr);
    } else if (expr instanceof ExprFunction3) {
        return normalize((ExprFunction3) expr);
    } else if (expr instanceof ExprFunctionN) {
        return normalize((ExprFunctionN) expr);
    } else if (expr instanceof ExprFunctionOp) {
        return normalize((ExprFunctionOp) expr);
    } else if (expr instanceof NodeValueNode) {
        return normalize((NodeValueNode) expr);
    } else if (expr instanceof ExprAggregator) {
        return normalize((ExprAggregator) expr);
    }
    return expr;
}
 
Example #6
Source File: NodeExprNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc
 */
@Override
public Object visit(Node_List node) {
    if (cache.containsKey(node)) {
        result = cache.get(node);
        return null;
    }
    if (node.getExpr().isVariable()) {
        result = node;
        return null;
    }
    Var var = Var.alloc(node.getLabel());
    final Expr expr = nzer.normalize(node.getExpr());
    bindings.add(new ElementBind(var, expr));
    Node_List nzedList = new Node_List(new ExprVar(var));
    cache.put(node, nzedList);
    this.result = nzedList;
    return null;
}
 
Example #7
Source File: PlanFactory.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ElementBox el) {
    final List<Expr> texprs = new ArrayList<>();
    texprs.add(new E_Function(ST.incr, new ExprList()));
    List<Element> elements = el.getTExpressions();
    for (int i = 0; i < elements.size(); i++) {
        elements.get(i).visit(this);
        if (result instanceof E_Function && ((E_Function) result).getFunctionIRI().equals(ST.concat)) {
            texprs.addAll(((E_Function) result).getArgs());
        } else {
            texprs.add(result);
        }
    }
    texprs.add(new E_Function(ST.decr, new ExprList()));
    result = new E_Function(ST.concat, new ExprList(texprs));
}
 
Example #8
Source File: SelectQueryPartialCopyVisitor.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitGroupBy(final Query query) {
    if (query.hasGroupBy()) {
        if (!query.getGroupBy().isEmpty()) {
            VarExprList namedExprs = query.getGroupBy();
            for (Var var : namedExprs.getVars()) {
                Expr expr = namedExprs.getExpr(var);
                if (expr != null) {
                    output.addGroupBy(var, expr);
                } else {
                    output.addGroupBy(var.getVarName());
                }
            }
        }
    }
}
 
Example #9
Source File: SelectExtractionVisitor.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitGroupBy(final Query query) {
    if (query.hasGroupBy()) {
    	isDummyQuery = false;
        if (!query.getGroupBy().isEmpty()) {
            VarExprList namedExprs = query.getGroupBy();
            for (Var var : namedExprs.getVars()) {
                Expr expr = namedExprs.getExpr(var);
                if (expr != null) {
                    output.addGroupBy(var, expr);
                    if (!query.isSelectType()) {
                        output.addResultVar(var);
                    }
                } else {
                    output.addGroupBy(var.getVarName());
                    if (!query.isSelectType()) {
                        output.addResultVar(var);
                    }
                }
            }
        }
    }
}
 
Example #10
Source File: QueryXExprNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visitGroupBy(Query query) {
    if (query.hasGroupBy() && !query.getGroupBy().isEmpty()) {
        // Can have an empty GROUP BY list if the grouping is implicit
        // by use of an aggregate in the SELECT clause.
        final VarExprList namedExprs = query.getGroupBy();
        final VarExprList newNamedExprs = new VarExprList();
        for (Var var : namedExprs.getVars()) {
            if (namedExprs.hasExpr(var)) {
                final Expr nzed = enzer.normalize(namedExprs.getExpr(var));
                newNamedExprs.add(var, nzed);
            } else {
                newNamedExprs.add(var);
            }
        }
        namedExprs.clear();
        namedExprs.addAll(newNamedExprs);
    }
}
 
Example #11
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ElementFilter el) {
    out.print("FILTER ");
    Expr expr = el.getExpr();
    SPARQLExtFmtExprSPARQL v = new SPARQLExtFmtExprSPARQL(out, context);

    // This assumes that complex expressions are bracketted
    // (parens) as necessary except for some cases:
    // Plain variable or constant
    boolean addParens = false;
    if (expr.isVariable()) {
        addParens = true;
    }
    if (expr.isConstant()) {
        addParens = true;
    }

    if (addParens) {
        out.print("( ");
    }
    v.format(expr);
    if (addParens) {
        out.print(" )");
    }
}
 
Example #12
Source File: AbstractClusiveConstraintExecutor.java    From shacl with Apache License 2.0 6 votes vote down vote up
@Override
public void executeConstraint(Constraint constraint, ValidationEngine engine, Collection<RDFNode> focusNodes) {
	long startTime = System.currentTimeMillis();
	NodeValue cmpValue = NodeValue.makeNode(constraint.getParameterValue().asNode());
	for(RDFNode focusNode : focusNodes) {
		for(RDFNode valueNode : engine.getValueNodes(constraint, focusNode)) {				
			try {
		        NodeValue value = NodeValue.makeNode(valueNode.asNode());
				int c = NodeValue.compare(cmpValue, value);
				if (c == Expr.CMP_INDETERMINATE) {
					engine.createValidationResult(constraint, focusNode, valueNode, () -> "Indeterminant comparison with " + engine.getLabelFunction().apply(constraint.getParameterValue())); 
				}
				else if(!condition.test(c)) {
					engine.createValidationResult(constraint, focusNode, valueNode, () -> "Value is not " + operator + " " + engine.getLabelFunction().apply(constraint.getParameterValue())); 
				}
			}
			catch (ExprNotComparableException ex) {
				engine.createValidationResult(constraint, focusNode, valueNode, () -> "Cannot compare with " + engine.getLabelFunction().apply(constraint.getParameterValue())); 
			}
		}
		engine.checkCanceled();
	}
	addStatistics(constraint, startTime);
}
 
Example #13
Source File: SelectExtractionVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitHaving(final Query query) {
    if (query.hasHaving()) {
    	isDummyQuery = false;
        for (Expr expr : query.getHavingExprs()) {
            output.addHavingCondition(expr);
        }
    }
}
 
Example #14
Source File: QueryXExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private void normalizeCallParams(SPARQLExtQuery query) {
    if (query.hasName()) {
        query.setName(enzer.normalize(query.getName()));
    }
    if (query.hasCallParameters()) {
        final List<Expr> parameters = query.getCallParameters().getList();
        final List<Expr> nzed = new ArrayList<>();
        parameters.forEach((p) -> {
            nzed.add(enzer.normalize(p));
        });
        query.setCallParameters(new ExprList(nzed));
    }
}
 
Example #15
Source File: QueryXExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitOrderBy(Query query) {
    if (query.hasOrderBy()) {
        query.getOrderBy().replaceAll((sc) -> {
            final Expr expr = enzer.normalize(sc.getExpression());
            return new SortCondition(expr, sc.getDirection());
        });
    }
}
 
Example #16
Source File: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private String evalSourceURI(Binding binding, Context context, Expr sourceExpr) {
	if (binding == null) {
		throw new NullPointerException("No binding to evaluate the source expression " + sourceExpr);
	}
	try {
		FunctionEnv env = new FunctionEnvBase(context);
		NodeValue nodeValue = sourceExpr.eval(binding, env);
		if (!nodeValue.isIRI()) {
			throw new IllegalArgumentException("FROM source expression did not eval to a URI " + sourceExpr);
		}
		return nodeValue.asNode().getURI();
	} catch (ExprEvalException ex) {
		throw new IllegalArgumentException("Exception when evaluating the source expression " + sourceExpr, ex);
	}
}
 
Example #17
Source File: SelectQueryPartialCopyVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private String evalSourceURI(Binding binding, Context context, Expr sourceExpr) {
	if (binding == null) {
		throw new NullPointerException("No binding to evaluate the source expression " + sourceExpr);
	}
	try {
		FunctionEnv env = new FunctionEnvBase(context);
		NodeValue nodeValue = sourceExpr.eval(binding, env);
		if (!nodeValue.isIRI()) {
			throw new IllegalArgumentException("FROM source expression did not eval to a URI " + sourceExpr);
		}
		return nodeValue.asNode().getURI();
	} catch (ExprEvalException ex) {
		throw new IllegalArgumentException("Exception when evaluating the source expression " + sourceExpr, ex);
	}
}
 
Example #18
Source File: SPARQLExtQuerySerializer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitHaving(Query query) {
    if (query.hasHaving()) {
        out.print("HAVING");
        for (Expr expr : query.getHavingExprs()) {
            out.print(" ");
            fmtExpr.format(expr);
        }
        out.println();
    }
}
 
Example #19
Source File: TemplatePlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public TemplatePlan(Expr before, Expr expr, Expr separator, Expr after) {
	Objects.requireNonNull(expr, "expr must not be null");
	this.before = before;
	this.expr = expr;
	this.separator = separator;
	this.after = after;
}
 
Example #20
Source File: QueryPatternNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementAssign el) {
    final ExprNormalizer enzer = new ExprNormalizer();
    final Var var = el.getVar();
    final Expr nzed = enzer.normalize(el.getExpr());
    result = new ElementAssign(var, nzed);
}
 
Example #21
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Expr normalize(ExprFunctionN func) {
    ExprList args = new ExprList();
    for (Expr expr : func.getArgs()) {
        Expr arg = normalize(expr);
        args.add(arg);
    }
    return func.copy(args);
}
 
Example #22
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Expr normalize(ExprFunction1 func) {
    Expr arg = normalize(func.getArg());
    if (func instanceof E_URIParam) {
        return new E_StrEncodeForURI(arg);
    } else {
        return func.copy(arg);
    }
}
 
Example #23
Source File: DatasetDeclarationPlan.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private void addNamedGraph(Binding binding, Context context, DatasetGraph dsg, SPARQLExtQuery generate, Expr name) {
	String sourceURI = evalSourceURI(binding, context, name);
	final String absURI = baseURI(sourceURI, baseURI);
	Node n = NodeFactory.createURI(absURI);
	Graph g = dsg.getGraph(n);
	if (g == null) {
		g = GraphFactory.createJenaDefaultGraph();
		dsg.addGraph(n, g);
	}
	loadGraph(binding, context, generate, g);
}
 
Example #24
Source File: OpVariableVistor.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void visit(OpLeftJoin join) {
	if (join.getExprs() != null) {
		for(Expr e : join.getExprs()) {
			processExpr(e);
		}
	}
}
 
Example #25
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Expr normalize(ExprAggregator eAgg) {
    final ExprList exprList = eAgg.getAggregator().getExprList();
    if (exprList == null) {
        return eAgg;
    } else {
        final Var v = eAgg.getVar();
        final ExprList x = new ExprList();
        for (Expr e : exprList) {
            x.add(normalize(e));
        }
        Aggregator agg = eAgg.getAggregator().copy(x);
        return new ExprAggregator(v, agg);
    }
}
 
Example #26
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Expr normalize(Node_Extended n) {
    if (n instanceof Node_Expr) {
        return normalize((Node_Expr) n);
    } else if (n instanceof Node_ExtendedURI) {
        return normalize((Node_ExtendedURI) n);
    } else if (n instanceof Node_ExtendedLiteral) {
        return normalize((Node_ExtendedLiteral) n);
    } else if (n instanceof Node_Template) {
        return normalize((Node_Template) n);
    }
    throw new NullPointerException();
}
 
Example #27
Source File: WhereTraversalBuilder.java    From tinkerpop with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a general {@code Expr} to an anonymous {@link GraphTraversal}.
 */
static GraphTraversal<?, ?> transform(final Expr expression) {
    if (expression instanceof E_Equals) return transform((E_Equals) expression);
    if (expression instanceof E_NotEquals) return transform((E_NotEquals) expression);
    if (expression instanceof E_LessThan) return transform((E_LessThan) expression);
    if (expression instanceof E_LessThanOrEqual) return transform((E_LessThanOrEqual) expression);
    if (expression instanceof E_GreaterThan) return transform((E_GreaterThan) expression);
    if (expression instanceof E_GreaterThanOrEqual) return transform((E_GreaterThanOrEqual) expression);
    if (expression instanceof E_LogicalAnd) return transform((E_LogicalAnd) expression);
    if (expression instanceof E_LogicalOr) return transform((E_LogicalOr) expression);
    if (expression instanceof E_Exists) return transform((E_Exists) expression);
    if (expression instanceof E_NotExists) return transform((E_NotExists) expression);
    throw new IllegalStateException(String.format("Unhandled expression: %s", expression));
}
 
Example #28
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
private Expr normalize(Node_ExtendedURI n) {
    ExprList args = new ExprList();
    List<Expr> components = n.getComponents();
    for (Expr e : components) {
        args.add(normalize(e));
    }
    Expr str = new E_StrConcat(args);
    Expr expr = new E_IRI(str);
    return expr;
}
 
Example #29
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
/**
 * Temp patch for a bug in Jena's syntaxtransform, also applying substitutions on
 * HAVING clauses.
 * @param query  the Query to transform
 * @param substitutions  the variable bindings
 * @return a new Query with the bindings applied
 */
public static Query queryWithSubstitutions(Query query, final Map<Var, Node> substitutions) {
	Query result = QueryTransformOps.transform(query, substitutions);
	
	// TODO: Replace this hack once there is a Jena patch
	if(result.hasHaving()) {
		NodeTransform nodeTransform = new NodeTransform() {
		    @Override
		    public Node apply(Node node) {
		        Node n = substitutions.get(node) ;
		        if ( n == null ) {
		            return node ;
		        }
		        return n ;
		    }
		};
        ElementTransform eltrans = new ElementTransformSubst(substitutions) ;
        ExprTransform exprTrans = new ExprTransformNodeElement(nodeTransform, eltrans) ;
		List<Expr> havingExprs = result.getHavingExprs();
		for(int i = 0; i < havingExprs.size(); i++) {
			Expr old = havingExprs.get(i);
            Expr neo = ExprTransformer.transform(exprTrans, old) ;
            if ( neo != old ) {
            	havingExprs.set(i, neo);
            }
		}
	}
	return result;
}
 
Example #30
Source File: OpVariableVistor.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void visit(OpExtend opExtend) {
	for(Entry<Var, Expr> v : opExtend.getVarExprList().getExprs().entrySet()) {
		add(processVar(v.getKey()));
		processExpr(v.getValue());
	}
}