Example usage for org.apache.commons.rdf.api Graph add

List of usage examples for org.apache.commons.rdf.api Graph add

Introduction

In this page you can find the example usage for org.apache.commons.rdf.api Graph add.

Prototype

void add(Triple triple);

Source Link

Document

Add a triple to the graph, possibly mapping any of the components of the Triple to those supported by this Graph.

Usage

From source file:example.IntroToRDF.java

public static void main(String[] args) {
    RDF rdf = new SimpleRDF();

    IRI alice = rdf.createIRI("Alice");
    System.out.println(alice.ntriplesString());

    IRI knows = rdf.createIRI("knows");
    IRI bob = rdf.createIRI("Bob");

    Triple aliceKnowsBob = rdf.createTriple(alice, knows, bob);
    System.out.println(aliceKnowsBob.getSubject().ntriplesString());

    System.out.println(aliceKnowsBob);

    Graph graph = rdf.createGraph();
    graph.add(aliceKnowsBob);

    IRI charlie = rdf.createIRI("Charlie");

    IRI plays = rdf.createIRI("plays");

    IRI football = rdf.createIRI("Football");
    IRI tennis = rdf.createIRI("Tennis");

    graph.add(alice, knows, charlie);//from   w  ww  . j  a v a 2s  .c om
    graph.add(alice, plays, tennis);
    graph.add(bob, knows, charlie);
    graph.add(bob, plays, football);
    graph.add(charlie, plays, tennis);

    System.out.println("Who plays Tennis?");
    for (Triple triple : graph.iterate(null, plays, tennis)) {
        System.out.println(triple.getSubject());
        System.out.println(plays.equals(triple.getPredicate()));
        System.out.println(tennis.equals(triple.getObject()));
    }

    System.out.println("Who does Alice know?");
    for (Triple triple : graph.iterate(alice, knows, null)) {
        System.out.println(triple.getObject());
    }

    System.out.println("Does Alice anyone that plays Football?");
    for (Triple triple : graph.iterate(alice, knows, null)) {
        RDFTerm aliceFriend = triple.getObject();
        if (!(aliceFriend instanceof BlankNodeOrIRI)) {
            continue;
        }
        if (graph.contains((BlankNodeOrIRI) aliceFriend, plays, football)) {
            System.out.println("Yes, it is " + aliceFriend);
        }
    }

    Literal aliceName = rdf.createLiteral("Alice W. Land");
    IRI name = rdf.createIRI("name");
    graph.add(alice, name, aliceName);

    Optional<? extends Triple> nameTriple = graph.stream(alice, name, null).findAny();
    if (nameTriple.isPresent()) {
        System.out.println(nameTriple.get());
    }

    graph.stream(alice, name, null).findAny().map(Triple::getObject).filter(obj -> obj instanceof Literal)
            .map(literalName -> ((Literal) literalName).getLexicalForm()).ifPresent(System.out::println);

    IRI playerRating = rdf.createIRI("playerRating");
    Literal aliceRating = rdf.createLiteral("13.37", Types.XSD_FLOAT);
    graph.add(alice, playerRating, aliceRating);

    Literal footballInEnglish = rdf.createLiteral("football", "en");
    Literal footballInNorwegian = rdf.createLiteral("fotball", "no");
    graph.add(football, name, footballInEnglish);
    graph.add(football, name, footballInNorwegian);

    Literal footballInAmericanEnglish = rdf.createLiteral("soccer", "en-US");
    graph.add(football, name, footballInAmericanEnglish);

    BlankNode someone = rdf.createBlankNode();
    graph.add(charlie, knows, someone);
    graph.add(someone, plays, football);

    BlankNode someoneElse = rdf.createBlankNode();
    graph.add(charlie, knows, someoneElse);

    for (Triple heKnows : graph.iterate(charlie, knows, null)) {
        if (!(heKnows.getObject() instanceof BlankNodeOrIRI)) {
            continue;
        }
        BlankNodeOrIRI who = (BlankNodeOrIRI) heKnows.getObject();
        System.out.println("Charlie knows " + who);
        for (Triple whoPlays : graph.iterate(who, plays, null)) {
            System.out.println("  who plays " + whoPlays.getObject());
        }
    }

    // Delete previous BlankNode statements
    graph.remove(null, null, someone);
    graph.remove(someone, null, null);

    // no Java variable for the new BlankNode instance
    graph.add(charlie, knows, rdf.createBlankNode("someone"));
    // at any point later (with the same RDF instance)
    graph.add(rdf.createBlankNode("someone"), plays, football);

    for (Triple heKnows : graph.iterate(charlie, knows, null)) {
        if (!(heKnows.getObject() instanceof BlankNodeOrIRI)) {
            continue;
        }
        BlankNodeOrIRI who = (BlankNodeOrIRI) heKnows.getObject();
        System.out.println("Charlie knows " + who);
        for (Triple whoPlays : graph.iterate(who, plays, null)) {
            System.out.println("  who plays " + whoPlays.getObject());
        }
    }

}

From source file:example.UserGuideTest.java

@Test
public void graph() throws Exception {
    IRI nameIri = factory.createIRI("http://example.com/name");
    BlankNode aliceBlankNode = factory.createBlankNode();
    Literal aliceLiteral = factory.createLiteral("Alice");
    Triple triple = factory.createTriple(aliceBlankNode, nameIri, aliceLiteral);

    Graph graph = factory.createGraph();

    graph.add(triple);

    IRI bob = factory.createIRI("http://example.com/bob");
    Literal bobName = factory.createLiteral("Bob");
    graph.add(bob, nameIri, bobName);/* w  w w. ja  v a2s . c  om*/

    System.out.println(graph.contains(triple));

    System.out.println(graph.contains(null, nameIri, bobName));

    System.out.println(graph.size());

    for (Triple t : graph.iterate()) {
        System.out.println(t.getObject());
    }

    for (Triple t : graph.iterate(null, null, bobName)) {
        System.out.println(t.getPredicate());
    }

    Stream<RDFTerm> subjects = graph.getTriples().map(t -> t.getObject());
    String s = subjects.map(RDFTerm::ntriplesString).collect(Collectors.joining(" "));
    System.out.println(s);

    Stream<? extends Triple> namedB = graph.getTriples(null, nameIri, null)
            .filter(t -> t.getObject().ntriplesString().contains("B"));
    System.out.println(namedB.map(t -> t.getSubject()).findAny().get());

    graph.remove(triple);
    System.out.println(graph.contains(triple));

    graph.remove(null, nameIri, null);

    graph.clear();
    System.out.println(graph.contains(null, null, null));

}

From source file:org.apache.jena.commonsrdf.JenaCommonsRDF.java

/** Convert a CommonsRDF Graph to a Jena Graph.
 * If the Graph was from Jena originally, return that original object else
 * create a copy using Jena objects. /*from www  . ja  v a  2 s  .c  om*/
 */
public static org.apache.jena.graph.Graph toJena(Graph graph) {
    if (graph instanceof JenaGraph)
        return ((JenaGraph) graph).getGraph();
    org.apache.jena.graph.Graph g = GraphFactory.createGraphMem();
    graph.getTriples().forEach(t -> g.add(toJena(t)));
    return g;
}

From source file:org.apache.jena.commonsrdf.JenaCommonsRDF.java

/** Convert from Jena to any RDFCommons implementation.
 *  This is a copy, even if the factory is a RDFTermFactoryJena.
 *  Use {@link #fromJena(org.apache.jena.graph.Graph)} for a wrapper.
 *//*  ww  w .  j  a va  2s  .  c  om*/
public static Graph fromJena(RDFTermFactory factory, org.apache.jena.graph.Graph graph) {
    Graph g = factory.createGraph();
    graph.find(Node.ANY, Node.ANY, Node.ANY).forEachRemaining(t -> {
        g.add(fromJena(factory, t));
    });
    return g;
}

From source file:org.trellisldp.http.impl.HttpUtilsTest.java

@Test
public void testSkolemize() {
    final String baseUrl = "http://example.org/";
    final Literal literal = rdf.createLiteral("A title");
    final BlankNode bnode = rdf.createBlankNode("foo");

    when(mockResourceService.skolemize(any(Literal.class))).then(returnsFirstArg());
    when(mockResourceService.skolemize(any(IRI.class))).then(returnsFirstArg());
    when(mockResourceService.skolemize(any(BlankNode.class))).thenAnswer(
            inv -> rdf.createIRI(TRELLIS_BNODE_PREFIX + ((BlankNode) inv.getArgument(0)).uniqueReference()));
    when(mockResourceService.unskolemize(any(IRI.class))).thenAnswer(inv -> {
        final String uri = ((IRI) inv.getArgument(0)).getIRIString();
        if (uri.startsWith(TRELLIS_BNODE_PREFIX)) {
            return bnode;
        }/*from w  w  w .ja v  a2 s  . c  om*/
        return (IRI) inv.getArgument(0);
    });
    when(mockResourceService.toExternal(any(RDFTerm.class), eq(baseUrl))).thenAnswer(inv -> {
        final RDFTerm term = (RDFTerm) inv.getArgument(0);
        if (term instanceof IRI) {
            final String identifierString = ((IRI) term).getIRIString();
            if (identifierString.startsWith(TRELLIS_DATA_PREFIX)) {
                return rdf.createIRI(baseUrl + identifierString.substring(TRELLIS_DATA_PREFIX.length()));
            }
        }
        return term;
    });
    when(mockResourceService.toInternal(any(RDFTerm.class), eq(baseUrl))).thenAnswer(inv -> {
        final RDFTerm term = (RDFTerm) inv.getArgument(0);
        if (term instanceof IRI) {
            final String identifierString = ((IRI) term).getIRIString();
            if (identifierString.startsWith(baseUrl)) {
                return rdf.createIRI(TRELLIS_DATA_PREFIX + identifierString.substring(baseUrl.length()));
            }
        }
        return term;
    });

    when(mockResourceService.unskolemize(any(Literal.class))).then(returnsFirstArg());

    final IRI subject = rdf.createIRI("http://example.org/resource");
    final Graph graph = rdf.createGraph();
    graph.add(rdf.createTriple(subject, DC.title, literal));
    graph.add(rdf.createTriple(subject, DC.subject, bnode));
    graph.add(rdf.createTriple(bnode, DC.title, literal));

    final List<Triple> triples = graph.stream()
            .map(HttpUtils.skolemizeTriples(mockResourceService, "http://example.org/")).collect(toList());

    assertTrue(triples.stream().anyMatch(t -> t.getSubject().equals(identifier)),
            "subject not in triple stream!");
    assertTrue(triples.stream().anyMatch(t -> t.getObject().equals(literal)), "Literal not in triple stream!");
    assertTrue(
            triples.stream()
                    .anyMatch(t -> t.getSubject().ntriplesString().startsWith("<" + TRELLIS_BNODE_PREFIX)),
            "Skolemized bnode not in triple stream!");

    assertAll(triples.stream().map(HttpUtils.unskolemizeTriples(mockResourceService, "http://example.org/"))
            .map(t -> () -> assertTrue(graph.contains(t), "Graph doesn't include triple: " + t)));
}

From source file:org.trellisldp.http.impl.RdfUtilsTest.java

@Test
public void testSkolemize() {
    final IRI iri = rdf.createIRI("trellis:repository/resource");
    final String baseUrl = "http://example.org/";
    final IRI anonIri = rdf.createIRI(TRELLIS_BNODE_PREFIX + "foo");
    final Literal literal = rdf.createLiteral("A title");
    final BlankNode bnode = rdf.createBlankNode("foo");

    when(mockResourceService.skolemize(any(Literal.class))).then(returnsFirstArg());
    when(mockResourceService.skolemize(any(IRI.class))).then(returnsFirstArg());
    when(mockResourceService.skolemize(any(BlankNode.class))).thenAnswer(
            inv -> rdf.createIRI(TRELLIS_BNODE_PREFIX + ((BlankNode) inv.getArgument(0)).uniqueReference()));
    when(mockResourceService.unskolemize(any(IRI.class))).thenAnswer(inv -> {
        final String uri = ((IRI) inv.getArgument(0)).getIRIString();
        if (uri.startsWith(TRELLIS_BNODE_PREFIX)) {
            return bnode;
        }//from  w  w  w.  j a  va 2  s  .  c om
        return (IRI) inv.getArgument(0);
    });
    when(mockResourceService.toExternal(any(RDFTerm.class), eq(baseUrl))).thenAnswer(inv -> {
        final RDFTerm term = (RDFTerm) inv.getArgument(0);
        if (term instanceof IRI) {
            final String iriString = ((IRI) term).getIRIString();
            if (iriString.startsWith(TRELLIS_PREFIX)) {
                return rdf.createIRI(baseUrl + iriString.substring(TRELLIS_PREFIX.length()));
            }
        }
        return term;
    });
    when(mockResourceService.toInternal(any(RDFTerm.class), eq(baseUrl))).thenAnswer(inv -> {
        final RDFTerm term = (RDFTerm) inv.getArgument(0);
        if (term instanceof IRI) {
            final String iriString = ((IRI) term).getIRIString();
            if (iriString.startsWith(baseUrl)) {
                return rdf.createIRI(TRELLIS_PREFIX + iriString.substring(baseUrl.length()));
            }
        }
        return term;
    });

    when(mockResourceService.unskolemize(any(Literal.class))).then(returnsFirstArg());

    final IRI subject = rdf.createIRI("http://example.org/repository/resource");
    final Graph graph = rdf.createGraph();
    graph.add(rdf.createTriple(subject, DC.title, literal));
    graph.add(rdf.createTriple(subject, DC.subject, bnode));
    graph.add(rdf.createTriple(bnode, DC.title, literal));

    final List<Triple> triples = graph.stream()
            .map(RdfUtils.skolemizeTriples(mockResourceService, "http://example.org/")).collect(toList());

    assertTrue(triples.stream().anyMatch(t -> t.getSubject().equals(iri)));
    assertTrue(triples.stream().anyMatch(t -> t.getObject().equals(literal)));
    assertTrue(triples.stream()
            .anyMatch(t -> t.getSubject().ntriplesString().startsWith("<" + TRELLIS_BNODE_PREFIX)));

    triples.stream().map(RdfUtils.unskolemizeTriples(mockResourceService, "http://example.org/"))
            .forEach(t -> assertTrue(graph.contains(t)));
}