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:com.ikanow.aleph2.search_service.elasticsearch.services.ElasticsearchIndexService.java

/** Low level utility - grab a stream of JsonNodes of template mappings
 * @param bucket//ww w.j  a  v  a2 s  .  co m
 * @param buffer_name
 * @return
 */
protected static Stream<JsonNode> getMatchingTemplatesWithMeta(final DataBucketBean bucket,
        final Optional<String> buffer_name, Client client) {

    final String base_index = ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.empty());
    final String index_glob = buffer_name
            .map(name -> ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.of(name))).orElseGet(() -> {
                final String random_string = Stream.generate(() -> (long) (Math.random() * 1000000L))
                        .map(l -> Long.toString(l)).filter(s -> !base_index.contains(s)).findAny().get();
                return ElasticsearchIndexUtils.getBaseIndexName(bucket, Optional.of(random_string))
                        .replace(random_string, "*");
            });

    final GetIndexTemplatesRequest gt = new GetIndexTemplatesRequest().names(index_glob);
    final GetIndexTemplatesResponse gtr = client.admin().indices().getTemplates(gt).actionGet();

    // OK for each template, grab the first element's "_meta" (requires converting to a string) and check if it has a secondary buffer
    return gtr.getIndexTemplates().stream().map(index -> index.getMappings()).filter(map -> !map.isEmpty())
            .map(map -> map.valuesIt().next()) // get the first type, will typically be _default_
            .map(comp_string -> new String(comp_string.uncompressed()))
            .flatMap(Lambdas.flatWrap_i(mapstr -> _mapper.readValue(mapstr, JsonNode.class)))
            .map(json -> json.iterator()).filter(json_it -> json_it.hasNext()).map(json_it -> json_it.next())
            .map(json -> json.get(ElasticsearchIndexUtils.CUSTOM_META))
            .filter(json -> (null != json) && json.isObject());
}

From source file:com.epages.checkout.CartController.java

private Cart addLineItemOrIncrementQuantity(Cart cart, AddLineItemRequest addLineItemRequest) {
    Optional<ProductLineItem> existingLineItemForProduct = cart.getLineItems().stream()
            .filter(item -> item.getProduct().getId().equals(addLineItemRequest.getProductId())).findFirst();

    return existingLineItemForProduct.map(item -> {
        item.setQuantity(item.getQuantity() + addLineItemRequest.getQuantity());
        return cart;
    }).orElseGet(() -> {//from   w w w. j a va2 s  .  c om
        ProductRef product = productRefRepository.findOne(addLineItemRequest.getProductId());
        cart.getLineItems().add(
                ProductLineItem.builder().product(product).quantity(addLineItemRequest.getQuantity()).build());
        return cart;
    });
}

From source file:com.teradata.benchto.service.BenchmarkService.java

private ZonedDateTime fromInstantOrCurrentDateTime(Optional<Instant> instant) {
    ZonedDateTime currentDateTime = currentDateTime();
    return instant.map(i -> i.atZone(currentDateTime.getZone())).orElse(currentDateTime);
}

From source file:io.kamax.mxisd.backend.rest.RestThreePidProvider.java

@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    String endpoint = cfg.getEndpoints().getIdentity().getSingle();
    HttpUriRequest req = RestClientUtils.post(endpoint, gson, "lookup",
            new LookupSingleRequestJson(request.getType(), request.getThreePid()));

    try (CloseableHttpResponse res = client.execute(req)) {
        int status = res.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            log.warn("REST endpoint {} answered with status {}, no binding found", endpoint, status);
            return Optional.empty();
        }/*from  w w w  .j  a  v  a2s  .  co m*/

        Optional<LookupSingleResponseJson> responseOpt = parser.parseOptional(res, "lookup",
                LookupSingleResponseJson.class);
        return responseOpt.map(lookupSingleResponseJson -> new SingleLookupReply(request,
                getMxId(lookupSingleResponseJson.getId())));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.jeanchampemont.notedown.utils.UserLocaleResolver.java

@Override
public Locale resolveLocale(HttpServletRequest request) {
    if (SecurityContextHolder.getContext().getAuthentication() == null) {
        return acceptHeaderLocaleResolver.resolveLocale(request);
    }/*  w  w w. j  a v a 2 s.  co m*/
    String email = SecurityContextHolder.getContext().getAuthentication().getName();
    Optional<User> user = userService.getUserByEmail(email);
    if (!user.isPresent() || StringUtils.isEmpty(user.get().getLocale())) {
        return acceptHeaderLocaleResolver.resolveLocale(request);
    }
    return user.map(u -> Locale.forLanguageTag(u.getLocale())).get();
}

From source file:com.spotify.heroic.grammar.CoreQueryParser.java

@Override
public String stringifyQuery(final Query q, Optional<Integer> indent) {
    final String prefix = indent.map(i -> StringUtils.repeat(' ', i)).orElse("");

    final Joiner joiner = indent.map(i -> Joiner.on("\n" + prefix)).orElseGet(() -> Joiner.on(" "));

    final List<String> parts = new ArrayList<>();

    parts.add(q.getAggregation().map(Aggregation::toDSL).orElse("*"));

    q.getSource().ifPresent(source -> {
        parts.add("from");

        parts.add(prefix + q.getRange().map(range -> {
            return source.identifier() + range.toDSL();
        }).orElseGet(source::identifier));
    });//w ww  .j  a  va  2 s .  c o  m

    q.getFilter().ifPresent(filter -> {
        parts.add("where");
        parts.add(prefix + filter.toDSL());
    });

    return joiner.join(parts);
}

From source file:io.syndesis.model.integration.Integration.java

@JsonIgnore
default Optional<IntegrationStatus> getStatus() {
    Optional<IntegrationRevision> deployedRevision = getDeployedRevision();

    return Optional.of(new IntegrationStatus.Builder()
            .currentState(//w w  w. j  a va 2  s  .c o m
                    deployedRevision.map(r -> r.getCurrentState()).orElse(IntegrationRevisionState.Pending))
            .build());
}

From source file:com.ikanow.aleph2.graph.titan.utils.TitanGraphBuildingUtils.java

/** (1/3) Calls user code to extract vertices and edges
 * @param batch/*  w ww .  j  av  a 2  s.  c  o  m*/
 * @param batch_size
 * @param grouping_key
 * @param maybe_decomposer
 * @return
 */
public static List<ObjectNode> buildGraph_getUserGeneratedAssets(final Stream<Tuple2<Long, IBatchRecord>> batch,
        final Optional<Integer> batch_size, final Optional<JsonNode> grouping_key,
        final Optional<Tuple2<IEnrichmentBatchModule, GraphDecompEnrichmentContext>> maybe_decomposer) {
    // First off build the edges and vertices

    maybe_decomposer.ifPresent(handler -> handler._1().onObjectBatch(batch, batch_size, grouping_key));

    final List<ObjectNode> vertices_and_edges = maybe_decomposer
            .map(context -> context._2().getAndResetVertexList()).orElse(Collections.emptyList());

    return vertices_and_edges;
}

From source file:com.diffplug.gradle.pde.PdeInstallation.java

/** Returns true iff it is installed. */
private boolean isInstalled() throws IOException {
    Optional<String> pdeBuild = FileMisc.readToken(getRootFolder(), TOKEN);
    pdeBuildFolder = pdeBuild.map(File::new).orElse(null);
    return pdeBuildFolder != null;
}

From source file:de.jfachwert.net.Telefonnummer.java

/**
 * Gibt den String nach DIN 5008 aus. Die Nummern werden dabei
 * funktionsbezogen durch Leerzeichen und die Durchwahl mit Bindestrich
 * abgetrennt.// w  w  w. j a  v a2  s .co  m
 *
 * @return z.B. "+49 30 12345-67" bzw. "030 12345-67"
 */
public String toDinString() {
    Optional<String> laenderkennzahl = getLaenderkennzahl();
    return laenderkennzahl.map(s -> s + " " + getVorwahl().substring(1) + " " + getRufnummer())
            .orElseGet(() -> getVorwahl() + " " + getRufnummer());
}