Java Code Examples for org.eclipse.rdf4j.model.Resource#equals()

The following examples show how to use org.eclipse.rdf4j.model.Resource#equals() . 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: ExploreServlet.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Gets whether this is the first time the result quad has been seen.
 *
 * @param patternPredicate the predicate asked for, or null if another quad element was asked for
 * @param patternObject    the object asked for, or null if another quad element was asked for
 * @param result           the result statement to determine if we've already seen
 * @param patternContext   the context asked for, or null if another quad element was asked for
 * @return true, if this is the first time the quad has been seen, false otherwise
 */
private boolean isFirstTimeSeen(Statement result, IRI patternPredicate, Value patternObject,
		Resource... patternContext) {
	Resource resultSubject = result.getSubject();
	IRI resultPredicate = result.getPredicate();
	Value resultObject = result.getObject();
	boolean firstTimeSeen;
	if (1 == patternContext.length) {
		// I.e., when context matches explore value.
		Resource ctx = patternContext[0];
		firstTimeSeen = !(ctx.equals(resultSubject) || ctx.equals(resultPredicate) || ctx.equals(resultObject));
	} else if (null != patternObject) {
		// I.e., when object matches explore value.
		firstTimeSeen = !(resultObject.equals(resultSubject) || resultObject.equals(resultPredicate));
	} else if (null != patternPredicate) {
		// I.e., when predicate matches explore value.
		firstTimeSeen = !(resultPredicate.equals(resultSubject));
	} else {
		// I.e., when subject matches explore value.
		firstTimeSeen = true;
	}
	return firstTimeSeen;
}
 
Example 2
Source File: Schema.java    From rya with Apache License 2.0 6 votes vote down vote up
/**
 * Add a particular characteristic to a property.
 */
private void addPropertyType(IRI p, Resource t) {
    OwlProperty prop = getProperty(p);
    if (t.equals(OWL.TRANSITIVEPROPERTY)) {
        prop.setTransitive();
    }
    else if (t.equals(OWL.SYMMETRICPROPERTY)) {
        prop.setSymmetric();
    }
    else if (t.equals(OWL2.ASYMMETRICPROPERTY)) {
        prop.setAsymmetric();
    }
    else if (t.equals(OWL.FUNCTIONALPROPERTY)) {
        prop.setFunctional();
    }
    else if (t.equals(OWL.INVERSEFUNCTIONALPROPERTY)) {
        prop.setInverseFunctional();
    }
    else if (t.equals(OWL2.IRREFLEXIVEPROPERTY)) {
        prop.setIrreflexive();
    }
}
 
Example 3
Source File: PropertyShape.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
static List<Value> toList(SailRepositoryConnection connection, Resource orList) {
	List<Value> ret = new ArrayList<>();
	while (!orList.equals(RDF.NIL)) {
		try (Stream<Statement> stream = connection.getStatements(orList, RDF.FIRST, null).stream()) {
			Value value = stream.map(Statement::getObject).findAny().get();
			ret.add(value);
		}

		try (Stream<Statement> stream = connection.getStatements(orList, RDF.REST, null).stream()) {
			orList = stream.map(Statement::getObject).map(v -> (Resource) v).findAny().get();
		}

	}

	return ret;

}
 
Example 4
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected void executeCreate(Create create, UpdateContext uc) throws SailException {
	// check if named graph exists, if so, we have to return an error.
	// Otherwise, we simply do nothing.
	Value graphValue = create.getGraph().getValue();

	if (graphValue instanceof Resource) {
		Resource namedGraph = (Resource) graphValue;

		try (CloseableIteration<? extends Resource, SailException> contextIDs = con.getContextIDs()) {
			while (contextIDs.hasNext()) {
				Resource contextID = contextIDs.next();

				if (namedGraph.equals(contextID)) {
					throw new SailException("Named graph " + namedGraph + " already exists. ");
				}
			}
		}
	}
}
 
Example 5
Source File: FilteredModel.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private boolean matches(Resource stContext, Resource... contexts) {
	if (contexts != null && contexts.length == 0) {
		// Any context matches
		return true;
	} else {
		OpenRDFUtil.verifyContextNotNull(contexts);
		// Accept if one of the contexts from the pattern matches
		for (Resource context : contexts) {
			if (context == null && stContext == null) {
				return true;
			}
			if (context != null && context.equals(stContext)) {
				return true;
			}
		}

		return false;
	}
}
 
Example 6
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected void consumeStatement(Statement st) throws RDFHandlerException {
	try {
		Resource subj = st.getSubject();
		IRI pred = st.getPredicate();
		inlineBNodes = getWriterConfig().get(BasicWriterSettings.INLINE_BLANK_NODES);
		if (inlineBNodes && (pred.equals(RDF.FIRST) || pred.equals(RDF.REST))) {
			handleList(st);
		} else if (inlineBNodes && !subj.equals(lastWrittenSubject) && stack.contains(subj)) {
			handleInlineNode(st);
		} else {
			closeHangingResource();
			handleStatementInternal(st, false, inlineBNodes, inlineBNodes);
		}
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example 7
Source File: SHACLManifestTestSuiteFactory.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private List<Resource> getListEntries(Model model, Resource rdfList) {
	if (rdfList == null || rdfList.equals(RDF.NIL)) {
		return new ArrayList<>();
	}
	Resource first = Models.objectResource(model.getStatements(rdfList, RDF.FIRST, null)).orElse(null);
	Resource rest = Models.objectResource(model.getStatements(rdfList, RDF.REST, null)).orElse(null);
	List<Resource> list = getListEntries(model, rest);
	list.add(0, first);
	return list;
}
 
Example 8
Source File: ReadCommittedWrapper.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static boolean containsContext(Resource[] haystack, Resource needle) {
	for (Resource resource : haystack) {
		if (resource == null && needle == null) {
			return true;
		}
		if (resource != null && resource.equals(needle)) {
			return true;
		}
	}
	return false;
}
 
Example 9
Source File: LocalReasoner.java    From rya with Apache License 2.0 5 votes vote down vote up
/**
 * Use the semantics of a fact to determine whether it could be relevant
 * to future reasoners, or whether we should assume we've extracted all
 * the information implied by the fact during this iteration. Considers
 * semantics but not age.
 * @return true if this fact might still be used later.
 */
boolean relevantToFuture(Fact fact) {
    // If it's a join rule, it needs to be kept no matter what
    if (relevantJoinRule(fact, schema) != Relevance.NONE) {
        return true;
    }
    // Otherwise, it can be skipped under certain circumstances.
    Relevance general = relevantFact(fact, schema);
    Resource s = fact.getSubject();
    Value o = fact.getObject();
    // Exception: if subject==object, recursive derivation is limited, so
    // we can't make assumptions about what's already been done.
    if (!s.equals(o)) {
        // Otherwise, if this is a reasoner for the subject, and the fact
        // is only relevant to the subject, we can assume this reasoner
        // did all the reasoning we needed to.
        if (general == Relevance.SUBJECT && node.equals(s)) {
            return false;
        }
        // Same reasoning for the object:
        if (general == Relevance.OBJECT && node.equals(o)) {
            return false;
        }
    }
    // If we can't skip it, return true if it's ever relevant
    return general != Relevance.NONE;
}
 
Example 10
Source File: HalyardStats.java    From Halyard with Apache License 2.0 5 votes vote down vote up
private boolean matchingGraphContext(Resource subject) {
    return graphContext == null
        || subject.equals(graphContext)
        || subject.stringValue().startsWith(graphContext.stringValue() + "_subject_")
        || subject.stringValue().startsWith(graphContext.stringValue() + "_property_")
        || subject.stringValue().startsWith(graphContext.stringValue() + "_object_");
}
 
Example 11
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @param add
 * @param uc
 * @throws SailException
 */
protected void executeAdd(Add add, UpdateContext uc, int maxExecTime) throws SailException {
	ValueConstant sourceGraph = add.getSourceGraph();
	ValueConstant destinationGraph = add.getDestinationGraph();

	Resource source = sourceGraph != null ? (Resource) sourceGraph.getValue() : null;
	Resource destination = destinationGraph != null ? (Resource) destinationGraph.getValue() : null;

	if (source == null && destination == null || (source != null && source.equals(destination))) {
		// source and destination are the same, copy is a null-operation.
		return;
	}

	// get all statements from source and add them to destination
	CloseableIteration<? extends Statement, SailException> statements = null;
	try {
		statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source);

		if (maxExecTime > 0) {
			statements = new TimeLimitIteration<Statement, SailException>(statements, 1000L * maxExecTime) {

				@Override
				protected void throwInterruptedException() throws SailException {
					throw new SailException("execution took too long");
				}
			};
		}

		while (statements.hasNext()) {
			Statement st = statements.next();
			con.addStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) destination);
		}
	} finally {
		if (statements != null) {
			statements.close();
		}
	}
}
 
Example 12
Source File: TriXWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static final boolean contextsEquals(Resource context1, Resource context2) {
	if (context1 == null) {
		return context2 == null;
	} else {
		return context1.equals(context2);
	}
}
 
Example 13
Source File: TriGWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private static final boolean contextsEquals(Resource context1, Resource context2) {
	if (context1 == null) {
		return context2 == null;
	} else {
		return context1.equals(context2);
	}
}
 
Example 14
Source File: LocalReasoner.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Determine whether a fact is a triple which might be used by a local
 * reasoner for its subject and/or object.
 * @param   fact  Fact to be evaluated
 * @param   schema  Global schema
 * @return  Relevance to subject and/or object. Relevance means that it's a
 *          triple that *could* be used in reasoning. It may only be useful
 *          when combined with other facts, which may or may not exist
 *          somewhere, so this doesn't guarantee that information will be
 *          derived.
 */
public static Relevance relevantFact(Fact fact, Schema schema) {
    // If this is schema information, we know it's already
    // contained in the schema object.
    if (Schema.isSchemaTriple(fact.getTriple())) {
        return Relevance.NONE;
    }
    // Otherwise, consider the semantics of the statement:
    Resource subject = fact.getSubject();
    IRI predIRI = fact.getPredicate();
    Value object = fact.getObject();
    boolean relevantToSubject = false;
    boolean relevantToObject = false;
    // Literals don't get reasoners, so determine whether object is a uri:
    boolean literalObject = object instanceof Literal;

    // Type statements could be relevant to the subject, if the schema gives
    // them any meaning:
    if (predIRI.equals(RDF.TYPE)) {
        // Assume the object is a valid URI
        Resource typeIRI = (Resource) fact.getObject();
        if (typeIRI.equals(OWL.NOTHING)
            || schema.hasClass(typeIRI)) {
            relevantToSubject = true;
        }
    }

    // If the schema knows about the property:
    if (schema.hasProperty(predIRI)) {
        OwlProperty prop = schema.getProperty(predIRI);

        // Relevant to both:
                // Any statement with an asymmetric property
        if (prop.isAsymmetric()
                // Any statement with a transitive property
                || prop.isTransitive()
                // Statements involving restricted properties
                || !prop.getRestrictions().isEmpty()) {
            relevantToSubject = true;
            relevantToObject = !literalObject;
        }

        // Relevant to subject:
        if (!relevantToSubject && // skip these checks if it already is
                // Any statement whose property has a domain.
                (!prop.getDomain().isEmpty()
                // Choose to apply superproperties here
                // (every property is its own superproperty; ignore that)
                || prop.getSuperProperties().size() > 1
                // Choose to apply disjoint properties here
                || !prop.getDisjointProperties().isEmpty())) {
            relevantToSubject = true;
        }

        // Relevant to object if the object is not a literal and one other
        // condition matches:
        if (!literalObject && !relevantToObject &&
                // Any statement whose property has a defined range
                (!prop.getRange().isEmpty()
                // Choose to apply inverse rule in the object's reasoner
                || !prop.getInverseProperties().isEmpty()
                // Choose to apply symmetry in the object's reasoner
                || prop.isSymmetric()
                // Choose to check irreflexivity in the object's reasoner
                || prop.isIrreflexive() && subject.equals(object))) {
            relevantToObject = true;
        }
    }
    return Relevance.get(relevantToSubject, relevantToObject);
}
 
Example 15
Source File: LocalReasoner.java    From rya with Apache License 2.0 4 votes vote down vote up
/**
 * Process a triple in which this node is the object.
 */
private void processIncoming(Fact fact) {
    Resource subject = fact.getSubject();
    IRI predURI = fact.getPredicate();
    OwlProperty prop = schema.getProperty(predURI);
    // RL rule prp-rng: Apply range(s), if appropriate
    for (Resource type : prop.getRange()) {
        types.processType(type, OwlRule.PRP_RNG, fact);
    }
    // RL rules prp-inv1, prp-inv2: assert any inverse properties
    for (IRI inverseProp : prop.getInverseProperties()) {
        collect(triple(node, inverseProp, subject, OwlRule.PRP_INV, fact));
    }
    // RL rule prp-symp: Assert the symmetric statement if appropriate
    if (prop.isSymmetric()
        && !fact.hasRule(OwlRule.PRP_SYMP)
        && !subject.equals(node)) {
        collect(triple(node, predURI, subject, OwlRule.PRP_SYMP, fact));
    }
    // RL rule prp-irp: (x p x) is inconsistent if p is irreflexive
    if (prop.isIrreflexive() && subject.equals(node)) {
        collectInconsistency(inconsistency(OwlRule.PRP_IRP, fact));
    }
    // RL rule prp-trp (part 1/2): We assume triples are sorted with
    // incoming first, so store this triple in case it needs to be joined
    // with any later outgoing triples with the same property.
    if (prop.isTransitive() && !subject.equals(node)
        && checkTransitivityIncoming(fact)) {
        if (!transitiveIncoming.containsKey(predURI)) {
            transitiveIncoming.put(predURI, new LinkedList<Fact>());
        }
        transitiveIncoming.get(predURI).add(fact);
    }
    // RL rule prp-asyp (part 1/2): Store this incoming edge so we can
    // compare later outgoing edges against it. (Assume sorted input.)
    if (prop.isAsymmetric()) {
        if (!asymmetricIncoming.containsKey(predURI)) {
            asymmetricIncoming.put(predURI, new LinkedList<Fact>());
        }
        asymmetricIncoming.get(predURI).add(fact);
    }
    for (Resource rNode : prop.getRestrictions()) {
        OwlClass restriction = schema.getClass(rNode);
        // RL rule cls-svf1: Check for a someValuesFrom restriction
        Set<Resource> valuesFrom = restriction.someValuesFrom();
        // type owl:Thing would be checked by cls-svf2
        valuesFrom.remove(OWL.THING);
        for (Resource commonType : valuesFrom) {
            // If we learn the type, assert the other node's membership in rNode
            types.onType(commonType, triple(subject, RDF.TYPE,
                rNode, OwlRule.CLS_SVF1, fact));
        }
    }
}
 
Example 16
Source File: TurtleWriter.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Internal method that differentiates between the pretty-print and streaming writer cases.
 *
 * @param st                     The next statement to write
 * @param endRDFCalled           True if endRDF has been called before this method is called. This is used to buffer
 *                               statements for pretty-printing before dumping them when all statements have been
 *                               delivered to us.
 * @param canShortenSubjectBNode True if, in the current context, we may be able to shorten the subject of this
 *                               statement iff it is an instance of {@link BNode}.
 * @param canShortenObjectBNode  True if, in the current context, we may be able to shorten the object of this
 *                               statement iff it is an instance of {@link BNode}.
 */
protected void handleStatementInternal(Statement st, boolean endRDFCalled, boolean canShortenSubjectBNode,
		boolean canShortenObjectBNode) {
	Resource subj = st.getSubject();
	IRI pred = st.getPredicate();
	Value obj = st.getObject();
	try {
		if (subj.equals(lastWrittenSubject)) {
			if (pred.equals(lastWrittenPredicate)) {
				// Identical subject and predicate
				writer.write(",");
				wrapLine(prettyPrint);
			} else {
				// Identical subject, new predicate
				writer.write(";");
				writer.writeEOL();

				// Write new predicate
				writer.decreaseIndentation();
				writePredicate(pred);
				writer.increaseIndentation();
				wrapLine(true);
				path.removeLast();
				path.addLast(pred);
				lastWrittenPredicate = pred;
			}
		} else {
			// New subject
			closePreviousStatement();
			stack.addLast(subj);

			// Write new subject:
			if (prettyPrint) {
				writer.writeEOL();
			}
			writeResource(subj, canShortenSubjectBNode);
			wrapLine(true);
			writer.increaseIndentation();
			lastWrittenSubject = subj;

			// Write new predicate
			writePredicate(pred);
			wrapLine(true);
			path.addLast(pred);
			lastWrittenPredicate = pred;

			statementClosed = false;
			writer.increaseIndentation();
		}

		writeValue(obj, canShortenObjectBNode);

		// Don't close the line just yet. Maybe the next
		// statement has the same subject and/or predicate.
	} catch (IOException e) {
		throw new RDFHandlerException(e);
	}
}
 
Example 17
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @param move
 * @param uc
 * @throws SailException
 */
protected void executeMove(Move move, UpdateContext uc, int maxExecutionTime) throws SailException {
	ValueConstant sourceGraph = move.getSourceGraph();
	ValueConstant destinationGraph = move.getDestinationGraph();

	Resource source = sourceGraph != null ? (Resource) sourceGraph.getValue() : null;
	Resource destination = destinationGraph != null ? (Resource) destinationGraph.getValue() : null;

	if (source == null && destination == null || (source != null && source.equals(destination))) {
		// source and destination are the same, move is a null-operation.
		return;
	}

	// clear destination
	final long start = System.currentTimeMillis();
	con.clear((Resource) destination);
	final long clearTime = (System.currentTimeMillis() - start) / 1000;

	if (maxExecutionTime > 0 && clearTime > maxExecutionTime) {
		throw new SailException("execution took too long");
	}

	// remove all statements from source and add them to destination
	CloseableIteration<? extends Statement, SailException> statements = null;

	try {
		statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source);
		if (maxExecutionTime > 0) {
			statements = new TimeLimitIteration<Statement, SailException>(statements,
					1000L * (maxExecutionTime - clearTime)) {

				@Override
				protected void throwInterruptedException() throws SailException {
					throw new SailException("execution took too long");
				}
			};
		}

		while (statements.hasNext()) {
			Statement st = statements.next();
			con.addStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) destination);
			con.removeStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) source);
		}
	} finally {
		if (statements != null) {
			statements.close();
		}
	}
}
 
Example 18
Source File: SailUpdateExecutor.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * @param copy
 * @param uc
 * @throws SailException
 */
protected void executeCopy(Copy copy, UpdateContext uc, int maxExecutionTime) throws SailException {
	ValueConstant sourceGraph = copy.getSourceGraph();
	ValueConstant destinationGraph = copy.getDestinationGraph();

	Resource source = sourceGraph != null ? (Resource) sourceGraph.getValue() : null;
	Resource destination = destinationGraph != null ? (Resource) destinationGraph.getValue() : null;

	if (source == null && destination == null || (source != null && source.equals(destination))) {
		// source and destination are the same, copy is a null-operation.
		return;
	}

	// clear destination
	final long start = System.currentTimeMillis();
	con.clear((Resource) destination);
	final long clearTime = (System.currentTimeMillis() - start) / 1000;

	if (maxExecutionTime > 0) {
		if (clearTime > maxExecutionTime) {
			throw new SailException("execution took too long");
		}
	}

	// get all statements from source and add them to destination
	CloseableIteration<? extends Statement, SailException> statements = null;
	try {
		statements = con.getStatements(null, null, null, uc.isIncludeInferred(), (Resource) source);

		if (maxExecutionTime > 0) {
			statements = new TimeLimitIteration<Statement, SailException>(statements,
					1000L * (maxExecutionTime - clearTime)) {

				@Override
				protected void throwInterruptedException() throws SailException {
					throw new SailException("execution took too long");
				}
			};
		}

		while (statements.hasNext()) {
			Statement st = statements.next();
			con.addStatement(uc, st.getSubject(), st.getPredicate(), st.getObject(), (Resource) destination);
		}
	} finally {
		if (statements != null) {
			statements.close();
		}
	}
}
 
Example 19
Source File: LuceneSail.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Starts a reindexation process of the whole sail. Basically, this will delete and add all data again, a
 * long-lasting process.
 *
 * @throws IOException
 */
public void reindex() throws Exception {
	// clear
	logger.info("Reindexing sail: clearing...");
	luceneIndex.clear();
	logger.info("Reindexing sail: adding...");

	luceneIndex.begin();
	try {
		// iterate
		SailRepository repo = new SailRepository(new NotifyingSailWrapper(getBaseSail()) {

			@Override
			public void init() {
				// don't re-initialize the Sail when we initialize the repo
			}

			@Override
			public void shutDown() {
				// don't shutdown the underlying sail
				// when we shutdown the repo.
			}
		});
		try (SailRepositoryConnection connection = repo.getConnection()) {
			TupleQuery query = connection.prepareTupleQuery(QueryLanguage.SPARQL, reindexQuery);
			try (TupleQueryResult res = query.evaluate()) {
				Resource current = null;
				ValueFactory vf = getValueFactory();
				List<Statement> statements = new ArrayList<>();
				while (res.hasNext()) {
					BindingSet set = res.next();
					Resource r = (Resource) set.getValue("s");
					IRI p = (IRI) set.getValue("p");
					Value o = set.getValue("o");
					Resource c = (Resource) set.getValue("c");
					if (current == null) {
						current = r;
					} else if (!current.equals(r)) {
						if (logger.isDebugEnabled()) {
							logger.debug("reindexing resource " + current);
						}
						// commit
						luceneIndex.addDocuments(current, statements);

						// re-init
						current = r;
						statements.clear();
					}
					statements.add(vf.createStatement(r, p, o, c));
				}
			}
		} finally {
			repo.shutDown();
		}
		// commit the changes
		luceneIndex.commit();

		logger.info("Reindexing sail: done.");
	} catch (Exception e) {
		logger.error("Rolling back", e);
		luceneIndex.rollback();
		throw e;
	}
}
 
Example 20
Source File: AccumuloTemporalIndexer.java    From rya with Apache License 2.0 2 votes vote down vote up
/**
 * Allow only if the context matches the statement.  This is a client side filter.
 * @param statement
 * @param context
 * @return
 */
protected static boolean allowedByContext(final Statement statement, final Resource context) {
    return context==null || context.equals( statement.getContext() );
}