Search in sources :

Example 6 with BindingBuilder

use of org.apache.jena.sparql.engine.binding.BindingBuilder in project jena by apache.

the class TSVInputIterator method parseNextBinding.

private Binding parseNextBinding() {
    String line;
    try {
        line = reader.readLine();
        // return false because there are no further bindings
        if (line == null)
            return null;
        this.lineNum++;
    } catch (IOException e) {
        throw new ResultSetException("Error parsing TSV results - " + e.getMessage());
    }
    if (line.isEmpty()) {
        // which means a non-empty string which we handle normally
        if (expectedItems > 1)
            throw new ResultSetException(format("Error Parsing TSV results at Line %d - The result row had 0/1 values when %d were expected", this.lineNum, expectedItems));
        return BindingFactory.empty();
    }
    String[] tokens = pattern.split(line, -1);
    if (tokens.length != expectedItems)
        throw new ResultSetException(format("Error Parsing TSV results at Line %d - The result row '%s' has %d values instead of the expected %d.", this.lineNum, line, tokens.length, expectedItems));
    BindingBuilder builder = Binding.builder();
    for (int i = 0; i < tokens.length; i++) {
        String token = tokens[i];
        // If we see an empty string this denotes an unbound value
        if (token.equals(""))
            continue;
        // Bound value so parse it and add to the binding
        try {
            Node node = NodeFactoryExtra.parseNode(token);
            if (!node.isConcrete())
                throw new ResultSetException(format("Line %d: Not a concrete RDF term: %s", lineNum, token));
            builder.add(this.vars.get(i), node);
        } catch (RiotException ex) {
            throw new ResultSetException(format("Line %d: Data %s contains error: %s", lineNum, token, ex.getMessage()));
        }
    }
    return builder.build();
}
Also used : RiotException(org.apache.jena.riot.RiotException) BindingBuilder(org.apache.jena.sparql.engine.binding.BindingBuilder) Node(org.apache.jena.graph.Node) IOException(java.io.IOException)

Example 7 with BindingBuilder

use of org.apache.jena.sparql.engine.binding.BindingBuilder in project jena by apache.

the class splitIRI method subjectIsIRI.

private QueryIterator subjectIsIRI(Node subject, PropFuncArg argObject, Binding binding, ExecutionContext execCxt) {
    String namespace = subject.getNameSpace();
    String localname = subject.getLocalName();
    Node namespaceNode = argObject.getArg(0);
    Node localnameNode = argObject.getArg(1);
    // New binding to return.
    BindingBuilder builder = null;
    if (Var.isVar(namespaceNode) || Var.isVar(localnameNode))
        builder = Binding.builder(binding);
    if (Var.isVar(namespaceNode)) {
        builder.add(Var.alloc(namespaceNode), NodeFactory.createURI(namespace));
        // but it's possible for strange URI schemes.
        if (localnameNode.isVariable() && Objects.equals(namespaceNode, localnameNode))
            // Set localnameNode to a constant which will get checked below.
            localnameNode = NodeFactory.createURI(namespace);
    } else {
        String ns = null;
        // Allow both IRIs and plain literals in the namespace position.
        if (namespaceNode.isURI())
            ns = namespaceNode.getURI();
        if (namespaceNode.isLiteral())
            ns = NodeUtils.stringLiteral(namespaceNode);
        if (ns == null || !ns.equals(namespace))
            return IterLib.noResults(execCxt);
    // Fall through and proceed to localname
    }
    if (Var.isVar(localnameNode))
        builder.add(Var.alloc(localnameNode), NodeFactory.createLiteral(localname));
    else {
        // Only string literals (plain strings or datatype xsd:string)
        String lc = NodeUtils.stringLiteral(localnameNode);
        if (lc == null || !lc.equals(localname))
            return IterLib.noResults(execCxt);
    }
    Binding b2 = (builder == null) ? binding : builder.build();
    return IterLib.result(b2, execCxt);
}
Also used : Binding(org.apache.jena.sparql.engine.binding.Binding) BindingBuilder(org.apache.jena.sparql.engine.binding.BindingBuilder) Node(org.apache.jena.graph.Node)

Example 8 with BindingBuilder

use of org.apache.jena.sparql.engine.binding.BindingBuilder in project jena by apache.

the class QueryExecTest method convertToStrings.

private ResultSetRewindable convertToStrings(ResultSetRewindable resultsActual) {
    List<Binding> bindings = new ArrayList<>();
    while (resultsActual.hasNext()) {
        Binding b = resultsActual.nextBinding();
        BindingBuilder builder = Binding.builder();
        for (String vn : resultsActual.getResultVars()) {
            Var v = Var.alloc(vn);
            Node n = b.get(v);
            String s;
            if (n == null)
                s = "";
            else if (n.isBlank())
                s = "_:" + n.getBlankNodeLabel();
            else
                s = NodeFunctions.str(n);
            builder.add(v, NodeFactory.createLiteral(s));
        }
        bindings.add(builder.build());
    }
    ResultSet rs = ResultSetStream.create(resultsActual.getResultVars(), null, QueryIterPlainWrapper.create(bindings.iterator()));
    return rs.rewindable();
}
Also used : Binding(org.apache.jena.sparql.engine.binding.Binding) BindingBuilder(org.apache.jena.sparql.engine.binding.BindingBuilder) Var(org.apache.jena.sparql.core.Var) Node(org.apache.jena.graph.Node) ArrayList(java.util.ArrayList)

Example 9 with BindingBuilder

use of org.apache.jena.sparql.engine.binding.BindingBuilder in project jena by apache.

the class RowSetReaderCSV method resultSetFromCSV.

/**
 * Read RowSet after header
 */
private static RowSet resultSetFromCSV(List<Var> vars, CSVParser parser) {
    BindingBuilder builder = Binding.builder();
    Function<List<String>, Binding> transform = new Function<List<String>, Binding>() {

        private int count = 1;

        @Override
        public Binding apply(List<String> row) {
            if (row.size() != vars.size())
                FmtLog.warn(log, "Row %d: Length=%d: expected=%d", count, row.size(), vars.size());
            builder.reset();
            // Check.
            for (int i = 0; i < vars.size(); i++) {
                Var v = vars.get(i);
                String field = (i < row.size()) ? row.get(i) : "";
                Node n = NodeFactory.createLiteral(field);
                builder.add(v, n);
            }
            count++;
            return builder.build();
        }
    };
    Iterator<Binding> bindings = Iter.map(parser.iterator(), transform);
    return RowSetStream.create(vars, bindings);
}
Also used : Binding(org.apache.jena.sparql.engine.binding.Binding) Function(java.util.function.Function) BindingBuilder(org.apache.jena.sparql.engine.binding.BindingBuilder) Var(org.apache.jena.sparql.core.Var) Node(org.apache.jena.graph.Node) ArrayList(java.util.ArrayList) List(java.util.List)

Example 10 with BindingBuilder

use of org.apache.jena.sparql.engine.binding.BindingBuilder in project jena by apache.

the class QueryIterGroup method calc.

private static Iterator<Binding> calc(final QueryIterator iter, final VarExprList groupVarExpr, final List<ExprAggregator> aggregators, final ExecutionContext execCxt) {
    return new IteratorDelayedInitialization<Binding>() {

        @Override
        protected Iterator<Binding> initializeIterator() {
            boolean hasAggregators = (aggregators != null && !aggregators.isEmpty());
            boolean hasGroupBy = !groupVarExpr.isEmpty();
            boolean noInput = !iter.hasNext();
            // 2/ No GROUP BY, e.g. COUNT=0, the results is one row always and not handled here.
            if (noInput) {
                if (hasGroupBy)
                    // GROUP
                    return Iter.nullIterator();
                if (!hasAggregators) {
                    // No GROUP BY, no aggregators. One result row of no columns.
                    return Iter.singleton(BindingFactory.binding());
                }
                // No GROUP BY, has aggregators. Insert default values.
                BindingBuilder builder = Binding.builder();
                for (ExprAggregator agg : aggregators) {
                    Node value = agg.getAggregator().getValueEmpty();
                    if (value == null)
                        continue;
                    Var v = agg.getVar();
                    builder.add(v, value);
                }
                return Iter.singleton(builder.build());
            }
            // Case: there is input.
            // Phase 1 : Create keys and aggregators per key, and pump bindings through the aggregators.
            Multimap<Binding, Pair<Var, Accumulator>> accumulators = MultimapBuilder.hashKeys().arrayListValues().build();
            while (iter.hasNext()) {
                Binding b = iter.nextBinding();
                Binding key = genKey(groupVarExpr, b, execCxt);
                if (!hasAggregators) {
                    // Put in a dummy to remember the input.
                    accumulators.put(key, placeholder);
                    continue;
                }
                // Create if does not exist.
                if (!accumulators.containsKey(key)) {
                    for (ExprAggregator agg : aggregators) {
                        Accumulator x = agg.getAggregator().createAccumulator();
                        Var v = agg.getVar();
                        accumulators.put(key, Pair.create(v, x));
                    }
                }
                // Do the per-accumulator calculation.
                for (Pair<Var, Accumulator> pair : accumulators.get(key)) pair.getRight().accumulate(b, execCxt);
            }
            if (!hasAggregators)
                // We used placeholder so there are always the key.
                return accumulators.keySet().iterator();
            List<Binding> results = new ArrayList<>();
            for (Binding k : accumulators.keySet()) {
                BindingBuilder builder2 = Binding.builder(k);
                Collection<Pair<Var, Accumulator>> accs = accumulators.get(k);
                for (Pair<Var, Accumulator> pair : accs) {
                    NodeValue value = pair.getRight().getValue();
                    if (value == null)
                        continue;
                    Var v = pair.getLeft();
                    builder2.add(v, value.asNode());
                }
                results.add(builder2.build());
            }
            return results.iterator();
        }
    };
}
Also used : Binding(org.apache.jena.sparql.engine.binding.Binding) Accumulator(org.apache.jena.sparql.expr.aggregate.Accumulator) NodeValue(org.apache.jena.sparql.expr.NodeValue) BindingBuilder(org.apache.jena.sparql.engine.binding.BindingBuilder) Var(org.apache.jena.sparql.core.Var) Node(org.apache.jena.graph.Node) ArrayList(java.util.ArrayList) IteratorDelayedInitialization(org.apache.jena.atlas.iterator.IteratorDelayedInitialization) ExprAggregator(org.apache.jena.sparql.expr.ExprAggregator) Pair(org.apache.jena.atlas.lib.Pair)

Aggregations

BindingBuilder (org.apache.jena.sparql.engine.binding.BindingBuilder)30 Node (org.apache.jena.graph.Node)19 Var (org.apache.jena.sparql.core.Var)16 Binding (org.apache.jena.sparql.engine.binding.Binding)14 ArrayList (java.util.ArrayList)6 Iterator (java.util.Iterator)4 Iter (org.apache.jena.atlas.iterator.Iter)4 Triple (org.apache.jena.graph.Triple)4 ExecutionContext (org.apache.jena.sparql.engine.ExecutionContext)4 Predicate (java.util.function.Predicate)3 Graph (org.apache.jena.graph.Graph)3 List (java.util.List)2 Objects (java.util.Objects)2 Function (java.util.function.Function)2 DatasetGraph (org.apache.jena.sparql.core.DatasetGraph)2 Quad (org.apache.jena.sparql.core.Quad)2 Substitute (org.apache.jena.sparql.core.Substitute)2 SolverLib.nodeTopLevel (org.apache.jena.sparql.engine.main.solver.SolverLib.nodeTopLevel)2 SolverLib.sameTermAs (org.apache.jena.sparql.engine.main.solver.SolverLib.sameTermAs)2 SolverLib.tripleHasEmbTripleWithVars (org.apache.jena.sparql.engine.main.solver.SolverLib.tripleHasEmbTripleWithVars)2