Java Code Examples for org.apache.jena.sparql.core.Var#alloc()

The following examples show how to use org.apache.jena.sparql.core.Var#alloc() . 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: TriplestoreResourceService.java    From trellis with Apache License 2.0 6 votes vote down vote up
/**
 * This code is equivalent to the SPARQL query below.
 *
 * <p><pre><code>
 * WITH trellis:PreferServerManaged
 *   DELETE { IDENTIFIER dc:modified ?time }
 *   INSERT { IDENTIFIER dc:modified TIME }
 *   WHERE { IDENTIFIER dc:modified ?time } .
 * </code></pre></p>
 */
private UpdateRequest buildUpdateModificationRequest(final IRI identifier, final Literal time) {
    final UpdateRequest req = new UpdateRequest();
    final Var modified = Var.alloc(MODIFIED);
    final UpdateDeleteInsert modify = new UpdateDeleteInsert();
    modify.setWithIRI(toJena(PreferServerManaged));
    modify.getDeleteAcc().addTriple(triple(toJena(identifier), toJena(DC.modified), modified));
    modify.getInsertAcc().addTriple(triple(toJena(identifier), toJena(DC.modified), toJena(time)));
    final ElementGroup eg = new ElementGroup();
    final ElementPathBlock epb = new ElementPathBlock();
    epb.addTriple(triple(toJena(identifier), toJena(DC.modified), modified));
    eg.addElement(epb);
    modify.setElement(eg);
    req.add(modify);
    return req;
}
 
Example 2
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 3
Source File: CSVParser.java    From tarql with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Var toVar(String s) {
	if (s == null)
		return null;
	/* SPARQL 1.1 VAR Gramar ?
	 VARNAME	  ::=  	( PN_CHARS_U | [0-9] ) ( PN_CHARS_U | [0-9] | #x00B7 | [#x0300-#x036F] | [#x203F-#x2040] )*
	 PN_CHARS_U	  ::=  	PN_CHARS_BASE | '_'
	 PN_CHARS_BASE	  ::=  	[A-Z] | [a-z] | [#x00C0-#x00D6] | [#x00D8-#x00F6] | [#x00F8-#x02FF] | [#x0370-#x037D] | [#x037F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
		I've omitted UTF-16 character range #x10000-#xEFFFF.
	*/

	String PN_CHARS_BASE = "A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD";
	String pattern = PN_CHARS_BASE + "0-9\u00B7\u0300-\u036F\u203F-\u2040";

	s = s.trim().replaceAll("[^" + pattern + "]", "_").replace(":", "");

	if ("".equals(s))
		return null;
	return Var.alloc(s);
}
 
Example 4
Source File: QueryIterTripleStarPattern.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
static protected boolean insert( Node inputNode,
                                 Node outputNode,
                                 BindingMap results,
                                 boolean inputNodeIsTripleWithVars )
{
	if ( inputNodeIsTripleWithVars )
    {
		if ( !(outputNode instanceof Node_Triple) )
			return false;

		final Triple outputTriple = ( (Node_Triple) outputNode ).get();
		final Triple inputTriple  = ( (Node_Triple) inputNode  ).get();

		return insert(outputTriple,
		              inputTriple.getSubject(),
		              inputTriple.getPredicate(),
		              inputTriple.getObject(),
		              results );
    }
    else if ( Var.isVar(inputNode) )
    {
    	final Var v = Var.alloc(inputNode);
        final Node x = results.get(v);
        if ( x != null )
            return outputNode.equals(x);

        results.add(v, outputNode);
        return true;
    }
    else
    	return true;
}
 
Example 5
Source File: Query.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public VarExprList getProject() {
	List<ProjectedVariable> variables = selectQuery.getSelectClause()
			.getProjectedVariables();
	VarExprList list = new VarExprList();
	for (ProjectedVariable variable : variables) {
		Var var = Var.alloc(variable.getVariable().getName());
		list.add(var);
	}

	return list;
}
 
Example 6
Source File: RuleSystemToUnionQuery.java    From quetzal with Eclipse Public License 2.0 5 votes vote down vote up
protected Node replace(Node old) {
	if (old!=null && old.isVariable()) {
		Var var = Var.alloc(old);
		Node newN = oldVar2NewValue.get(var);
		if (newN!=null) {
			return newN;
		}
	}
	return old;
}
 
Example 7
Source File: TriplestoreResource.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch data for this resource.
 *
 * <p>This is equivalent to the following SPARQL query:
 * <pre><code>
 * SELECT ?predicate ?object ?binarySubject ?binaryPredicate ?binaryObject
 * WHERE {
 *   GRAPH trellis:PreferServerManaged {
 *     IDENTIFIER ?predicate ?object
 *     OPTIONAL {
 *       IDENTIFIER dc:hasPart ?binarySubject .
 *       ?binarySubject ?binaryPredicate ?binaryObject
 *     }
 *   }
 * }
 * </code></pre>
 */
protected void fetchData() {
    LOGGER.debug("Fetching data from RDF datastore for: {}", identifier);
    final Var binarySubject = Var.alloc("binarySubject");
    final Var binaryPredicate = Var.alloc("binaryPredicate");
    final Var binaryObject = Var.alloc("binaryObject");
    final Query q = new Query();
    q.setQuerySelectType();
    q.addResultVar(PREDICATE);
    q.addResultVar(OBJECT);
    q.addResultVar(binarySubject);
    q.addResultVar(binaryPredicate);
    q.addResultVar(binaryObject);

    final ElementPathBlock epb1 = new ElementPathBlock();
    epb1.addTriple(create(toJena(identifier), PREDICATE, OBJECT));

    final ElementPathBlock epb2 = new ElementPathBlock();
    epb2.addTriple(create(toJena(identifier), toJena(DC.hasPart), binarySubject));
    epb2.addTriple(create(toJena(identifier), type.asNode(), toJena(LDP.NonRDFSource)));
    epb2.addTriple(create(binarySubject, binaryPredicate, binaryObject));

    final ElementGroup elg = new ElementGroup();
    elg.addElement(epb1);
    elg.addElement(new ElementOptional(epb2));

    q.setQueryPattern(new ElementNamedGraph(toJena(Trellis.PreferServerManaged), elg));

    rdfConnection.querySelect(q, qs -> {
        final RDFNode s = qs.get("binarySubject");
        final RDFNode p = qs.get("binaryPredicate");
        final RDFNode o = qs.get("binaryObject");
        nodesToTriple(s, p, o).ifPresent(t -> data.put(t.getPredicate(), t.getObject()));
        data.put(getPredicate(qs), getObject(qs));
    });
}
 
Example 8
Source File: TriplestoreResource.java    From trellis with Apache License 2.0 5 votes vote down vote up
/**
 * This code is equivalent to the SPARQL query below.
 *
 * <p><pre><code>
 * SELECT ?subject ?predicate ?object
 * WHERE {
 *   GRAPH trellis:PreferServerManaged {
 *      ?s ldp:member IDENTIFIER .
 *      ?s ldp:membershipResource ?subject .
 *      ?s rdf:type ldp:IndirectContainer .
 *      ?s ldp:membershipRelation ?predicate .
 *      ?s ldp:insertedContentRelation ?o .
 *      ?res dc:isPartOf ?s .
 *   }
 *   GRAPH ?res { ?res ?o ?object }
 * }
 * </code></pre>
 */
private Stream<Quad> fetchIndirectMemberQuads() {
    final Var s = Var.alloc("s");
    final Var o = Var.alloc("o");
    final Var res = Var.alloc("res");

    final Query q = new Query();
    q.setQuerySelectType();
    q.addResultVar(SUBJECT);
    q.addResultVar(PREDICATE);
    q.addResultVar(OBJECT);

    final ElementPathBlock epb1 = new ElementPathBlock();
    epb1.addTriple(create(s, toJena(LDP.member), toJena(identifier)));
    epb1.addTriple(create(s, toJena(LDP.membershipResource), SUBJECT));
    epb1.addTriple(create(s, type.asNode(), toJena(LDP.IndirectContainer)));
    epb1.addTriple(create(s, toJena(LDP.hasMemberRelation), PREDICATE));
    epb1.addTriple(create(s, toJena(LDP.insertedContentRelation), o));
    epb1.addTriple(create(res, toJena(DC.isPartOf), s));

    final ElementPathBlock epb2 = new ElementPathBlock();
    epb2.addTriple(create(res, o, OBJECT));

    final ElementGroup elg = new ElementGroup();
    elg.addElement(new ElementNamedGraph(toJena(Trellis.PreferServerManaged), epb1));
    elg.addElement(new ElementNamedGraph(res, epb2));

    q.setQueryPattern(elg);

    final Stream.Builder<Quad> builder = builder();
    rdfConnection.querySelect(q, qs ->
        builder.accept(rdf.createQuad(LDP.PreferMembership, getSubject(qs), getPredicate(qs), getObject(qs))));
    return builder.build();
}
 
Example 9
Source File: CSVParser.java    From tarql with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private Var getVar(int column) {
	if (vars.size() < column) {
		getVar(column - 1);
	}
	if (vars.size() == column) {
		Var var = Var.alloc(getColumnName(column));
		while (vars.contains(var)) {
			var = Var.alloc("_" + var.getName());
		}
		vars.add(var);
	}
	return vars.get(column);
}
 
Example 10
Source File: SelectQueryPartialCopyVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitFunctionExpression(SPARQLExtQuery query) {
    Var var = Var.alloc("out");
    ElementBind bind = new ElementBind(var, query.getFunctionExpression());
    output.setQueryPattern(bind);
    output.addResultVar(var);
}
 
Example 11
Source File: SelectExtractionVisitor.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visitFunctionExpression(SPARQLExtQuery query) {
    Var var = Var.alloc("out");
    ElementBind bind = new ElementBind(var, query.getFunctionExpression());
    output.setQueryPattern(bind);
    output.addResultVar(var);
	isDummyQuery = false;
}
 
Example 12
Source File: VarUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static Var allocVar(String label) {
    Var var = CACHE.getIfPresent(label);
    if (var == null) {
        var = Var.alloc(label);
        CACHE.put(label, var);
    }
    return var;
}
 
Example 13
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 14
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 15
Source File: labelSearch.java    From xcurator with Apache License 2.0 4 votes vote down vote up
private static Var createNewVar()
{
    hiddenVariableCount ++ ;
    String varName = "-search-"+hiddenVariableCount ;
    return Var.alloc(varName) ;
}
 
Example 16
Source File: ExProg1.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() ;
    
    // Build pattern
    
    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) ;
    
    // Don't use bNodes for anon variables.  The conversion is done in parsing.
    // BNodes here are assumed to be values from the target graph.
    Triple t2 = new Triple(varX, DC.description.asNode(), Var.alloc("desc")) ;
    elg.addTriplePattern(t2) ;
    
    // Attach the group to query.  
    query.setQueryPattern(elg) ;

    // Choose what we want - SELECT *
    //query.setQueryResultStar(true) ;
    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 17
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
public void visit(ElementPathBlock el) {
    // Write path block - don't put in a final trailing "." 
    if (el.isEmpty()) {
        out.println("# Empty BGP");
        return;
    }

    // Split into BGP-path-BGP-...
    // where the BGPs may be empty.
    PathBlock pBlk = el.getPattern();
    BasicPattern bgp = new BasicPattern();
    boolean first = true;      // Has anything been output?
    for (TriplePath tp : pBlk) {
        if (tp.isTriple()) {
            Triple t = tp.asTriple();
            Node s = t.getSubject();
            if(s.isVariable()) {
                s = Var.alloc(Var.canonical(((Var)s).getVarName()));
            }
            Node p = t.getPredicate();
            Node o = t.getObject();
            if(o.isVariable()) {
                o = Var.alloc(Var.canonical(((Var)o).getVarName()));
            }
            bgp.add(new Triple(s, p, o));
            continue;
        }

        if (!bgp.isEmpty()) {
            if (!first) {
                out.println(" .");
            }
            flush(bgp);
            first = false;
        }
        if (!first) {
            out.println(" .");
        }
        // Path
        printSubject(tp.getSubject());
        out.print(" ");
        SPARQLExtPathWriter.write(out, tp.getPath(), context);
        out.print(" ");
        printObject(tp.getObject());
        first = false;
    }
    // Flush any stored triple patterns.
    if (!bgp.isEmpty()) {
        if (!first) {
            out.println(" .");
        }
        flush(bgp);
        first = false;
    }
}
 
Example 18
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 votes vote down vote up
static protected Var $V3()  { return Var.alloc("V3"); } 
Example 19
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 votes vote down vote up
static protected Var $V2()  { return Var.alloc("V2"); } 
Example 20
Source File: QueryIterTripleStarPatternTest.java    From RDFstarTools with Apache License 2.0 votes vote down vote up
static protected Var $V1()  { return Var.alloc("V1"); }