Java Code Examples for org.eclipse.rdf4j.query.algebra.StatementPattern#getContextVar()

The following examples show how to use org.eclipse.rdf4j.query.algebra.StatementPattern#getContextVar() . 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: DistanceQuerySpec.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void setGeometryPattern(StatementPattern sp) {
	if (sp.getSubjectVar().hasValue()) {
		throw new IllegalArgumentException("Subject cannot be bound: " + sp);
	}
	if (!sp.getPredicateVar().hasValue()) {
		throw new IllegalArgumentException("Predicate must be bound: " + sp);
	}
	if (sp.getObjectVar().hasValue()) {
		throw new IllegalArgumentException("Object cannot be bound: " + sp);
	}
	if (!sp.getObjectVar().getName().equals(geoVar)) {
		throw new IllegalArgumentException("Object var name does not match geometry var name");
	}
	this.geoStatement = sp;
	this.subjectVar = sp.getSubjectVar().getName();
	this.contextVar = sp.getContextVar();
	this.geoProperty = (IRI) sp.getPredicateVar().getValue();
}
 
Example 2
Source File: Changeset.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void prepare() throws SailException {
	if (prepend != null && observations != null) {
		for (StatementPattern p : observations) {
			Resource subj = (Resource) p.getSubjectVar().getValue();
			IRI pred = (IRI) p.getPredicateVar().getValue();
			Value obj = p.getObjectVar().getValue();
			Var ctxVar = p.getContextVar();
			Resource[] contexts;
			if (ctxVar == null) {
				contexts = new Resource[0];
			} else {
				contexts = new Resource[] { (Resource) ctxVar.getValue() };
			}
			for (Changeset changeset : prepend) {
				if (changeset.hasApproved(subj, pred, obj, contexts)
						|| (changeset.hasDeprecated(subj, pred, obj, contexts))) {
					throw new SailConflictException("Observed State has Changed");
				}
			}
		}
	}
}
 
Example 3
Source File: FedXUtil.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Retrieve the contexts from the {@link StatementPattern} and {@link Dataset}.
 *
 * @param stmt
 * @param dataset
 * @return
 */
public static Resource[] toContexts(StatementPattern stmt, Dataset dataset) {
	if (dataset == null && (stmt.getContextVar() == null || !stmt.getContextVar().hasValue())) {
		return new Resource[0];
	}

	Set<Resource> contexts = Sets.newHashSet();

	if (dataset != null) {
		contexts.addAll(dataset.getDefaultGraphs());
	}

	if (stmt.getScope().equals(Scope.NAMED_CONTEXTS)) {
		if (stmt.getContextVar().hasValue()) {
			contexts.add((Resource) stmt.getContextVar().getValue());
		}
	}

	return contexts.toArray(new Resource[contexts.size()]);
}
 
Example 4
Source File: SpinParser.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void meet(StatementPattern node) throws RuntimeException {
	if (node.getContextVar() != null) {
		buf.append("GRAPH <").append(node.getContextVar().getValue()).append("> { ");
	}
	buf.append("<")
			.append(node.getSubjectVar().getValue())
			.append("> <")
			.append(node.getPredicateVar().getValue())
			.append("> <")
			.append(node.getObjectVar().getValue())
			.append("> .");
	if (node.getContextVar() != null) {
		buf.append(" } ");
	}
}
 
Example 5
Source File: HalyardStatsBasedStatementPatternCardinalityCalculator.java    From Halyard with Apache License 2.0 5 votes vote down vote up
@Override
public Double getCardinality(StatementPattern sp, Collection<String> boundVars) { //get the cardinality of the Statement form VOID statistics
    final Var contextVar = sp.getContextVar();
    final IRI graphNode = contextVar == null || !contextVar.hasValue() ? HALYARD.STATS_ROOT_NODE : (IRI) contextVar.getValue();
    final long triples = getTriplesCount(graphNode, -1l);
    if (triples > 0) { //stats are present
        final double card;
        boolean sv = hasValue(sp.getSubjectVar(), boundVars);
        boolean pv = hasValue(sp.getPredicateVar(), boundVars);
        boolean ov = hasValue(sp.getObjectVar(), boundVars);
        long defaultCardinality = Math.round(Math.sqrt(triples));
        if (sv) {
            if (pv) {
                if (ov) {
                    card = 1.0;
                } else {
                    card = (double) subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality) / triples;
                }
            } else if (ov) {
                card = (double) subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality) / triples;
            } else {
                card = subsetTriplesPart(graphNode, VOID_EXT.SUBJECT, sp.getSubjectVar(), defaultCardinality);
            }
        } else if (pv) {
            if (ov) {
                card = (double) subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality) * subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality) / triples;
            } else {
                card = subsetTriplesPart(graphNode, VOID.PROPERTY, sp.getPredicateVar(), defaultCardinality);
            }
        } else if (ov) {
            card = subsetTriplesPart(graphNode, VOID_EXT.OBJECT, sp.getObjectVar(), defaultCardinality);
        } else {
            card = triples;
        }
        LOG.log(Level.FINE, "cardinality of {0} = {1}", new Object[]{sp.toString(), card});
        return card;
    } else { // stats are not present
        return null;
    }
}
 
Example 6
Source File: ConstructorBuilder.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void meet(StatementPattern node) {
	if (!Scope.DEFAULT_CONTEXTS.equals(node.getScope())) {
		basicPattern = false;
	} else if (node.getContextVar() != null) {
		basicPattern = false;
	} else {
		super.meet(node);
	}
}
 
Example 7
Source File: SymmetricPropertyVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();

    final Var predVar = sp.getPredicateVar();
    IRI pred = (IRI) predVar.getValue();
    String predNamespace = pred.getNamespace();

    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null &&
            !RDF.NAMESPACE.equals(predNamespace) &&
            !SESAME.NAMESPACE.equals(predNamespace) &&
            !RDFS.NAMESPACE.equals(predNamespace)
            && !EXPANDED.equals(cntxtVar)) {
        /**
         *
         * { ?a ?pred ?b .}\n" +
         "       UNION " +
         "      { ?b ?pred ?a }
         */

        IRI symmPropIri = (IRI) predVar.getValue();
        if(inferenceEngine.isSymmetricProperty(symmPropIri)) {
            Var subjVar = sp.getSubjectVar();
            Union union = new InferUnion();
            union.setLeftArg(sp);
            union.setRightArg(new StatementPattern(objVar, predVar, subjVar, cntxtVar));
            node.replaceWith(union);
        }
    }
}
 
Example 8
Source File: MemorySailStore.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public synchronized void prepare() throws SailException {
	acquireExclusiveTransactionLock();
	if (observations != null) {
		for (StatementPattern p : observations) {
			Resource subj = (Resource) p.getSubjectVar().getValue();
			IRI pred = (IRI) p.getPredicateVar().getValue();
			Value obj = p.getObjectVar().getValue();
			Var ctxVar = p.getContextVar();
			Resource[] contexts;
			if (ctxVar == null) {
				contexts = new Resource[0];
			} else {
				contexts = new Resource[] { (Resource) ctxVar.getValue() };
			}
			try (CloseableIteration<MemStatement, SailException> iter = createStatementIterator(subj, pred, obj,
					null, -1, contexts);) {
				while (iter.hasNext()) {
					MemStatement st = iter.next();
					int since = st.getSinceSnapshot();
					int till = st.getTillSnapshot();
					if (serializable < since && since < nextSnapshot
							|| serializable < till && till < nextSnapshot) {
						throw new SailConflictException("Observed State has Changed");
					}
				}
			}
		}
	}
}
 
Example 9
Source File: ContextCollector.java    From semagrow with Apache License 2.0 5 votes vote down vote up
/**
 * @inheritDoc
 */
@Override
public void meet(StatementPattern thePattern)
        throws Exception
{
    Var aCtxVar = thePattern.getContextVar();

    if (aCtxVar != null) {
        mContexts.put(thePattern, aCtxVar);
    }
}
 
Example 10
Source File: IntersectionOfVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(final StatementPattern node) throws Exception {
    final StatementPattern currentNode = node.clone();
    final Var subVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    final Var conVar = node.getContextVar();
    if (predVar != null && objVar != null && objVar.getValue() != null && RDF.TYPE.equals(predVar.getValue()) && !EXPANDED.equals(conVar)) {
        final List<Set<Resource>> intersections = inferenceEngine.getIntersectionsImplying((IRI) objVar.getValue());
        if (intersections != null && !intersections.isEmpty()) {
            final List<TupleExpr> joins = new ArrayList<>();
            for (final Set<Resource> intersection : intersections) {
                final Set<Resource> sortedIntersection = new TreeSet<>(new ResourceComparator());
                sortedIntersection.addAll(intersection);

                // Create a join tree of all statement patterns in the
                // current intersection.
                final TupleExpr joinTree = createJoinTree(new ArrayList<>(sortedIntersection), subVar, conVar);
                if (joinTree != null) {
                    joins.add(joinTree);
                }
            }

            if (!joins.isEmpty()) {
                // Combine all the intersection join trees for the type
                // together into a union tree.  This will be a join tree if
                // only one intersection exists.
                final TupleExpr unionTree = createUnionTree(joins);
                // Union the above union tree of intersections with the
                // original node.
                final Union union = new InferUnion(unionTree, currentNode);
                node.replaceWith(union);
                log.trace("Replacing node with inferred intersection union: " + union);
            }
        }
    }
}
 
Example 11
Source File: InverseOfVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(StatementPattern node) throws Exception {
    StatementPattern sp = node.clone();
    final Var predVar = sp.getPredicateVar();

    IRI pred = (IRI) predVar.getValue();
    String predNamespace = pred.getNamespace();

    final Var objVar = sp.getObjectVar();
    final Var cntxtVar = sp.getContextVar();
    if (objVar != null &&
            !RDF.NAMESPACE.equals(predNamespace) &&
            !SESAME.NAMESPACE.equals(predNamespace) &&
            !RDFS.NAMESPACE.equals(predNamespace)
            && !EXPANDED.equals(cntxtVar)) {
        /**
         *
         * { ?a ?pred ?b .}\n" +
         "       UNION " +
         "      { ?b ?pred ?a }
         */

        IRI predIri = (IRI) predVar.getValue();
        IRI invPropIri = inferenceEngine.findInverseOf(predIri);
        if (invPropIri != null) {
            Var subjVar = sp.getSubjectVar();
            Union union = new InferUnion();
            union.setLeftArg(sp);
            union.setRightArg(new StatementPattern(objVar, new Var(predVar.getName(), invPropIri), subjVar, cntxtVar));
            node.replaceWith(union);
        }
    }
}
 
Example 12
Source File: OneOfVisitor.java    From rya with Apache License 2.0 5 votes vote down vote up
@Override
protected void meetSP(final StatementPattern node) throws Exception {
    final Var subVar = node.getSubjectVar();
    final Var predVar = node.getPredicateVar();
    final Var objVar = node.getObjectVar();
    final Var conVar = node.getContextVar();
    if (predVar != null && objVar != null && objVar.getValue() != null && objVar.getValue() instanceof Resource && RDF.TYPE.equals(predVar.getValue()) && !EXPANDED.equals(conVar)) {
        final Resource object = (Resource) objVar.getValue();
        if (inferenceEngine.isEnumeratedType(object)) {
            final Set<BindingSet> solutions = new LinkedHashSet<>();
            final Set<Resource> enumeration = inferenceEngine.getEnumeration(object);
            for (final Resource enumType : enumeration) {
                final QueryBindingSet qbs = new QueryBindingSet();
                qbs.addBinding(subVar.getName(), enumType);
                solutions.add(qbs);
            }

            if (!solutions.isEmpty()) {
                final BindingSetAssignment enumNode = new BindingSetAssignment();
                enumNode.setBindingSets(solutions);

                node.replaceWith(enumNode);
                log.trace("Replacing node with inferred one of enumeration: " + enumNode);
            }
        }
    }
}
 
Example 13
Source File: TrueStatementPattern.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public TrueStatementPattern(StatementPattern node) {
	super(node.getSubjectVar(), node.getPredicateVar(), node.getObjectVar(), node.getContextVar());
}
 
Example 14
Source File: EmptyStatementPattern.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public EmptyStatementPattern(StatementPattern node) {
	super(node.getSubjectVar(), node.getPredicateVar(), node.getObjectVar(), node.getContextVar());
}
 
Example 15
Source File: SubPropertyOfVisitor.java    From rya with Apache License 2.0 4 votes vote down vote up
@Override
    protected void meetSP(final StatementPattern node) throws Exception {
        final StatementPattern sp = node.clone();
        final Var predVar = sp.getPredicateVar();

        final IRI pred = (IRI) predVar.getValue();
        final String predNamespace = pred.getNamespace();

        final Var objVar = sp.getObjectVar();
        final Var cntxtVar = sp.getContextVar();
        if (objVar != null &&
                !RDF.NAMESPACE.equals(predNamespace) &&
                !SESAME.NAMESPACE.equals(predNamespace) &&
                !RDFS.NAMESPACE.equals(predNamespace)
                && !EXPANDED.equals(cntxtVar)) {
            /**
             *
             * { ?subProp rdfs:subPropertyOf ub:worksFor . ?y ?subProp <http://www.Department0.University0.edu> }\n" +
             "       UNION " +
             "      { ?y ub:worksFor <http://www.Department0.University0.edu> }
             */
//            String s = UUID.randomUUID().toString();
//            Var subPropVar = new Var(s);
//            StatementPattern subPropOf = new StatementPattern(subPropVar, new Var("c-" + s, SESAME.DIRECTSUBPROPERTYOF), predVar, EXPANDED);
//            StatementPattern subPropOf2 = new StatementPattern(sp.getSubjectVar(), subPropVar, objVar, EXPANDED);
//            InferJoin join = new InferJoin(subPropOf, subPropOf2);
//            join.getProperties().put(InferConstants.INFERRED, InferConstants.TRUE);
//            node.replaceWith(join);

//            Collection<URI> parents = inferenceEngine.findParents(inferenceEngine.subPropertyOfGraph, (URI) predVar.getValue());
//            if (parents != null && parents.size() > 0) {
//                StatementPatterns statementPatterns = new StatementPatterns();
//                statementPatterns.patterns.add(node);
//                Var subjVar = node.getSubjectVar();
//                for (IRI iri : parents) {
//                    statementPatterns.patterns.add(new StatementPattern(subjVar, new Var(predVar.getName(), iri), objVar));
//                }
//                node.replaceWith(statementPatterns);
//            }
//            if (parents != null && parents.size() > 0) {
//                VarCollection vc = new VarCollection();
//                vc.setName(predVar.getName());
//                vc.values.add(predVar);
//                for (IRI iri : parents) {
//                    vc.values.add(new Var(predVar.getName(), iri));
//                }
//                Var subjVar = node.getSubjectVar();
//                node.replaceWith(new StatementPattern(subjVar, vc, objVar, node.getContextVar()));
//            }

            final IRI subprop_iri = (IRI) predVar.getValue();
            final Set<IRI> parents = InferenceEngine.findParents(inferenceEngine.getSubPropertyOfGraph(), subprop_iri);
            if (parents != null && parents.size() > 0) {
                final String s = UUID.randomUUID().toString();
                final Var typeVar = new Var(s);
                final FixedStatementPattern fsp = new FixedStatementPattern(typeVar, new Var("c-" + s, RDFS.SUBPROPERTYOF), predVar, cntxtVar);
//                fsp.statements.add(new NullableStatementImpl(subprop_uri, RDFS.SUBPROPERTYOF, subprop_uri));
                //add self
                parents.add(subprop_iri);
                for (final IRI u : parents) {
                    fsp.statements.add(new NullableStatementImpl(u, RDFS.SUBPROPERTYOF, subprop_iri));
                }

                final StatementPattern rdfType = new DoNotExpandSP(sp.getSubjectVar(), typeVar, sp.getObjectVar(), cntxtVar);
                final InferJoin join = new InferJoin(fsp, rdfType);
                join.getProperties().put(InferConstants.INFERRED, InferConstants.TRUE);
                node.replaceWith(join);
            }
        }
    }
 
Example 16
Source File: PrepareOwnedTupleExpr.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
public void meet(StatementPattern node) throws RepositoryException {
	StringBuilder builder = new StringBuilder();
	Scope scope = node.getScope();
	Var subj = node.getSubjectVar();
	Var pred = node.getPredicateVar();
	Var obj = node.getObjectVar();
	Var ctx = node.getContextVar();
	boolean cokay = ctx == null && scope.equals(Scope.DEFAULT_CONTEXTS)
			|| ctx != null && scope.equals(Scope.NAMED_CONTEXTS);
	boolean sokay = !subj.hasValue() || subj.isAnonymous() || subj.getValue() instanceof IRI;
	boolean ookay = !obj.hasValue() || obj.isAnonymous() || obj.getValue() instanceof IRI
			|| obj.getValue() instanceof Literal;
	if (cokay && sokay && ookay) {
		variables.clear();
		if (ctx != null) {
			builder.append("GRAPH ");
			appendVar(builder, ctx.getName());
			builder.append(" {\n");
		}
		appendVar(builder, subj);
		appendVar(builder, pred);
		appendVar(builder, obj);
		builder.append(" .");
		appendFilter(builder, subj);
		appendFilter(builder, pred);
		appendFilter(builder, obj);
		if (ctx != null) {
			if (ctx.hasValue()) {
				builder.append("\nFILTER sameTerm(");
				appendVar(builder, ctx.getName());
				builder.append(", ");
				writeValue(builder, ctx.getValue());
				builder.append(")\n");
			}
			builder.append("}");
		}
		this.pattern = builder.toString();
		this.patternNode = node;
	} else {
		this.patternNode = null; // NOPMD
	}
}
 
Example 17
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @param whereBinding
 * @param deleteClause
 * @throws SailException
 */
private void deleteBoundTriples(BindingSet whereBinding, TupleExpr deleteClause, UpdateContext uc)
		throws SailException {
	if (deleteClause != null) {
		List<StatementPattern> deletePatterns = StatementPatternCollector.process(deleteClause);

		Value patternValue;
		for (StatementPattern deletePattern : deletePatterns) {

			patternValue = getValueForVar(deletePattern.getSubjectVar(), whereBinding);
			Resource subject = patternValue instanceof Resource ? (Resource) patternValue : null;

			patternValue = getValueForVar(deletePattern.getPredicateVar(), whereBinding);
			IRI predicate = patternValue instanceof IRI ? (IRI) patternValue : null;

			Value object = getValueForVar(deletePattern.getObjectVar(), whereBinding);

			Resource context = null;
			if (deletePattern.getContextVar() != null) {
				patternValue = getValueForVar(deletePattern.getContextVar(), whereBinding);
				context = patternValue instanceof Resource ? (Resource) patternValue : null;
			}

			if (subject == null || predicate == null || object == null) {
				/*
				 * skip removal of triple if any variable is unbound (may happen with optional patterns or if triple
				 * pattern forms illegal triple). See SES-1047 and #610.
				 */
				continue;
			}

			if (context != null) {
				if (SESAME.NIL.equals(context)) {
					con.removeStatement(uc, subject, predicate, object, (Resource) null);
				} else {
					con.removeStatement(uc, subject, predicate, object, context);
				}
			} else {
				IRI[] remove = getDefaultRemoveGraphs(uc.getDataset());
				con.removeStatement(uc, subject, predicate, object, remove);
			}
		}
	}
}
 
Example 18
Source File: TrueStatementPattern.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
public TrueStatementPattern(StatementPattern node) {
	super(node.getSubjectVar(), node.getPredicateVar(), node.getObjectVar(), node.getContextVar());
}
 
Example 19
Source File: StarQuery.java    From rya with Apache License 2.0 4 votes vote down vote up
public static boolean isValidStarQuery(final Collection<StatementPattern> nodes) {

        Set<String> bindings = null;
        boolean contextSet = false;
        Var context = null;

        if(nodes.size() < 2) {
            return false;
        }

        for(final StatementPattern sp: nodes) {

            final Var tempContext = sp.getContextVar();
            final Var predVar = sp.getPredicateVar();

            //does not support variable context
            if(tempContext != null && !tempContext.isConstant()) {
               return false;
            }
            if(!contextSet) {
                context = tempContext;
                contextSet = true;
            } else {

                if(context == null && tempContext != null) {
                    return false;
                } else if (context != null && !context.equals(tempContext)) {
                    return false;
                }
            }

            if(!predVar.isConstant()) {
                return false;
            }

            if(bindings == null ) {
                bindings = sp.getBindingNames();
                if(bindings.size() == 0) {
                    return false;
                }
            } else {
                bindings = Sets.intersection(bindings, sp.getBindingNames());
                if(bindings.size() == 0) {
                    return false;
                }
            }

        }


        return isBindingsetValid(bindings);
    }
 
Example 20
Source File: EmptyStatementPattern.java    From CostFed with GNU Affero General Public License v3.0 4 votes vote down vote up
public EmptyStatementPattern(StatementPattern node) {
	super(node.getSubjectVar(), node.getPredicateVar(), node.getObjectVar(), node.getContextVar());
}