Example usage for java.util Optional isPresent

List of usage examples for java.util Optional isPresent

Introduction

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

Prototype

public boolean isPresent() 

Source Link

Document

If a value is present, returns true , otherwise false .

Usage

From source file:com.lithium.flow.shell.tunnel.ShellTunneler.java

@Nonnull
public Tunnel getTunnel(@Nonnull String host, int port, @Nullable String through) throws IOException {
    List<Login> logins = Lists.newArrayList();

    Login endLogin = access.getLogin(host);
    logins.add(endLogin);/*from ww  w  .j  ava2s  . c  om*/

    if (through != null) {
        logins.add(access.getLogin(through));
    }

    Optional<String> match = config.getMatch("shell.tunnels", endLogin.getHost());
    if (match.isPresent()) {
        for (String tunnel : Splitter.on(';').split(match.get())) {
            logins.add(access.getLogin(tunnel));
        }
    }

    Collections.reverse(logins);

    Tunnel tunnel = null;
    for (int i = 0; i < logins.size() - 1; i++) {
        Login thisLogin = logins.get(i);
        Login nextLogin = logins.get(i + 1);
        if (i == logins.size() - 2) {
            nextLogin = nextLogin.toBuilder().setPort(port).build();
        }

        log.debug("tunneling through {} to {}", thisLogin, nextLogin.getHostAndPort());

        Login login = thisLogin;
        if (tunnel != null) {
            login = login.toBuilder().setHost("localhost").setPort(tunnel.getPort()).build();
        }

        String message = login.getKeyPath() != null ? login.getKeyPath() : thisLogin.getDisplayString();
        Function<Boolean, String> pass = retry -> access.getPrompt().prompt(message, message, true, retry);
        login = login.toBuilder().setPass(pass).build();

        tunnel = shore.getShell(login).tunnel(0, nextLogin.getHost(), nextLogin.getPortOrDefault(22));
    }

    if (tunnel != null) {
        tunnels.add(tunnel);
        return tunnel;
    } else {
        return new NoTunnel(host, port);
    }
}

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

private List<AttributeValidationReport> validateAttributeSerializable(String attributeName,
        Serializable serializable) {
    Attribute newAttribute = new AttributeImpl(attributeName, serializable);
    List<AttributeValidationReport> validationReportList = new ArrayList<>();

    for (AttributeValidator attributeValidator : validators) {
        Optional<AttributeValidationReport> attributeValidationReport = attributeValidator
                .validate(newAttribute);
        if (attributeValidationReport.isPresent()) {
            validationReportList.add(attributeValidationReport.get());
        }//  www  .j a  va  2  s  .  c  om
    }

    return validationReportList;
}

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

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

    //then/* w w w  .  j  a  v  a2 s  .  c  o m*/
    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:com.astamuse.asta4d.web.form.flow.base.StepAwaredValidationFormHelper.java

static final Object getValidationTargetByAnnotation(Object form, String step) {
    String cacheKey = step + "@" + form.getClass().getName();
    Optional<Field> oField = ValidationTargetFieldCache.get(cacheKey);

    if (oField == null) {
        List<Field> list = new ArrayList<>(ClassUtil.retrieveAllFieldsIncludeAllSuperClasses(form.getClass()));
        Iterator<Field> it = list.iterator();
        while (it.hasNext()) {
            Field f = it.next();//  w w  w .j  a va  2  s .c  o  m
            StepAwaredValidationTarget vtAnno = f.getAnnotation(StepAwaredValidationTarget.class);
            if (vtAnno == null) {
                continue;
            }
            String representingStep = vtAnno.value();
            if (step.equals(representingStep)) {
                oField = Optional.of(f);
                break;
            }
        }
        if (oField == null) {
            oField = Optional.empty();
        }
        if (Configuration.getConfiguration().isCacheEnable()) {
            Map<String, Optional<Field>> newCache = new HashMap<>(ValidationTargetFieldCache);
            newCache.put(cacheKey, oField);
            ValidationTargetFieldCache = newCache;
        }
    }

    if (oField.isPresent()) {
        try {
            return FieldUtils.readField(oField.get(), form, true);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    } else {
        return form;
    }
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.caching.view.provider.KubernetesV2InstanceProvider.java

@Override
public KubernetesV2Instance getInstance(String account, String location, String fullName) {
    Pair<KubernetesKind, String> parsedName;
    try {/* w  w w .j  a va2 s .  co m*/
        parsedName = KubernetesManifest.fromFullResourceName(fullName);
    } catch (Exception e) {
        return null;
    }

    KubernetesKind kind = parsedName.getLeft();
    String name = parsedName.getRight();
    String key = Keys.infrastructure(kind, account, location, name);

    Optional<CacheData> optionalInstanceData = cacheUtils.getSingleEntry(kind.toString(), key);
    if (!optionalInstanceData.isPresent()) {
        return null;
    }

    CacheData instanceData = optionalInstanceData.get();

    return KubernetesV2Instance.fromCacheData(instanceData);
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantFromSystemProperty() {
    System.setProperty(GatewayConfiguration.MULTI_TENANT_SYSTEM_PROPERTY, "europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("europe", tenantOpt.get());
}

From source file:io.gravitee.gateway.env.GatewayConfigurationTest.java

@Test
public void shouldReturnTenantFromConfiguration() {
    Mockito.when(environment.getProperty(GatewayConfiguration.MULTI_TENANT_CONFIGURATION)).thenReturn("europe");
    gatewayConfiguration.afterPropertiesSet();

    Optional<String> tenantOpt = gatewayConfiguration.tenant();
    Assert.assertTrue(tenantOpt.isPresent());

    Assert.assertEquals("europe", tenantOpt.get());
}

From source file:uk.gov.hmrc.controllers.HelloWorldController.java

@RequestMapping("/oauth20/callback")
public String callback(HttpSession session, @RequestParam("code") Optional<String> code,
        @RequestParam("error") Optional<String> error) {
    if (!code.isPresent()) {
        throw new RuntimeException("Couldn't get Authorization code: " + error.orElse("unknown_reason"));
    }/*from ww  w.  j av a2  s.  com*/
    try {
        Token token = oauthService.getToken(code.get());
        session.setAttribute("userToken", token);
        return "redirect:/hello-user";
    } catch (Exception e) {
        throw new RuntimeException("Failed to get Token", e);
    }
}

From source file:com.teradata.benchto.driver.graphite.GraphiteMetricsLoader.java

private void addMeanMaxMeasurements(Map<String, double[]> loadedMetrics, List<Measurement> measurements,
        String metricName, String unit) {
    Optional<StatisticalSummary> statistics = getStats(loadedMetrics, metricName);
    if (statistics.isPresent()) {
        measurements.add(/* w  w  w  .  j av  a  2 s.co m*/
                Measurement.measurement("cluster-" + metricName + "_max", unit, statistics.get().getMax()));
        measurements.add(
                Measurement.measurement("cluster-" + metricName + "_mean", unit, statistics.get().getMean()));
    }
}

From source file:com.formkiq.core.form.bean.FormJSONDateFieldInterceptor.java

@Override
public boolean isSupported(final Class<?> clazz, final FormJSON form) {
    Optional<FormJSONField> inserted = FormFinder.findValueByKey(form, "insertedDate");
    Optional<FormJSONField> updated = FormFinder.findValueByKey(form, "updatedDate");

    return (inserted.isPresent() && isEmpty(inserted.get().getValue()) || updated.isPresent());
}