Example usage for java.util Optional ifPresent

List of usage examples for java.util Optional ifPresent

Introduction

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

Prototype

public void ifPresent(Consumer<? super T> action) 

Source Link

Document

If a value is present, performs the given action with the value, otherwise does nothing.

Usage

From source file:org.obiba.mica.core.upgrade.Mica310Upgrade.java

private void addMethodsIfMissing(Study study, List<JSONObject> history, String methodsAttribute) {

    try {// ww w .j  a v  a2s .c  o  m
        if (!containsValidMethods(study, methodsAttribute)) {
            Optional<Map<String, String>> optionalMethodsAttributeValue = history.stream()
                    .filter(studyHistoryAsJson -> this.containsOldMethods(studyHistoryAsJson, methodsAttribute))
                    .filter(Objects::nonNull).map(studyHistoryAsJson -> this
                            .extractMethodsLocalizedString(studyHistoryAsJson, methodsAttribute))
                    .findFirst();

            optionalMethodsAttributeValue.ifPresent(methodsAttributeValue -> (getModelMethods(study))
                    .put(methodsAttribute, methodsAttributeValue));
        }
    } catch (RuntimeException ignore) {
    }
}

From source file:com.homeadvisor.kafdrop.service.CuratorKafkaMonitor.java

@Override
public Optional<TopicVO> getTopic(String topic) {
    validateInitialized();//  ww  w . ja  v a2 s  .c o  m
    final Optional<TopicVO> topicVO = Optional.ofNullable(getTopicMetadata(topic).get(topic));
    topicVO.ifPresent(vo -> {
        getTopicPartitionSizes(vo, kafka.api.OffsetRequest.LatestTime()).entrySet()
                .forEach(entry -> vo.getPartition(entry.getKey()).ifPresent(p -> p.setSize(entry.getValue())));
        getTopicPartitionSizes(vo, kafka.api.OffsetRequest.EarliestTime()).entrySet().forEach(
                entry -> vo.getPartition(entry.getKey()).ifPresent(p -> p.setFirstOffset(entry.getValue())));
    });
    return topicVO;
}

From source file:frontend.GUIController.java

@FXML
void editPreferences(ActionEvent event) {
    EditPreferences dialog = new EditPreferences(stage);
    Optional<AppProperties> result = dialog.showAndWait();
    result.ifPresent(props -> {
        at.setCustomModelFile(props.getModel());
        at.setLexiconPath(props.getLexicon());
        at.setQueryTerms(props.getQueryList());

        System.out.println("Updating preferences to: ");
        System.out.println(props.toString());
        System.out.println("Saving in file: " + GUI.configFile);
        FileOutputStream saveFile;
        try {/*w  ww . java 2 s . c om*/
            saveFile = new FileOutputStream(GUI.configFile);
            props.store(saveFile, "Saving file");
            saveFile.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    });
}

From source file:alfio.manager.PaypalManager.java

public boolean refund(alfio.model.transaction.Transaction transaction, Event event, Optional<Integer> amount) {
    String captureId = transaction.getTransactionId();
    try {//w w  w  .j ava2 s .c o m
        APIContext apiContext = getApiContext(event);
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Paypal: trying to do a refund for payment {} with amount: {}", captureId, amountOrFull);
        Capture capture = Capture.get(apiContext, captureId);
        RefundRequest refundRequest = new RefundRequest();
        amount.ifPresent(
                a -> refundRequest.setAmount(new Amount(capture.getAmount().getCurrency(), formatCents(a))));
        DetailedRefund res = capture.refund(apiContext, refundRequest);
        log.info("Paypal: refund for payment {} executed with success for amount: {}", captureId, amountOrFull);
        return true;
    } catch (PayPalRESTException ex) {
        log.warn("Paypal: was not able to refund payment with id " + captureId, ex);
        return false;
    }
}

From source file:com.spotify.heroic.suggest.elasticsearch.SuggestBackendKV.java

@Override
public AsyncFuture<TagValueSuggest> tagValueSuggest(final TagValueSuggest.Request request) {
    return connection.doto((final Connection c) -> {
        final BoolQueryBuilder bool = boolQuery();

        final Optional<String> key = request.getKey();

        key.ifPresent(k -> {
            if (!k.isEmpty()) {
                bool.must(termQuery(TAG_SKEY_RAW, k));
            }/*from www  .j  a va 2s  .  c  o  m*/
        });

        QueryBuilder query = bool.hasClauses() ? bool : matchAllQuery();

        if (!(request.getFilter() instanceof TrueFilter)) {
            query = new BoolQueryBuilder().must(query).filter(filter(request.getFilter()));
        }

        final SearchRequestBuilder builder = c.search(TAG_TYPE).setSize(0).setQuery(query);

        final OptionalLimit limit = request.getLimit();

        {
            final TermsAggregationBuilder terms = AggregationBuilders.terms("values").field(TAG_SVAL_RAW)
                    .order(Order.term(true));

            limit.asInteger().ifPresent(l -> terms.size(l + 1));
            builder.addAggregation(terms);
        }

        return bind(builder.execute()).directTransform((SearchResponse response) -> {
            final ImmutableList.Builder<String> suggestions = ImmutableList.builder();

            if (response.getAggregations() == null) {
                return TagValueSuggest.of(Collections.emptyList(), Boolean.FALSE);
            }

            final Terms terms = response.getAggregations().get("values");

            final List<Bucket> buckets = terms.getBuckets();

            for (final Terms.Bucket bucket : limit.limitList(buckets)) {
                suggestions.add(bucket.getKeyAsString());
            }

            return TagValueSuggest.of(suggestions.build(), limit.isGreater(buckets.size()));
        });
    });
}

From source file:alfio.manager.StripeManager.java

public boolean refund(Transaction transaction, Event event, Optional<Integer> amount) {
    String chargeId = transaction.getTransactionId();
    try {/*from w w  w .java2  s. com*/
        String amountOrFull = amount.map(MonetaryUtil::formatCents).orElse("full");
        log.info("Stripe: trying to do a refund for payment {} with amount: {}", chargeId, amountOrFull);
        Map<String, Object> params = new HashMap<>();
        params.put("charge", chargeId);
        amount.ifPresent(a -> params.put("amount", a));
        if (isConnectEnabled(event)) {
            params.put("refund_application_fee", true);
        }

        Optional<RequestOptions> requestOptionsOptional = options(event);
        if (requestOptionsOptional.isPresent()) {
            RequestOptions options = requestOptionsOptional.get();
            Refund r = Refund.create(params, options);
            if ("succeeded".equals(r.getStatus())) {
                log.info("Stripe: refund for payment {} executed with success for amount: {}", chargeId,
                        amountOrFull);
                return true;
            } else {
                log.warn(
                        "Stripe: was not able to refund payment with id {}, returned status is not 'succeded' but {}",
                        chargeId, r.getStatus());
                return false;
            }
        }
        return false;
    } catch (StripeException e) {
        log.warn("Stripe: was not able to refund payment with id " + chargeId, e);
        return false;
    }
}

From source file:alfio.manager.system.ConfigurationManager.java

public void saveSystemConfiguration(ConfigurationKeys key, String value) {
    Optional<Configuration> conf = optionally(() -> findByConfigurationPathAndKey(Configuration.system(), key));
    if (key.isBooleanComponentType()) {
        Optional<Boolean> state = getThreeStateValue(value);
        if (conf.isPresent()) {
            if (state.isPresent()) {
                configurationRepository.update(key.getValue(), value);
            } else {
                configurationRepository.deleteByKey(key.getValue());
            }//  w w w.  ja v  a2 s.c o  m
        } else {
            state.ifPresent(
                    v -> configurationRepository.insert(key.getValue(), v.toString(), key.getDescription()));
        }
    } else {
        Optional<String> valueOpt = Optional.ofNullable(value);
        if (!conf.isPresent()) {
            valueOpt.ifPresent(v -> configurationRepository.insert(key.getValue(), v, key.getDescription()));
        } else {
            configurationRepository.update(key.getValue(), value);
        }
    }
}

From source file:com.hubrick.vertx.rest.impl.DefaultRestClientRequest.java

private void finishRequest(Optional<MultiKey> key) {
    if (timeoutInMillis > 0) {
        httpClientRequest.setTimeout(timeoutInMillis);
    }/*w  ww. j av a 2 s .  c om*/
    httpClientRequest.end(Buffer.buffer(bufferedHttpOutputMessage.getBody()));
    key.ifPresent(e -> restClient.getRunningRequests().put(e, this));
    logRequest();
}

From source file:org.fineract.module.stellar.horizonadapter.HorizonServerUtilities.java

private ManageOfferOperation offerOperation(final KeyPair sourceAccountKeyPair, final Asset fromAsset,
        final Asset toAsset, final BigDecimal amount, final Optional<Long> offerId) {
    final ManageOfferOperation.Builder offerOperationBuilder = new ManageOfferOperation.Builder(fromAsset,
            toAsset, StellarAccountHelpers.bigDecimalToStellarBalance(amount), "1");
    offerOperationBuilder.setSourceAccount(sourceAccountKeyPair);

    offerId.ifPresent(offerOperationBuilder::setOfferId);

    return offerOperationBuilder.build();
}

From source file:com.vsct.dt.strowgr.admin.repository.consul.ConsulRepository.java

private Optional<Session> createSession(EntryPointKey entryPointKey, Integer ttlInSec,
        SESSION_BEHAVIOR behavior) throws IOException {
    HttpPut createSessionURI = new HttpPut("http://" + host + ":" + port + "/v1/session/create");
    if (ttlInSec != null) {
        String payload = "{\"Behavior\":\"" + behavior.value + "\",\"TTL\":\"" + ttlInSec + "s\", \"Name\":\""
                + entryPointKey.getID() + "\", \"LockDelay\": \"0\" }";
        LOGGER.trace("create a consul session with theses options: {} ", payload);
        createSessionURI.setEntity(new StringEntity(payload));
    }/*w  w  w.  j a va 2 s . c o  m*/
    Optional<Session> session = client.execute(createSessionURI,
            response -> consulReader.parseHttpResponse(response, consulReader::parseSessionFromHttpEntity));
    session.ifPresent(s -> LOGGER.debug("get session {} for key {}", s.ID, entryPointKey));
    return session;
}