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:com.liaison.shachi.resmgr.PoolingHBaseResourceManager.java

/**
 * TODO/*from  ww w.  j  a  v a 2 s .  com*/
 * @param context
 * @param poolMap
 * @param poolBuilder
 * @return
 */
private static <P extends StatsAwareResourcePool<?>> P obtainPool(final HBaseContext context,
        final Map<HBaseContext, P> poolMap, final Function<HBaseContext, P> poolBuilder)
        throws HBaseInitializationException {
    final String logMsg;
    P pool;

    pool = poolMap.get(context);
    if (pool != null) {
        return pool;
    } else {
        poolMap.putIfAbsent(context, poolBuilder.apply(context));
        pool = poolMap.get(context);
        if (pool != null) {
            logPoolStats("fds", pool);
            return pool;
        } else {
            /* 
             * should never happen, since there should be no other ways to modify poolMap, except
             * by this method
             */
            logMsg = "PROBABLE CONCURRENCY FAILURE: Unable to obtain object pool for "
                    + HBaseContext.class.getSimpleName() + " '" + context.getId()
                    + "', either by acquiring the existing one or by creating a new one";
            throw new HBaseInitializationException(logMsg);
        }
    }
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static Map<String, AtomicInteger> parseDir(String dir) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?" + dir);
    try {// w ww . j ava 2s.co  m
        Files.walkFileTree(Paths.get(dir), new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                Map<String, AtomicInteger> rs = parseFile(file.toFile().getAbsolutePath());
                rs.keySet().forEach(k -> {
                    data.putIfAbsent(k, new AtomicInteger());
                    data.get(k).addAndGet(rs.get(k).get());
                });
                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:org.apdplat.superword.rule.TextAnalysis.java

public static Map<String, AtomicInteger> frequency(InputStream inputStream) {
    Map<String, AtomicInteger> map = new ConcurrentHashMap<>();

    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(new BufferedInputStream(inputStream)))) {
        String line = null;//from  w ww. j  a  v a  2 s. c o m
        while ((line = reader.readLine()) != null) {
            if (StringUtils.isBlank(line)) {
                continue;
            }
            List<String> words = seg(line);
            words.forEach(word -> {
                map.putIfAbsent(word, new AtomicInteger());
                map.get(word).incrementAndGet();
            });
            words.clear();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    LOGGER.info("unique words count: " + map.size());
    return map;
}

From source file:hr.fer.tel.rovkp.homework03.task01.JokesCollection.java

public static Map<Integer, String> parseInputFile(String file) throws IOException {
    Path filePath = Paths.get(file);
    Map<Integer, String> results = new HashMap<>();

    List<String> currentJoke = new LinkedList<>();
    LinkedList<Integer> ids = new LinkedList<>();

    try (Stream<String> stream = Files.lines(filePath)) {
        stream.forEach(line -> {//w w w  .  jav  a 2  s .  co m
            if (line == null)
                return;
            line = line.trim();

            if (line.isEmpty() && !currentJoke.isEmpty()) {
                int currentId = ids.getLast();
                String jokeText = StringUtils.join(currentJoke, "\n");
                jokeText = StringEscapeUtils.unescapeXml(jokeText.toLowerCase().replaceAll("\\<.*?\\>", ""));
                if (results.putIfAbsent(currentId, jokeText) != null)
                    System.err.println("Joke with id " + currentId + "already exists. Not overwriting.");
            } else if (line.matches("^[0-9]+:$")) {
                ids.addLast(Integer.parseInt(line.substring(0, line.length() - 1)));
                currentJoke.clear();
            } else {
                currentJoke.add(line);
            }
        });
    }

    return results;
}

From source file:org.openecomp.sdc.vendorsoftwareproduct.services.CompositionDataExtractor.java

private static Map<String, List<String>> getComputeToPortsConnection(
        Map<String, NodeTemplate> portNodeTemplates) {
    Map<String, List<String>> computeToPortConnection = new HashMap<>();
    if (MapUtils.isEmpty(portNodeTemplates)) {
        return computeToPortConnection;
    }/*from  w ww .  j  av  a2 s. c  o  m*/
    for (String portId : portNodeTemplates.keySet()) {
        List<RequirementAssignment> bindingRequirementsToCompute = toscaAnalyzerService
                .getRequirements(portNodeTemplates.get(portId), ToscaConstants.BINDING_REQUIREMENT_ID);
        for (RequirementAssignment bindingRequirementToCompute : bindingRequirementsToCompute) {
            computeToPortConnection.putIfAbsent(bindingRequirementToCompute.getNode(), new ArrayList<>());
            computeToPortConnection.get(bindingRequirementToCompute.getNode()).add(portId);
        }

    }

    return computeToPortConnection;
}

From source file:org.apdplat.superword.tools.JavaCodeAnalyzer.java

public static Map<String, AtomicInteger> parseZip(String zipFile) {
    LOGGER.info("?ZIP" + zipFile);
    Map<String, AtomicInteger> data = new HashMap<>();
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile),
            JavaCodeAnalyzer.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from  ww  w  . jav  a  2  s  . c  om
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/java-source-code.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> r = parseFile(temp.toFile().getAbsolutePath());
                    r.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(r.get(k).get());
                    });
                    r.clear();
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?ZIP", e);
    }
    return data;
}

From source file:org.ow2.proactive.connector.iaas.cache.InstanceCache.java

public void registerInfrastructureInstances(Infrastructure infrastructure, Set<Instance> instances) {
    Map<String, Set<Instance>> tempInstances = cloneCreatedInstances();
    tempInstances.putIfAbsent(infrastructure.getId(), Sets.newHashSet());
    Set<Instance> cachedInstances = tempInstances.get(infrastructure.getId());
    cachedInstances.addAll(instances);//from  w w  w . jav  a2  s.c o  m
    tempInstances.put(infrastructure.getId(), cachedInstances);
    createdInstances = ImmutableMap.copyOf(tempInstances);
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static Map<String, AtomicInteger> parseFile(String file) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?" + file);
    try (BufferedReader reader = new BufferedReader(
            new InputStreamReader(new BufferedInputStream(new FileInputStream(file))))) {
        String line = null;// ww w.  j  a  va 2s  .  c o  m
        while ((line = reader.readLine()) != null) {
            //LOGGER.debug("line:"+line);
            String[] attrs = line.split("\\s+");
            for (String attr : attrs) {
                if (attr.contains("-")) {
                    String[] parts = attr.split("-");
                    if (parts.length == 2 && parts[0].length() > 1 && parts[1].length() > 1
                            && WordSources.isEnglish(parts[0]) && WordSources.isEnglish(parts[1])) {
                        LOGGER.debug("?" + attr);
                        attr = attr.toLowerCase();
                        data.putIfAbsent(attr, new AtomicInteger());
                        data.get(attr).incrementAndGet();
                    }
                }
            }
        }
    } catch (IOException e) {
        LOGGER.error("?", e);
    }
    return data;
}

From source file:com.netflix.spinnaker.clouddriver.google.names.GoogleLabeledResourceNamer.java

public void applyMoniker(GoogleLabeledResource labeledResource, Moniker moniker) {
    Map<String, String> templateLabels = labeledResource.getLabels();
    setIfPresent(value -> templateLabels.putIfAbsent(APP, value.toLowerCase()), moniker.getApp());
    setIfPresent(value -> templateLabels.putIfAbsent(CLUSTER, value.toLowerCase()), moniker.getCluster());
    setIfPresent(value -> templateLabels.putIfAbsent(DETAIL, value.toLowerCase()), moniker.getDetail());
    setIfPresent(value -> templateLabels.putIfAbsent(STACK, value.toLowerCase()), moniker.getStack());
    setIfPresent(value -> templateLabels.put(SEQUENCE, value),
            moniker.getSequence() != null ? moniker.getSequence().toString() : null); // Always overwrite sequence
}

From source file:org.apdplat.superword.extract.HyphenExtractor.java

public static Map<String, AtomicInteger> parseZip(String zipFile) {
    Map<String, AtomicInteger> data = new HashMap<>();
    LOGGER.info("?ZIP" + zipFile);
    try (FileSystem fs = FileSystems.newFileSystem(Paths.get(zipFile), WordClassifier.class.getClassLoader())) {
        for (Path path : fs.getRootDirectories()) {
            LOGGER.info("?" + path);
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {

                @Override//from  w  ww . java2s  .  c o m
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    LOGGER.info("?" + file);
                    // ?
                    Path temp = Paths.get("target/origin-html-temp.txt");
                    Files.copy(file, temp, StandardCopyOption.REPLACE_EXISTING);
                    Map<String, AtomicInteger> rs = parseFile(temp.toFile().getAbsolutePath());
                    rs.keySet().forEach(k -> {
                        data.putIfAbsent(k, new AtomicInteger());
                        data.get(k).addAndGet(rs.get(k).get());
                    });
                    return FileVisitResult.CONTINUE;
                }

            });
        }
    } catch (Exception e) {
        LOGGER.error("?", e);
    }
    return data;
}