Example usage for java.util Optional get

List of usage examples for java.util Optional get

Introduction

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

Prototype

public T get() 

Source Link

Document

If a value is present, returns the value, otherwise throws NoSuchElementException .

Usage

From source file:com.github.lukaszbudnik.dqueue.QueueClientIntegrationTest.java

@Test
public void shouldHandlePreviousDay() throws ExecutionException, InterruptedException {
    long yesterdayTimestamp = System.currentTimeMillis() - 24 * 60 * 60 * 1_000;

    UUID yesterdayUUID = UUIDsTesting.timeBased(yesterdayTimestamp);

    Future<UUID> published = queueClient.publish(new Item(yesterdayUUID, ByteBuffer.wrap("".getBytes())));
    published.get();/*from   ww  w  .  j av  a 2s  . c  o  m*/

    Future<Optional<Item>> itemFuture = queueClient.consume();
    Optional<Item> itemOptional = itemFuture.get();
    Item item = itemOptional.get();

    assertEquals(yesterdayUUID, item.getStartTime());
}

From source file:com.netflix.spectator.aws.SpectatorRequestMetricCollectorTest.java

@Test
public void testMetricCollection() {
    execRequest("http://foo", 200);

    //then//from w  w  w  . ja  v a  2s  .c  om
    List<Meter> allMetrics = new ArrayList<>();
    registry.iterator().forEachRemaining(allMetrics::add);

    assertEquals(2, allMetrics.size());
    Optional<Timer> expectedTimer = registry.timers().findFirst();
    assertTrue(expectedTimer.isPresent());
    Timer timer = expectedTimer.get();
    assertEquals(1, timer.count());
    assertEquals(100000, timer.totalTime());

    Optional<Counter> expectedCounter = registry.counters().findFirst();
    assertTrue(expectedCounter.isPresent());
    assertEquals(12345L, expectedCounter.get().count());
}

From source file:org.homiefund.web.controllers.SignUpController.java

@GetMapping(value = { "/signup/", "/signup/{inviteToken}/" })
public String signup(@PathVariable Optional<String> inviteToken, Model model) {
    UserRegistrationForm form = new UserRegistrationForm();
    if (inviteToken.isPresent()) {
        form.setInviteToken(inviteToken.get());
    }/*from w ww.  j a v  a  2s .  co  m*/

    model.addAttribute("userRegistrationForm", form);

    return "signup";
}

From source file:io.mapzone.controller.vm.http.ServiceAuthProvision.java

protected Boolean isValidToken(String token, ProjectInstanceIdentifier pid) {
    CacheKey key = new CacheKey(token, pid);
    return loggedIn.get(key, _key -> {
        Project project = projectUow().findProject(pid.organization(), pid.project())
                .orElseThrow(() -> new HttpProvisionRuntimeException(404, "No such project: " + pid));
        Optional<AuthToken> projectToken = project.serviceAuthToken();
        return projectToken.isPresent() ? projectToken.get().isValid(token) : false;
    });//from   w  w  w. j  a v a 2  s . c  o m
}

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

private void executeHealthCheck(Benchmark benchmark) {
    Optional<List<String>> macros = properties.getHealthCheckMacros();
    if (macros.isPresent()) {
        LOG.info("Running health check macros: {}", macros.get());
        macroService.runBenchmarkMacros(macros.get(), benchmark);
    }/*  ww w  .  j  ava2  s. com*/
}

From source file:org.zalando.riptide.Router.java

final <A> Capture route(final ClientHttpResponse response, final List<HttpMessageConverter<?>> converters,
        final Selector<A> selector, final Collection<Binding<A>> bindings) {

    final Optional<A> attribute;

    try {// w w  w  .j ava2  s.  c  om
        attribute = selector.attributeOf(response);
    } catch (final IOException e) {
        throw new RestClientException("Unable to retrieve attribute of response", e);
    }

    final Map<Optional<A>, Binding<A>> index = bindings.stream()
            .collect(toMap(Binding::getAttribute, identity(), this::denyDuplicates, LinkedHashMap::new));

    final Optional<Binding<A>> match = selector.select(attribute, index);

    try {
        if (match.isPresent()) {
            final Binding<A> binding = match.get();

            try {
                return binding.execute(response, converters);
            } catch (final NoRouteException e) {
                return propagateNoMatch(response, converters, index, e);
            }
        } else {
            return routeNone(response, converters, index);
        }
    } catch (final IOException e) {
        throw new RestClientException("Unable to execute binding", e);
    }
}

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 {/*from w w  w. ja v a 2s . c  om*/
            // 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:com.yfiton.api.Notifier.java

public NotificationResult handle(Parameters parameters) throws NotificationException {
    Optional<String> message = checkParameters(parameters).getMessage();

    if (message.isPresent()) {
        throw new NotificationException(message.get());
    }// www  .j ava  2s.c  o m

    stopwatch.start();

    notify(parameters);

    stopwatch.stop();

    return new NotificationResult(getKey(), stopwatch);
}

From source file:org.openmhealth.shim.jawbone.mapper.JawboneBodyWeightDataPointMapper.java

@Override
protected Optional<Measure.Builder<BodyWeight, ?>> newMeasureBuilder(JsonNode listEntryNode) {

    Optional<Double> optionalWeight = asOptionalDouble(listEntryNode, "weight");

    if (!optionalWeight.isPresent()) {
        return Optional.empty();
    }//  w w w .j av  a  2  s . c  o  m

    return Optional.of(new BodyWeight.Builder(new MassUnitValue(KILOGRAM, optionalWeight.get())));
}

From source file:com.facebook.presto.accumulo.AccumuloClient.java

/**
 * Gets a collection of Accumulo Range objects from the given Presto domain.
 * This maps the column constraints of the given Domain to an Accumulo Range scan.
 *
 * @param domain Domain, can be null (returns (-inf, +inf) Range)
 * @param serializer Instance of an {@link AccumuloRowSerializer}
 * @return A collection of Accumulo Range objects
 * @throws TableNotFoundException If the Accumulo table is not found
 *//*from  w  w  w.j a va2s.co  m*/
public static Collection<Range> getRangesFromDomain(Optional<Domain> domain, AccumuloRowSerializer serializer)
        throws TableNotFoundException {
    // if we have no predicate pushdown, use the full range
    if (!domain.isPresent()) {
        return ImmutableSet.of(new Range());
    }

    ImmutableSet.Builder<Range> rangeBuilder = ImmutableSet.builder();
    for (com.facebook.presto.spi.predicate.Range range : domain.get().getValues().getRanges()
            .getOrderedRanges()) {
        rangeBuilder.add(getRangeFromPrestoRange(range, serializer));
    }

    return rangeBuilder.build();
}