Search in sources :

Example 21 with Resource

use of org.eclipse.rdf4j.model.Resource in project rdf4j by eclipse.

the class Models method matchModels.

/**
 * A recursive method for finding a complete mapping between blank nodes in model1 and blank nodes in
 * model2. The algorithm does a depth-first search trying to establish a mapping for each blank node
 * occurring in model1.
 *
 * @param model1
 * @param model2
 * @param bNodeMapping
 * @param idx
 * @return true if a complete mapping has been found, false otherwise.
 */
private static boolean matchModels(List<? extends Statement> model1, Model model2, Map<Resource, Resource> bNodeMapping, int idx) {
    boolean result = false;
    if (idx < model1.size()) {
        Statement st1 = model1.get(idx);
        List<Statement> matchingStats = findMatchingStatements(st1, model2, bNodeMapping);
        for (Statement st2 : matchingStats) {
            // Map bNodes in st1 to bNodes in st2
            Map<Resource, Resource> newBNodeMapping = new HashMap<Resource, Resource>(bNodeMapping);
            if (isBlank(st1.getSubject()) && isBlank(st2.getSubject())) {
                newBNodeMapping.put(st1.getSubject(), st2.getSubject());
            }
            if (isBlank(st1.getObject()) && isBlank(st2.getObject())) {
                newBNodeMapping.put((Resource) st1.getObject(), (Resource) st2.getObject());
            }
            if (isBlank(st1.getContext()) && isBlank(st2.getContext())) {
                newBNodeMapping.put(st1.getContext(), st2.getContext());
            }
            // FIXME: this recursive implementation has a high risk of
            // triggering a stack overflow
            // Enter recursion
            result = matchModels(model1, model2, newBNodeMapping, idx + 1);
            if (result == true) {
                // models match, look no further
                break;
            }
        }
    } else {
        // All statements have been mapped successfully
        result = true;
    }
    return result;
}
Also used : HashMap(java.util.HashMap) Statement(org.eclipse.rdf4j.model.Statement) Resource(org.eclipse.rdf4j.model.Resource)

Example 22 with Resource

use of org.eclipse.rdf4j.model.Resource in project rdf4j by eclipse.

the class RDFCollections method consumeCollection.

/**
 * Converts the supplied {@link Iterable} to an
 * <a href="http://www.w3.org/TR/rdf-schema/#ch_collectionvocab">RDF Collection</a>, using the supplied
 * {@code head} resource as the starting resource of the RDF Collection. The statements making up the new
 * RDF Collection will be reported to the supplied {@link Consumer} function.
 *
 * @param values
 *        an {@link Iterable} of objects (such as a Java {@link Collection} ), which will be converted to
 *        an RDF Collection. May not be {@code null}. The method attempts to convert each value that is
 *        not already an instance of {@link Value} to a {@link Literal}. This conversion will fail with a
 *        {@link LiteralUtilException} if the value's object type is not supported. See
 *        {@link Literals#createLiteralOrFail(ValueFactory, Object)} for an overview of supported types.
 * @param head
 *        a {@link Resource} which will be used as the head of the list, that is, the starting point of
 *        the created RDF Collection. May be {@code null}, in which case a new resource is generated to
 *        represent the list head.
 * @param consumer
 *        the {@link Consumer} function for the Statements of the RDF Collection. May not be {@code null}.
 * @param contexts
 *        the context(s) in which to add the RDF Collection. This argument is an optional vararg and can
 *        be left out.
 * @throws LiteralUtilException
 *         if one of the supplied values can not be converted to a Literal.
 * @see <a href="http://www.w3.org/TR/rdf-schema/#ch_collectionvocab">RDF Schema 1.1 section on Collection
 *      vocabulary</a>.
 * @see Literals#createLiteralOrFail(ValueFactory, Object)
 */
public static void consumeCollection(Iterable<?> values, Resource head, Consumer<Statement> consumer, Resource... contexts) {
    Objects.requireNonNull(values, "input collection may not be null");
    Objects.requireNonNull(consumer, "consumer may not be null");
    final ValueFactory vf = SimpleValueFactory.getInstance();
    Resource current = head != null ? head : vf.createBNode();
    Statements.consume(vf, current, RDF.TYPE, RDF.LIST, consumer, contexts);
    Iterator<?> iter = values.iterator();
    while (iter.hasNext()) {
        Object o = iter.next();
        Value v = o instanceof Value ? (Value) o : Literals.createLiteralOrFail(vf, o);
        Statements.consume(vf, current, RDF.FIRST, v, consumer, contexts);
        if (iter.hasNext()) {
            Resource next = vf.createBNode();
            Statements.consume(vf, current, RDF.REST, next, consumer, contexts);
            current = next;
        } else {
            Statements.consume(vf, current, RDF.REST, RDF.NIL, consumer, contexts);
        }
    }
}
Also used : Resource(org.eclipse.rdf4j.model.Resource) Value(org.eclipse.rdf4j.model.Value) ValueFactory(org.eclipse.rdf4j.model.ValueFactory) SimpleValueFactory(org.eclipse.rdf4j.model.impl.SimpleValueFactory)

Example 23 with Resource

use of org.eclipse.rdf4j.model.Resource in project rdf4j by eclipse.

the class RDFCollections method extract.

/**
 * Extracts an RDF Collection starting with the supplied list head from the statement supplier and sends
 * all statements that make up the collection to the supplied {@link Consumer} function. This method
 * expects the RDF Collection to be well-formed. If the collection is not well-formed the method may
 * report only part of the collection, or may throw an exception.
 *
 * @param statementSupplier
 *        the source of the statements from which the RDF collection is to be read, specified as a
 *        functional interface.
 * @param head
 *        the {@link Resource} that represents the list head, that is the start resource of the RDF
 *        Collection to be read. May not be {@code null}.
 * @param collectionConsumer
 *        the Java {@link Consumer} function to which the collection statements are reported.
 * @param exceptionSupplier
 *        a functional interface that produces the exception type this method will throw when an error
 *        occurs.
 * @param contexts
 *        the context(s) from which to read the RDF Collection. This argument is an optional vararg and
 *        can be left out.
 * @throws E
 *         if a problem occurs reading the RDF Collection, for example if it is not well-formed.
 */
public static <E extends RDF4JException> void extract(GetStatementOptional statementSupplier, Resource head, Consumer<Statement> collectionConsumer, Function<String, Supplier<E>> exceptionSupplier, Resource... contexts) throws E {
    OpenRDFUtil.verifyContextNotNull(contexts);
    Objects.requireNonNull(head, "list head may not be null");
    Objects.requireNonNull(collectionConsumer, "collection consumer may not be null");
    Resource current = head;
    final Set<Resource> visited = new HashSet<>();
    while (!RDF.NIL.equals(current)) {
        if (visited.contains(current)) {
            throw exceptionSupplier.apply("list not well-formed: cycle detected").get();
        }
        statementSupplier.get(current, RDF.TYPE, RDF.LIST, contexts).ifPresent(collectionConsumer);
        collectionConsumer.accept(statementSupplier.get(current, RDF.FIRST, null, contexts).orElseThrow(exceptionSupplier.apply("list not wellformed: rdf:first statement missing.")));
        Statement next = statementSupplier.get(current, RDF.REST, null, contexts).orElseThrow(exceptionSupplier.apply("list not well-formed: rdf:rest statement missing."));
        collectionConsumer.accept(next);
        if (!(next.getObject() instanceof Resource)) {
            throw exceptionSupplier.apply("list not well-formed: value of rdf:rest should be one of (IRI, BNode).").get();
        }
        visited.add(current);
        current = (Resource) next.getObject();
    }
}
Also used : Statement(org.eclipse.rdf4j.model.Statement) Resource(org.eclipse.rdf4j.model.Resource) HashSet(java.util.HashSet)

Example 24 with Resource

use of org.eclipse.rdf4j.model.Resource in project rdf4j by eclipse.

the class TransactionSAXParser method createAddStatementOperation.

private TransactionOperation createAddStatementOperation() throws SAXException {
    if (parsedValues.size() < 3) {
        throw new SAXException("At least three values required for AddStatementOperation, found: " + parsedValues.size());
    }
    try {
        Resource subject = (Resource) parsedValues.get(0);
        IRI predicate = (IRI) parsedValues.get(1);
        Value object = parsedValues.get(2);
        Resource[] contexts = createContexts(3);
        parsedValues.clear();
        if (subject == null || predicate == null || object == null) {
            throw new SAXException("Subject, predicate and object cannot be null for an AddStatementOperation");
        }
        return new AddStatementOperation(subject, predicate, object, contexts);
    } catch (ClassCastException e) {
        throw new SAXException("Invalid argument(s) for AddStatementOperation", e);
    }
}
Also used : IRI(org.eclipse.rdf4j.model.IRI) AddStatementOperation(org.eclipse.rdf4j.http.protocol.transaction.operations.AddStatementOperation) Resource(org.eclipse.rdf4j.model.Resource) Value(org.eclipse.rdf4j.model.Value) SAXException(org.xml.sax.SAXException)

Example 25 with Resource

use of org.eclipse.rdf4j.model.Resource in project rdf4j by eclipse.

the class RDFXMLPrettyWriterBackgroundTest method outOfSequenceItemsAreNotAbbreviated.

@Test
public void outOfSequenceItemsAreNotAbbreviated() throws RDFHandlerException, IOException {
    StringWriter writer = new StringWriter();
    RDFWriter rdfWriter = rdfWriterFactory.getWriter(writer);
    rdfWriter.startRDF();
    Resource res = vf.createIRI("http://example.com/#");
    rdfWriter.handleStatement(vf.createStatement(res, RDF.TYPE, RDF.BAG));
    rdfWriter.handleStatement(vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_0"), vf.createIRI("http://example.com/#0")));
    rdfWriter.handleStatement(vf.createStatement(res, vf.createIRI(RDF.NAMESPACE + "_2"), vf.createIRI("http://example.com/#2")));
    rdfWriter.endRDF();
    List<String> rdfLines = rdfOpenTags(writer.toString());
    assertEquals(Arrays.asList("<rdf:RDF", "<rdf:Bag", "<rdf:_0", "<rdf:_2"), rdfLines);
}
Also used : StringWriter(java.io.StringWriter) Resource(org.eclipse.rdf4j.model.Resource) RDFWriter(org.eclipse.rdf4j.rio.RDFWriter) Test(org.junit.Test)

Aggregations

Resource (org.eclipse.rdf4j.model.Resource)90 IRI (org.eclipse.rdf4j.model.IRI)37 Value (org.eclipse.rdf4j.model.Value)30 Test (org.junit.Test)16 Statement (org.eclipse.rdf4j.model.Statement)15 Model (org.eclipse.rdf4j.model.Model)12 RDFHandlerException (org.eclipse.rdf4j.rio.RDFHandlerException)12 BNode (org.eclipse.rdf4j.model.BNode)11 IOException (java.io.IOException)9 Literal (org.eclipse.rdf4j.model.Literal)9 RepositoryException (org.eclipse.rdf4j.repository.RepositoryException)7 StringWriter (java.io.StringWriter)6 ParsedIRI (org.eclipse.rdf4j.common.net.ParsedIRI)6 ValueFactory (org.eclipse.rdf4j.model.ValueFactory)6 SimpleValueFactory (org.eclipse.rdf4j.model.impl.SimpleValueFactory)6 TreeModel (org.eclipse.rdf4j.model.impl.TreeModel)6 RepositoryConnection (org.eclipse.rdf4j.repository.RepositoryConnection)6 RDFWriter (org.eclipse.rdf4j.rio.RDFWriter)6 LinkedHashModel (org.eclipse.rdf4j.model.impl.LinkedHashModel)5 ArrayList (java.util.ArrayList)4