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:com.netflix.genie.web.jpa.services.JpaJobPersistenceServiceImpl.java

private void setRequestedAgentEnvironmentFields(final JobEntity jobEntity,
        final AgentEnvironmentRequest requestedAgentEnvironment) {
    jobEntity.setRequestedEnvironmentVariables(requestedAgentEnvironment.getRequestedEnvironmentVariables());
    requestedAgentEnvironment.getRequestedJobMemory().ifPresent(jobEntity::setRequestedMemory);
    requestedAgentEnvironment.getRequestedJobCpu().ifPresent(jobEntity::setRequestedCpu);
    final Optional<JsonNode> agentEnvironmentExt = requestedAgentEnvironment.getExt();
    agentEnvironmentExt.ifPresent(
            jsonNode -> EntityDtoConverters.setJsonField(jsonNode, jobEntity::setRequestedAgentEnvironmentExt));
}

From source file:nu.yona.server.subscriptions.service.BuddyService.java

private boolean processPossiblePendingBuddyResponseMessage(UserDto user, Buddy buddy,
        Page<Message> messagePage) {

    Stream<BuddyConnectResponseMessage> buddyConnectResponseMessages = messagePage.getContent().stream()
            .filter(m -> m instanceof BuddyConnectResponseMessage).map(m -> (BuddyConnectResponseMessage) m);
    Stream<BuddyConnectResponseMessage> messagesFromBuddy = buddyConnectResponseMessages
            .filter(m -> buddy.getUserId().equals(getUserId(m).orElse(null)));
    Optional<BuddyConnectResponseMessage> messageToBeProcessed = messagesFromBuddy.filter(m -> !m.isProcessed())
            .findFirst();/*w w  w. ja v  a  2  s . c o  m*/
    messageToBeProcessed.ifPresent(m -> connectResponseMessageHandler.handleAction_Process(user, m,
            new MessageActionDto(Collections.emptyMap())));
    return messageToBeProcessed.isPresent();
}

From source file:jp.pigumer.mqtt.Client.java

void createMqttConnectOptions() {
    Optional<SSLContext> context = initTrustManagers().map(trustManagers -> {
        try {/* www.j  a  va2 s.co m*/
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustManagers, new SecureRandom());
            return sslContext;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "failed load", e);
            return null;
        }
    });

    options = new MqttConnectOptions();
    options.setUserName(userName);
    options.setPassword(password);
    context.ifPresent(sslContext -> options.setSocketFactory(sslContext.getSocketFactory()));
}

From source file:net.sf.jabref.external.DroppedFileHandler.java

/**
 * Make a extension to the file.//from w ww  . ja va2 s  .com
 *
 * @param entry    The entry to extension from.
 * @param fileType The FileType associated with the file.
 * @param filename The path to the file.
 * @param edits    An NamedCompound action this action is to be added to. If none
 *                 is given, the edit is added to the panel's undoManager.
 */
private void doLink(BibEntry entry, ExternalFileType fileType, String filename, boolean avoidDuplicate,
        NamedCompound edits) {

    Optional<String> oldValue = entry.getFieldOptional(FieldName.FILE);
    FileListTableModel tm = new FileListTableModel();
    oldValue.ifPresent(tm::setContent);

    // If avoidDuplicate==true, we should check if this file is already linked:
    if (avoidDuplicate) {
        // For comparison, find the absolute filename:
        List<String> dirs = panel.getBibDatabaseContext().getFileDirectory();
        String absFilename;
        if (new File(filename).isAbsolute() || dirs.isEmpty()) {
            absFilename = filename;
        } else {
            Optional<File> file = FileUtil.expandFilename(filename, dirs);
            if (file.isPresent()) {
                absFilename = file.get().getAbsolutePath();
            } else {
                absFilename = ""; // This shouldn't happen based on the old code, so maybe one should set it something else?
            }
        }

        LOGGER.debug("absFilename: " + absFilename);

        for (int i = 0; i < tm.getRowCount(); i++) {
            FileListEntry flEntry = tm.getEntry(i);
            // Find the absolute filename for this existing link:
            String absName;
            if (new File(flEntry.link).isAbsolute() || dirs.isEmpty()) {
                absName = flEntry.link;
            } else {
                Optional<File> file = FileUtil.expandFilename(flEntry.link, dirs);
                if (file.isPresent()) {
                    absName = file.get().getAbsolutePath();
                } else {
                    absName = null;
                }
            }
            LOGGER.debug("absName: " + absName);
            // If the filenames are equal, we don't need to link, so we simply return:
            if (absFilename.equals(absName)) {
                return;
            }
        }
    }

    tm.addEntry(tm.getRowCount(), new FileListEntry("", filename, fileType));
    String newValue = tm.getStringRepresentation();
    UndoableFieldChange edit = new UndoableFieldChange(entry, FieldName.FILE, oldValue.orElse(null), newValue);
    entry.setField(FieldName.FILE, newValue);

    if (edits == null) {
        panel.getUndoManager().addEdit(edit);
    } else {
        edits.addEdit(edit);
    }
}

From source file:com.epam.ta.reportportal.events.handler.LaunchFinishedEventHandler.java

private void afterFinishLaunch(final Project project, final Launch launch) { // NOSONAR

    /* Should we send email right now or wait till AA is finished? */
    boolean waitForAutoAnalysis;

    /* Avoid NULL object processing */
    if (null == project || null == launch)
        return;/*from  ww w  . j a  v  a 2s . co m*/

    Optional<EmailService> emailService = emailServiceFactory
            .getDefaultEmailService(project.getConfiguration().getEmailConfig());

    /* If AA enabled then waiting results processing */
    waitForAutoAnalysis = BooleanUtils.toBoolean(project.getConfiguration().getIsAutoAnalyzerEnabled());

    /* If email enabled and AA disabled then send results immediately */
    if (!waitForAutoAnalysis) {
        emailService.ifPresent(service -> sendEmailRightNow(launch, project, service));
    }

    // Do not process debug launches.
    if (launch.getMode().equals(Mode.DEBUG))
        return;
    List<FailReferenceResource> resources = issuesRepository.findAllLaunchIssues(launch.getId());
    if (!project.getConfiguration().getIsAutoAnalyzerEnabled()) {
        this.clearInvestigatedIssues(resources);
        return;
    }
    List<TestItem> previous = analyzerService.collectPreviousIssues(autoAnalysisDepth, launch.getId(),
            project.getName());
    List<TestItem> converted = resources.stream()
            .map(resource -> testItemRepository.findOne(resource.getTestItemRef()))
            .collect(Collectors.toList());
    analyzerService.analyze(launch.getId(), converted, previous);

    // Remove already processed items from repository
    this.clearInvestigatedIssues(resources);

    /* Previous email sending cycle was skipped due waiting AA results */
    if (waitForAutoAnalysis) {
        // Get launch with AA results
        Launch freshLaunch = launchRepository.findOne(launch.getId());
        emailService.ifPresent(it -> sendEmailRightNow(freshLaunch, project, it));
    }
}

From source file:com.ikanow.aleph2.graph.titan.services.TitanGraphBuilderEnrichmentService.java

@Override
public void onStageInitialize(IEnrichmentModuleContext context, DataBucketBean bucket,
        EnrichmentControlMetadataBean control, Tuple2<ProcessingStage, ProcessingStage> previous_next,
        Optional<List<String>> next_grouping_fields) {

    final GraphBuilderConfigBean dedup_config = BeanTemplateUtils
            .from(Optional.ofNullable(control.config()).orElse(Collections.emptyMap()),
                    GraphBuilderConfigBean.class)
            .get();//w ww  .j av a  2s.  co  m

    final GraphSchemaBean graph_schema = Optional.ofNullable(dedup_config.graph_schema_override())
            .orElse(bucket.data_schema().graph_schema()); //(exists by construction)
    _config.set(
            BeanTemplateUtils.clone(graph_schema)
                    .with(GraphSchemaBean::custom_finalize_all_objects,
                            Optional.ofNullable(graph_schema.custom_finalize_all_objects()).orElse(false))
                    .with(GraphSchemaBean::deduplication_fields,
                            Optional.ofNullable(graph_schema.deduplication_fields())
                                    .orElse(Arrays.asList(GraphAnnotationBean.name, GraphAnnotationBean.type)))
                    .done());

    // Get the Titan graph

    _service_context.set(context.getServiceContext());
    _logger.set(context.getLogger(Optional.of(bucket)));
    _security_context.set(Tuples._2T(bucket.owner_id(), _service_context.get().getSecurityService()));
    _bucket.set(bucket);
    _mutable_stats.set(new MutableStatsBean());

    _service_context.get().getService(IGraphService.class, Optional.ofNullable(graph_schema.service_name()))
            .flatMap(graph_service -> graph_service.getUnderlyingPlatformDriver(TitanGraph.class,
                    Optional.empty()))
            .ifPresent(titan -> _titan.set(titan));
    ;

    // Set up decomposition enrichment

    final Optional<EnrichmentControlMetadataBean> custom_decomp_config = Optionals
            .ofNullable(graph_schema.custom_decomposition_configs()).stream().findFirst();
    custom_decomp_config.ifPresent(cfg -> {
        final Optional<String> entry_point = Optional.ofNullable(cfg.entry_point()).map(Optional::of)
                .orElseGet(() -> {
                    // Get the shared library bean:

                    return BucketUtils
                            .getBatchEntryPoint(context.getServiceContext().getCoreManagementDbService()
                                    .readOnlyVersion().getSharedLibraryStore()
                                    .getObjectBySpec(CrudUtils.anyOf(SharedLibraryBean.class)
                                            .when(SharedLibraryBean::_id, cfg.module_name_or_id()).when(
                                                    SharedLibraryBean::path_name, cfg.module_name_or_id()))
                                    .join()
                                    .map(bean -> (Map<String, SharedLibraryBean>) ImmutableMap
                                            .of(cfg.module_name_or_id(), bean))
                                    .orElse(Collections.<String, SharedLibraryBean>emptyMap()), cfg);
                });

        entry_point.ifPresent(
                Lambdas.wrap_consumer_u(ep -> _custom_graph_decomp_handler.set((IEnrichmentBatchModule) Class
                        .forName(ep, true, Thread.currentThread().getContextClassLoader()).newInstance())));

        _custom_graph_decomp_context.set(new GraphDecompEnrichmentContext(context, _config.get()));

        _custom_graph_decomp_handler.optional()
                .ifPresent(base_module -> base_module.onStageInitialize(_custom_graph_decomp_context.get(),
                        bucket, cfg, previous_next, next_grouping_fields));
    });

    // Set up merging enrichment

    final Optional<EnrichmentControlMetadataBean> custom_merge_config = Optionals
            .ofNullable(graph_schema.custom_merge_configs()).stream().findFirst();
    custom_merge_config.ifPresent(cfg -> {
        final Optional<String> entry_point = Optional.ofNullable(cfg.entry_point()).map(Optional::of)
                .orElseGet(() -> {
                    // Get the shared library bean:

                    return BucketUtils
                            .getBatchEntryPoint(context.getServiceContext().getCoreManagementDbService()
                                    .readOnlyVersion().getSharedLibraryStore()
                                    .getObjectBySpec(CrudUtils.anyOf(SharedLibraryBean.class)
                                            .when(SharedLibraryBean::_id, cfg.module_name_or_id()).when(
                                                    SharedLibraryBean::path_name, cfg.module_name_or_id()))
                                    .join()
                                    .map(bean -> (Map<String, SharedLibraryBean>) ImmutableMap
                                            .of(cfg.module_name_or_id(), bean))
                                    .orElse(Collections.<String, SharedLibraryBean>emptyMap()), cfg);
                });

        entry_point.ifPresent(
                Lambdas.wrap_consumer_u(ep -> _custom_graph_merge_handler.set((IEnrichmentBatchModule) Class
                        .forName(ep, true, Thread.currentThread().getContextClassLoader()).newInstance())));

        _custom_graph_merge_context.set(new GraphMergeEnrichmentContext(context, _config.get()));

        _custom_graph_merge_handler.optional()
                .ifPresent(base_module -> base_module.onStageInitialize(_custom_graph_merge_context.get(),
                        bucket, cfg, previous_next, next_grouping_fields));
    });
}

From source file:alfio.util.TemplateResource.java

public static Map<String, Object> prepareModelForConfirmationEmail(Organization organization, Event event,
        TicketReservation reservation, Optional<String> vat, List<Ticket> tickets, OrderSummary orderSummary,
        String reservationUrl, String reservationShortID, Optional<String> invoiceAddress,
        Optional<String> bankAccountNr, Optional<String> bankAccountOwner) {
    Map<String, Object> model = new HashMap<>();
    model.put("organization", organization);
    model.put("event", event);
    model.put("ticketReservation", reservation);
    model.put("hasVat", vat.isPresent());
    model.put("vatNr", vat.orElse(""));
    model.put("tickets", tickets);
    model.put("orderSummary", orderSummary);
    model.put("reservationUrl", reservationUrl);
    model.put("locale", reservation.getUserLanguage());

    ZonedDateTime confirmationTimestamp = Optional.ofNullable(reservation.getConfirmationTimestamp())
            .orElseGet(ZonedDateTime::now);
    model.put("confirmationDate", confirmationTimestamp.withZoneSameInstant(event.getZoneId()));

    if (reservation.getValidity() != null) {
        model.put("expirationDate",
                ZonedDateTime.ofInstant(reservation.getValidity().toInstant(), event.getZoneId()));
    }/* w w  w .j  a  v  a  2 s  .  co  m*/

    model.put("reservationShortID", reservationShortID);

    model.put("hasInvoiceAddress", invoiceAddress.isPresent());
    invoiceAddress.ifPresent(addr -> {
        model.put("invoiceAddress", StringUtils.replace(addr, "\n", ", "));
        model.put("invoiceAddressAsList", Arrays.asList(StringUtils.split(addr, '\n')));
    });

    model.put("hasBankAccountNr", bankAccountNr.isPresent());
    bankAccountNr.ifPresent(nr -> {
        model.put("bankAccountNr", nr);
    });

    model.put("isOfflinePayment",
            reservation.getStatus() == TicketReservation.TicketReservationStatus.OFFLINE_PAYMENT);
    model.put("paymentReason", event.getShortName() + " " + reservationShortID);
    model.put("hasBankAccountOnwer", bankAccountOwner.isPresent());
    bankAccountOwner.ifPresent(owner -> {
        model.put("bankAccountOnwer", StringUtils.replace(owner, "\n", ", "));
        model.put("bankAccountOnwerAsList", Arrays.asList(StringUtils.split(owner, '\n')));
    });

    return model;
}

From source file:natalia.dymnikova.cluster.scheduler.impl.OutSubscriberFactory.java

public SubscriberWithMore getOutSubscriber(final Optional<ActorSelection> nextActor, final ActorRef parent,
        final ActorRef self, final long onStartCount) {
    return new SubscriberWithMore() {
        @Override/*from   w ww.j  av  a  2 s. com*/
        public void onStart() {
            request(onStartCount);
        }

        @Override
        public void onCompleted() {
            onCompleted.accept(Pair.apply(nextActor, parent), self);
        }

        @Override
        public void onError(final Throwable e) {
            self.tell(new HandleException(e), self);
        }

        @Override
        public void onNext(final Serializable serializable) {
            nextActor.ifPresent(actor -> actor
                    .tell(Flow.Data.newBuilder().setData(wrap(codec.packObject(serializable))).build(), self));
        }
    };
}

From source file:com.github.larsq.spring.embeddedamqp.SimpleAmqpMessageContainer.java

void route(Queue queue, Message message) throws IOException {
    LOG.debug("route message {} to queue {}", message.getEnvelope(), queue);

    String defaultTag = String.join(".", SYSTEM, queue.getName());

    SuppressedThrowable<IOException> suppressed = SuppressedThrowable.wrap(IOException.class);

    Queue key = queue(queue.getName()).orElseThrow(Exception.queueNotFound(queue.getName()));

    List<AbstractSubscription<Consumer>> list = consumers.get(key);

    LOG.debug("found {} consumers", list.size());

    Optional<QueueingConsumer> queueingConsumer = subscription(String.join(".", SYSTEM, queue.getName()))
            .filter(untyped(instanceOf(QueueingConsumer.class))).map(c -> (QueueingConsumer) c);

    queueingConsumer.ifPresent(c -> c.setEnabled(list.size() == 1));

    LOG.debug("found queue: {}", queueingConsumer.isPresent());

    list.forEach(Unchecked.consumer(s -> s.onMessage(message), suppressed));

    suppressed.check();/* w w  w. j a  v  a  2  s  .  com*/
}

From source file:com.microsoft.azure.hdinsight.spark.common.SparkSubmitModel.java

public Single<Artifact> buildArtifactObservable(@NotNull String artifactName) {
    Optional<JobStatusManager> jsmOpt = Optional.ofNullable(HDInsightUtil.getJobStatusManager(project));

    return Single.fromEmitter(em -> {
        jsmOpt.ifPresent((jsm) -> jsm.setJobRunningState(true));
        postEventAction();//from   w w  w .ja va 2  s. c o  m

        if (isLocalArtifact()) {
            em.onError(new NotSupportExecption());
            return;
        }

        final Artifact artifact = artifactHashMap.get(artifactName);
        final List<Artifact> artifacts = Collections.singletonList(artifact);

        ArtifactsWorkspaceSettings.getInstance(project).setArtifactsToBuild(artifacts);
        ApplicationManager.getApplication().invokeAndWait(() -> {
            final CompileScope scope = ArtifactCompileScope.createArtifactsScope(project, artifacts, true);

            CompilerManager.getInstance(project).make(scope, (aborted, errors, warnings, compileContext) -> {
                if (aborted || errors != 0) {
                    showCompilerErrorMessage(compileContext);
                    jsmOpt.ifPresent((jsm) -> jsm.setJobRunningState(false));
                    String errorMessage = StringUtils
                            .join(compileContext.getMessages(CompilerMessageCategory.ERROR), "\\n");

                    postEventProperty.put("IsSubmitSucceed", "false");
                    postEventProperty.put("SubmitFailedReason", errorMessage.substring(0, 50));

                    AppInsightsClient.create(HDInsightBundle.message("SparkProjectDebugCompileFailed"), null,
                            postEventProperty);

                    em.onError(new CompilationException(errorMessage));
                } else {
                    postEventProperty.put("IsSubmitSucceed", "true");
                    postEventProperty.put("SubmitFailedReason", "CompileSuccess");

                    AppInsightsClient.create(HDInsightBundle.message("SparkProjectDebugCompileSuccess"), null,
                            postEventProperty);

                    HDInsightUtil.showInfoOnSubmissionMessageWindow(project,
                            String.format("Info : Build %s successfully.", artifact.getOutputFile()));

                    em.onSuccess(artifact);
                }
            });
        }, ModalityState.defaultModalityState());
    });
}