Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

In this page you can find the example usage for java.util Optional ifPresent.

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

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

@Test
public void testTooManyMembershipTriples() {
    final Optional<ConstraintViolation> res = svc.constrainedBy(LDP.IndirectContainer,
            asGraph("/tooManyMembershipTriples.ttl", domain + "foo"), domain).findFirst();
    assertTrue(res.isPresent(), "no constraint violation found!");
    res.ifPresent(violation -> assertEquals(Trellis.InvalidCardinality, violation.getConstraint(),
            "no InvalidCardinality violation!"));
}

From source file:org.trellisldp.file.FileUtilsTest.java

@Test
public void testParseQuad() {
    final Optional<Quad> quad = FileUtils.parseQuad("<trellis:data/resource> <http://purl.org/dc/terms/title> "
            + "\"Some title\" <http://www.trellisldp.org/ns/trellis#PreferUserManaged> .").findFirst();
    assertTrue(quad.isPresent(), "Quad isn't present in parsed string!");
    quad.ifPresent(q -> {
        assertEquals("trellis:data/resource", ((IRI) q.getSubject()).getIRIString(), "Incorrect subject!");
        assertEquals(DC.title, q.getPredicate(), "Incorrect predicate!");
        assertEquals("Some title", ((Literal) q.getObject()).getLexicalForm(), "Incorrect literal object!");
        assertTrue(q.getGraphName().isPresent(), "Graph name isn't present!");
        q.getGraphName().ifPresent(g -> assertEquals(Trellis.PreferUserManaged, g, "Incorrect graph name!"));
    });/*from w  w  w.ja  v  a  2  s  .co  m*/
}

From source file:org.trellisldp.file.FileUtilsTest.java

@Test
public void testParseQuadWithComment() {
    final Optional<Quad> quad = FileUtils
            .parseQuad("<trellis:data/resource> <http://purl.org/dc/terms/description> "
                    + "\"A description\" <http://www.trellisldp.org/ns/trellis#PreferUserManaged> . # some comment")
            .findFirst();/*from w  ww . ja v  a 2  s.c om*/
    assertTrue(quad.isPresent(), "Quad isn't present in parsed string!");
    quad.ifPresent(q -> {
        assertEquals("trellis:data/resource", ((IRI) q.getSubject()).getIRIString(), "Incorrect subject!");
        assertEquals(DC.description, q.getPredicate(), "Incorrect predicate!");
        assertEquals("A description", ((Literal) q.getObject()).getLexicalForm(), "Incorrect literal object!");
        assertTrue(q.getGraphName().isPresent(), "Graph name isn't present!");
        q.getGraphName().ifPresent(g -> assertEquals(Trellis.PreferUserManaged, g, "Incorrect graph name!"));
    });
}

From source file:org.trellisldp.file.FileUtilsTest.java

@Test
public void testParseQuadNoGraph() {
    final Optional<Quad> quad = FileUtils
            .parseQuad("<trellis:data/resource> <http://purl.org/dc/terms/title> " + "\"A different title\" .")
            .findFirst();//from ww w.j  ava 2  s. c om
    assertTrue(quad.isPresent(), "Quad isn't present in parsed Triple string!");
    quad.ifPresent(q -> {
        assertEquals("trellis:data/resource", ((IRI) q.getSubject()).getIRIString(), "Incorrect subject!");
        assertEquals(DC.title, q.getPredicate(), "Incorrect predicate!");
        assertEquals("A different title", ((Literal) q.getObject()).getLexicalForm(),
                "Incorrect literal object!");
        assertFalse(q.getGraphName().isPresent(), "Graph name shouldn't have been present!");
    });
}

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

private ResponseBuilder basicGetResponseBuilder(final Resource res, final Optional<RDFSyntax> syntax) {
    final ResponseBuilder builder = ok();

    // Standard HTTP Headers
    builder.lastModified(from(res.getModified()));

    final IRI model;

    if (isNull(req.getExt())) {
        syntax.ifPresent(s -> {
            builder.header(VARY, PREFER);
            builder.type(s.mediaType);/*from w ww.ja  va2 s.c  o m*/
        });

        model = res.getBinary().isPresent() && syntax.isPresent() ? LDP.RDFSource : res.getInteractionModel();
        // Link headers from User data
        res.getTypes().forEach(type -> builder.link(type.getIRIString(), "type"));
        res.getInbox().map(IRI::getIRIString).ifPresent(inbox -> builder.link(inbox, "inbox"));
        res.getAnnotationService().map(IRI::getIRIString)
                .ifPresent(svc -> builder.link(svc, annotationService.getIRIString()));
    } else {
        model = LDP.RDFSource;
    }

    // Add LDP-required headers
    ldpResourceTypes(model).forEach(type -> {
        builder.link(type.getIRIString(), "type");
        // Mementos don't accept POST or PATCH
        if (LDP.Container.equals(type) && !res.isMemento()) {
            builder.header(ACCEPT_POST, MEDIA_TYPES.stream().map(mt -> mt.getType() + "/" + mt.getSubtype())
                    // text/html is excluded
                    .filter(mt -> !TEXT_HTML.equals(mt)).collect(joining(",")));
        } else if (LDP.RDFSource.equals(type) && !res.isMemento()) {
            builder.header(ACCEPT_PATCH, APPLICATION_SPARQL_UPDATE);
        }
    });

    // Memento-related headers
    if (res.isMemento()) {
        builder.header(MEMENTO_DATETIME, from(res.getModified()));
    } else {
        builder.header(VARY, ACCEPT_DATETIME);
    }

    return builder;
}

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

@Test
public void testWriteResource() {
    final Dataset data = rdf.createDataset();
    data.add(rdf.createQuad(Trellis.PreferUserManaged, testResource, DC.title, rdf.createLiteral("A title")));
    data.add(rdf.createQuad(Trellis.PreferServerManaged, testResource, type, LDP.RDFSource));
    assertFalse(service.get(testResource).isPresent());
    assertFalse(service.get(testResource, now()).isPresent());

    assertTrue(service.put(testResource, data));
    final Optional<Resource> res = service.get(testResource, now());
    assertTrue(res.isPresent());/*from  ww w . j ava  2  s  .  c o m*/
    res.ifPresent(r -> {
        assertEquals(LDP.RDFSource, r.getInteractionModel());
        assertEquals(testResource, r.getIdentifier());
        assertTrue(r.stream().anyMatch(q -> q.getPredicate().equals(DC.title)));
        assertTrue(r.getModified().isBefore(now()));
    });
    final Optional<Resource> res2 = service.get(testResource);
    assertTrue(res2.isPresent());
    res2.ifPresent(r -> {
        assertEquals(LDP.RDFSource, r.getInteractionModel());
        assertEquals(testResource, r.getIdentifier());
        assertTrue(r.stream().anyMatch(q -> q.getPredicate().equals(DC.title)));
        assertTrue(r.getModified().isBefore(now()));
    });
}

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

@Test
public void testCacheWriter1() throws IOException {
    final Instant time = parse("2017-03-15T01:23:45Z");
    assertTrue(CachedResource.write(directory2, identifier, time));
    final Optional<Resource> resource = CachedResource.find(directory2, identifier);
    assertTrue(resource.isPresent());// w w  w  . j av a 2 s  . co m
    resource.ifPresent(res -> {
        assertEquals(identifier, res.getIdentifier());
        assertEquals(LDP.RDFSource, res.getInteractionModel());
        assertFalse(res.getMembershipResource().isPresent());
        assertFalse(res.getMemberRelation().isPresent());
        assertFalse(res.getMemberOfRelation().isPresent());
        assertFalse(res.getInsertedContentRelation().isPresent());
        assertFalse(res.getBinary().isPresent());
        assertFalse(res.isMemento());
        assertEquals(of(rdf.createIRI("http://example.org/receiver/inbox")), res.getInbox());
        assertEquals(parse("2017-03-03T02:34:12Z"), res.getModified());
        assertEquals(2L, res.getTypes().size());
        assertTrue(res.getTypes().contains(rdf.createIRI("http://example.org/types/Foo")));
        assertTrue(res.getTypes().contains(rdf.createIRI("http://example.org/types/Bar")));
        assertEquals(0L, res.stream().filter(TestUtils.isContainment.or(TestUtils.isMembership)).count());

        final List<Triple> triples = res.stream().filter(TestUtils.isUserManaged).map(Quad::asTriple)
                .collect(toList());
        assertEquals(5L, triples.size());
        assertTrue(triples.contains(
                rdf.createTriple(identifier, LDP.inbox, rdf.createIRI("http://example.org/receiver/inbox"))));
        assertTrue(triples
                .contains(rdf.createTriple(identifier, type, rdf.createIRI("http://example.org/types/Foo"))));
        assertTrue(triples
                .contains(rdf.createTriple(identifier, type, rdf.createIRI("http://example.org/types/Bar"))));
        assertTrue(triples
                .contains(rdf.createTriple(identifier, RDFS.label, rdf.createLiteral("A label", "eng"))));
        assertTrue(triples.contains(rdf.createTriple(rdf.createIRI("http://example.org/some/other/resource"),
                RDFS.label, rdf.createLiteral("Some other resource", "eng"))));

        final List<VersionRange> mementos = res.getMementos();
        assertEquals(3L, mementos.size());
        assertEquals(parse("2017-02-15T10:05:00Z"), mementos.get(0).getFrom());
        assertEquals(parse("2017-02-15T11:15:00Z"), mementos.get(0).getUntil());
        assertEquals(parse("2017-02-15T11:15:00Z"), mementos.get(1).getFrom());
        assertEquals(parse("2017-03-02T02:34:12Z"), mementos.get(1).getUntil());
        assertEquals(parse("2017-03-02T02:34:12Z"), mementos.get(2).getFrom());
        assertEquals(parse("2017-03-03T02:34:12Z"), mementos.get(2).getUntil());
    });
}

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

@Test
public void testCacheWriter2() throws IOException {
    CachedResource.write(directory4, identifier.getIRIString());
    final Optional<Resource> resource = CachedResource.find(directory4, identifier);
    assertTrue(resource.isPresent());//from  ww  w . j a  v  a 2s.  c  o  m
    resource.ifPresent(res -> {
        assertEquals(identifier, res.getIdentifier());
        assertEquals(LDP.RDFSource, res.getInteractionModel());
        assertFalse(res.getMembershipResource().isPresent());
        assertFalse(res.getMemberRelation().isPresent());
        assertFalse(res.getMemberOfRelation().isPresent());
        assertFalse(res.getInsertedContentRelation().isPresent());
        assertFalse(res.getBinary().isPresent());
        assertFalse(res.isMemento());
        assertFalse(res.getInbox().isPresent());
        assertEquals(parse("2017-02-15T10:05:00Z"), res.getModified());
        assertEquals(0L, res.getTypes().size());
        assertEquals(0L, res.stream().filter(TestUtils.isContainment.or(TestUtils.isMembership)).count());

        final List<Triple> triples = res.stream().filter(TestUtils.isUserManaged).map(Quad::asTriple)
                .collect(toList());
        assertEquals(0L, triples.size());

        final List<VersionRange> mementos = res.getMementos();
        assertEquals(0L, mementos.size());
    });
}

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

@Test
public void testReadData() {
    final Optional<ResourceData> data = VersionedResource.read(directory, "trellis:repository/versioned", MAX);
    assertTrue(data.isPresent());/*from   w  w  w .j  a  va  2 s . co m*/
    data.ifPresent(d -> {
        assertEquals("trellis:repository/versioned", d.getId());
        assertEquals("http://www.w3.org/ns/ldp#BasicContainer", d.getLdpType());
        assertEquals("http://example.org/receiver/inbox", d.getInbox());
        assertTrue(d.getUserTypes().contains("http://example.org/types/Foo"));
        assertTrue(d.getUserTypes().contains("http://example.org/types/Bar"));
    });
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.AbstractPipedStreamRestSynchronizerImpl.java

protected void execute(ExecutionEnvironment executionEnvironment) {
    Validate.notNull(executionEnvironment);
    Optional<ConsumerWithoutArgument> afterExecutionCallback = executionEnvironment.getAfterExecutionCallback();
    try {//from w  w w .j  av  a2  s.  c o  m
        callRestWith(executionEnvironment);
    } catch (RuntimeException runtimeException) {
        executionEnvironment.getRuntimeExceptionHandler()
                .ifPresent(consumer -> consumer.accept(runtimeException));
        throw runtimeException;
    } finally {
        afterExecutionCallback.ifPresent(ConsumerWithoutArgument::apply);
    }
}