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:it.polimi.diceH2020.SPACE4CloudWS.fineGrainedLogicForOptimization.ReactorConsumer.java

private Pair<Boolean, Long> runSolver(SolutionPerJob solPerJob) {
    Pair<Optional<Double>, Long> solverResult = solverCache.evaluate(solPerJob);
    Optional<Double> solverMetric = solverResult.getLeft();
    long runtime = solverResult.getRight();

    if (solverMetric.isPresent()) {
        PerformanceSolver solver = solverCache.getPerformanceSolver();
        Technology technology = dataService.getScenario().getTechnology();
        Double mainMetric = solver.transformationFromSolverResult(solPerJob, technology)
                .apply(solverMetric.get());
        solver.metricUpdater(solPerJob, technology).accept(mainMetric);
        boolean feasible = solver.feasibilityCheck(solPerJob, technology).test(mainMetric);
        solPerJob.setFeasible(feasible);
        return new ImmutablePair<>(true, runtime);
    }//from   ww  w  . ja v a2s. c o m

    solverCache.invalidate(solPerJob);
    return new ImmutablePair<>(false, runtime);
}

From source file:com.javaeeeee.repositories.UsersRepositoryTest.java

/**
 * Method tests sad path./*from  w ww.  j  av a  2 s. c o m*/
 */
@Test
public void findByUsernameAndPasswordShouldReturnEmpty() {
    final String name = "Phil";
    final String password = "1";
    entityManager.persist(new User(name, password));
    Optional<User> optional = usersRepository.findByUsernameAndPassword(name, password + "mmm");

    Assert.assertFalse(optional.isPresent());
}

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

@Override
public void validate(final Metacard metacard) throws ValidationException {
    final Optional<MetacardValidationReport> reportOptional = validateMetacard(metacard);

    if (reportOptional.isPresent()) {
        final List<String> errors = reportOptional.get().getMetacardValidationViolations().stream()
                .map(ValidationViolation::getMessage).collect(Collectors.toList());

        final ValidationExceptionImpl exception = new ValidationExceptionImpl();
        exception.setErrors(errors);/*from   ww  w. j a  v a 2  s  .  co m*/
        throw exception;
    }
}

From source file:org.springsource.restbucks.payment.PaymentServiceImpl.java

@Override
public CreditCardPayment pay(Order order, CreditCardNumber creditCardNumber) {

    if (order.isPaid()) {
        throw new PaymentException(order, "Order already paid!");
    }//from  ww w. j a  v  a2 s . c o  m

    // Using Optional.orElseThrow() doesn't work due to https://bugs.openjdk.java.net/browse/JDK-8054569
    Optional<CreditCard> creditCardResult = creditCardRepository.findByNumber(creditCardNumber);

    if (!creditCardResult.isPresent()) {
        throw new PaymentException(order,
                String.format("No credit card found for number: %s", creditCardNumber.getNumber()));
    }

    CreditCard creditCard = creditCardResult.get();

    if (!creditCard.isValid()) {
        throw new PaymentException(order, String.format("Invalid credit card with number %s, expired %s!",
                creditCardNumber.getNumber(), creditCard.getExpirationDate()));
    }

    order.markPaid();
    CreditCardPayment payment = paymentRepository.save(new CreditCardPayment(creditCard, order));

    publisher.publishEvent(new OrderPaidEvent(order.getId()));

    return payment;
}

From source file:com.macrossx.wechat.impl.WechatMenuHelper.java

/**
 * create menu/*from w  w  w . j a va  2  s.co m*/
 * 
 * @param menu
 *            menu to create
 *            {@link https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141013&token=&lang=zh_CN}
 * @return true sucess
 */
@Override
public boolean createMenu(List<WechatButton> menu) {
    try {
        Map<String, List<WechatButton>> menus = Maps.newConcurrentMap();
        menus.put("button", menu);
        Optional<WechatAccessToken> token = wechatHelper.getAccessToken();
        if (token.isPresent()) {
            WechatAccessToken accessToken = token.get();
            HttpPost httpPost = new HttpPost();
            httpPost.setEntity(new StringEntity(new Gson().toJson(menus), "utf-8"));
            httpPost.setURI(new URI(
                    MessageFormat.format(WechatConstants.MENU_CREATE_URL, accessToken.getAccess_token())));
            Optional<WechatResponseObj> response = new WechatHttpClient().send(httpPost,
                    WechatResponseObj.class);
            if (response.isPresent()) {
                WechatResponseObj e = response.get();
                log.info(e.toString());
                if (0 == e.getErrcode()) {
                    return true;
                }
            }
        }
    } catch (URISyntaxException e) {
        log.info(e.getMessage());
    }
    return false;
}

From source file:com.michellemay.URLLanguageDetectorTest.java

public void validateTestCases(URLLanguageDetector detector, List<Pair<String, String>> testCases)
        throws Exception {
    List<Pair<Pair<String, String>, Optional<Locale>>> failedTests = testCases.stream()
            .map((test) -> Pair.of(test, detector.detect(test.getKey()))).filter((testAndResult) -> {
                Pair<String, String> test = testAndResult.getKey();
                Optional<Locale> detectedLanguage = testAndResult.getValue();
                boolean localTestFailed = (detectedLanguage.isPresent() != !test.getValue().isEmpty());
                if (!localTestFailed && detectedLanguage.isPresent()) {
                    localTestFailed = !detectedLanguage.get().equals(LocaleUtils.toLocale(test.getValue()));
                }// w ww.j  a v a2s  .  c  om
                return localTestFailed;
            }).collect(Collectors.toList());

    failedTests
            .forEach((test) -> System.out.println("FAILED: " + test.getKey() + ", FOUND: " + test.getValue()));
    assertTrue(failedTests.isEmpty());

}

From source file:de.Keyle.MyPet.util.Updater.java

public void update() {
    if (Configuration.Update.CHECK) {
        Optional<Update> update = check();
        if (update.isPresent()) {
            latest = update.get();//from w  ww.j a  v  a2s  .  c  om

            notifyVersion();

            if (Configuration.Update.DOWNLOAD) {
                download();
            }
        }
    }
}

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());
    }//w w w . j  a  va 2  s. com

    model.addAttribute("userRegistrationForm", form);

    return "signup";
}

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

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

    checkNotNull(measureUnitMagicNumber);

    double bloodGlucoseValue = asRequiredDouble(listEntryNode, "BG");

    if (bloodGlucoseValue == 0) {
        return Optional.empty();
    }//from   ww w. j  a v  a2  s .  c om

    BloodGlucoseUnit bloodGlucoseUnit = getBloodGlucoseUnitFromMagicNumber(measureUnitMagicNumber);

    BloodGlucose.Builder bloodGlucoseBuilder = new BloodGlucose.Builder(
            new TypedUnitValue<>(bloodGlucoseUnit, bloodGlucoseValue));

    Optional<String> relationshipToMeal = asOptionalString(listEntryNode, "DinnerSituation");

    if (relationshipToMeal.isPresent()) {

        IHealthTemporalRelationshipToMeal temporalRelationshipToMeal = IHealthTemporalRelationshipToMeal
                .findByResponseValue(relationshipToMeal.get()).get();

        bloodGlucoseBuilder.setTemporalRelationshipToMeal(temporalRelationshipToMeal.getStandardConstant());
    }

    getEffectiveTimeFrameAsDateTime(listEntryNode).ifPresent(bloodGlucoseBuilder::setEffectiveTimeFrame);
    getUserNoteIfExists(listEntryNode).ifPresent(bloodGlucoseBuilder::setUserNotes);

    BloodGlucose bloodGlucose = bloodGlucoseBuilder.build();

    /*  The "temporal_relationship_to_medication" property is not part of the Blood Glucose schema, so its name and
    values may change or we may remove support for this property at any time. */
    asOptionalString(listEntryNode, "DrugSituation").ifPresent(drugSituation -> bloodGlucose
            .setAdditionalProperty("temporal_relationship_to_medication", drugSituation));

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

From source file:ch.wisv.areafiftylan.extras.consumption.service.ConsumptionServiceImpl.java

@Override
public ConsumptionMap getByTicketIdIfValid(Long ticketId) {
    if (!ticketService.getTicketById(ticketId).isValid()) {
        throw new InvalidTicketException("Ticket is invalid; It can not be used for consumptions.");
    }/*  w w  w  .jav  a 2 s  .c o m*/

    Optional<ConsumptionMap> mapOptional = consumptionMapsRepository.findByTicketId(ticketId);

    if (mapOptional.isPresent()) {
        return mapOptional.get();
    } else {
        return initializeConsumptionMap(ticketId);
    }
}