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

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

Introduction

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

Prototype

boolean contains(BlankNodeOrIRI subject, IRI predicate, RDFTerm object);

Source Link

Document

Check if graph contains a pattern of triples.

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);// w  w w  .  j a  va 2s . c om

    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);
    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:org.apache.commons.rdf.integrationtests.JSONLDParsingTest.java

private void checkGraph(Graph g) {
    assertTrue(g.contains(alice, name, aliceWLand));
    assertTrue(g.contains(alice, type, person));
}

From source file:org.trellisldp.constraint.LdpConstraints.java

private static boolean hasMembershipProps(final Graph graph) {
    return graph.contains(null, LDP.membershipResource, null)
            && (graph.stream(null, LDP.hasMemberRelation, null).count()
                    + graph.stream(null, LDP.isMemberOfRelation, null).count() == 1L);
}

From source file:org.trellisldp.rosid.file.RDFPatchTest.java

@Test
public void testStream1() throws Exception {
    final File file = new File(getClass().getResource("/journal1.txt").toURI());
    final Instant time = parse("2017-02-11T02:51:35Z");
    final Graph graph = rdf.createGraph();
    RDFPatch.asStream(rdf, file, identifier, time).map(Quad::asTriple).forEach(graph::add);
    assertEquals(2L, graph.size());/*from w  w w.  ja v a 2s  . co m*/
    assertTrue(
            graph.contains(identifier, rdf.createIRI("http://www.w3.org/2004/02/skos/core#prefLabel"), null));
}

From source file:org.trellisldp.rosid.file.RDFPatchTest.java

@Test
public void testStream2() throws Exception {
    final File file = new File(getClass().getResource("/journal1.txt").toURI());
    final Instant time = parse("2017-02-09T02:51:35Z");
    final Graph graph = rdf.createGraph();
    RDFPatch.asStream(rdf, file, identifier, time).map(Quad::asTriple).forEach(graph::add);
    assertEquals(3L, graph.size());//from  w w  w.  j av a 2s  .  c o  m
    assertTrue(
            graph.contains(identifier, rdf.createIRI("http://www.w3.org/2004/02/skos/core#prefLabel"), null));
    assertTrue(graph.contains(identifier, DC.isPartOf, null));
}

From source file:org.trellisldp.rosid.file.RDFPatchTest.java

@Test
public void testStream3() throws Exception {
    final File file = new File(getClass().getResource("/journal1.txt").toURI());
    final Instant time = parse("2017-01-30T02:51:35Z");
    final Graph graph = rdf.createGraph();
    RDFPatch.asStream(rdf, file, identifier, time).map(Quad::asTriple).forEach(graph::add);
    assertEquals(7L, graph.size());/*www.j  a  v a2s .  c o  m*/
    assertFalse(
            graph.contains(identifier, rdf.createIRI("http://www.w3.org/2004/02/skos/core#prefLabel"), null));
    assertTrue(graph.contains(identifier, DC.extent, null));
    assertTrue(graph.contains(identifier, DC.spatial, null));
    assertTrue(graph.contains(identifier, DC.title, null));
    assertTrue(graph.contains(identifier, DC.description, null));
    assertTrue(graph.contains(identifier, DC.subject, null));
    assertEquals(2L, graph.stream(identifier, DC.subject, null).count());
}

From source file:org.trellisldp.rosid.file.RDFPatchTest.java

@Test
public void testStream4() throws Exception {
    final File file = new File(getClass().getResource("/journal1.txt").toURI());
    final Instant time = parse("2017-01-15T09:14:00Z");
    final Graph graph = rdf.createGraph();
    RDFPatch.asStream(rdf, file, identifier, time).map(Quad::asTriple).forEach(graph::add);
    assertEquals(5L, graph.size());/*www  . ja v a  2 s.c  o m*/
    assertFalse(
            graph.contains(identifier, rdf.createIRI("http://www.w3.org/2004/02/skos/core#prefLabel"), null));
    assertFalse(graph.contains(identifier, DC.extent, null));
    assertFalse(graph.contains(identifier, DC.spatial, null));
    assertTrue(graph.contains(identifier, DC.title, null));
    assertTrue(graph.contains(identifier, DC.description, null));
    assertTrue(graph.contains(identifier, DC.subject, null));
    assertEquals(2L, graph.stream(identifier, DC.subject, null).count());
}

From source file:org.trellisldp.test.AuditTests.java

/**
 * Check the presence of audit triples./*from w ww . j  a  va 2s.c o  m*/
 */
@Test
@DisplayName("Check the presence of audit triples.")
default void testAuditTriples() {
    final RDF rdf = getInstance();
    try (final Response res = target(getResourceLocation()).request()
            .header("Prefer", "return=representation; include=\"" + Trellis.PreferAudit.getIRIString() + "\"")
            .get()) {
        final Graph g = readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE);
        assertEquals(3L, g.stream(rdf.createIRI(getResourceLocation()), PROV.wasGeneratedBy, null).count(),
                "Check for the presence of audit triples in the graph");
        assertAll("Check the graph triples",
                g.stream(rdf.createIRI(getResourceLocation()), PROV.wasGeneratedBy, null).flatMap(triple -> of(
                        () -> assertTrue(g.contains((BlankNodeOrIRI) triple.getObject(), type, PROV.Activity),
                                "Verify that the prov:activity type is present for the resource"),
                        () -> assertTrue(g.contains((BlankNodeOrIRI) triple.getObject(), PROV.atTime, null),
                                "Verify that the prov:atTime property is present for the resource"),
                        () -> assertEquals(4L,
                                g.stream((BlankNodeOrIRI) triple.getObject(), null, null).count(),
                                "Verify that we have the right number of triples for the resource"))));
        assertTrue(g.contains(null, PROV.wasAssociatedWith, Trellis.AdministratorAgent), "Verify agent 1");
        assertTrue(g.contains(null, PROV.wasAssociatedWith,
                rdf.createIRI("https://madison.example.com/profile#me")), "Verify agent 2");
        assertTrue(g.contains(null, PROV.wasAssociatedWith,
                rdf.createIRI("https://people.apache.org/~acoburn/#i")), "Verify agent 3");
        assertEquals(2L, g.stream(null, type, AS.Update).count(), "Count the number of update events");
        assertEquals(1L, g.stream(null, type, AS.Create).count(), "Count the number of create events");
        assertEquals(17L, g.size(), "Get the total graph size");
    }
}

From source file:org.trellisldp.test.CommonTests.java

/**
 * Check an RDF graph.//from   w w  w. j  av  a  2 s .  com
 * @param graph the graph
 * @param identifier the identifier
 * @return a stream of testable assertions
 */
default Stream<Executable> checkRdfGraph(final Graph graph, final IRI identifier) {
    return Stream.of(
            () -> assertTrue(
                    graph.contains(identifier, SKOS.prefLabel,
                            getInstance().createLiteral(BASIC_CONTAINER_LABEL, ENG)),
                    "Check for the presence of a skos:prefLabel triple"),
            () -> assertTrue(graph.contains(identifier, DC.description, null),
                    "Check for the presence fo a dc:description triple"));
}

From source file:org.trellisldp.test.LdpBasicContainerTests.java

/**
 * Test with ldp:PreferMinimalContainer Prefer header.
 *//*from  ww w .  ja v  a  2  s .  com*/
@Test
@DisplayName("Test with ldp:PreferMinimalContainer Prefer header")
default void testGetEmptyContainer() {
    final RDF rdf = getInstance();
    try (final Response res = target(getContainerLocation()).request()
            .header(PREFER,
                    "return=representation; include=\"" + LDP.PreferMinimalContainer.getIRIString() + "\"")
            .get()) {
        assertAll("Check a container response", checkRdfResponse(res, LDP.BasicContainer, TEXT_TURTLE_TYPE));
        final IRI identifier = rdf.createIRI(getContainerLocation());
        final Graph g = readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE);
        assertAll("Check the graph for triples", checkRdfGraph(g, identifier));
        assertFalse(g.contains(identifier, LDP.contains, null),
                "Verify that no ldp:contains triples are present");
    }
}