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:io.github.mzmine.modules.plots.msspectrum.MsSpectrumPlotWindowController.java

public void handleSetMzShiftManually(Event event) {
    DecimalFormat mzFormat = MZmineCore.getConfiguration().getMZFormat();
    String newMzShiftString = "0.0";
    Double newMzShift = (Double) setToMenuItem.getUserData();
    if (newMzShift != null)
        newMzShiftString = mzFormat.format(newMzShift);
    TextInputDialog dialog = new TextInputDialog(newMzShiftString);
    dialog.setTitle("m/z shift");
    dialog.setHeaderText("Set m/z shift value");
    Optional<String> result = dialog.showAndWait();
    result.ifPresent(value -> {
        try {// ww w  .j a v  a  2s.c om
            double newValue = Double.parseDouble(value);
            mzShift.set(newValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    });

}

From source file:io.github.swagger2markup.internal.component.ResponseComponent.java

@Override
public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    PathOperation operation = params.operation;
    Map<String, Response> responses = operation.getOperation().getResponses();

    MarkupDocBuilder responsesBuilder = copyMarkupDocBuilder(markupDocBuilder);
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_RESPONSES_BEGIN, responsesBuilder, operation));
    if (MapUtils.isNotEmpty(responses)) {
        StringColumn.Builder httpCodeColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(HTTP_CODE_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "2");
        StringColumn.Builder descriptionColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "14")
                .putMetaData(TableComponent.HEADER_COLUMN, "true");
        StringColumn.Builder schemaColumnBuilder = StringColumn
                .builder(StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
                .putMetaData(TableComponent.WIDTH_RATIO, "4").putMetaData(TableComponent.HEADER_COLUMN, "true");

        Map<String, Response> sortedResponses = toSortedMap(responses, config.getResponseOrdering());
        sortedResponses.forEach((String responseName, Response response) -> {
            String schemaContent = labels.getLabel(NO_CONTENT);
            if (response.getSchema() != null) {
                Property property = response.getSchema();
                Type type = new PropertyAdapter(property).getType(definitionDocumentResolver);

                if (config.isInlineSchemaEnabled()) {
                    type = createInlineType(type, labels.getLabel(RESPONSE) + " " + responseName,
                            operation.getId() + " " + labels.getLabel(RESPONSE) + " " + responseName,
                            params.inlineDefinitions);
                }//from  ww  w  . j av a 2s .c  o  m

                schemaContent = type.displaySchema(markupDocBuilder);
            }

            MarkupDocBuilder descriptionBuilder = copyMarkupDocBuilder(markupDocBuilder);

            descriptionBuilder.text(markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder,
                    response.getDescription()));

            Map<String, Property> headers = response.getHeaders();
            if (MapUtils.isNotEmpty(headers)) {
                descriptionBuilder.newLine(true).boldText(labels.getLabel(HEADERS_COLUMN)).text(COLON);
                for (Map.Entry<String, Property> header : headers.entrySet()) {
                    descriptionBuilder.newLine(true);
                    Property headerProperty = header.getValue();
                    PropertyAdapter headerPropertyAdapter = new PropertyAdapter(headerProperty);
                    Type propertyType = headerPropertyAdapter.getType(null);
                    String headerDescription = markupDescription(config.getSwaggerMarkupLanguage(),
                            markupDocBuilder, headerProperty.getDescription());
                    Optional<Object> optionalDefaultValue = headerPropertyAdapter.getDefaultValue();

                    descriptionBuilder.literalText(header.getKey())
                            .text(String.format(" (%s)", propertyType.displaySchema(markupDocBuilder)));

                    if (isNotBlank(headerDescription) || optionalDefaultValue.isPresent()) {
                        descriptionBuilder.text(COLON);

                        if (isNotBlank(headerDescription) && !headerDescription.endsWith("."))
                            headerDescription += ".";

                        descriptionBuilder.text(headerDescription);

                        optionalDefaultValue.ifPresent(
                                o -> descriptionBuilder.text(" ").boldText(labels.getLabel(DEFAULT_COLUMN))
                                        .text(COLON).literalText(Json.pretty(o)));
                    }
                }
            }

            httpCodeColumnBuilder.add(boldText(markupDocBuilder, responseName));
            descriptionColumnBuilder.add(descriptionBuilder.toString());
            schemaColumnBuilder.add(schemaContent);
        });

        responsesBuilder = tableComponent.apply(responsesBuilder, TableComponent.parameters(
                httpCodeColumnBuilder.build(), descriptionColumnBuilder.build(), schemaColumnBuilder.build()));
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_RESPONSES_END, responsesBuilder, operation));
    String responsesContent = responsesBuilder.toString();

    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_RESPONSES_BEFORE, markupDocBuilder, operation));
    if (isNotBlank(responsesContent)) {
        markupDocBuilder.sectionTitleLevel(params.titleLevel, labels.getLabel(RESPONSES));
        markupDocBuilder.text(responsesContent);
    }
    applyPathsDocumentExtension(new PathsDocumentExtension.Context(
            PathsDocumentExtension.Position.OPERATION_RESPONSES_AFTER, markupDocBuilder, operation));
    return markupDocBuilder;
}

From source file:tech.beshu.ror.utils.containers.ESWithReadonlyRestContainer.java

private WaitStrategy waitStrategy(Optional<ESWithReadonlyRestContainer.ESInitalizer> initalizer) {
    final ObjectMapper mapper = new ObjectMapper();
    return new GenericContainer.AbstractWaitStrategy() {
        @Override//from   w w  w.j  av a 2  s . c om
        protected void waitUntilReady() {
            logger.info("Waiting for ES container ...");
            final RestClient client = getAdminClient();
            final Instant startTime = Instant.now();
            while (!isReady(client) && !checkTimeout(startTime, startupTimeout)) {
                try {
                    Thread.sleep(WAIT_BETWEEN_RETRIES.toMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            initalizer.ifPresent(i -> i.initialize(client));
            logger.info("ES container stated");
        }

        private boolean isReady(RestClient client) {
            try {
                HttpResponse result = client.execute(new HttpGet(client.from("_cluster/health")));
                if (result.getStatusLine().getStatusCode() != 200)
                    return false;
                Map<String, String> healthJson = mapper.readValue(result.getEntity().getContent(),
                        new TypeReference<Map<String, String>>() {
                        });
                return "green".equals(healthJson.get("status"));
            } catch (IOException | URISyntaxException e) {
                return false;
            }
        }
    };
}

From source file:org.ow2.proactive.connector.iaas.cloud.provider.azure.AzureProvider.java

@Override
public void deleteInstance(Infrastructure infrastructure, String instanceId) {
    Azure azureService = azureServiceCache.getService(infrastructure);

    VirtualMachine vm = azureProviderUtils.searchVirtualMachineByID(azureService, instanceId).orElseThrow(
            () -> new RuntimeException("ERROR unable to find instance with ID: '" + instanceId + "'"));

    // Retrieve all resources attached to the instance
    NetworkInterface networkInterface = vm.getPrimaryNetworkInterface();
    com.microsoft.azure.management.network.Network network = networkInterface.primaryIpConfiguration()
            .getNetwork();/*from  ww  w  . jav a2 s .  c  o  m*/
    NetworkSecurityGroup networkSecurityGroup = networkInterface.getNetworkSecurityGroup();
    Optional<PublicIpAddress> optionalPublicIPAddress = Optional.ofNullable(vm.getPrimaryPublicIpAddress());
    String osDiskID = vm.osDiskId();

    // Delete the VM first
    azureService.virtualMachines().deleteById(vm.id());

    // Then delete its network interface
    azureService.networkInterfaces().deleteById(networkInterface.id());

    // Delete its public IP address if present
    optionalPublicIPAddress.ifPresent(pubIPAddr -> azureService.publicIpAddresses().deleteById(pubIPAddr.id()));

    // Delete its main disk (OS), and keep data disks
    azureService.disks().deleteById(osDiskID);

    // Delete the security group if present and not attached to any network interface
    if (azureService.networkInterfaces().list().stream().map(NetworkInterface::getNetworkSecurityGroup)
            .filter(netSecGrp -> Optional.ofNullable(netSecGrp).isPresent())
            .noneMatch(netSecGrp -> netSecGrp.id().equals(networkSecurityGroup.id()))) {
        azureService.networkSecurityGroups().deleteById(networkSecurityGroup.id());
    }

    // Delete the virtual network if not attached to any network interface
    if (azureService.networkInterfaces().list().stream().map(NetworkInterface::primaryIpConfiguration)
            .filter(ipConf -> Optional.ofNullable(ipConf).isPresent()).map(NicIpConfiguration::getNetwork)
            .filter(net -> Optional.ofNullable(net).isPresent())
            .noneMatch(net -> net.id().equals(network.id()))) {
        azureService.networks().deleteById(network.id());
    }
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

private MapValue removeInternal(String key, Optional<byte[]> value, Optional<MapValue> tombstone) {
    checkState(!closed, destroyedMessage);
    checkNotNull(key, ERROR_NULL_KEY);//from   w  w  w  .j av a 2s  .  c om
    checkNotNull(value, ERROR_NULL_VALUE);
    tombstone.ifPresent(v -> checkState(v.isTombstone()));

    counter.incrementCount();
    AtomicBoolean updated = new AtomicBoolean(false);
    AtomicReference<MapValue> previousValue = new AtomicReference<>();
    items.compute(key, (k, existing) -> {
        boolean valueMatches = true;
        if (value.isPresent() && existing != null && existing.isAlive()) {
            valueMatches = Arrays.equals(value.get(), existing.get());
        }
        if (existing == null) {
            log.trace("ECMap Remove: Existing value for key {} is already null", k);
        }
        if (valueMatches) {
            if (existing == null) {
                updated.set(tombstone.isPresent());
            } else {
                updated.set(!tombstone.isPresent() || tombstone.get().isNewerThan(existing));
            }
        }
        if (updated.get()) {
            previousValue.set(existing);
            return tombstone.orElse(null);
        } else {
            return existing;
        }
    });
    return previousValue.get();
}

From source file:me.Wundero.Ray.utils.TextUtils.java

/**
 * Apply the actions provided onto a builder.
 *//*from w  ww  .  ja  v a  2 s .c  o m*/
public static Text.Builder apply(Text.Builder b, Optional<ClickAction<?>> c, Optional<HoverAction<?>> h,
        Optional<ShiftClickAction<?>> s) {
    c.ifPresent(x -> b.onClick(x));
    h.ifPresent(x -> b.onHover(x));
    s.ifPresent(x -> b.onShiftClick(x));
    return b;
}

From source file:com.ikanow.aleph2.example.flume_harvester.services.FlumeHarvesterSink.java

@Override
public Status process() throws EventDeliveryException {
    Status status = null;/*from  w ww .j  av  a 2  s  .  co  m*/

    //TODO (ALEPH-10): handy to know: there's a timeout that appears to occur, so can log a heartbeat every N seconds and use in the poll freq to ensure this thread hasn't crashed...
    //TODO (ALEPH-10): also have a log the first time an error occurs, and maybe hourly log messages reporting data sizes

    // Start transaction
    final Channel ch = getChannel();
    final Transaction txn = ch.getTransaction();
    txn.begin();
    try {
        // This try clause includes whatever Channel operations you want to do

        final Event event = ch.take();

        final Optional<JsonNode> maybe_json_event = getEventJson(event, _config)
                // Extra step
                .map(json -> _time_field.filter(tf -> !json.has(tf)) // (ie filter out JSON objects with the timestamp field, those are passed unchanged by the orElse 
                        .<JsonNode>map(tf -> ((ObjectNode) json).put(tf, LocalDateTime.now().toString())) // put the timestamp field in
                        .orElse(json));

        maybe_json_event.ifPresent(json_event -> {
            if (_config.map(cfg -> cfg.output()).map(out -> out.direct_output()).isPresent()) {
                this.directOutput(json_event, _config.get(), _bucket);
            } else {
                if (_streaming) {
                    _context.sendObjectToStreamingPipeline(Optional.empty(), Either.left(json_event));
                }
                if (_batch) {
                    this.directOutput(json_event, _BATCH_CONFIG, _bucket);
                }
            }
        });

        txn.commit();
        status = Status.READY;
    } catch (Throwable t) {
        //DEBUG
        //_logger.warn("Error", t);

        txn.rollback();

        // Log exception, handle individual exceptions as needed

        status = Status.BACKOFF;

        // re-throw all Errors
        if (t instanceof Error) {
            throw (Error) t;
        }
    } finally {
        txn.close();
    }
    return status;
}

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

private RequestBody prepareBody(Event event, String to, List<String> cc, String subject, String text,
        Optional<String> html, Attachment... attachments) throws IOException {

    String from = event.getDisplayName() + " <" + configurationManager
            .getRequiredValue(Configuration.from(event.getOrganizationId(), event.getId(), MAILGUN_FROM)) + ">";

    if (ArrayUtils.isEmpty(attachments)) {
        FormBody.Builder builder = new FormBody.Builder().add("from", from).add("to", to)
                .add("subject", subject).add("text", text);
        if (cc != null && !cc.isEmpty()) {
            builder.add("cc", StringUtils.join(cc, ','));
        }// w  ww.j a  v  a2s.com

        String replyTo = configurationManager.getStringConfigValue(
                Configuration.from(event.getOrganizationId(), event.getId(), MAIL_REPLY_TO), "");
        if (StringUtils.isNotBlank(replyTo)) {
            builder.add("h:Reply-To", replyTo);
        }
        html.ifPresent((htmlContent) -> builder.add("html", htmlContent));
        return builder.build();

    } else {
        MultipartBody.Builder multipartBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        multipartBuilder.addFormDataPart("from", from).addFormDataPart("to", to)
                .addFormDataPart("subject", subject).addFormDataPart("text", text);

        if (cc != null && !cc.isEmpty()) {
            multipartBuilder.addFormDataPart("cc", StringUtils.join(cc, ','));
        }

        html.ifPresent((htmlContent) -> multipartBuilder.addFormDataPart("html", htmlContent));

        for (Attachment attachment : attachments) {
            byte[] data = attachment.getSource();
            multipartBuilder.addFormDataPart("attachment", attachment.getFilename(), RequestBody
                    .create(MediaType.parse(attachment.getContentType()), Arrays.copyOf(data, data.length)));
        }
        return multipartBuilder.build();
    }
}

From source file:acmi.l2.clientmod.xdat.Controller.java

private MenuItem createAddMenu(String name, TreeView<Object> elements, TreeItem<Object> selected) {
    ListHolder listHolder = (ListHolder) selected.getValue();

    MenuItem add = new MenuItem(name);
    add.setOnAction(event -> {//from  w ww  .ja v  a  2s  . c o m
        Stream<ClassHolder> st = SubclassManager.getInstance().getClassWithAllSubclasses(listHolder.type)
                .stream().map(ClassHolder::new);
        List<ClassHolder> list = st.collect(Collectors.toList());

        Optional<ClassHolder> choice;

        if (list.size() == 1) {
            choice = Optional.of(list.get(0));
        } else {
            ChoiceDialog<ClassHolder> cd = new ChoiceDialog<>(list.get(0), list);
            cd.setTitle("Select class");
            cd.setHeaderText(null);
            choice = cd.showAndWait();
        }
        choice.ifPresent(toCreate -> {
            try {
                IOEntity obj = toCreate.clazz.newInstance();

                listHolder.list.add(obj);
                TreeItem<Object> treeItem = createTreeItem(obj);
                selected.getChildren().add(treeItem);
                elements.getSelectionModel().select(treeItem);
                elements.scrollTo(elements.getSelectionModel().getSelectedIndex());

                editor.getHistory().valueCreated(treeItemToScriptString(selected), toCreate.clazz);
            } catch (ReflectiveOperationException e) {
                log.log(Level.WARNING, String.format("Couldn't instantiate %s", toCreate.clazz.getName()), e);
                Dialogs.show(Alert.AlertType.ERROR, "ReflectiveOperationException", null,
                        "Couldn't instantiate " + toCreate.clazz);
            }
        });
    });

    return add;
}