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:videoshop.controller.CartController.java

/**
 * Checks out the current state of the {@link Cart}. Using a method parameter of type {@code Optional<UserAccount>}
 * annotated with {@link LoggedIn} you can access the {@link UserAccount} of the currently logged in user.
 * //  ww  w  . j  av a 2 s  .co m
 * @param session must not be {@literal null}.
 * @param userAccount must not be {@literal null}.
 * @return
 */
@RequestMapping(value = "/checkout", method = RequestMethod.POST)
public String buy(@ModelAttribute Cart cart, @LoggedIn Optional<UserAccount> userAccount) {

    return userAccount.map(account -> {

        // ()
        // Mit commit wird der Warenkorb in die Order berfhrt, diese wird dann bezahlt und abgeschlossen.
        // Orders knnen nur abgeschlossen werden, wenn diese vorher bezahlt wurden.
        Order order = new Order(account, Cash.CASH);

        cart.addItemsTo(order);

        orderManager.payOrder(order);
        orderManager.completeOrder(order);

        cart.clear();

        return "redirect:/";
    }).orElse("redirect:/cart");
}

From source file:videoshop.controller.CatalogController.java

@RequestMapping("/detail/{pid}")
public String detail(@PathVariable("pid") Disc disc, Model model) {

    Optional<InventoryItem> item = inventory.findByProductIdentifier(disc.getIdentifier());
    Quantity quantity = item.map(InventoryItem::getQuantity).orElse(NONE);

    model.addAttribute("disc", disc);
    model.addAttribute("quantity", quantity);
    model.addAttribute("orderable", quantity.isGreaterThan(NONE));

    return "detail";
}

From source file:com.ikanow.aleph2.distributed_services.utils.KafkaUtils.java

/**
 * Checks if a topic exists, if not creates a new kafka queue for it.
 * /*from   w  w  w .  j a  va  2  s  .co  m*/
 * After creating a new topic, waits to see if a leader gets elected (it always seems to fail),
 * then creates a consumer as a hack to get a leader elected and the offset set correctly.
 * 
 * I haven't found a way to create a topic and then immediately be able to produce on it without
 * crashing a consumer first.  This is horrible.
 * 
 * @param topic
 */
public synchronized static void createTopic(String topic, Optional<Map<String, Object>> options,
        final ZkUtils zk_client1) {

    //TODO (ALEPH-10): need to handle topics getting deleted but not being removed from this map
    //TODO (ALEPH-10): override options if they change? not sure if that's possible 

    if (!my_topics.containsKey(topic)) {
        logger.debug("CREATE TOPIC");
        //http://stackoverflow.com/questions/27036923/how-to-create-a-topic-in-kafka-through-java

        // For some reason need to create a new zk_client in here for the createTopic call, otherwise the partitions aren't set correctly?!
        final ZkUtils zk_client = getNewZkClient();

        try {
            if (!AdminUtils.topicExists(zk_client, topic)) {
                final Properties props = options.map(o -> {
                    final Properties p = new Properties();
                    p.putAll(o);
                    return p;
                }).orElse(new Properties());
                AdminUtils.createTopic(zk_client, topic, 1, 1, props);
                boolean leader_elected = waitUntilLeaderElected(zk_client, topic, 1000);
                logger.debug("LEADER WAS ELECTED: " + leader_elected);

                //create a consumer to fix offsets (this is a hack, idk why it doesn't work until we create a consumer)
                WrappedConsumerIterator iter = new WrappedConsumerIterator(
                        getKafkaConsumer(topic, Optional.empty()), topic, 1);
                iter.hasNext();

                //debug info
                if (logger.isDebugEnabled()) {
                    logger.error("DONE CREATING TOPIC");
                    //(this was removed in 0.9):
                    //logger.debug(AdminUtils.fetchTopicConfig(zk_client, topic).toString());
                    TopicMetadata meta = AdminUtils.fetchTopicMetadataFromZk(topic, zk_client);
                    logger.error("META: " + meta);
                }

                // (close resources)
                iter.close();
            }
        } finally {
            zk_client.close();
        }
        my_topics.put(topic, true); //topic either already existed or was created
    }
}

From source file:com.github.horrorho.inflatabledonkey.protobuf.util.ProtobufParser.java

T protocParse(InputStream input, ProtocRawDecoder decoder) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOUtils.copy(input, baos);//  ww w.  j a  v a  2  s  . c o  m

    Optional<String> rawProtos = decoder.decode(new ByteArrayInputStream(baos.toByteArray()));
    logger.debug("-- protocParse() - raw decode: {}", rawProtos.map(Object::toString).orElse("error"));

    return parse(new ByteArrayInputStream(baos.toByteArray()));
}

From source file:org.apache.ambari.view.web.service.PackageScannerServiceImpl.java

@Override
public Optional<Date> getLastScannedTimestamp(String repoName) {
    Optional<Registry> registryOptional = registryRepository.findByName(repoName);
    return registryOptional.map(Registry::getLastScannedAt);
}

From source file:fi.helsinki.opintoni.service.UserSettingsService.java

public BufferedImage getUserAvatarImageByOodiPersonId(String oodiPersonId) {
    Optional<User> user = userRepository.findByOodiPersonId(oodiPersonId);
    return user.map(u -> u.id).map(this::getUserAvatarImage)
            .orElseThrow(notFoundException("Avatar not found for user"));
}

From source file:org.apache.ambari.view.internal.actor.repository.Scanner.java

private void scan() {
    log().info("Scanning URL '{}' for new packages.", url);

    Optional<Date> lastScannedTs = packageService.getLastScannedTimestamp(name);
    Long lastScanned = lastScannedTs.map(Date::getTime).orElse(0L);

    URI uri = null;//from  w w w.  j  a  v  a 2  s.c  om

    try {
        URIBuilder builder = new URIBuilder(url);
        builder.addParameter("after", String.valueOf(lastScanned));
        uri = builder.build();
    } catch (URISyntaxException e) {
        throw new RestClientException("URL Syntax error", e);
    }

    ApplicationsWrapper wrapper = ws.getForObject(uri, ApplicationsWrapper.class);
    packageService.updateApplications(wrapper.getApplications(), name);

    // Do Something
    scheduleRescanMessage();
}

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

private Optional<String> getCurrentCursor() {
    final Optional<StellarCursorPersistency> cursorPersistency = stellarCursorRepository
            .findTopByProcessedTrueOrderByCreatedOnDesc();

    return cursorPersistency.map(StellarCursorPersistency::getCursor);
}

From source file:fi.helsinki.opintoni.service.portfolio.PortfolioService.java

private PortfolioDto convertPortfolioToDto(Optional<Portfolio> portfolioOptional,
        PortfolioConverter.ComponentFetchStrategy componentFetchStrategy) {
    return portfolioOptional.map((portfolio) -> portfolioConverter.toDto(portfolio, componentFetchStrategy))
            .orElseThrow(notFoundException("Portfolio not found"));
}

From source file:alfio.controller.DynamicResourcesController.java

@RequestMapping("/resources/js/google-analytics")
public void getGoogleAnalyticsScript(HttpSession session, HttpServletResponse response,
        @RequestParam("e") Integer eventId) throws IOException {
    response.setContentType("application/javascript");
    Optional<Event> ev = Optional.ofNullable(eventId)
            .flatMap(id -> Optional.ofNullable(eventRepository.findById(id)));
    ConfigurationPathKey pathKey = ev
            .map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_KEY))
            .orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_KEY));
    final Optional<String> id = configurationManager.getStringConfigValue(pathKey);
    final String script;
    ConfigurationPathKey anonymousPathKey = ev
            .map(e -> Configuration.from(e.getOrganizationId(), e.getId(), GOOGLE_ANALYTICS_ANONYMOUS_MODE))
            .orElseGet(() -> Configuration.getSystemConfiguration(GOOGLE_ANALYTICS_ANONYMOUS_MODE));
    if (id.isPresent() && configurationManager.getBooleanConfigValue(anonymousPathKey, true)) {
        String trackingId = Optional
                .ofNullable(StringUtils.trimToNull((String) session.getAttribute("GA_TRACKING_ID")))
                .orElseGet(() -> UUID.randomUUID().toString());
        Map<String, Object> model = new HashMap<>();
        model.put("clientId", trackingId);
        model.put("account", id.get());
        script = templateManager.renderTemplate(TemplateResource.GOOGLE_ANALYTICS, model, Locale.ENGLISH);
    } else {//ww  w. j  a  v  a 2 s .  com
        script = id.map(x -> String.format(GOOGLE_ANALYTICS_SCRIPT, x)).orElse(EMPTY);
    }
    response.getWriter().write(script);
}