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.openwms.tms.state.Starter.java

/**
 * Handle an application event./*from   w w  w  .j  a v  a  2  s.co  m*/
 *
 * @param event the event to respond to
 */
@Override
public void onApplicationEvent(TransportServiceEvent event) {
    switch (event.getType()) {
    case INITIALIZED:
    case TRANSPORT_FINISHED:
    case TRANSPORT_ONFAILURE:
    case TRANSPORT_CANCELED:
    case TRANSPORT_INTERRUPTED:

        final TransportOrder to = repository.findOne((Long) event.getSource());
        //                List<TransportOrder> transportOrders = repository.findByTransportUnitBKAndStates(to.getTransportUnitBK(), TransportOrderState.CREATED);
        LOGGER.debug("> Request to start the TransportOrder with PKey [{}]", to.getPersistentKey());
        Optional<LocationGroup> lg = commonGateway.getLocationGroup(to.getTargetLocationGroup());
        Optional<Location> loc = commonGateway.getLocation(to.getTargetLocation());
        if (!lg.isPresent() && !loc.isPresent()) {
            // At least one target must be set
            throw new NotFoundException(
                    "Neither a valid target LocationGroup nor a Location are set, hence it is not possible to start the TransportOrder");
        }
        lg.ifPresent(l -> {
            if (l.isInfeedBlocked())
                throw new StateChangeException(
                        "Cannot start the TransportOrder because TargetLocationGroup is blocked");
        });
        loc.ifPresent(l -> {
            if (l.isInfeedBlocked())
                throw new StateChangeException(
                        "Cannot start the TransportOrder because TargetLocation is blocked");
        });
        lg.ifPresent(l -> to.setTargetLocationGroup(l.toString()));
        loc.ifPresent(l -> to.setTargetLocation(l.toString()));

        List<TransportOrder> others = repository.findByTransportUnitBKAndStates(to.getTransportUnitBK(),
                TransportOrderState.STARTED);
        if (!others.isEmpty()) {
            throw new StateChangeException("Cannot start TransportOrder for TransportUnit ["
                    + to.getTransportUnitBK() + "] because " + others.size()
                    + " TransportOrders already started [" + others.get(0).getPersistentKey() + "]");
        }
        to.changeState(TransportOrderState.STARTED);
        repository.save(to);
        LOGGER.info("TransportOrder for TransportUnit with Barcode {} STARTED at {}. Persisted key is {}",
                to.getTransportUnitBK(), to.getStartDate(), to.getPk());
        break;
    }
}

From source file:io.neba.core.resourcemodels.registration.ModelRegistryConsolePlugin.java

private void spoolComponentIcon(HttpServletResponse response, String suffix) throws IOException {
    response.setContentType("image/png");
    String iconPath = suffix.substring(API_COMPONENTICON.length());

    if (iconPath.isEmpty()) {
        streamDefaultIcon(response);//from w  w w.  j a v  a2s .  c o m
        return;
    }

    Optional<ResourceResolver> resolver = getResourceResolver();

    if (!resolver.isPresent()) {
        streamDefaultIcon(response);
        return;
    }

    resolver.ifPresent(r -> {
        InputStream in = null;
        try {
            Resource componentIcon = r.getResource(iconPath + "/icon.png");
            if (componentIcon != null) {
                in = componentIcon.adaptTo(InputStream.class);
                if (in != null) {
                    copy(in, response.getOutputStream());
                }
            }
        } catch (IOException e) {
            throw new IllegalStateException(e);
        } finally {
            r.close();
            closeQuietly(in);
        }
    });
}

From source file:com.qpark.eip.core.model.analysis.AnalysisDao.java

/**
 * Get the {@link FieldMappingType} with the id.
 *
 * @param modelVersion/*from   w  w  w  .j  a v  a2  s .c  o  m*/
 *            the model version.
 * @param id
 *            the id to return.
 * @return the {@link FieldMappingType}.
 * @since 3.5.1
 */
@Transactional(value = EipModelAnalysisPersistenceConfig.TRANSACTION_MANAGER_NAME, propagation = Propagation.REQUIRED)
public Optional<FieldMappingType> getFieldMappingTypeById(final String modelVersion, final String id) {
    final CriteriaBuilder cb = this.em.getCriteriaBuilder();
    final CriteriaQuery<FieldMappingType> q = cb.createQuery(FieldMappingType.class);
    final Root<FieldMappingType> f = q.from(FieldMappingType.class);
    q.where(cb.equal(f.<String>get(FieldMappingType_.modelVersion), modelVersion),
            cb.equal(f.<String>get(FieldMappingType_.id), id));
    final TypedQuery<FieldMappingType> typedQuery = this.em.createQuery(q);
    final List<FieldMappingType> list = typedQuery.getResultList();

    final Optional<FieldMappingType> value = list.stream().findFirst();
    value.ifPresent(ct -> EagerLoader.load(ct));
    return value;
}

From source file:ddf.catalog.impl.operations.OperationsCrudSupport.java

void commitAndCleanup(StorageRequest storageRequest, Optional<String> historianTransactionKey,
        HashMap<String, Path> tmpContentPaths) {
    if (storageRequest != null) {
        try {//w ww .  j  av a 2 s .c om
            sourceOperations.getStorage().commit(storageRequest);
            historianTransactionKey.ifPresent(historian::commit);
        } catch (StorageException e) {
            LOGGER.error("Unable to commit content changes for id: {}", storageRequest.getId(), e);
            try {
                sourceOperations.getStorage().rollback(storageRequest);
            } catch (StorageException e1) {
                LOGGER.error("Unable to remove temporary content for id: {}", storageRequest.getId(), e1);
            } finally {
                try {
                    historianTransactionKey.ifPresent(historian::rollback);
                } catch (RuntimeException re) {
                    LOGGER.error("Unable to commit versioned items for historian transaction: {}",
                            historianTransactionKey.orElseGet(String::new), re);
                }
            }
        }
    }

    tmpContentPaths.values().forEach(path -> FileUtils.deleteQuietly(path.toFile()));
    tmpContentPaths.clear();

}

From source file:org.jboss.pnc.buildagent.client.BuildAgentClient.java

private void registerBinaryResponseConsumer(Optional<Consumer<String>> responseDataConsumer, Client client) {
    Consumer<byte[]> responseConsumer = (bytes) -> {
        String responseData = new String(bytes);
        if ("% ".equals(responseData)) {
            log.info("Binary consumer received command line 'ready'(%) marker.");
            onCommandPromptReady();/*  w  w w  .j a  v a 2s .c o m*/
        } else {
            responseDataConsumer.ifPresent((rdc) -> rdc.accept(responseData));
            ;
        }
    };
    client.onBinaryMessage(responseConsumer);
}

From source file:alfio.controller.api.support.TicketHelper.java

/**
 * This method has been implemented explicitly for PayPal, since we need to pre-assign tickets before payment, in order to keep the data inserted by the customer
 *///from   w  ww  . j  a  v  a  2  s .c o m
public Optional<Triple<ValidationResult, Event, Ticket>> preAssignTicket(String eventName, String reservationId,
        String ticketIdentifier, UpdateTicketOwnerForm updateTicketOwner, Optional<Errors> bindingResult,
        HttpServletRequest request, Consumer<Triple<ValidationResult, Event, Ticket>> reservationConsumer,
        Optional<UserDetails> userDetails) {

    Optional<Triple<ValidationResult, Event, Ticket>> triple = ticketReservationManager
            .from(eventName, reservationId, ticketIdentifier)
            .filter(temp -> PENDING_RESERVATION_STATUSES.contains(temp.getMiddle().getStatus())
                    && temp.getRight().getStatus() == Ticket.TicketStatus.PENDING)
            .map(result -> assignTicket(updateTicketOwner, bindingResult, request, userDetails, result));
    triple.ifPresent(reservationConsumer);
    return triple;
}

From source file:at.medevit.elexis.emediplan.core.internal.EMediplanServiceImpl.java

@Override
public void exportEMediplanPdf(Mandant author, Patient patient, List<Prescription> prescriptions,
        OutputStream output) {/*from  w w w . j  a va2s .c o m*/
    if (prescriptions != null && !prescriptions.isEmpty() && output != null) {
        Optional<String> jsonString = getJsonString(author, patient, prescriptions);
        Optional<Image> qrCode = jsonString.map(json -> getQrCode(json)).orElse(Optional.empty());

        Optional<at.medevit.elexis.emediplan.core.model.print.Medication> jaxbModel = getJaxbModel(author,
                patient, prescriptions);
        jaxbModel.ifPresent(model -> {
            createPdf(qrCode, model, output);
        });
    }
}

From source file:com.twosigma.beakerx.kernel.magic.command.ClasspathAddMvnDepsMagicCommandTest.java

private void handleClasspathAddMvnDep(String allCode, String expected) throws Exception {
    MagicCommand command = new MagicCommand(
            new ClasspathAddMvnMagicCommand(configuration.mavenResolverParam(kernel), kernel), allCode);
    Code code = Code.createCode(allCode, singletonList(command), NO_ERRORS,
            new Message(new Header(JupyterMessages.COMM_MSG, "session1")));
    //when/*from w w w .j  a va  2s .  com*/
    code.execute(kernel, 1);
    //then
    Optional<Message> updateMessage = EvaluatorResultTestWatcher.waitForUpdateMessage(kernel);
    String text = (String) TestWidgetUtils.getState(updateMessage.get()).get("value");
    assertThat(text).contains(expected);
    String mvnDir = kernel.getTempFolder().toString() + MavenJarResolver.MVN_DIR;
    Stream<Path> paths = Files.walk(Paths.get(mvnDir));
    Optional<Path> dep = paths.filter(file -> (file.getFileName().toFile().getName().contains("gson")
            || file.getFileName().toFile().getName().contains("slf4j"))).findFirst();
    assertThat(dep).isPresent();
    assertThat(kernel.getClasspath().get(0)).contains(mvnDir);
    assertThat(Files.exists(Paths.get(configuration.mavenResolverParam(kernel).getPathToNotebookJars()
            + File.separator + MAVEN_BUILT_CLASSPATH_FILE_NAME))).isTrue();
    dep.ifPresent(path -> {
        try {
            FileUtils.forceDelete(path.toFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

From source file:com.netflix.genie.web.jpa.services.JpaJobPersistenceServiceImpl.java

private void setJobMetadataFields(final JobEntity jobEntity, final JobMetadata jobMetadata) {
    // Required fields
    jobEntity.setName(jobMetadata.getName());
    jobEntity.setUser(jobMetadata.getUser());
    jobEntity.setVersion(jobMetadata.getVersion());

    // Optional fields
    jobEntity.setTags(this.createAndGetTagEntities(jobMetadata.getTags()));

    final Optional<JsonNode> jsonMetadata = jobMetadata.getMetadata();
    jsonMetadata.ifPresent(jsonNode -> EntityDtoConverters.setJsonField(jsonNode, jobEntity::setMetadata));
    jobMetadata.getDescription().ifPresent(jobEntity::setDescription);
    jobMetadata.getEmail().ifPresent(jobEntity::setEmail);
    jobMetadata.getGroup().ifPresent(jobEntity::setGenieUserGroup);
    jobMetadata.getGrouping().ifPresent(jobEntity::setGrouping);
    jobMetadata.getGroupingInstance().ifPresent(jobEntity::setGroupingInstance);
}

From source file:com.epam.catgenome.manager.BiologicalDataItemManager.java

private String makeUrl(List<BiologicalDataItem> items, Project project, Reference reference,
        String chromosomeName, Integer startIndex, Integer endIndex) throws JsonProcessingException {
    String indexes;/*from  w  w w .jav a2 s .c om*/
    if (startIndex != null && endIndex != null && chromosomeName != null) {
        Map<String, Object> params = new HashMap<>();
        params.put("START_INDEX", startIndex);
        params.put("END_INDEX", endIndex);

        indexes = new StrSubstitutor(params).replace(INDEXES_PATTERN);
    } else {
        indexes = "";
    }

    Map<String, String> params = new HashMap<>();
    params.put("REFERENCE_NAME", reference.getName());
    params.put("INDEXES", indexes);

    if (chromosomeName != null) {
        Optional<Chromosome> chromosomeOpt = reference.getChromosomes().stream()
                .filter(c -> c.getName().equalsIgnoreCase(chromosomeName)
                        || c.getName().equals(Utils.changeChromosomeName(chromosomeName)))
                .findFirst();
        Assert.isTrue(chromosomeOpt.isPresent(),
                getMessage(MessagesConstants.ERROR_CHROMOSOME_NAME_NOT_FOUND, chromosomeName));

        chromosomeOpt.ifPresent(chromosome -> params.put("CHROMOSOME_NAME", "/" + chromosome.getName()));
    } else {
        params.put("CHROMOSOME_NAME", "");
    }

    List<TrackVO> vos;
    if (items.isEmpty()) {
        vos = new ArrayList<>();
        TrackVO vo = new TrackVO();
        vo.setP(project.getName());
        vos.add(vo);
    } else {
        vos = items.stream().map(item -> new TrackVO(item.getName(), project.getName()))
                .collect(Collectors.toList());
    }

    JsonMapper mapper = new JsonMapper();
    params.put("TRACKS", mapper.writeValueAsString(vos));

    return new StrSubstitutor(params).replace(URL_PATTERN);
}