Example usage for java.util Optional map

List of usage examples for java.util Optional map

Introduction

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

Prototype

public <U> Optional<U> map(Function<? super T, ? extends U> mapper) 

Source Link

Document

If a value is present, returns an Optional describing (as if by #ofNullable ) the result of applying the given mapping function to the value, otherwise returns an empty Optional .

Usage

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/failure", method = RequestMethod.GET)
public String showFailurePage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        @RequestParam(value = "confirmation-email-sent", required = false, defaultValue = "false") boolean confirmationEmailSent,
        @RequestParam(value = "ticket-email-sent", required = false, defaultValue = "false") boolean ticketEmailSent,
        Model model) {//from w  w w .j  a v  a 2 s. com
    Optional<Event> event = eventRepository.findOptionalByShortName(eventName);
    if (!event.isPresent()) {
        return "redirect:/";
    }

    Optional<TicketReservation> reservation = ticketReservationManager.findById(reservationId);
    Optional<TicketReservationStatus> status = reservation.map(TicketReservation::getStatus);

    if (!status.isPresent()) {
        return redirectReservation(reservation, eventName, reservationId);
    }

    TicketReservationStatus ticketReservationStatus = status.get();
    if (ticketReservationStatus == TicketReservationStatus.IN_PAYMENT
            || ticketReservationStatus == TicketReservationStatus.STUCK) {
        model.addAttribute("reservation", reservation.get());
        model.addAttribute("organizer", organizationRepository.getById(event.get().getOrganizationId()));
        model.addAttribute("pageTitle", "reservation-page-error-status.header.title");
        model.addAttribute("event", event.get());
        return "/event/reservation-page-error-status";
    }

    return redirectReservation(reservation, eventName, reservationId);
}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/waitingPayment", method = RequestMethod.GET)
public String showWaitingPaymentPage(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId, Model model, Locale locale) {

    Optional<Event> event = eventRepository.findOptionalByShortName(eventName);
    if (!event.isPresent()) {
        return "redirect:/";
    }//from  ww  w .j  av a2 s .  c  om

    Optional<TicketReservation> reservation = ticketReservationManager.findById(reservationId);
    TicketReservationStatus status = reservation.map(TicketReservation::getStatus)
            .orElse(TicketReservationStatus.PENDING);
    if (reservation.isPresent() && status == TicketReservationStatus.OFFLINE_PAYMENT) {
        Event ev = event.get();
        TicketReservation ticketReservation = reservation.get();
        OrderSummary orderSummary = ticketReservationManager.orderSummaryForReservationId(reservationId, ev,
                locale);
        model.addAttribute("totalPrice", orderSummary.getTotalPrice());
        model.addAttribute("emailAddress", organizationRepository.getById(ev.getOrganizationId()).getEmail());
        model.addAttribute("reservation", ticketReservation);
        model.addAttribute("paymentReason",
                ev.getShortName() + " " + ticketReservationManager.getShortReservationID(ev, reservationId));
        model.addAttribute("pageTitle", "reservation-page-waiting.header.title");
        model.addAttribute("bankAccount",
                configurationManager
                        .getStringConfigValue(
                                Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_NR))
                        .orElse(""));

        Optional<String> maybeAccountOwner = configurationManager.getStringConfigValue(
                Configuration.from(ev.getOrganizationId(), ev.getId(), BANK_ACCOUNT_OWNER));
        model.addAttribute("hasBankAccountOwnerSet", maybeAccountOwner.isPresent());
        model.addAttribute("bankAccountOwner", Arrays.asList(maybeAccountOwner.orElse("").split("\n")));

        model.addAttribute("expires",
                ZonedDateTime.ofInstant(ticketReservation.getValidity().toInstant(), ev.getZoneId()));
        model.addAttribute("event", ev);
        return "/event/reservation-waiting-for-payment";
    }

    return redirectReservation(reservation, eventName, reservationId);
}

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

@Override
public boolean isAutoreload(String haproxyId) {
    Optional<String> autoreload = getHaproxyProperty(haproxyId, "autoreload");
    return autoreload.map(Boolean::valueOf).orElse(false);
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.MongoDbManagementDbService.java

@Override
public ICrudService<AssetStateDirectoryBean> getStateDirectory(final Optional<DataBucketBean> bucket_filter,
        final Optional<StateDirectoryType> type_filter) {
    final Optional<QueryComponent<AssetStateDirectoryBean>> extra_terms = Optional
            .of(bucket_filter
                    .map(bf -> CrudUtils.allOf(AssetStateDirectoryBean.class)
                            .when(AssetStateDirectoryBean::asset_path, bf.full_name()))
                    .orElse(CrudUtils.allOf(AssetStateDirectoryBean.class)))
            .map(bfq -> type_filter.map(tf -> bfq.when(AssetStateDirectoryBean::state_type, tf)).orElse(bfq))
            .filter(q -> !q.getAll().isEmpty()).map(bfq -> (QueryComponent<AssetStateDirectoryBean>) bfq);

    final ICrudService<AssetStateDirectoryBean> raw_state_crud = Lambdas.get(() -> {
        synchronized (this) {
            if (!_optimized_state_directory.isSet()) {
                final ICrudService<AssetStateDirectoryBean> raw_state_crud_internal = (ICrudService<AssetStateDirectoryBean>) _crud_factory
                        .getMongoDbCrudService(AssetStateDirectoryBean.class, String.class,
                                _crud_factory
                                        .getMongoDbCollection(MongoDbManagementDbService.STATE_DIRECTORY_STORE),
                                Optional.empty(), Optional.empty(), Optional.empty());

                final MethodNamingHelper<AssetStateDirectoryBean> h = BeanTemplateUtils
                        .from(AssetStateDirectoryBean.class);
                raw_state_crud_internal// ww  w  .  j a v a2s.c o m
                        .optimizeQuery(Arrays.asList(h.field(AssetStateDirectoryBean::asset_path),
                                h.field(AssetStateDirectoryBean::state_type)));
                raw_state_crud_internal
                        .optimizeQuery(Arrays.asList(h.field(AssetStateDirectoryBean::state_type)));
                _optimized_state_directory.set(raw_state_crud_internal);
            }
        }
        return _optimized_state_directory.get();
    });

    return extra_terms
            .<ICrudService<AssetStateDirectoryBean>>map(
                    et -> CrudServiceUtils.intercept(AssetStateDirectoryBean.class, raw_state_crud, extra_terms,
                            Optional.empty(), Collections.emptyMap(), Optional.empty()))
            .orElse(raw_state_crud).readOnlyVersion(_read_only);
}

From source file:alfio.manager.support.CustomMessageManager.java

public void sendMessages(String eventName, Optional<Integer> categoryId, List<MessageModification> input,
        String username) {//ww  w .  j  a  va 2s .c  om

    Event event = eventManager.getSingleEvent(eventName, username);
    preview(event, input, username);//dry run for checking the syntax
    Organization organization = eventManager.loadOrganizer(event, username);
    AtomicInteger counter = new AtomicInteger();
    Map<String, List<MessageModification>> byLanguage = input.stream()
            .collect(Collectors.groupingBy(m -> m.getLocale().getLanguage()));

    sendMessagesExecutor.execute(() -> {
        categoryId.map(id -> ticketRepository.findConfirmedByCategoryId(event.getId(), id))
                .orElseGet(() -> ticketRepository.findAllConfirmed(event.getId())).stream()
                .filter(t -> isNotBlank(t.getFullName()) && isNotBlank(t.getEmail())).parallel().map(t -> {
                    Model model = new ExtendedModelMap();
                    model.addAttribute("eventName", eventName);
                    model.addAttribute("fullName", t.getFullName());
                    model.addAttribute("organizationName", organization.getName());
                    model.addAttribute("organizationEmail", organization.getEmail());
                    model.addAttribute("reservationURL",
                            ticketReservationManager.reservationUrl(t.getTicketsReservationId(), event));
                    model.addAttribute("reservationID",
                            ticketReservationManager.getShortReservationID(event, t.getTicketsReservationId()));
                    model.addAttribute("ticketURL",
                            ticketReservationManager.ticketUpdateUrl(event, t.getUuid()));
                    return Triple.of(t, t.getEmail(), model);
                }).forEach(triple -> {
                    Ticket ticket = triple.getLeft();
                    MessageModification m = Optional.ofNullable(byLanguage.get(ticket.getUserLanguage()))
                            .orElseGet(() -> byLanguage.get(byLanguage.keySet().stream().findFirst()
                                    .orElseThrow(IllegalStateException::new)))
                            .get(0);
                    Model model = triple.getRight();
                    String subject = renderResource(m.getSubject(), model, m.getLocale(), templateManager);
                    String text = renderResource(m.getText(), model, m.getLocale(), templateManager);
                    List<Mailer.Attachment> attachments = new ArrayList<>();
                    if (m.isAttachTicket()) {
                        ticketReservationManager.findById(ticket.getTicketsReservationId())
                                .ifPresent(reservation -> {
                                    ticketCategoryRepository.getByIdAndActive(ticket.getCategoryId())
                                            .ifPresent(ticketCategory -> {
                                                attachments.add(generateTicketAttachment(ticket, reservation,
                                                        ticketCategory, organization));
                                            });
                                });
                    }
                    counter.incrementAndGet();
                    notificationManager.sendSimpleEmail(event, triple.getMiddle(), subject, () -> text,
                            attachments);
                });
    });

}

From source file:alfio.controller.ReservationController.java

@RequestMapping(value = "/event/{eventName}/reservation/{reservationId}/ticket/{ticketIdentifier}/assign", method = RequestMethod.POST)
public String assignTicketToPerson(@PathVariable("eventName") String eventName,
        @PathVariable("reservationId") String reservationId,
        @PathVariable("ticketIdentifier") String ticketIdentifier, UpdateTicketOwnerForm updateTicketOwner,
        BindingResult bindingResult, HttpServletRequest request, Model model) throws Exception {

    Optional<Triple<ValidationResult, Event, Ticket>> result = ticketHelper.assignTicket(eventName,
            reservationId, ticketIdentifier, updateTicketOwner, Optional.of(bindingResult), request, model);
    return result.map(t -> "redirect:/event/" + t.getMiddle().getShortName() + "/reservation/"
            + t.getRight().getTicketsReservationId() + "/success").orElse("redirect:/");
}

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

Optional<BlockingQueue<Message>> messages(String queue) {
    Optional<QueueingConsumer> optionalConsumer = subscription(String.join(".", SYSTEM, queue))
            .filter(untyped(instanceOf(QueueingConsumer.class))).map(c -> (QueueingConsumer) c);

    if (!optionalConsumer.isPresent()) {
        return Optional.empty();
    }/*from  ww  w. j  av  a  2  s. c  om*/

    return optionalConsumer.map(QueueingConsumer::getStore);
}

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

private Stream<ConsumerPartitionVO> getConsumerPartitionStream(String groupId, String topicName,
        TopicVO topicOpt) {//from   w  w  w.j a va  2 s .  c om
    ZKGroupTopicDirs groupTopicDirs = new ZKGroupTopicDirs(groupId, topicName);

    if (topicOpt == null || topicOpt.getName().equals(topicName)) {
        topicOpt = getTopic(topicName).orElse(null);
    }

    if (topicOpt != null) {
        final TopicVO topic = topicOpt;

        Map<Integer, Long> consumerOffsets = getConsumerOffsets(groupId, topic);

        return topic.getPartitions().stream().map(partition -> {
            int partitionId = partition.getId();

            final ConsumerPartitionVO consumerPartition = new ConsumerPartitionVO(groupId, topicName,
                    partitionId);
            consumerPartition.setOwner(Optional
                    .ofNullable(consumerTreeCache
                            .getCurrentData(groupTopicDirs.consumerOwnerDir() + "/" + partitionId))
                    .map(data -> new String(data.getData())).orElse(null));

            consumerPartition.setOffset(consumerOffsets.getOrDefault(partitionId, -1L));

            final Optional<TopicPartitionVO> topicPartition = topic.getPartition(partitionId);
            consumerPartition.setSize(topicPartition.map(TopicPartitionVO::getSize).orElse(-1L));
            consumerPartition.setFirstOffset(topicPartition.map(TopicPartitionVO::getFirstOffset).orElse(-1L));

            return consumerPartition;
        });
    } else {
        return Stream.empty();
    }
}

From source file:io.pravega.controller.store.stream.InMemoryStream.java

@Override
CompletableFuture<Integer> getTransactionEpoch(UUID txId) {
    Optional<Integer> epoch;
    synchronized (txnsLock) {
        epoch = epochTxnMap.entrySet().stream().filter(x -> x.getValue().contains(txId.toString())).findFirst()
                .map(Map.Entry::getKey);
    }//  www.  java  2 s  .c o m
    return epoch.map(CompletableFuture::completedFuture).orElseGet(
            () -> FutureHelpers.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND,
                    "Stream: " + getName() + " Transaction: " + txId.toString())));
}

From source file:io.syndesis.controllers.integration.IntegrationController.java

private void checkIntegrationStatus(Integration integration) {
    if (integration == null) {
        return;/*w  w  w. j a  va  2 s. c o m*/
    }
    Optional<Integration.Status> desired = integration.getDesiredStatus();
    Optional<Integration.Status> current = integration.getCurrentStatus();
    if (!current.equals(desired)) {
        desired.ifPresent(desiredStatus -> integration.getId().ifPresent(integrationId -> {
            StatusChangeHandlerProvider.StatusChangeHandler statusChangeHandler = handlers.get(desiredStatus);
            if (statusChangeHandler != null) {
                LOG.info(
                        "Integration {} : Desired status \"{}\" != current status \"{}\" --> calling status change handler",
                        integrationId, desiredStatus.toString(), current.map(Enum::toString).orElse("[none]"));
                callStatusChangeHandler(statusChangeHandler, integrationId);
            }
        }));
    } else {
        // When the desired state is reached remove the marker so that a next change trigger a check again
        // Doesn't harm when no such key exists
        desired.ifPresent(d -> scheduledChecks.remove(getIntegrationMarkerKey(integration)));
    }
}