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

The following examples show how to use org.apache.jena.sparql.expr.ExprVar. 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: 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 #2
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 #3
Source File: SPARQLExtFmtExprSPARQL.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ExprVar nv) {
	String s = nv.getVarName();
	if (Var.isBlankNodeVarName(s)) {
		// Return to a bNode via the bNode mapping of a variable.
		Var v = Var.alloc(s);
		out.print(context.getBNodeMap().asString(v));
	} else {
		// Print in variable form or as an aggregator expression
		out.print(nv.asSparqlExpr());
	}
}
 
Example #4
Source File: JenaUtil.java    From shacl with Apache License 2.0 5 votes vote down vote up
public static Node invokeFunction3(Resource function, RDFNode argument1, RDFNode argument2, RDFNode argument3, Dataset dataset) {
	ExprList args = new ExprList();
	args.add(argument1 != null ? NodeValue.makeNode(argument1.asNode()) : new ExprVar("arg1"));
	args.add(argument2 != null ? NodeValue.makeNode(argument2.asNode()) : new ExprVar("arg2"));
	args.add(argument3 != null ? NodeValue.makeNode(argument3.asNode()) : new ExprVar("arg3"));
	return invokeFunction(function, args, dataset);
}
 
Example #5
Source File: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static E_Equals toEqualsFilter(Expr left, Expr right) {
	Node ln = toNode(left);
	org.apache.jena.sparql.expr.Expr le = ln.isVariable()? new ExprVar(ln.getName()) : new NodeValueNode(ln);
	Node rn = toNode(right);
	org.apache.jena.sparql.expr.Expr re = rn.isVariable()? new ExprVar(rn.getName()) : new NodeValueNode(rn);
	return new E_Equals(le, re);
}
 
Example #6
Source File: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static E_Equals toIRIEqualsFilter(Expr left, Expr right) {
	Node ln = toNode(left);
	org.apache.jena.sparql.expr.Expr le = ln.isVariable()? new ExprVar(ln.getName()) : new NodeValueNode(ln);
	Node rn = toNode(right);
	org.apache.jena.sparql.expr.Expr re = rn.isVariable()? new ExprVar(rn.getName()) : new NodeValueNode(rn);
	return new E_Equals(new E_Str(le), new E_Str(re));
}
 
Example #7
Source File: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static E_NotEquals toNotEqualsFilter(Expr left, Expr right) {
	Node ln = toNode(left);
	org.apache.jena.sparql.expr.Expr le = ln.isVariable()? new ExprVar(ln.getName()) : new NodeValueNode(ln);
	Node rn = toNode(right);
	org.apache.jena.sparql.expr.Expr re = rn.isVariable()? new ExprVar(rn.getName()) : new NodeValueNode(rn);
	return new E_NotEquals(le, re);
}
 
Example #8
Source File: RuleSystemToQueries.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected static E_NotEquals toIRINotEqualsFilter(Expr left, Expr right) {
	Node ln = toNode(left);
	org.apache.jena.sparql.expr.Expr le = ln.isVariable()? new ExprVar(ln.getName()) : new NodeValueNode(ln);
	Node rn = toNode(right);
	org.apache.jena.sparql.expr.Expr re = rn.isVariable()? new ExprVar(rn.getName()) : new NodeValueNode(rn);
	return new E_NotEquals(new E_Str(le), new E_Str(re));
}
 
Example #9
Source File: ExprNormalizer.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
private Expr normalize(ExprAggregator eAgg) {
	Var var = VarUtils.allocVar(UUID.randomUUID().toString().substring(0, 8));
	query.addPostSelect(var, eAgg);
	return new ExprVar(var);
}
 
Example #10
Source File: ResolutionEngineForJena.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
/***
 * Takes a SELECT query and unroll it into a more complex SPARQL query under
 * rules
 * 
 * @param query
 */
public Query unfold(Query query) {

	ResolutionVisitor visitor = new ResolutionVisitor(rules);
	Op body = Algebra.compile(query);

	OpVariableVistor<String> collector = new OpVariableVistor<String>(body,
			true) {
		@Override
		protected String processVar(Node v) {
			return v.getName();
		}
	};
	OpWalker.walk(body, collector);

	Set<String> bindingNames = new HashSet<String>(collector.getResult());

	visitor.setBindingNames(bindingNames);

	Op newQuery = body;
	newQuery = Transformer.transform(visitor, body);

	
	VarExprList expr = new VarExprList();	
//	E_StrConcat trace = getRuleTracingConcat(newQuery);
	E_StrConcat trace = null;
	
	if (trace!=null) {
		expr.add(Var.alloc("trace"),trace);		
		newQuery = OpExtend.extend(newQuery, expr);
		newQuery = OpJoin.create(newQuery, OpTable.unit());
		
		if (SPARQLRewriterForJena.GENERATE_TRACE_SUMMARY) {
			
			VarExprList groupVars = new VarExprList();
			groupVars.add(Var.alloc("trace"));
			AggCount count = new AggCount();
			ExprAggregator aggregators = new ExprAggregator(Var.alloc("trace.sum"), count);
			List<ExprAggregator> list = new LinkedList<ExprAggregator>();
			list.add(aggregators);
			
			Op groupBy = new OpGroup(newQuery, groupVars, list);
			
			VarExprList expr2 = new VarExprList();	
			expr2.add(Var.alloc("sum"), new ExprVar("trace.sum"));			
			groupBy = OpExtend.extend(groupBy, expr2);
			List<Var> vars = new LinkedList<Var>();
			vars.add(Var.alloc("sum"));
			vars.add(Var.alloc("trace"));
			OpProject project = new OpProject(groupBy, vars);
			newQuery = project;
			
			
		}

	}
	
	
	
	
	
	Query q = OpAsQuery.asQuery(newQuery);
	q.setDistinct(true);	// KAVITHA: Not setting distinct on the consequent leaves duplicates
	return q;

}
 
Example #11
Source File: PropertyPathRewrite.java    From quetzal with Eclipse Public License 2.0 4 votes vote down vote up
protected Expr getExpr(Node n) {
	return n.isVariable()? new ExprVar(n.getName()) : new NodeValueNode(n);
}
 
Example #12
Source File: AlgebraExec.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public static void main (String[] argv)
{
    String BASE = "http://example/" ; 
    BasicPattern bp = new BasicPattern() ;
    Var var_x = Var.alloc("x") ;
    Var var_z = Var.alloc("z") ;
    
    // ---- Build expression
    bp.add(new Triple(var_x, NodeFactory.createURI(BASE+"p"), var_z)) ;
    Op op = new OpBGP(bp) ;
    //Expr expr = ExprUtils.parse("?z < 2 ") ;
    Expr expr = new E_LessThan(new ExprVar(var_z), NodeValue.makeNodeInteger(2)) ;
    op = OpFilter.filter(expr, op) ;

    // ---- Example setup
    Model m = makeModel() ;
    m.write(System.out, "TTL") ;
    System.out.println("--------------") ;
    System.out.print(op) ;
    System.out.println("--------------") ;

    // ---- Execute expression
    QueryIterator qIter = Algebra.exec(op, m.getGraph()) ;
    
    // -------- Either read the query iterator directly ...
    if ( false )
    {
        for ( ; qIter.hasNext() ; )
        {
            Binding b = qIter.nextBinding() ;
            Node n = b.get(var_x) ;
            System.out.println(NodeFmtLib.displayStr(n)) ;
            System.out.println(b) ; 
        }
        qIter.close() ;
    }
    else
    {
        // -------- Or make ResultSet from it (but not both - reading an
        //          iterator consumes the current solution)
        List<String> varNames = new ArrayList<String>() ;
        varNames.add("x") ;
        varNames.add("z") ;
        ResultSet rs = new ResultSetStream(varNames, m, qIter);
        ResultSetFormatter.out(rs) ;
        qIter.close() ;
    }
    System.exit(0) ;
}
 
Example #13
Source File: labelSearch.java    From xcurator with Apache License 2.0 4 votes vote down vote up
@Override
public QueryIterator exec(QueryIterator input, PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt)
{
    // No real need to check the pattern arguments because
    // the replacement triple pattern and regex will cope
    // but we illustrate testing here.

    Node nodeVar = argSubject.getArg() ;
    String pattern = NodeUtils.stringLiteral(argObject.getArg()) ;
    if ( pattern == null )
    {
        Log.warn(this, "Pattern must be a plain literal or xsd:string: "+argObject.getArg()) ;
        return QueryIterNullIterator.create(execCxt) ;
    }

    if ( false )
        // Old (ARQ 1) way - not recommended.
        return buildSyntax(input, nodeVar, pattern, execCxt) ;
    
    // Better 
    // Build a SPARQL algebra expression
    Var var2 = createNewVar() ;                     // Hidden variable
    
    BasicPattern bp = new BasicPattern() ;
    Triple t = new Triple(nodeVar, RDFS.label.asNode(), var2) ;
    bp.add(t) ;
    OpBGP op = new OpBGP(bp) ;
    
    Expr regex = new E_Regex(new ExprVar(var2.getName()), pattern, "i") ;
    Op filter = OpFilter.filter(regex, op) ;

    // ---- Evaluation
    if ( true )
    {
        // Use the reference query engine
        // Create a table for the input stream (so it uses working memory at this point, 
        // which is why this is not the preferred way).  
        // Then join to expression for this stage.
        Table table = TableFactory.create(input) ;
        Op op2 = OpJoin.create(OpTable.create(table), filter) ;
        return Algebra.exec(op2, execCxt.getDataset()) ;
    }        
    
    // Use the default, optimizing query engine.
    return QC.execute(filter, input, execCxt) ;
}
 
Example #14
Source File: ExProg2.java    From xcurator with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args)
{
    Model model = createModel() ;
    
    Query query = QueryFactory.make() ;
    query.setQuerySelectType() ;
    
    // See also ExProg1
    
    ElementGroup elg = new ElementGroup() ;
    
    Var varTitle = Var.alloc("title") ;
    Var varX = Var.alloc("x") ;
    
    Triple t1 = new Triple(varX, DC.title.asNode(),  varTitle) ;
    elg.addTriplePattern(t1) ;
    
    // Adds a filter.  Need to wrap variable in a NodeVar.
    Expr expr = new E_Regex(new ExprVar(varTitle), "sparql", "i") ;
    ElementFilter filter = new  ElementFilter(expr) ;
    elg.addElementFilter(filter) ;
    
    // Attach the group to query.  
    query.setQueryPattern(elg) ;
    
    // Choose what we want - SELECT ?title
    query.addResultVar(varTitle) ;
    
    // Print query with line numbers
    // Prefix mapping just helps serialization
    query.getPrefixMapping().setNsPrefix("dc" , DC.getURI()) ;
    query.serialize(new IndentedWriter(System.out,true)) ;
    System.out.println() ;
    
    try(QueryExecution qexec = QueryExecutionFactory.create(query, model)) {
        // Assumption: it's a SELECT query.
        ResultSet rs = qexec.execSelect() ;
        
        // The order of results is undefined.
        System.out.println("Titles: ") ;
        for ( ; rs.hasNext() ; )
        {
            QuerySolution rb = rs.nextSolution() ;
            
            // Get title - variable names do not include the '?' (or '$')
            RDFNode x = rb.get("title") ;
            
            // Check the type of the result value
            if ( x instanceof Literal )
            {
                Literal titleStr = (Literal)x  ;
                System.out.println("    "+titleStr) ;
            }
            else
                System.out.println("Strange - not a literal: "+x) ;
                
        }
    }
}
 
Example #15
Source File: JenaUtil.java    From shacl with Apache License 2.0 3 votes vote down vote up
/**
 * Calls a given SPARQL function with two arguments.
 *
 * @param function  the URI resource of the function to call
 * @param argument1 the first argument
 * @param argument2 the second argument
 * @param dataset   the Dataset to operate on or null for default
 * @return the result of the function call
 */
public static Node invokeFunction2(Resource function, RDFNode argument1, RDFNode argument2, Dataset dataset) {
	ExprList args = new ExprList();
	args.add(argument1 != null ? NodeValue.makeNode(argument1.asNode()) : new ExprVar("arg1"));
	args.add(argument2 != null ? NodeValue.makeNode(argument2.asNode()) : new ExprVar("arg2"));
	return invokeFunction(function, args, dataset);
}
 
Example #16
Source File: JenaUtil.java    From shacl with Apache License 2.0 2 votes vote down vote up
/**
 * Calls a given SPARQL function with one argument.
 *
 * @param function the URI resource of the function to call
 * @param argument the first argument
 * @param dataset  the Dataset to operate on or null for default
 * @return the result of the function call
 */
public static Node invokeFunction1(Resource function, RDFNode argument, Dataset dataset) {
	ExprList args = new ExprList();
	args.add(argument != null ? NodeValue.makeNode(argument.asNode()) : new ExprVar("arg1"));
	return invokeFunction(function, args, dataset);
}