Example usage for java.util Map putIfAbsent

List of usage examples for java.util Map putIfAbsent

Introduction

In this page you can find the example usage for java.util Map putIfAbsent.

Prototype

default V putIfAbsent(K key, V value) 

Source Link

Document

If the specified key is not already associated with a value (or is mapped to null ) associates it with the given value and returns null , else returns the current value.

Usage

From source file:org.fcrepo.camel.processor.EventProcessor.java

private Map<String, List<String>> getValuesFromJson(final JsonNode body) {
    final Map<String, List<String>> data = new HashMap<>();
    getValues(body, "@id").ifPresent(id -> data.put(FCREPO_URI, id));
    getValues(body, "id").ifPresent(id -> data.putIfAbsent(FCREPO_URI, id));

    getValues(body, "@type").ifPresent(type -> data.put(FCREPO_RESOURCE_TYPE, type));
    getValues(body, "type").ifPresent(type -> data.putIfAbsent(FCREPO_RESOURCE_TYPE, type));

    if (body.has("wasGeneratedBy")) {
        final JsonNode generatedBy = body.get("wasGeneratedBy");
        getValues(generatedBy, "type").ifPresent(type -> data.put(FCREPO_EVENT_TYPE, type));
        getValues(generatedBy, "atTime").ifPresent(time -> data.put(FCREPO_DATE_TIME, time));
        getValues(generatedBy, "identifier").ifPresent(id -> data.put(FCREPO_EVENT_ID, id));
    }/*w  w w.  j a va  2  s  .c om*/

    if (body.has("wasAttributedTo")) {
        final JsonNode attributedTo = body.get("wasAttributedTo");
        if (attributedTo.isArray()) {
            final List<String> agents = new ArrayList<>();
            for (final JsonNode agent : attributedTo) {
                getString(agent, "name").ifPresent(agents::add);
            }
            data.put(FCREPO_AGENT, agents);
        } else {
            getString(attributedTo, "name").ifPresent(name -> data.put(FCREPO_AGENT, singletonList(name)));
        }
    }

    return data;
}

From source file:cop.maven.plugins.AbstractRamlConfigMojo.java

private void checkMavenApiPart() {
    api = CollectionUtils.size(api) > 0 ? api : new LinkedHashMap<>();
    api.putIfAbsent(Config.KEY_API_TITLE, "${project.name}");
    api.putIfAbsent(Config.KEY_API_BASE_URI, "${project.url}");

    Map<String, Object> doc = (Map<String, Object>) api.get(Config.KEY_API_DOC);

    if (doc == null)
        api.put(Config.KEY_API_DOC, doc = new LinkedHashMap<>());

    doc.putIfAbsent(Config.KEY_API_DOC_TITLE, "Public");
    doc.putIfAbsent(Config.KEY_API_DOC_CONTENT, "${project.description}");
}

From source file:com.github.pjungermann.config.types.groovy.ConfigObjectConverter.java

@SuppressWarnings("unchecked")
protected void addHierarchicalEntry(@NotNull final Map config, @NotNull final String key, final Object value) {
    final int index = key.indexOf(keyBuilder.getSeparator());
    if (index == -1) {
        config.put(key, value);//w w  w  . ja  va 2 s .  c  o m
        return;
    }

    final String rootKey = key.substring(0, index);
    config.putIfAbsent(rootKey, new ConfigObject());
    final Map subConfig = synchronizedMap((Map) config.get(rootKey));

    addHierarchicalEntry(subConfig, key.substring(index + 1), value);
}

From source file:io.klerch.alexa.state.handler.AlexaSessionStateHandler.java

/**
 * {@inheritDoc}/*from  w  ww . ja va 2 s.  c o  m*/
 */
@Override
public Map<String, AlexaStateObject> readValues(final Collection<String> ids, final AlexaScope scope)
        throws AlexaStateException {
    final Map<String, AlexaScope> idsInScope = new HashMap<>();
    ids.forEach(id -> idsInScope.putIfAbsent(id, scope));
    return readValues(idsInScope);
}

From source file:io.silverware.microservices.Boot.java

/**
 * Creates initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 *
 * @param args Command line arguments.// ww w. j  a  v a  2s .co m
 * @return Initial context pre-filled with system properties, command line arguments, custom property file and default property file.
 */
@SuppressWarnings("static-access")
private static Context getInitialContext(final String... args) {
    final Context context = new Context();
    final Map<String, Object> contextProperties = context.getProperties();
    final Options options = new Options();
    final CommandLineParser commandLineParser = new DefaultParser();

    System.getProperties().forEach((key, value) -> contextProperties.put((String) key, value));

    options.addOption(Option.builder(PROPERTY_LETTER).argName("property=value").numberOfArgs(2).valueSeparator()
            .desc("system properties").build());
    options.addOption(Option.builder(PROPERTY_FILE_LETTER).longOpt("properties").desc("Custom property file")
            .hasArg().argName("PROPERTY_FILE").build());

    try {
        final CommandLine commandLine = commandLineParser.parse(options, args);
        commandLine.getOptionProperties(PROPERTY_LETTER)
                .forEach((key, value) -> contextProperties.put((String) key, value));

        // process custom properties file
        if (commandLine.hasOption(PROPERTY_FILE_LETTER)) {
            final File propertiesFile = new File(commandLine.getOptionValue(PROPERTY_FILE_LETTER));
            if (propertiesFile.exists()) {
                final Properties props = loadProperties();
                props.forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));
            } else {
                log.error("Specified property file %s does not exists.", propertiesFile.getAbsolutePath());
            }
        }
    } catch (ParseException pe) {
        log.error("Cannot parse arguments: ", pe);
        new HelpFormatter().printHelp("SilverWare usage:", options);
        System.exit(1);
    }

    // now add in default properties from silverware.properties on a classpath
    loadProperties().forEach((key, val) -> contextProperties.putIfAbsent(key.toString(), val));

    context.getProperties().put(Executor.SHUTDOWN_HOOK, "true");

    return context;
}

From source file:com.netflix.spinnaker.kork.archaius.SpringEnvironmentPolledConfigurationSource.java

@Override
public PollResult poll(boolean initial, Object checkPoint) throws Exception {
    Map<String, Object> result = new HashMap<>();
    environment.getPropertySources().iterator().forEachRemaining(source -> {
        if (source instanceof EnumerablePropertySource) {
            EnumerablePropertySource<?> enumerable = (EnumerablePropertySource<?>) source;
            for (String key : enumerable.getPropertyNames()) {
                result.putIfAbsent(key, enumerable.getProperty(key));
            }//from ww w  .j  a v a  2s.c om
        }
    });
    return PollResult.createFull(result);
}

From source file:uk.ac.ebi.eva.pipeline.io.writers.VepAnnotationMongoWriter.java

private Map<String, List<VariantAnnotation>> groupVariantAnnotationById(
        List<? extends VariantAnnotation> variantAnnotations) {
    // The following method is not working with java8 .<40. Should be resuscitated when travis is updated to a
    // more recent java version (1.8.0_31 atm)
    // http://stackoverflow.com/questions/37368060/why-this-code-compiles-with-jdk8u45-and-above-but-not-with-jdk8u25
    //Map<String, List<VariantAnnotation>> variantAnnotationsByStorageId = variantAnnotations.stream()
    //        .collect(Collectors.groupingBy(this::buildStorageIdFromVariantAnnotation));

    Map<String, List<VariantAnnotation>> variantAnnotationsByStorageId = new HashMap<>();
    for (VariantAnnotation variantAnnotation : variantAnnotations) {
        String id = buildStorageIdFromVariantAnnotation(variantAnnotation);

        variantAnnotationsByStorageId.putIfAbsent(id, new ArrayList<>());
        variantAnnotationsByStorageId.get(id).add(variantAnnotation);
    }/*from www  . j  a v a 2s .c  om*/

    return variantAnnotationsByStorageId;
}

From source file:org.apache.samza.system.hdfs.partitioner.DirectoryPartitioner.java

private List<List<FileMetadata>> generatePartitionGroups(List<FileMetadata> filteredFiles) {
    Map<String, List<FileMetadata>> map = new HashMap<>();
    for (FileMetadata fileMetadata : filteredFiles) {
        String groupId = extractGroupIdentifier(fileMetadata.getPath());
        map.putIfAbsent(groupId, new ArrayList<>());
        map.get(groupId).add(fileMetadata);
    }/*from   w  w  w  .j av a 2 s  . c  o  m*/
    List<List<FileMetadata>> ret = new ArrayList<>();
    // sort the map to guarantee consistent ordering
    List<String> sortedKeys = new ArrayList<>(map.keySet());
    sortedKeys.sort(Comparator.<String>naturalOrder());
    sortedKeys.stream().forEach(key -> ret.add(map.get(key)));
    return ret;
}

From source file:com.thoughtworks.go.remote.work.ArtifactsPublisher.java

public Map<String, List<ArtifactPlan>> artifactPlansToArtifactStore(List<ArtifactPlan> artifactPlans) {
    final Map<String, List<ArtifactPlan>> artifactPlansToArtifactStore = new HashMap<>();
    for (ArtifactPlan artifactPlan : artifactPlans) {
        final String storeId = (String) artifactPlan.getPluggableArtifactConfiguration().get("storeId");
        artifactPlansToArtifactStore.putIfAbsent(storeId, new ArrayList<>());
        artifactPlansToArtifactStore.get(storeId).add(artifactPlan);
    }//from  w ww  .ja  va 2s .  c om
    return artifactPlansToArtifactStore;
}

From source file:org.onosproject.net.resource.impl.LabelAllocator.java

/**
 * Allocates labels and associates them to source
 * and destination ports of a link.//from   w  ww  .ja  v  a 2 s .  c  om
 *
 * @param links the links on which labels will be reserved
 * @param id the intent Id
 * @param type the encapsulation type
 * @return the list of ports and associated labels
 */
public Map<ConnectPoint, Identifier<?>> assignLabelToPorts(Set<Link> links, IntentId id,
        EncapsulationType type) {
    Map<LinkKey, Identifier<?>> allocation = this.assignLabelToLinks(links, id, type);
    if (allocation.isEmpty()) {
        return Collections.emptyMap();
    }
    Map<ConnectPoint, Identifier<?>> finalAllocation = Maps.newHashMap();
    allocation.forEach((key, value) -> {
        finalAllocation.putIfAbsent(key.src(), value);
        finalAllocation.putIfAbsent(key.dst(), value);
    });
    return ImmutableMap.copyOf(finalAllocation);
}