org.apache.jena.sparql.engine.binding.Binding Java Examples
The following examples show how to use
org.apache.jena.sparql.engine.binding.Binding.
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: QueryExecutor.java From sparql-generate with Apache License 2.0 | 6 votes |
private List<Binding> getNewValues(String queryName, SPARQLExtQuery query, List<Var> signature, List<List<Node>> callParameters) { final int size = signature.size(); final List<Binding> bindings = new ArrayList<>(); for (List<Node> callParams : callParameters) { if (callParams.size() != size) { throw new SPARQLExtException("Query " + queryName + " called with " + callParams.size() + " parameters but accepts only " + size); } final BindingHashMap b = new BindingHashMap(); for (int i = 0; i < size; i++) { if(callParams.get(i) != null) { b.add(signature.get(i), callParams.get(i)); } } bindings.add(b); } return bindings; }
Example #2
Source File: QueryIterTripleStarPattern.java From RDFstarTools with Apache License 2.0 | 6 votes |
public TripleMapper( Binding binding, Triple tp, ExecutionContext cxt ) { super(cxt) ; this.s = ExtendedSubstitute.substitute( tp.getSubject(), binding ); this.p = ExtendedSubstitute.substitute( tp.getPredicate(), binding ); this.o = ExtendedSubstitute.substitute( tp.getObject(), binding ); this.sIsTripleWithVars = isTripleWithVars(s); this.oIsTripleWithVars = isTripleWithVars(o); this.binding = binding; final Node s2 = sIsTripleWithVars ? Node.ANY : convertToBeUsedForFind(s); final Node p2 = convertToBeUsedForFind(p); final Node o2 = oIsTripleWithVars ? Node.ANY : convertToBeUsedForFind(o); final Graph graph = cxt.getActiveGraph(); this.graphIter = graph.find(s2, p2, o2); }
Example #3
Source File: QueryIterTripleStarPatternTest.java From RDFstarTools with Apache License 2.0 | 6 votes |
@Test public void matchSubjectInSubjectTriple() { // << ?V1 ex:p ex:o >> ex:m1 ex:x1 final Triple tp1 = new Triple( $V1(), $p(), $o() ); final Node nTP1 = new Node_TripleStarPattern( tp1 ); final Triple tp2 = new Triple( nTP1, $m1(), $x1() ); final Binding inputBinding = BindingFactory.binding(); final ExecutionContext execCxt = createTestExecCxt(); final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt); final QueryIterator it = QueryIterTripleStarPattern.create( input, tp2, execCxt ); assertTrue( it.hasNext() ); final Binding outputBinding = it.nextBinding(); assertEquals( 1, outputBinding.size() ); assertEquals( $V1(), outputBinding.vars().next() ); assertEquals( $s(), outputBinding.get($V1()) ); assertFalse( it.hasNext() ); it.close(); }
Example #4
Source File: localname.java From xcurator with Apache License 2.0 | 6 votes |
private QueryIterator execFixedSubject(Node nodeURI, Node nodeLocalname, Binding binding, ExecutionContext execCxt) { if ( ! nodeURI.isURI() ) // Subject bound but not a URI return QueryIterNullIterator.create(execCxt) ; // Subject is bound and a URI - get the localname as a Node Node localname = NodeFactory.createLiteral(nodeURI.getLocalName()) ; // Object - unbound variable or a value? if ( ! nodeLocalname.isVariable() ) { // Object bound or a query constant. Is it the same as the calculated value? if ( nodeLocalname.equals(localname) ) // Same return QueryIterSingleton.create(binding, execCxt) ; // No - different - no match. return QueryIterNullIterator.create(execCxt) ; } // Object unbound variable - assign the localname to it. return QueryIterSingleton.create(binding, Var.alloc(nodeLocalname), localname, execCxt) ; }
Example #5
Source File: QueryIterTripleStarPatternTest.java From RDFstarTools with Apache License 2.0 | 6 votes |
@Test public void matchNothingWithGivenObjectInObjectTriple() { // ?V1 ?V2 << ex:s ex:p ?V3 >> final Triple tp1 = new Triple( $s(), $p(), $V3() ); final Node nTP1 = new Node_TripleStarPattern( tp1 ); final Triple tp2 = new Triple( $V1(), $V2(), nTP1 ); // ?V3 --> ex:x1 final Binding inputBinding = BindingFactory.binding( $V3(), $x1() ); final ExecutionContext execCxt = createTestExecCxt(); final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt); final QueryIterator it = QueryIterTripleStarPattern.create( input, tp2, execCxt ); assertFalse( it.hasNext() ); it.close(); }
Example #6
Source File: CSVParser.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
@Override public Binding next() { Binding current = binding; binding = null; String[] row; try { while ((row = csv.readNext()) != null) { // Skip rows without data if (isEmpty(row)) continue; binding = toBinding(row); rownum++; break; } } catch (IOException e) { throw new TarqlException(e); } return current; }
Example #7
Source File: LogUtils.java From sparql-generate with Apache License 2.0 | 6 votes |
private static ElementData compress(List<Binding> input) { ElementData el = new ElementData(); if (input.size() < 10) { input.forEach((b) -> { addCompressedToElementData(el, b); }); return el; } for (int i = 0; i < 5; i++) { addCompressedToElementData(el, input.get(i)); } BindingMap binding = BindingFactory.create(); Node n = NodeFactory.createLiteral("[ " + (input.size() - 10) + " more ]"); el.getVars().forEach((v) -> binding.add(v, n)); el.add(binding); for (int i = input.size() - 5; i < input.size(); i++) { addCompressedToElementData(el, input.get(i)); } return el; }
Example #8
Source File: DatasetDeclarationPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
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 #9
Source File: QueryIterTripleStarPatternTest.java From RDFstarTools with Apache License 2.0 | 6 votes |
@Test public void matchObjectRequiresRedundancyAugmentation() { // ex:s ex:p ?V3 final Triple tp = new Triple( $s(), $p(), $V3() ); final Binding inputBinding = BindingFactory.binding(); final ExecutionContext execCxt = createTestExecCxt(); final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt); final QueryIterator it = QueryIterTripleStarPattern.create( input, tp, execCxt ); assertTrue( it.hasNext() ); final Binding outputBinding = it.nextBinding(); assertEquals( 1, outputBinding.size() ); assertEquals( $o(), outputBinding.get($V3()) ); assertFalse( it.hasNext() ); it.close(); }
Example #10
Source File: QueryIterTripleStarPatternTest.java From RDFstarTools with Apache License 2.0 | 6 votes |
@Test public void matchSubjectWithGivenObjectRequiresRedundancyAugmentation() { // ?V1 ex:p ?V3 final Triple tp = new Triple( $V1(), $p(), $V3() ); // ?V3 --> ex:x1 final Binding inputBinding = BindingFactory.binding( $V3(), $o() ); final ExecutionContext execCxt = createTestExecCxt(); final QueryIterator input = QueryIterSingleton.create(inputBinding, execCxt); final QueryIterator it = QueryIterTripleStarPattern.create( input, tp, execCxt ); assertTrue( it.hasNext() ); final Binding outputBinding = it.nextBinding(); assertEquals( 2, outputBinding.size() ); assertEquals( $s(), outputBinding.get($V1()) ); assertEquals( $o(), outputBinding.get($V3()) ); assertFalse( it.hasNext() ); it.close(); }
Example #11
Source File: BindPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override protected final Binding exec(Binding binding, Context context) { LOG.debug("Start " + this); context.set(ARQConstants.sysCurrentTime, NodeFactoryExtra.nowAsDateTime()); final FunctionEnv env = new FunctionEnvBase(context); try { final NodeValue n = expr.eval(binding, env); if (LOG.isTraceEnabled()) { LOG.trace("New binding " + var + " = " + LogUtils.compress(n.asNode())); } return BindingFactory.binding(binding, var, n.asNode()); } catch(ExprEvalException ex) { LOG.trace("No evaluation for " + this + " " + ex.getMessage()); return binding; } }
Example #12
Source File: FUN_Property.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { if (args == null) { throw new ARQInternalErrorException("FunctionBase: Null args list"); } if (args.size() != 2) { throw new ExprEvalException("Expecting two argument"); } NodeValue file = args.get(0).eval(binding, env); NodeValue propertyNode = args.get(1).eval(binding, env); if (!propertyNode.isString()) { throw new ExprEvalException("Second argument must be a string. Got " + propertyNode); } Properties properties; try { properties = getProperties(file, env); } catch (IOException ex) { throw new ExprEvalException("IOException while extracting properties document " + file, ex); } String prop = properties.getProperty(propertyNode.getString()); if (prop == null) { throw new ExprEvalException("Property " + prop + " not found in properties document " + file); } return new NodeValueString(prop); }
Example #13
Source File: ST_Incr.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { if (args == null) { throw new ARQInternalErrorException("FunctionBase: Null args list"); } if (args.size() != 0) { throw new ExprEvalException("Expecting zero argument"); } IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext()); if(writer != null) { writer.incIndent(); } else { LOG.warn("calling st:incr() outside TEMPLATE context."); } return EMPTY_NODE; }
Example #14
Source File: EvalUtils.java From sparql-generate with Apache License 2.0 | 6 votes |
/** * The query name may be an expression, which evaluates differently * depending on the input bindings. This method groups the bindings for * which the query name evaluation is the same. * * @param expr the expression for the query name * @param bindings * @param env * @return */ public static Map<String, List<Binding>> splitBindingsForQuery( final Expr expr, final List<Binding> bindings, final FunctionEnv env) { final Map<String, List<Binding>> calls = new HashMap<>(); for (Binding binding : bindings) { final Node n = eval(expr, binding, env); if (n == null) { continue; } if (!n.isURI()) { LOG.warn("Name of sub query resolved to something else than a" + " URI: " + n); continue; } String queryName = n.getURI(); List<Binding> call = calls.get(queryName); if (call == null) { call = new ArrayList<>(); calls.put(queryName, call); } call.add(binding); } return calls; }
Example #15
Source File: SelectPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
private Query createQuery(final SPARQLExtQuery select, final List<Var> variables, final List<Binding> values, final Context context) { // SPARQLExtQuery q = select.cloneQuery(); Binding binding = !values.isEmpty() ? values.get(0) : null; SelectQueryPartialCopyVisitor cloner = new SelectQueryPartialCopyVisitor(binding, context); select.visit(cloner); Query q = cloner.getOutput(); if (!isSelectType && !q.hasGroupBy() && !q.hasAggregators()) { variables.forEach(v -> { if (!q.getProjectVars().contains(v)) { q.getProject().add(v); } }); } return q; }
Example #16
Source File: ARQTest.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void testQueryAddValuesInQueryPattern() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}"); ElementGroup group = new ElementGroup(); ElementData table = new ElementData(); table.add(Var.alloc("a")); table.add(Var.alloc("b")); table.add(b1); table.add(b2); group.addElement(q.getQueryPattern()); group.addElement(table); q.setQueryPattern(group); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars()); assertTrue(rs.hasNext()); assertEquals(b1, rs.nextBinding()); assertTrue(rs.hasNext()); assertEquals(b2, rs.nextBinding()); assertFalse(rs.hasNext()); }
Example #17
Source File: SourcePlan.java From sparql-generate with Apache License 2.0 | 6 votes |
/** * * @param binding - * @return the actual URI that represents the location of the query to be * fetched. */ private String getActualSource( final Binding binding) { if (node.isVariable()) { Node actualSource = binding.get((Var) node); if (actualSource == null) { return null; } if (!actualSource.isURI()) { throw new SPARQLExtException("Variable " + node.getName() + " must be bound to a IRI that represents the location" + " of the query to be fetched."); } return actualSource.getURI(); } else { if (!node.isURI()) { throw new SPARQLExtException("The source must be a IRI" + " that represents the location of the query to be" + " fetched. Got " + node.getURI()); } return node.getURI(); } }
Example #18
Source File: RootPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
private void execIteratorAndSourcePlans(final List<Var> variables, final List<Binding> values, final Context context, final int i) { if (i < iteratorAndSourcePlans.size()) { final BindingsClausePlan plan = iteratorAndSourcePlans.get(i); if (plan instanceof BindOrSourcePlan) { final BindOrSourcePlan bindOrSourcePlan = (BindOrSourcePlan) plan; variables.add(bindOrSourcePlan.getVar()); final List<Binding> newValues = bindOrSourcePlan.exec(values, context); execIteratorAndSourcePlans(variables, newValues, context, i + 1); LOG.debug("Finished plan " + bindOrSourcePlan); } else { IteratorPlan iteratorPlan = (IteratorPlan) plan; iteratorPlan.exec(variables, values, context, (newValues) -> { final List<Var> newVariables = new ArrayList<>(variables); newVariables.addAll(iteratorPlan.getVars()); execIteratorAndSourcePlans(newVariables, newValues, context, i + 1); LOG.debug("Finished batch for " + iteratorPlan); }); LOG.debug("Finished plan " + iteratorPlan); } } else { execSelectPlan(variables, values, context); } }
Example #19
Source File: RootPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
private List<Var> getVariables(List<Binding> values) { Set<Var> variables = new HashSet<>(); if (values != null) { for (Binding binding : values) { for (Iterator<Var> it = binding.vars(); it.hasNext();) { variables.add(it.next()); } } } List<Var> signature = query.getSignature(); if (signature == null) { return new ArrayList<>(variables); } if (!signature.containsAll(variables)) { Set<Var> superfluousVars = variables.stream().filter((v) -> !signature.contains(v)) .collect(Collectors.toSet()); throw new SPARQLExtException(String.format( "The given input bindings use variables that are not in the signature: %s are not in the signature %s", superfluousVars, signature)); } return new ArrayList<>(signature); }
Example #20
Source File: ARQTest.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
@Test public void testQuerySetValuesDataBlock() { List<Var> header = vars("a", "b"); Binding b1 = binding(header, "1", "2"); Binding b2 = binding(header, "3", "4"); Query q = QueryFactory.create("SELECT * {}"); q.setValuesDataBlock(header, bindings(b1, b2)); ResultSet rs = QueryExecutionFactory.create(q, ModelFactory.createDefaultModel()).execSelect(); assertEquals(Arrays.asList(new String[]{"a","b"}), rs.getResultVars()); assertTrue(rs.hasNext()); assertEquals(b1, rs.nextBinding()); assertTrue(rs.hasNext()); assertEquals(b2, rs.nextBinding()); assertFalse(rs.hasNext()); }
Example #21
Source File: SelectPlan.java From sparql-generate with Apache License 2.0 | 6 votes |
private ElementData mergeValues(final ElementData qData, final List<Var> variables, final List<Binding> values) { if (values.isEmpty()) { return qData; } List<Var> vars = qData.getVars(); if (!Collections.disjoint(vars, variables)) { throw new SPARQLExtException("Variables " + vars.retainAll(variables) + "were already bound."); } ElementData data = new ElementData(); qData.getVars().forEach(data::add); variables.forEach(data::add); qData.getRows().forEach((qbinding) -> { values.forEach((binding) -> { BindingHashMap newb = new BindingHashMap(qbinding); variables.forEach((v) -> newb.add(v, binding.get(v))); data.add(newb); }); }); return data; }
Example #22
Source File: JenaUtil.java From shacl with Apache License 2.0 | 6 votes |
/** * Turns a QuerySolution into a Binding. * @param map the input QuerySolution * @return a Binding or null if the input is null */ public static Binding asBinding(final QuerySolution map) { if(map != null) { BindingHashMap result = new BindingHashMap(); Iterator<String> varNames = map.varNames(); while(varNames.hasNext()) { String varName = varNames.next(); RDFNode node = map.get(varName); if(node != null) { result.add(Var.alloc(varName), node.asNode()); } } return result; } else { return null; } }
Example #23
Source File: TarqlTest.java From tarql with BSD 2-Clause "Simplified" License | 6 votes |
private void assertSelect(TarqlQuery tq, Binding... bindings) throws IOException{ TarqlQueryExecution ex; if (csv == null) { ex = TarqlQueryExecutionFactory.create(tq, options); } else { ex = TarqlQueryExecutionFactory.create(tq, InputStreamSource.fromBytes(csv.getBytes("utf-8")), options); } ResultSet rs = ex.execSelect(); int counter = 0; while (rs.hasNext()) { if (counter >= bindings.length) { fail("Too many bindings in result; expected " + bindings.length); } assertEquals(bindings[counter], rs.nextBinding()); counter += 1; } assertEquals(bindings.length, counter); }
Example #24
Source File: TemplatePlan.java From sparql-generate with Apache License 2.0 | 6 votes |
public void exec(List<Var> variables, List<Binding> values, Context context) { final IndentedWriter writer = ContextUtils.getTemplateOutput(context); boolean first = true; final FunctionEnv env = new FunctionEnvBase(context); String result; for(Iterator<Binding> it=values.iterator(); it.hasNext();) { Binding binding = it.next(); if (first && before != null) { result = getExprEval(before, binding, context, env); writer.print(result); } if (!first && separator != null) { result = getExprEval(separator, binding, context, env); writer.print(result); } result = getExprEval(expr, binding, context, env); writer.print(result); first = false; if (!it.hasNext() && after != null) { result = getExprEval(after, binding, context, env); writer.print(result); } writer.flush(); } }
Example #25
Source File: TargetContainsPFunction.java From shacl with Apache License 2.0 | 6 votes |
@Override public QueryIterator exec(Binding binding, PropFuncArg argSubject, Node predicate, PropFuncArg argObject, ExecutionContext execCxt) { argSubject = Substitute.substitute(argSubject, binding); argObject = Substitute.substitute(argObject, binding); if(!argObject.getArg().isVariable()) { throw new ExprEvalException("Right hand side of tosh:targetContains must be a variable"); } Node targetNode = argSubject.getArgList().get(0); Node shapesGraphNode = argSubject.getArgList().get(1); Model currentModel = ModelFactory.createModelForGraph(execCxt.getActiveGraph()); Dataset dataset = new DatasetWithDifferentDefaultModel(currentModel, DatasetImpl.wrap(execCxt.getDataset())); Model model = dataset.getNamedModel(shapesGraphNode.getURI()); Resource target = (Resource) model.asRDFNode(targetNode); Set<Node> focusNodes = new HashSet<Node>(); SHACLUtil.addNodesInTarget(target, dataset, focusNodes); return new QueryIterExtendByVar(binding, (Var) argObject.getArg(), focusNodes.iterator(), execCxt); }
Example #26
Source File: ST_Decr.java From sparql-generate with Apache License 2.0 | 6 votes |
@Override public NodeValue exec(Binding binding, ExprList args, String uri, FunctionEnv env) { if (args == null) { throw new ARQInternalErrorException("FunctionBase: Null args list"); } if (args.size() != 0) { throw new ExprEvalException("Expecting zero argument"); } IndentedWriter writer = ContextUtils.getTemplateOutput(env.getContext()); if(writer != null) { writer.decIndent(); } else { LOG.warn("calling st:decr() outside TEMPLATE context."); } return EMPTY_NODE; }
Example #27
Source File: CSVTable.java From tarql with BSD 2-Clause "Simplified" License | 5 votes |
@Override public ClosableIterator<Binding> rows() { ensureHasParser(); final ClosableIterator<Binding> wrappedIterator = nextParser; nextParser = null; // We will add a wrapper to the iterator that removes it // from the list of open iterators once it is closed and // exhausted, and that fills the size cache once the // iterator is exhausted. return new ClosableIterator<Binding>() { private int count = 0; @Override public boolean hasNext() { if (wrappedIterator.hasNext()) return true; if (sizeCache == null) sizeCache = count; openIterators.remove(wrappedIterator); return false; } @Override public Binding next() { count++; return wrappedIterator.next(); } @Override public void remove() { wrappedIterator.remove(); } @Override public void close() { openIterators.remove(wrappedIterator); wrappedIterator.close(); } }; }
Example #28
Source File: IteratorPlan.java From sparql-generate with Apache License 2.0 | 5 votes |
void add( final Binding binding, final List<List<NodeValue>> nodeValues) { final List<Binding> bindings = getListBinding(binding, nodeValues); final Batch batch = getNextBatch(binding); lastBatch.put(binding, batch); if (batch.addAndCheckIfEmpty(binding, bindings)) { batchComplete(batch); } }
Example #29
Source File: QueryIterTripleStarPattern.java From RDFstarTools with Apache License 2.0 | 5 votes |
protected Binding mapper(Triple r) { final BindingMap results = BindingFactory.create(binding); if ( ! insert(r, s, p, o, results, sIsTripleWithVars, oIsTripleWithVars) ) return null; return results; }
Example #30
Source File: ExtendedSubstitute.java From RDFstarTools with Apache License 2.0 | 5 votes |
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; }