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:io.github.carlomicieli.footballdb.starter.parsers.PlayerProfileParser.java

protected static Map<String, String> extractInfo(Optional<String> str) {
    return str.map(val -> {
        Matcher matcher = patternMatchString(infoPattern(), val);
        Map<String, String> v = newMap();
        if (matcher.find()) {
            v.put("height", matcher.group(1));
            v.put("weight", matcher.group(2));
            v.put("age", matcher.group(3));
        }//from   w ww.j  a v  a  2s. c  o m

        return unmodifiableMap(v);
    }).orElse(Collections.emptyMap());
}

From source file:io.github.carlomicieli.footballdb.starter.parsers.PlayerProfileParser.java

protected static Map<String, String> extractHighSchool(Optional<String> str) {
    return str.map(val -> {
        String s = normalize(val);
        List<String> tokens = Stream
                .of(s.replace("High School: ", "").replace("]", "").replace("[", ",").split(","))
                .map(String::trim).collect(Collectors.toList());

        if (tokens.size() < 2) {
            return Collections.<String, String>emptyMap();
        }//from w  w w. ja  va 2  s.co  m

        Map<String, String> v = newMap();
        v.put("high_school", tokens.get(0));
        if (tokens.size() == 2)
            v.put("state", tokens.get(1));
        else {
            v.put("city", tokens.get(1));
            v.put("state", tokens.get(2));
        }
        return unmodifiableMap(v);
    }).orElse(Collections.emptyMap());
}

From source file:com.spotify.styx.api.deprecated.BackfillPayload.java

public static BackfillPayload create(com.spotify.styx.api.BackfillPayload backfillPayload) {
    final com.spotify.styx.model.Backfill backfill = backfillPayload.backfill();
    final Optional<com.spotify.styx.api.RunStateDataPayload> runStateDataPayload = backfillPayload.statuses();

    final Backfill deprecatedBackfill = Backfill.create(backfill);
    final Optional<RunStateDataPayload> deprecatedRunStateDataPayload = runStateDataPayload
            .map(RunStateDataPayload::create);
    return new AutoValue_BackfillPayload(deprecatedBackfill, deprecatedRunStateDataPayload);
}

From source file:org.apache.metron.elasticsearch.client.ElasticsearchClientFactory.java

/**
 * <p>Setup connection encryption details (SSL) if applicable.
 * If ssl.enabled=true, sets up SSL connection. If enabled, keystore.path is required. User can
 * also optionally set keystore.password and keystore.type.
 * https://www.elastic.co/guide/en/elasticsearch/client/java-rest/5.6/_encrypted_communication.html
 * <p>//from   w w  w  . j  a  va2 s. com
 * <p>Other guidance on the HTTP Component library and configuring SSL connections.
 * http://www.robinhowlett.com/blog/2016/01/05/everything-you-ever-wanted-to-know-about-ssl-but-were-afraid-to-ask.
 * <p>
 * <p>JSSE docs - https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html
 * <p>
 * <p>Additional guidance for configuring Elasticsearch for SSL can be found here - https://www.elastic.co/guide/en/x-pack/5.6/ssl-tls.html
 */
private static SSLContext getSSLContext(ElasticsearchClientConfig esClientConfig) {
    if (esClientConfig.isSSLEnabled()) {
        LOG.info("Configuring client for SSL connection.");
        if (!esClientConfig.getKeyStorePath().isPresent()) {
            throw new IllegalStateException("KeyStore path must be provided for SSL connection.");
        }
        Optional<String> optKeyStorePass = esClientConfig.getKeyStorePassword();
        char[] keyStorePass = optKeyStorePass.map(String::toCharArray).orElse(null);
        KeyStore trustStore = getStore(esClientConfig.getKeyStoreType(), esClientConfig.getKeyStorePath().get(),
                keyStorePass);
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(trustStore, null);
            return sslBuilder.build();
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
            throw new IllegalStateException("Unable to load truststore.", e);
        }
    }
    return null;
}

From source file:com.ikanow.aleph2.data_model.utils.TimeUtils.java

/** Returns the suffix of a time-based index given the grouping period
 * @param grouping_period - the grouping period
 * @param lowest_granularity//from   ww  w. j a  v  a 2s .  c  om
 * @return the index suffix, ie added to the base index
 */
public static String getTimeBasedSuffix(final ChronoUnit grouping_period,
        final Optional<ChronoUnit> lowest_granularity) {
    return lowest_granularity
            .map(lg -> grouping_period.compareTo(lg) < 0 ? getTimeBasedSuffix(lg, Optional.empty()) : null)
            .orElse(Patterns.match(grouping_period).<String>andReturn()
                    .when(p -> ChronoUnit.SECONDS == p, __ -> "yyyy.MM.dd.HH:mm:ss")
                    .when(p -> ChronoUnit.MINUTES == p, __ -> "yyyy.MM.dd.HH:mm")
                    .when(p -> ChronoUnit.HOURS == p, __ -> "yyyy.MM.dd.HH")
                    .when(p -> ChronoUnit.DAYS == p, __ -> "yyyy.MM.dd")
                    .when(p -> ChronoUnit.WEEKS == p, __ -> "YYYY-ww") // (deliberately 'Y' (week-year) not 'y' since 'w' is week-of-year 
                    .when(p -> ChronoUnit.MONTHS == p, __ -> "yyyy.MM")
                    .when(p -> ChronoUnit.YEARS == p, __ -> "yyyy").otherwise(__ -> ""));
}

From source file:com.github.horrorho.inflatabledonkey.pcs.xfile.FileAssembler.java

public static void assemble(Path file, List<Chunk> chunkData, int length, Optional<byte[]> key)
        throws UncheckedIOException {

    logger.debug("-- assemble() - file: {} chunks: {} length: {} key: 0x{}", file, chunkData.size(), length,
            key.map(Hex::toHexString).orElse("NULL"));
    logger.info("-- assemble() - file: {}", file);

    if (!createDirectories(file)) {
        return;/*from  www  .  j  a va  2 s  .  c  om*/
    }
    copy(file, chunkData, key);
    truncate(file, length);
}

From source file:com.ikanow.aleph2.data_model.utils.PropertiesUtils.java

/** Gets a merged set of configs
 * @param config_dir/*w ww .  j  a v a 2s . co  m*/
 * @param default_config
 * @return
 */
public static Config getMergedConfig(final Optional<File> config_dir, final File default_config) {
    final Config fallback_config = ConfigFactory.parseFile(default_config);
    final List<Config> extra_confs = config_dir.map(dir -> FileUtils
            .listFiles(dir, Arrays.asList("conf", "properties", "json").toArray(new String[0]), false).stream()
            .sorted().<Config>map(f -> ConfigFactory.parseFile(f)).collect(Collectors.toList()))
            .orElse(Collections.emptyList());

    return getMergedConfig(extra_confs, fallback_config);
}

From source file:alfio.util.Validator.java

private static boolean isInternal(Optional<Event> event, EventModification ev) {
    return event.map(Event::getType).orElse(ev.getEventType()) == Event.EventType.INTERNAL;
}

From source file:gov.ca.cwds.cals.util.PlacementHomeUtil.java

/**
 * Composes facility name according to applicantDTOs list.
 *
 * <p> <b>Rules for Facility / Family name</b>
 *
 * Reads Applicant Name(s) as Last Name, First Name of Applicant #1 and Last Name, First Name of
 * Applicant #2. (ex. Smith, John & Jones, Jane) Last Name is separated from First Name by a
 * comma. Applicant Names are separated from each other by "and" or "&". When the Last Name is
 * the same for Applicant #1 and Applicant #2, name reads "Common Last Name, First Name
 * Applicant #1 & First Name Applicant #2" (ex. Smith, John & Jane). </p>
 *
 * @param applicantsList applicantsDTOs list
 * @return facility name/*from w ww .  j a  va  2s  . c  o m*/
 */
public static String composeFacilityName(List<ApplicantDTO> applicantsList) {
    // Assume that Facility/Family name composed from the first 2 applicants
    return Optional.ofNullable(applicantsList).map(applicants -> {
        Optional<ApplicantDTO> firstApplicant = getApplicantBuIndex(applicants, 0);
        Optional<ApplicantDTO> secondApplicant = getApplicantBuIndex(applicants, 1);

        StringBuilder firstPartSb = firstApplicant.map(PlacementHomeUtil::composeFirstPartOfFacilityName)
                .orElse(new StringBuilder());

        StringBuilder secondPartSb = secondApplicant
                .map(applicantDTO -> composeSecondPartOfFacilityName(firstApplicant, applicantDTO))
                .orElse(new StringBuilder());

        if (firstPartSb.length() > 0 && secondPartSb.length() > 0) {
            firstPartSb.append(" & ");
        }
        firstPartSb.append(secondPartSb);

        return firstPartSb.toString();
    }).orElse(null);
}

From source file:com.ikanow.aleph2.example.flume_harvester.utils.FlumeUtils.java

private static String addOptionalAgentName(final Optional<String> agent_name, final int max_len) {
    return agent_name.map(sc -> "_" + safeTruncate(sc, max_len)).orElse("");
}