org.apache.jena.sparql.core.BasicPattern Java Examples

The following examples show how to use org.apache.jena.sparql.core.BasicPattern. 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: StageGeneratorAlt.java    From xcurator with Apache License 2.0 6 votes vote down vote up
@Override
public QueryIterator execute(BasicPattern pattern, 
                             QueryIterator input,
                             ExecutionContext execCxt)
{
    // Just want to pick out some BGPs (e.g. on a particualr graph)
    // Test ::  execCxt.getActiveGraph() 
    if ( ! ( execCxt.getActiveGraph() instanceof GraphBase ) )
        // Example: pass on up to the original StageGenerator if
        // not based on GraphBase (which most Graph implementations are). 
        return other.execute(pattern, input, execCxt) ;
    
    System.err.println("MyStageGenerator.compile:: triple patterns = "+pattern.size()) ;

    // Stream the triple matches together, one triple matcher at a time. 
    QueryIterator qIter = input ;
    for (Triple triple : pattern.getList())
        qIter = new QueryIterTriplePattern(qIter, triple, execCxt) ;
    return qIter ;
}
 
Example #2
Source File: QueryPatternNormalizer.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
@Override
public void visit(ElementTriplesBlock el) {
    final BasicPattern bgp = el.getPattern();
    final ElementTriplesBlock nzed = new ElementTriplesBlock();
    final NodeExprNormalizer nenzer = new NodeExprNormalizer();
    bgp.forEach((t) -> {
        t.getSubject().visitWith(nenzer);
        Node s = nenzer.getResult();
        t.getPredicate().visitWith(nenzer);
        Node p = nenzer.getResult();
        t.getObject().visitWith(nenzer);
        Node o = nenzer.getResult();
        nzed.addTriple(new Triple(s, p, o));
    });
    endVisit(nzed, nenzer);
}
 
Example #3
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 6 votes vote down vote up
private void setWidths(BasicPattern triples) {
    subjectWidth = -1;
    predicateWidth = -1;

    for (Triple t : triples) {
        String s = slotToString(t.getSubject());
        if (s.length() > subjectWidth) {
            subjectWidth = s.length();
        }

        String p = slotToString(t.getPredicate());
        if (p.length() > predicateWidth) {
            predicateWidth = p.length();
        }
    }
}
 
Example #4
Source File: SPARQLExtFormatterTemplate.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void format(Template template) {
    out.print("{");
    out.incIndent(INDENT);
    out.pad();

    List<Quad> quads = template.getQuads();
    for (Quad quad : quads) {
        BasicPattern bgp = new BasicPattern();
        bgp.add(quad.asTriple());
        out.newline();
        if (!Quad.defaultGraphNodeGenerated.equals(quad.getGraph())) {

            out.print("GRAPH");
            out.print(" ");
            out.print(slotToString(quad.getGraph()));
            out.print(" ");

            out.newline();
            out.incIndent(INDENT);
            out.pad();
            out.print("{");
            out.incIndent(INDENT);
            out.pad();
        }

        formatTriples(bgp);

        if (!Quad.defaultGraphNodeGenerated.equals(quad.getGraph())) {
            out.decIndent(INDENT);
            out.print("}");
            out.decIndent(INDENT);
        }
    }
    out.newline();
    out.decIndent(INDENT);
    out.print("}");
    out.newline();
}
 
Example #5
Source File: SPARQLExtFmtUtils.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
public static void formatPattern(IndentedWriter out, BasicPattern pattern, SerializationContext sCxt) {
    boolean first = true;
    for (Triple triple : pattern) {
        if (!first) {
            out.print("\n");
        }
        printTriple(out, triple, sCxt);
        out.print(" .");
        first = false;
    }
}
 
Example #6
Source File: StageGeneratorSPARQLStar.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
@Override
protected QueryIterator execute(BasicPattern pattern,
                                ReorderTransformation reorder,
                                StageGenerator execution,
                                QueryIterator input,
                                ExecutionContext execCxt)
{
	// The implementation of this method is a copy of the
	// superclass method that is modified to use SPARQL*-aware
	// versions of Substitute and QueryIterBlockTriples.

       Explain.explain(pattern, execCxt.getContext());

       if ( ! input.hasNext() )
           return input;

       if ( reorder != null && pattern.size() >= 2 ) {
           // If pattern size is 0 or 1, nothing to do.
           BasicPattern bgp2 = pattern;

           // Try to ground the pattern
           if ( ! input.isJoinIdentity() ) {
               QueryIterPeek peek = QueryIterPeek.create(input, execCxt);
               // And now use this one
               input = peek;
               Binding b = peek.peek();
               bgp2 = ExtendedSubstitute.substitute(pattern, b);
           }
           ReorderProc reorderProc = reorder.reorderIndexes(bgp2);
           pattern = reorderProc.reorder(pattern);
       }
       Explain.explain("Reorder/generic", pattern, execCxt.getContext());

       QueryIterator chain = input;
       for ( final Triple triple : pattern )
           chain = QueryIterTripleStarPattern.create(chain, triple, execCxt);
       return chain;
}
 
Example #7
Source File: OutputClauseNormalizer.java    From sparql-generate with Apache License 2.0 5 votes vote down vote up
@Override
public void visit(ElementGenerateTriplesBlock el) {
    final BasicPattern bgp = el.getPattern();
    final ElementGenerateTriplesBlock nzed = new ElementGenerateTriplesBlock();
    bgp.forEach((t) -> {
        t.getSubject().visitWith(nenzer);
        Node s = nenzer.getResult();
        t.getPredicate().visitWith(nenzer);
        Node p = nenzer.getResult();
        t.getObject().visitWith(nenzer);
        Node o = nenzer.getResult();
        nzed.addTriple(new Triple(s, p, o));
    });
    result = nzed;
}
 
Example #8
Source File: ExtendedSubstitute.java    From RDFstarTools with Apache License 2.0 5 votes vote down vote up
public static BasicPattern substitute( BasicPattern bgp, Binding binding )
{
    if ( binding == null || binding.isEmpty() )
        return bgp;

    final BasicPattern bgp2 = new BasicPattern();
    for ( final Triple triple : bgp ) {
        final Triple t = substitute(triple, binding);
        bgp2.add(t);
    }
    return bgp2;
}
 
Example #9
Source File: ElementGenerateTriplesBlock.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public BasicPattern getPattern() {
    return pattern;
}
 
Example #10
Source File: SPARQLExtFormatterBase.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
protected void formatTriples(BasicPattern pattern) {
    SPARQLExtFmtUtils.formatPattern(out, pattern, context);
}
 
Example #11
Source File: ElementGenerateTriplesBlock.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public ElementGenerateTriplesBlock(BasicPattern bgp) {
    pattern = bgp;
}
 
Example #12
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 #13
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
private void flush(BasicPattern bgp) {
    formatTriples(bgp);
    bgp.getList().clear();
}
 
Example #14
Source File: SPARQLExtFormatterElement.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
@Override
protected void formatTriples(BasicPattern triples) {
    if (!PRETTY_PRINT) {
        super.formatTriples(triples);
        return;
    }

    // TODO RDF Collections - spot the parsers pattern
    if (triples.isEmpty()) {
        return;
    }

    setWidths(triples);
    if (subjectWidth > TRIPLES_SUBJECT_COLUMN) {
        subjectWidth = TRIPLES_SUBJECT_COLUMN;
    }
    if (predicateWidth > TRIPLES_PROPERTY_COLUMN) {
        predicateWidth = TRIPLES_PROPERTY_COLUMN;
    }

    // Loops:
    List<Triple> subjAcc = new ArrayList<>(); // Accumulate all triples
    // with the same subject.
    Node subj = null; // Subject being accumulated

    boolean first = true; // Print newlines between blocks.

    int indent = -1;
    for (Triple t : triples) {
        if (subj != null && t.getSubject().equals(subj)) {
            subjAcc.add(t);
            continue;
        }

        if (subj != null) {
            if (!first) {
                out.println(" .");
            }
            formatSameSubject(subj, subjAcc);
            first = false;
            // At end of line of a block of triples with same subject.
            // Drop through and start new block of same subject triples.
        }

        // New subject
        subj = t.getSubject();
        subjAcc.clear();
        subjAcc.add(t);
    }

    // Flush accumulator
    if (subj != null && subjAcc.size() != 0) {
        if (!first) {
            out.println(" .");
        }
        first = false;
        formatSameSubject(subj, subjAcc);
    }
}
 
Example #15
Source File: ElementGenerateTriplesBlock.java    From sparql-generate with Apache License 2.0 4 votes vote down vote up
public ElementGenerateTriplesBlock() {
    pattern = new BasicPattern();
}
 
Example #16
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 #17
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 #18
Source File: GenerateFormPlan.java    From sparql-generate with Apache License 2.0 2 votes vote down vote up
/**
 * Constructor.
 *
 * @param basicGraphPattern the basic pattern.
 * @param subQueries the sub queries.
 */
public GenerateFormPlan(final BasicPattern basicGraphPattern, List<RootPlan> subQueries) {
    this.bgp = basicGraphPattern;
    this.subQueries = subQueries;
}