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:ch.wisv.areafiftylan.security.TokenAuthenticationFilter.java

private AuthenticationToken extractOptional(Optional<AuthenticationToken> op, ServletResponse response)
        throws IOException {
    if (!op.isPresent()) {
        ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED, "Token not found");
        return null;
    } else {//from ww w. j a v  a 2  s .c om
        return op.get();
    }
}

From source file:org.apache.ambari.view.web.controller.PackageController.java

@GetMapping("/versions/{versionId}")
public PackageWrapper.FindOneVersionResponse getPackageVersion(@PathVariable("versionId") Long versionId) {
    Optional<PackageVersion> versionOptional = service.getVersion(versionId);
    if (!versionOptional.isPresent()) {
        log.error("Package version id: {} not found", versionId);
        throw new RuntimeException("Package Version not found");
    }//from  w ww . j  ava  2s . c om
    return new PackageWrapper.FindOneVersionResponse(versionOptional.get());
}

From source file:com.arpnetworking.configuration.jackson.JsonNodeUriSourceTest.java

@Test
public void test() throws MalformedURLException {
    final WireMockServer server = new WireMockServer(0);
    server.start();// w ww  .j  a  v  a2  s . c o m
    final WireMock wireMock = new WireMock(server.port());

    wireMock.register(WireMock.get(WireMock.urlEqualTo("/configuration"))
            .willReturn(WireMock.aResponse().withStatus(200)
                    .withHeader("Content-Type", "application/json; charset=utf-8")
                    .withBody("{\"values\":[\"foo\",\"bar\"]}")));

    final JsonNodeUriSource jsonNodeUriSource = new JsonNodeUriSource.Builder()
            .setUri(URI.create("http://localhost:" + server.port() + "/configuration")).build();

    final Optional<JsonNode> jsonNode = jsonNodeUriSource.getJsonNode();
    Assert.assertTrue(jsonNode.isPresent());
    Assert.assertTrue(jsonNode.get().isObject());
    Assert.assertEquals(1, Iterators.size(((ObjectNode) jsonNode.get()).fieldNames()));

    final Optional<JsonNode> valuesJsonNode = jsonNodeUriSource.getValue("values");
    Assert.assertTrue(valuesJsonNode.isPresent());
    Assert.assertTrue(valuesJsonNode.get().isArray());
    Assert.assertEquals(2, ((ArrayNode) valuesJsonNode.get()).size());
    Assert.assertEquals("foo", ((ArrayNode) valuesJsonNode.get()).get(0).textValue());
    Assert.assertEquals("bar", ((ArrayNode) valuesJsonNode.get()).get(1).textValue());

    server.stop();
}

From source file:com.ejisto.util.collector.MockedFieldCollector.java

@Override
public Function<Map<String, List<MockedField>>, FieldNode> finisher() {
    return map -> {
        FieldNode root = new FieldNode(null, null);
        map.entrySet().stream().filter(e -> !e.getValue().isEmpty()).flatMap(EXTRACT_ENTRY).forEach(entry -> {
            MockedField first = entry.getValue().get(0);
            Optional<FieldNode> parent = root.findDirectParent(first);
            if (!parent.isPresent()) {
                parent = root.findClosestParent(first);
            }/*from   w  ww  .j  ava 2 s  . c  o  m*/
            final FieldNode parentNode = parent.get();
            FieldNode container = parentNode.fillGap(first);
            entry.getValue().forEach(v -> container.addChild(new FieldNode(v)));
        });
        return root;
    };
}

From source file:com.rockagen.gnext.test.BaseTest.java

protected void newAccount() throws RegisterException {
    accountServ.newAccount(uid, AccountType.INDIVIDUAL);

    Optional<Account> acc = accountServ.loadByUid(uid);
    if (acc.isPresent()) {
        account = acc.get();/*ww  w .  j a  v  a 2 s  .co  m*/
        accountId = account.getId();
    } else {
        fail("account not exist!");
    }
}

From source file:tds.assessment.services.impl.AccommodationServiceImpl.java

@Override
@Cacheable(CacheType.LONG_TERM)/*  ww  w.j  a  v a2s .c  o m*/
public List<Accommodation> findAccommodationsByAssessmentKey(final String clientName,
        final String assessmentKey) {
    //Implements the replacement for CommonDLL.TestKeyAccommodations_FN
    Optional<Assessment> maybeAssessment = assessmentService.findAssessment(clientName, assessmentKey);
    if (!maybeAssessment.isPresent()) {
        throw new NotFoundException("Could not find assessment for %s", assessmentKey);
    }

    Assessment assessment = maybeAssessment.get();
    return accommodationsQueryRepository.findAssessmentAccommodationsByKey(assessment.getKey(),
            assessment.getLanguageCodes());
}

From source file:com.hortonworks.registries.storage.impl.jdbc.provider.sql.query.AbstractStorableUpdateQuery.java

public AbstractStorableUpdateQuery(Storable storable) {
    super(storable);
    Map<String, Object> columnsToValues = storable.toMap();
    columns.forEach(col -> bindings.add(Pair.of(col, columnsToValues.get(col.getName()))));
    primaryKey.getFieldsToVal().forEach((f, o) -> {
        bindings.add(Pair.of(f, o));//from  ww  w  .  j av  a  2 s .c  o  m
        whereFields.add(f);
    });
    try {
        Optional<Pair<Field, Long>> versionFieldValue = StorageUtils.getVersionFieldValue(storable);
        if (versionFieldValue.isPresent()) {
            Pair<Field, Long> fv = versionFieldValue.get();
            Schema.Field versionField = Schema.Field.of(fv.getKey().getName(),
                    Schema.fromJavaType(fv.getValue().getClass()));
            whereFields.add(versionField);
            // update only if its the previous
            bindings.add(Pair.of(versionField, fv.getValue() - 1));
        }
    } catch (Exception ex) {
        LOG.error("Got exception", ex);
    }
}

From source file:com.openthinks.webscheduler.controller.ProfileController.java

@Mapping("/pwd/edit")
public String editPwd(WebAttributers was) {
    String oldPwd = was.get(StaticDict.PAGE_PARAM_USER_OLD_PWD);
    String newPwd = was.get(StaticDict.PAGE_PARAM_USER_NEW_PWD);
    String newPwdAgain = was.get(StaticDict.PAGE_PARAM_USER_NEW_PWD_AGAIN);

    try {/*from w w w . j  a v a  2 s.co m*/
        Checker.require(oldPwd).notEmpty("Old user password can not be empty.");
        Checker.require(newPwd).notEmpty("New user password can not be empty.");
        Checker.require(newPwdAgain).notEmpty("New user password again can not be empty.");
    } catch (Exception e) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, e.getMessage(), WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }
    Optional<User> currentUser = getCurrentUser(was);
    if (!currentUser.isPresent()) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, "Session timeout, please login again.",
                WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }
    User user = currentUser.get();
    if (!user.getPass().equals(DigestUtils.md5Hex(oldPwd))) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, "Invalid old password.", WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }

    if (!newPwd.equals(newPwdAgain)) {
        was.addError(StaticDict.PAGE_ATTRIBUTE_ERROR_1, "The twice new password are not same, please check.",
                WebScope.REQUEST);
        return StaticUtils.errorPage(was, PageMap.build());
    }
    user.setPass(DigestUtils.md5Hex(newPwd));
    securityService.saveToDisk();
    return WebUtils.redirect("/security/logout");
}

From source file:de.rnd7.urlcache.URLCacheLoader.java

@Override
public CachedElement load(final URLCacheKey key) throws Exception {
    final Optional<CachedElement> fromDisk = this.loadFromDisk(key);
    if (fromDisk.isPresent()) {
        return fromDisk.get();
    }//from w w w.j  av a 2  s .co m

    final CachedElement element = this.loadFromURL(key);
    this.saveToDisk(element, key);

    return element;
}

From source file:org.anhonesteffort.p25.ACAP25.java

private Optional<Double> findActiveControlChannel(Integer systemId, Integer systemWacn, Site site) {
    for (Double channelFreq : site.getControlChannels()) {
        P25ChannelSpec channelSpec = new P25ChannelSpec(channelFreq);
        P25Channel channel = new P25Channel(channelSpec);
        ControlChannelQualifier channelQualifier = new ControlChannelQualifier(controlChannelPool,
                samplesController, channel, systemId, systemWacn);

        try {//from  w ww .j  a va2 s  . co m

            Future<Optional<Double>> channelQualified = controlChannelPool.submit(channelQualifier);
            Optional<Double> controlFreq = channelQualified.get();

            if (controlFreq.isPresent()) {
                log.info(
                        "found active control channel at " + controlFreq.get() + " for site " + site.getName());
                return Optional.of(controlFreq.get());
            }

        } catch (InterruptedException | ExecutionException e) {
            log.error("error while identifying active control channels, exiting", e);
            java.lang.System.exit(1);
        }
    }

    return Optional.empty();
}