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:net.sf.jabref.logic.fulltext.DoiResolution.java

@Override
public Optional<URL> findFullText(BibEntry entry) throws IOException {
    Objects.requireNonNull(entry);
    Optional<URL> pdfLink = Optional.empty();

    Optional<DOI> doi = entry.getFieldOptional(FieldName.DOI).flatMap(DOI::build);

    if (doi.isPresent()) {
        String sciLink = doi.get().getURIAsASCIIString();

        // follow all redirects and scan for a single pdf link
        if (!sciLink.isEmpty()) {
            try {
                Connection connection = Jsoup.connect(sciLink);
                connection.followRedirects(true);
                connection.ignoreHttpErrors(true);
                // some publishers are quite slow (default is 3s)
                connection.timeout(5000);

                Document html = connection.get();
                // scan for PDF
                Elements elements = html.body().select("[href]");
                List<Optional<URL>> links = new ArrayList<>();

                for (Element element : elements) {
                    String href = element.attr("abs:href");
                    // Only check if pdf is included in the link
                    // See https://github.com/lehner/LocalCopy for scrape ideas
                    if (href.contains("pdf") && MimeTypeDetector.isPdfContentType(href)) {
                        links.add(Optional.of(new URL(href)));
                    }//www. ja va2  s.co  m
                }
                // return if only one link was found (high accuracy)
                if (links.size() == 1) {
                    LOGGER.info("Fulltext PDF found @ " + sciLink);
                    pdfLink = links.get(0);
                }
            } catch (IOException e) {
                LOGGER.warn("DoiResolution fetcher failed: ", e);
            }
        }
    }
    return pdfLink;
}

From source file:jp.pigumer.mqtt.Client.java

Optional<KeyStore> loadKeyStore() {
    X509Certificate cert;// w w w . jav a 2  s . com

    if (caFile == null) {
        return Optional.empty();
    }
    try (InputStream is = caFile.getInputStream()) {
        InputStreamReader isr = new InputStreamReader(is);
        PEMParser parser = new PEMParser(isr);
        X509CertificateHolder holder = (X509CertificateHolder) parser.readObject();
        cert = new JcaX509CertificateConverter().getCertificate(holder);
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("ca", cert);
        return Optional.of(keyStore);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "failed load", e);
        return Optional.empty();
    }
}

From source file:com.yodle.vantage.component.service.ComponentServiceTest.java

/**
 * createOrUpdateVersion/*from  www. j av a2  s  .  c o m*/
 */

@Test
public void givenVersionHasNoDependencies_createOrUpdateVersion_justCreatesVersion() {
    when(versionDao.getVersion(COMPONENT, VERSION)).thenReturn(Optional.of(new Version(COMPONENT, VERSION)));

    componentService.createOrUpdateVersion(new Version(COMPONENT, VERSION));

    verify(componentDao).ensureCreated(COMPONENT);
    verify(versionDao).createNewVersion(COMPONENT, VERSION);
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthBloodPressureDataPointMapper.java

@Override
protected Optional<DataPoint<BloodPressure>> asDataPoint(JsonNode listEntryNode,
        Integer measureUnitMagicNumber) {

    checkNotNull(measureUnitMagicNumber);

    double systolicValue = getBloodPressureValueInMmHg(asRequiredDouble(listEntryNode, "HP"),
            measureUnitMagicNumber);//from   w  w  w . ja v  a2s  .c  o  m
    SystolicBloodPressure systolicBloodPressure = new SystolicBloodPressure(MM_OF_MERCURY, systolicValue);

    double diastolicValue = getBloodPressureValueInMmHg(asRequiredDouble(listEntryNode, "LP"),
            measureUnitMagicNumber);
    DiastolicBloodPressure diastolicBloodPressure = new DiastolicBloodPressure(MM_OF_MERCURY, diastolicValue);

    BloodPressure.Builder bloodPressureBuilder = new BloodPressure.Builder(systolicBloodPressure,
            diastolicBloodPressure);

    getEffectiveTimeFrameAsDateTime(listEntryNode).ifPresent(bloodPressureBuilder::setEffectiveTimeFrame);

    getUserNoteIfExists(listEntryNode).ifPresent(bloodPressureBuilder::setUserNotes);

    BloodPressure bloodPressure = bloodPressureBuilder.build();
    return Optional.of(new DataPoint<>(createDataPointHeader(listEntryNode, bloodPressure), bloodPressure));
}

From source file:org.openmhealth.shim.ihealth.mapper.IHealthStepCountDataPointMapper.java

@Override
protected Optional<DataPoint<StepCount>> asDataPoint(JsonNode listEntryNode, Integer measureUnitMagicNumber) {

    BigDecimal steps = asRequiredBigDecimal(listEntryNode, "Steps");

    if (steps.intValue() == 0) {
        return Optional.empty();
    }//from w  w w.  jav  a  2s . c o  m

    StepCount.Builder stepCountBuilder = new StepCount.Builder(steps);

    Optional<Long> dateTimeString = asOptionalLong(listEntryNode, "MDate");

    if (dateTimeString.isPresent()) {

        Optional<String> timeZone = asOptionalString(listEntryNode, "TimeZone");

        if (timeZone.isPresent()) {

            /* iHealth provides daily summaries for step counts and timestamp the datapoint at either the end of
            the day (23:50) or at the latest time that datapoint was synced */
            stepCountBuilder.setEffectiveTimeFrame(ofStartDateTimeAndDuration(
                    getDateTimeAtStartOfDayWithCorrectOffset(dateTimeString.get(), timeZone.get()),
                    new DurationUnitValue(DAY, 1)));
        }
    }

    getUserNoteIfExists(listEntryNode).ifPresent(stepCountBuilder::setUserNotes);

    StepCount stepCount = stepCountBuilder.build();

    return Optional.of(new DataPoint<>(createDataPointHeader(listEntryNode, stepCount), stepCount));
}

From source file:org.jhk.pulsing.search.elasticsearch.client.ESRestClient.java

public Optional<String> getDocument(String index, String type, String id) {
    String endpoint = new StringJoiner("/").add(index).add(type).add(id).toString();

    try {//from   w  w  w .ja va 2 s.  c om
        Optional<Response> response = performRequest("GET", endpoint, Collections.EMPTY_MAP, null,
                EMPTY_HEADER);
        if (response.isPresent()) {
            HttpEntity hEntity = response.get().getEntity();
            String result = EntityUtils.toString(hEntity);

            _LOGGER.debug("ESRestClient.getDocument: result - " + result);
            return Optional.of(result);
        }
    } catch (IOException iException) {
        iException.printStackTrace();
    }

    return Optional.empty();
}

From source file:com.teradata.benchto.driver.execution.ExecutionDriverTest.java

@Before
public void setUp() {
    Benchmark benchmark = mock(Benchmark.class);
    when(benchmark.getConcurrency()).thenReturn(1);

    when(benchmarkLoader.loadBenchmarks(anyString())).thenReturn(ImmutableList.of(benchmark));
    when(benchmarkProperties.getBeforeAllMacros()).thenReturn(Optional.of(ImmutableList.of("before-macro")));
    when(benchmarkProperties.getAfterAllMacros()).thenReturn(Optional.of(ImmutableList.of("after-macro")));
    when(benchmarkProperties.getHealthCheckMacros())
            .thenReturn(Optional.of(ImmutableList.of("health-check-macro")));
    when(benchmarkProperties.getExecutionSequenceId()).thenReturn(Optional.of("sequence-id"));
    when(benchmarkExecutionDriver.execute(any(Benchmark.class), anyInt(), anyInt()))
            .thenReturn(successfulBenchmarkExecution());
    when(benchmarkProperties.getTimeLimit()).thenReturn(Optional.empty());
}

From source file:com.hortonworks.registries.storage.util.StorageUtils.java

public static Optional<Pair<Field, Long>> getVersionFieldValue(Storable storable)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    for (Pair<Field, Object> kv : getAnnotatedFieldValues(storable, VersionField.class)) {
        if (kv.getValue() instanceof Long) {
            return Optional.of(Pair.of(kv.getKey(), (Long) kv.getValue()));
        }/*from  w w  w .j  a  v  a2  s .  c o  m*/
    }
    return Optional.empty();
}

From source file:com.devicehive.resource.DeviceCommandResourceTest.java

@Test
public void should_get_empty_response_with_status_204_when_command_not_processed() throws Exception {
    DeviceClassEquipmentVO equipment = DeviceFixture.createEquipmentVO();
    DeviceClassUpdate deviceClass = DeviceFixture.createDeviceClass();
    deviceClass.setEquipment(Optional.of(Collections.singleton(equipment)));
    NetworkVO network = DeviceFixture.createNetwork();
    String guid = UUID.randomUUID().toString();
    DeviceUpdate deviceUpdate = DeviceFixture.createDevice(guid);
    deviceUpdate.setDeviceClass(Optional.of(deviceClass));
    deviceUpdate.setNetwork(Optional.of(network));

    // register device
    Response response = performRequest("/device/" + guid, "PUT", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), deviceUpdate, NO_CONTENT,
            null);/*w  w w.j  a va  2  s.c om*/
    assertNotNull(response);
    TimeUnit.SECONDS.sleep(1);

    // create command
    DeviceCommand command = DeviceFixture.createDeviceCommand();
    command = performRequest("/device/" + guid + "/command", "POST", emptyMap(),
            singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), command, CREATED,
            DeviceCommand.class);
    assertNotNull(command.getId());
    TimeUnit.SECONDS.sleep(1);

    // try get not processed command
    Map<String, Object> params = new HashMap<>();
    params.put("waitTimeout", 1);
    DeviceCommand updatedCommand = performRequest("/device/" + guid + "/command/" + command.getId() + "/poll",
            "GET", params, singletonMap(HttpHeaders.AUTHORIZATION, tokenAuthHeader(ACCESS_KEY)), command,
            NO_CONTENT, DeviceCommand.class);
    assertNull(updatedCommand);

}

From source file:io.kamax.mxisd.backend.wordpress.WordpressThreePidProvider.java

protected Optional<_MatrixID> find(ThreePid tpid) {
    String query = cfg.getSql().getQuery().getThreepid().get(tpid.getMedium());
    if (Objects.isNull(query)) {
        return Optional.empty();
    }//from  w w  w.  j a  v  a2  s. c om

    try (Connection conn = wordpress.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setString(1, tpid.getAddress());

        try (ResultSet rSet = stmt.executeQuery()) {
            while (rSet.next()) {
                String uid = rSet.getString("uid");
                log.info("Found match: {}", uid);
                try {
                    return Optional.of(MatrixID.from(uid, mxCfg.getDomain()).valid());
                } catch (IllegalArgumentException ex) {
                    log.warn("Ignoring match {} - Invalid characters for a Matrix ID", uid);
                }
            }

            log.info("No valid match found in Wordpress");
            return Optional.empty();
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}