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:org.openmhealth.shim.ihealth.mapper.IHealthSleepDurationDataPointMapper.java

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

    SleepDuration.Builder sleepDurationBuilder = new SleepDuration.Builder(
            new DurationUnitValue(DurationUnit.MINUTE, asRequiredBigDecimal(listEntryNode, "HoursSlept")));

    Optional<Long> startTime = asOptionalLong(listEntryNode, "StartTime");
    Optional<Long> endTime = asOptionalLong(listEntryNode, "EndTime");

    if (startTime.isPresent() && endTime.isPresent()) {

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

        if (timeZone.isPresent()) {

            sleepDurationBuilder.setEffectiveTimeFrame(ofStartDateTimeAndEndDateTime(
                    getDateTimeWithCorrectOffset(startTime.get(), ZoneOffset.of(timeZone.get())),
                    getDateTimeWithCorrectOffset(endTime.get(), ZoneOffset.of(timeZone.get()))));
        }//from  w  w w  .j  a va  2  s. com
    }

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

    SleepDuration sleepDuration = sleepDurationBuilder.build();

    asOptionalBigDecimal(listEntryNode, "Awaken")
            .ifPresent(awaken -> sleepDuration.setAdditionalProperty("wakeup_count", awaken));

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

From source file:tech.beshu.ror.integration.JwtAuthTests.java

@Test
public void acceptValidTokentWithUserClaimAndCustomHeader() throws Exception {
    int sc = test(makeToken(KEY, makeClaimMap(USER_CLAIM, "user")), Optional.of("x-custom-header"), false);
    assertEquals(200, sc);/*from  w w w.  j a v a2  s  . co  m*/
}

From source file:br.com.blackhubos.eventozero.updater.github.searcher.GitHubSearcher.java

@Override
public Optional<Version> getLatestVersion() {
    try {//from  www .  j a v  a2 s.  com
        // Conecta ao URL de ultimas verses
        Optional<Collection<Version>> versions = connect(Optional.of(LATEST_PATH));
        // Verifica se h alguma
        if (versions.isPresent()) {
            // Retorna a primeira
            Iterator<Version> versionIterator = versions.get().iterator();
            return Optional.of(versionIterator.next());
        }
    } catch (IOException | ParseException | java.text.ParseException e) {
        e.printStackTrace();
    }
    return Optional.empty();
}

From source file:io.mandrel.cluster.node.impl.MongoNodeRepository.java

@Override
@SneakyThrows(IOException.class)
public Optional<Node> get(String id) {
    Document doc = collection.find(new Document("_id", id)).first();
    return doc == null ? Optional.empty() : Optional.of(mapper.readValue(doc.toJson(), Node.class));
}

From source file:com.amazonaws.service.apigateway.importer.config.AwsConfig.java

private Optional<String> loadRegion() {
    String file = System.getProperty("user.home") + "/.aws/config";

    boolean foundProfile = false;
    try (BufferedReader br = new BufferedReader(new FileReader(new File(file)))) {
        String line;/*from   w  ww  .  j av a 2s.com*/
        String region;
        Pattern regionPat = Pattern.compile("[a-z]{2}+-[a-z]{2,}+-[0-9]");
        Matcher regionMat;
        Integer eqPos;

        while ((line = br.readLine()) != null) {

            if (line.startsWith("[") && line.contains(this.profile)) {
                foundProfile = true;
            }

            if (foundProfile && line.startsWith("region")) {
                eqPos = line.indexOf("=");
                region = line.substring(eqPos + 1, line.length()).trim();
                regionMat = regionPat.matcher(region);
                if (!regionMat.matches()) {
                    LOG.error("Region does not match '[a-z]{2}+-[a-z]{2,}+-[0-9]': " + region);
                    throw new RuntimeException("Region does not match '[a-z]{2}+-[a-z]{2,}+-[0-9]'" + region);
                }
                return Optional.of(region);
            }
        }
    } catch (Throwable t) {
        throw new RuntimeException("Could not load configuration. Please run 'aws configure'");
    }

    return Optional.empty();
}

From source file:org.jspare.jsdbc.JsdbcTransportImpl.java

@Override
public String execute(DataSource datasource, Credential credential, Optional<Domain> domain, String operation,
        int method, String data) throws JsdbcException {

    if (datasource == null) {

        throw new JsdbcException("DataSource not loaded");
    }/*  w  w w  .ja v  a 2 s .  c om*/

    try {

        Request request = null;
        org.apache.http.client.fluent.Response response = null;

        String uriAddress = getUrlConnection(datasource, operation,
                Optional.of(domain.orElse(Domain.of(StringUtils.EMPTY)).domain()));
        if (method == RETRIEVE) {
            request = Request.Get(new URIBuilder(uriAddress).build().toString());
        } else if (method == SEND) {
            request = Request.Post(new URIBuilder(uriAddress).build().toString()).bodyString(data,
                    ContentType.APPLICATION_JSON);
        } else {
            throw new JsdbcException("Method called is not mapped");
        }
        request.addHeader(AGENT_KEY, AGENT);

        response = buildAuthentication(request, datasource, credential).execute();

        HttpResponse httpResponse = response.returnResponse();

        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (statusCode < HttpStatus.SC_OK || statusCode >= HttpStatus.SC_MULTIPLE_CHOICES) {

            if (statusCode == HttpStatus.SC_BAD_REQUEST) {

                throw new JsdbcException("Authorization error, validate your credentials.");
            }
            if (statusCode == HttpStatus.SC_FORBIDDEN) {

                throw new JsdbcException("Forbidden access, validate your user roles.");
            }

            String content = IOUtils.toString(httpResponse.getEntity().getContent());

            ErrorResult result = my(Serializer.class).fromJSON(content, ErrorResult.class);
            throw new CommandFailException(result);
        }

        return IOUtils.toString(httpResponse.getEntity().getContent());

    } catch (Exception e) {

        log.error(e.getMessage(), e);
        throw new JsdbcException("JSDB Server Error");
    }
}

From source file:com.ikanow.aleph2.analytics.storm.assets.PassthroughTopology.java

@Override
public Tuple2<Object, Map<String, String>> getTopologyAndConfiguration(final DataBucketBean bucket,
        final IEnrichmentModuleContext context) {
    final TopologyBuilder builder = new TopologyBuilder();

    final Collection<Tuple2<BaseRichSpout, String>> entry_points = context
            .getTopologyEntryPoints(BaseRichSpout.class, Optional.of(bucket));

    //DEBUG/*from w ww  . jav a 2  s  .  com*/
    _logger.debug("Passthrough topology: loaded: "
            + entry_points.stream().map(x -> x.toString()).collect(Collectors.joining(":")));

    entry_points.forEach(spout_name -> builder.setSpout(spout_name._2(), spout_name._1()));
    entry_points.stream()
            .reduce(builder.setBolt(BOLT_NAME,
                    context.getTopologyStorageEndpoint(BaseRichBolt.class, Optional.of(bucket))),
                    (acc, v) -> acc.localOrShuffleGrouping(v._2()), (acc1, acc2) -> acc1 // (not possible in practice)
    );

    return Tuples._2T(builder.createTopology(), Collections.emptyMap());
}

From source file:com.siemens.sw360.fossology.ssh.JSchSessionProvider.java

private Optional<Session> pollCachedSession() {
    Session session = sessions.poll();/*  ww w  .ja  va  2 s  .  c o m*/
    if (session != null && session.isConnected()) {
        return Optional.of(session);
    } else {
        return Optional.empty();
    }
}

From source file:org.openmhealth.shim.fitbit.mapper.FitbitSleepDurationDataPointMapper.java

@Override
protected Optional<DataPoint<SleepDuration>> asDataPoint(JsonNode node) {

    DurationUnitValue unitValue = new DurationUnitValue(MINUTE, asRequiredDouble(node, "minutesAsleep"));
    SleepDuration.Builder sleepDurationBuilder = new SleepDuration.Builder(unitValue);

    Optional<LocalDateTime> localStartTime = asOptionalLocalDateTime(node, "startTime");

    if (localStartTime.isPresent()) {

        OffsetDateTime offsetStartDateTime = combineDateTimeAndTimezone(localStartTime.get());
        Optional<Double> timeInBed = asOptionalDouble(node, "timeInBed");

        if (timeInBed.isPresent()) {
            sleepDurationBuilder.setEffectiveTimeFrame(TimeInterval.ofStartDateTimeAndDuration(
                    offsetStartDateTime, new DurationUnitValue(MINUTE, timeInBed.get())));
        } else {/*ww w. j ava2 s .c o  m*/
            // in this case, there is no "time in bed" value, however we still have a start time, so we can set
            // the data point to a single date time point
            sleepDurationBuilder.setEffectiveTimeFrame(offsetStartDateTime);
        }
    }

    SleepDuration measure = sleepDurationBuilder.build();

    Optional<Long> externalId = asOptionalLong(node, "logId");

    return Optional.of(newDataPoint(measure, externalId.orElse(null)));
}

From source file:net.minecraftforge.oredict.DyeUtils.java

/**
 * Get a dye's color.//  ww w. j av a2  s  . c om
 * @param stack the item stack
 * @return an {@link Optional} holding the dye color if present, or an empty {@link Optional} otherwise
 */
public static Optional<EnumDyeColor> colorFromStack(ItemStack stack) {
    final OptionalInt meta = metaFromStack(stack);
    return meta.isPresent() ? Optional.of(EnumDyeColor.byMetadata(meta.getAsInt())) : Optional.empty();
}