Example usage for java.util Optional of

List of usage examples for java.util Optional of

Introduction

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

Prototype

public static <T> Optional<T> of(T value) 

Source Link

Document

Returns an Optional describing the given non- null value.

Usage

From source file:com.opopov.cloud.image.service.ImageStitchingServiceImpl.java

private Optional<DecodedImage> decompressImage(int imageIndex, IndexMap indexMap, ResponseEntity<byte[]> resp) {
    Optional<BufferedImage> image = decompressImage(resp);
    Optional<DecodedImage> result = image.isPresent() ? Optional.of(new DecodedImage(image.get(), imageIndex))
            : Optional.empty();// www .j a v  a 2 s.  c  o  m
    indexMap.put(imageIndex, result);
    return result;
}

From source file:org.jhk.pulsing.web.dao.prod.db.sql.MySqlUserDao.java

public Optional<User> validateUser(String email, String password) {
    _LOGGER.debug("MySqlUserDao.validateUser" + email + " : " + password);

    List<?> entries = getSession().createNamedQuery("findUser").setParameter("email", email)
            .setParameter("password", password).getResultList();

    _LOGGER.debug("Result " + entries.size() + " : " + entries);

    if (entries == null || entries.size() == 0) {
        return Optional.empty();
    }//from   w  w  w .  java 2  s .  co  m

    return Optional.of(AvroMySqlMappers.mySqlToAvro((MUser) entries.get(0)));
}

From source file:ddf.catalog.validation.impl.validator.PatternValidator.java

/**
 * {@inheritDoc}/*from ww  w  . j a v a2  s  .  c  om*/
 * <p>
 * Validates only the values of {@code attribute} that are {@link CharSequence}s.
 */
@Override
public Optional<AttributeValidationReport> validate(final Attribute attribute) {
    Preconditions.checkArgument(attribute != null, "The attribute cannot be null.");

    final String name = attribute.getName();
    for (final Serializable value : attribute.getValues()) {
        if (value instanceof CharSequence && !(pattern.matcher((CharSequence) value)).matches()) {
            final AttributeValidationReportImpl report = new AttributeValidationReportImpl();
            report.addViolation(new ValidationViolationImpl(Collections.singleton(name),
                    name + " does not follow the pattern " + pattern.pattern(), Severity.ERROR));
            return Optional.of(report);
        }
    }

    return Optional.empty();
}

From source file:co.runrightfast.vertx.orientdb.config.NetworkSSLConfig.java

public NetworkSSLConfig(@NonNull final Path serverKeyStorePath, @NonNull final String serverKeyStorePassword,
        @NonNull final Path serverTrustStorePath, @NonNull final String serverTrustStorePassword) {
    this(DEFAULT_SSL_PORT, serverKeyStorePath, serverKeyStorePassword, Optional.of(serverTrustStorePath),
            Optional.of(serverTrustStorePassword));
}

From source file:com.yodle.vantage.component.dao.QueueDao.java

public Optional<QueueCreateRequest> getCreateRequest() {

    try {//from   w ww .  j  a  va  2 s .  c o  m
        Map<String, Object> rs = jdbcTemplate.queryForMap(
                "MATCH(c:QueueCreateRequest) " + "WHERE NOT ()-[:BEFORE]->(c) " + "return c.id, c.blob");

        return Optional.of(new QueueCreateRequest(
                objectMapper.readValue((String) rs.get("c.blob"), Version.class), (String) rs.get("c.id")));
    } /*catch (UncategorizedSQLException e) {
      l.debug("Exception occurred getting create request, probably because of queue locking", e);
      }*/ catch (EmptyResultDataAccessException e) {
        return Optional.empty();
    } catch (IOException e) {
        l.error("Error deserializing queue entry", e);
        return Optional.empty();
    }
}

From source file:com.galenframework.ide.services.filebrowser.FileBrowserServiceImpl.java

private Optional<FileItem> upFrom(File folder) {
    File parentFile = folder.getParentFile();
    if (parentFile != null) {
        return Optional.of(FileItem.directory("..", parentFile.getPath()));
    } else if (!folder.getName().equals(".")) {
        return Optional.of(FileItem.directory("..", "."));
    } else {//  w w  w.  ja va 2 s . c o  m
        return Optional.empty();
    }
}

From source file:org.camunda.bpm.spring.boot.starter.configuration.impl.custom.EnterLicenseKeyConfiguration.java

protected Optional<String> readLicenseKeyFromUrl(URL licenseFileUrl) {
    if (licenseFileUrl == null) {
        return Optional.empty();
    }/* w  ww  .  ja  va  2s .  c  o  m*/
    try {
        return Optional.of(new Scanner(licenseFileUrl.openStream(), "UTF-8").useDelimiter("\\A"))
                .filter(Scanner::hasNext).map(Scanner::next).map(s -> s.split("---------------")[2])
                .map(s -> s.replaceAll("\\n", "")).map(String::trim);
    } catch (IOException e) {
        return Optional.empty();
    }
}

From source file:com.ikanow.aleph2.shared.crud.elasticsearch.data_model.TestElasticsearchContext.java

@Test
public void test_context() throws JsonProcessingException, IOException {

    final Calendar c1 = GregorianCalendar.getInstance();
    final Calendar c2 = GregorianCalendar.getInstance();
    final Calendar cnow = GregorianCalendar.getInstance();

    // Just going to test the non-trivial logic:
    {//from  ww  w  .  java 2s.c o m
        final ElasticsearchContext.IndexContext.ReadOnlyIndexContext.TimedRoIndexContext index_context_1 = new ElasticsearchContext.IndexContext.ReadOnlyIndexContext.TimedRoIndexContext(
                Arrays.asList("test1_{yyyy}", "test_2_{yyyy.MM}", "test3__MYID"));

        assertEquals(Arrays.asList("test1*", "test_2*", "test3__MYID*"),
                index_context_1.getReadableIndexList(Optional.empty()));

        c1.set(2004, 11, 28);
        c2.set(2005, 0, 2);
        assertEquals(
                Arrays.asList("test1_2004*", "test1_2005*", "test_2_2004.12*", "test_2_2005.01*",
                        "test3__MYID*"),
                index_context_1.getReadableIndexList(
                        Optional.of(Tuples._2T(c1.getTime().getTime(), c2.getTime().getTime()))));
    }

    // Check get an invalid entry if the index list is empty
    {
        final ElasticsearchContext.IndexContext.ReadOnlyIndexContext.TimedRoIndexContext index_context_1 = new ElasticsearchContext.IndexContext.ReadOnlyIndexContext.TimedRoIndexContext(
                Arrays.asList());

        assertEquals(Arrays.asList(ElasticsearchContext.NO_INDEX_FOUND),
                index_context_1.getReadableIndexList(Optional.empty()));
    }

    // Some timestamp testing
    {
        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext index_context_2 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext(
                "test1_{yyyy}", Optional.of("@timestamp"), Optional.empty(), Either.left(true));

        assertTrue("timestamp field present", index_context_2.timeField().isPresent());
        assertEquals("@timestamp", index_context_2.timeField().get());

        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext index_context_3 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext(
                "test_2_{yyyy.MM}", Optional.empty(), Optional.empty(), Either.left(true));

        assertFalse("no timestamp field", index_context_3.timeField().isPresent());

        cnow.setTime(new Date());
        int month = cnow.get(Calendar.MONTH) + 1;
        assertEquals("test_2_" + cnow.get(Calendar.YEAR) + "." + ((month < 10) ? ("0" + month) : (month)),
                index_context_3.getWritableIndex(
                        Optional.of(BeanTemplateUtils.configureMapper(Optional.empty()).createObjectNode())));

        // This isn't supported any more, valid strings only
        //         final ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext index_context_4 = 
        //               new ElasticsearchContext.IndexContext.ReadWriteIndexContext.TimedRwIndexContext("test3", Optional.of("@timestamp"));

        assertEquals(Arrays.asList("test1*"), index_context_2.getReadableIndexList(Optional.empty()));
        assertEquals(Arrays.asList("test_2*"), index_context_3.getReadableIndexList(Optional.empty()));

        assertEquals(Arrays.asList("test1_2004*", "test1_2005*"), index_context_2
                .getReadableIndexList(Optional.of(Tuples._2T(c1.getTime().getTime(), c2.getTime().getTime()))));
        assertEquals(Arrays.asList("test_2_2004.12*", "test_2_2005.01*"), index_context_3
                .getReadableIndexList(Optional.of(Tuples._2T(c1.getTime().getTime(), c2.getTime().getTime()))));
        // (see index_context_4 declaration, above)
        //         assertEquals(Arrays.asList("test3*"), index_context_4.getReadableIndexList(Optional.of(Tuples._2T(c1.getTime().getTime(), c2.getTime().getTime()))));

        // Check gets the right timestamp when writing objects into an index

        c1.set(2004, 11, 28, 12, 00, 01);
        final ObjectNode obj = ((ObjectNode) BeanTemplateUtils.configureMapper(Optional.empty())
                .readTree("{\"val\":\"test1\"}".getBytes())).put("@timestamp", c1.getTime().getTime());

        final String expected3 = new SimpleDateFormat("yyyy.MM").format(new Date());

        assertEquals("test1_2004", index_context_2.getWritableIndex(Optional.of(obj)));
        assertEquals("test_2_" + expected3, index_context_3.getWritableIndex(Optional.of(obj)));
        // (see index_context_4 declaration, above)
        //         assertEquals("test3", index_context_4.getWritableIndex(Optional.of(obj)));
    }

    // Test readable index differences depending on whether the max index size is set or not

    {
        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext index_context_1 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext(
                "test1", Optional.empty(), Either.left(true));

        assertEquals(Arrays.asList("test1"), index_context_1.getReadableIndexList(Optional.empty()));

        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext index_context_2 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext(
                "test2", Optional.of(-1L), Either.left(true));

        assertEquals(Arrays.asList("test2"), index_context_2.getReadableIndexList(Optional.empty()));

        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext index_context_3 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext(
                "test3", Optional.of(0L), Either.left(true));

        assertEquals(Arrays.asList("test3*"), index_context_3.getReadableIndexList(Optional.empty()));

        final ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext index_context_4 = new ElasticsearchContext.IndexContext.ReadWriteIndexContext.FixedRwIndexContext(
                "test4", Optional.of(10L), Either.left(true));

        assertEquals(Arrays.asList("test4*"), index_context_4.getReadableIndexList(Optional.empty()));
    }
}

From source file:com.vsct.dt.hesperides.applications.SnapshotRegistry.java

@Override
public <U> Optional<U> getSnapshot(SnapshotKey snapshotKey, Class snapshotClass) {
    try (A jedis = connectionPool.getResource()) {

        String objectAsString = jedis.get(snapshotKey.getIdentifier());
        return Optional.of((U) MAPPER.readValue(objectAsString, snapshotClass));

    } catch (Exception e) {
        LOGGER.error("A problem occured when trying to get snapshot object");
        LOGGER.error(e.getMessage());/*from w  w w . ja  va  2 s.  c o m*/
        return Optional.empty();
    }
}