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.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

@Override
public Map<NodeId, Map<String, InfluxMetric>> allMetrics() {
    Map<NodeId, Set<String>> nameMap = allMetricNames();
    Map<NodeId, Map<String, InfluxMetric>> metricsMap = Maps.newHashMap();

    nameMap.forEach((nodeId, metricNames) -> metricsMap.putIfAbsent(nodeId, metricsByNodeId(nodeId)));

    return metricsMap;
}

From source file:com.frederikam.gensokyobot.Config.java

@SuppressWarnings("unchecked")
public Config(File credentialsFile, File configFile) {
    try {//from ww w .  ja va2s  .  co m
        Yaml yaml = new Yaml();
        String credsFileStr = FileUtils.readFileToString(credentialsFile, "UTF-8");
        String configFileStr = FileUtils.readFileToString(configFile, "UTF-8");
        //remove those pesky tab characters so a potential json file is YAML conform
        credsFileStr = credsFileStr.replaceAll("\t", "");
        configFileStr = configFileStr.replaceAll("\t", "");
        Map<String, Object> creds = (Map<String, Object>) yaml.load(credsFileStr);
        Map<String, Object> config = (Map<String, Object>) yaml.load(configFileStr);
        //avoid null values, rather change them to empty strings
        creds.keySet().forEach((String key) -> creds.putIfAbsent(key, ""));
        config.keySet().forEach((String key) -> config.putIfAbsent(key, ""));

        // Determine distribution
        if ((boolean) config.getOrDefault("development", false)) {//Determine distribution
            distribution = DistributionEnum.DEVELOPMENT;
        } else {
            distribution = DistributionEnum.MUSIC;
        }

        log.info("Determined distribution: " + distribution);

        token = (String) creds.get("token");
        numShards = DiscordUtil.getRecommendedShardCount(token);
        prefix = (String) config.getOrDefault("prefix", DEFAULT_PREFIX);
        streamUrl = (String) config.getOrDefault("streamUrl", GENSOKYO_RADIO_STREAM_URL);

    } catch (IOException | UnirestException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.eagle.alert.engine.publisher.impl.AlertPublisherImpl.java

private void addPublishmentPolicies(Map<String, List<String>> newPolicyPublishPluginMapping,
        List<String> addedPolicyIds, String pubName) {
    if (addedPolicyIds == null || pubName == null) {
        return;/* www  .  j  a va 2 s .c om*/
    }

    for (String policyId : addedPolicyIds) {
        newPolicyPublishPluginMapping.putIfAbsent(policyId, new ArrayList<>());
        newPolicyPublishPluginMapping.get(policyId).add(pubName);
    }
}

From source file:org.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

@Override
public Map<NodeId, Map<String, List<InfluxMetric>>> allMetrics(int period, TimeUnit unit) {
    Map<NodeId, Set<String>> nameMap = allMetricNames();
    Map<NodeId, Map<String, List<InfluxMetric>>> metricsMap = Maps.newHashMap();

    nameMap.forEach(//from  w  ww. j  av  a2  s.  c om
            (nodeId, metricNames) -> metricsMap.putIfAbsent(nodeId, metricsByNodeId(nodeId, period, unit)));

    return metricsMap;
}

From source file:com.teradata.benchto.driver.loader.BenchmarkLoader.java

private List<BenchmarkDescriptor> createBenchmarkDescriptors(Map<String, Object> yaml) {
    List<Map<String, String>> variablesCombinations = extractVariableMapList(yaml);
    Map<String, String> globalVariables = extractGlobalVariables(yaml);

    for (Map<String, String> variablesMap : variablesCombinations) {
        for (Entry<String, String> globalVariableEntry : globalVariables.entrySet()) {
            variablesMap.putIfAbsent(globalVariableEntry.getKey(), globalVariableEntry.getValue());
        }/*from   w  w  w .j ava2s.  c om*/

        evaluateValueExpressions(variablesMap);
    }

    return variablesCombinations.stream().map(BenchmarkDescriptor::new).collect(toList());
}

From source file:com.flipkart.flux.api.StateMachineDefinition.java

@JsonIgnore
public Map<EventDefinition, EventData> getEventDataMap() {
    Map<EventDefinition, EventData> eventDataMap = new HashMap<>();
    for (StateDefinition aState : this.states) {
        final Set<EventDefinition> dependenciesForCurrentState = aState.getDependencies();
        for (EventDefinition anEventDefinition : dependenciesForCurrentState) {
            eventDataMap.putIfAbsent(anEventDefinition, retrieveEventDataFor(anEventDefinition));
        }//from  ww w.ja  va  2  s.c  om
        final EventDefinition outputEventDefinition = aState.getOutputEvent();
        if (outputEventDefinition != null) {
            eventDataMap.put(outputEventDefinition, retrieveEventDataFor(outputEventDefinition));
        }
    }
    return eventDataMap;
}

From source file:org.eclipse.hono.service.registration.impl.FileBasedRegistrationService.java

/**
 * Adds a device to this registry./*  w  ww .  j  a v  a 2s.  c o m*/
 * 
 * @param tenantId The tenant the device belongs to.
 * @param deviceId The ID of the device to add.
 * @param data Additional data to register with the device (may be {@code null}).
 * @return The outcome of the operation indicating success or failure.
 */
public RegistrationResult addDevice(final String tenantId, final String deviceId, final JsonObject data) {

    JsonObject obj = data != null ? data : new JsonObject().put(FIELD_ENABLED, Boolean.TRUE);
    Map<String, JsonObject> devices = getDevicesForTenant(tenantId);
    if (devices.size() < maxDevicesPerTenant) {
        if (devices.putIfAbsent(deviceId, obj) == null) {
            dirty = true;
            return RegistrationResult.from(HTTP_CREATED);
        } else {
            return RegistrationResult.from(HTTP_CONFLICT);
        }
    } else {
        return RegistrationResult.from(HTTP_FORBIDDEN);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.argumentation.io.writer.json.JCasTextSpanAnnotationGraphFactory.java

@Override
public SpanAnnotationGraph<SpanTextLabel> apply(final JCas jCas) {
    final ReverseLookupOrderedSet<SpanTextLabel> spanAnnotationVector;
    final Sparse3DObjectMatrix<String, SpanTextLabel> spanAnnotationMatrix;
    {/* ww  w  .  ja  v a 2s  .c om*/
        final Collection<ArgumentComponent> argumentComponents = JCasUtil.select(jCas, ArgumentComponent.class);

        {
            final int argumentComponentCount = argumentComponents.size();
            LOG.info(String.format("Processing %d argument components.", argumentComponentCount));
            // The list of all annotations, their index in the list serving
            // as
            // their
            // ID
            spanAnnotationVector = new ReverseLookupOrderedSet<>(
                    new ArrayList<SpanTextLabel>(argumentComponentCount));
            // Just use the size "argumentComponentCount" directly here
            // because
            // it
            // is assumed that spans
            // don't overlap
            spanAnnotationMatrix = new Sparse3DObjectMatrix<>(
                    new Int2ObjectOpenHashMap<>(argumentComponentCount + 1),
                    ESTIMATED_SPAN_BEGIN_TO_END_MAP_MAX_CAPACITY, ESTIMATED_ANNOTATION_MAP_MAX_CAPACITY);
        }

        for (final ArgumentComponent argumentComponent : argumentComponents) {
            final SpanTextLabel spanAnnotation = SpanTextAnnotationFactory.getInstance()
                    .apply(argumentComponent);
            final Span span = spanAnnotation.getSpanText().getSpan();
            final int begin = span.getBegin();
            final int end = span.getEnd();
            final String label = spanAnnotation.getLabel();
            final Map<String, SpanTextLabel> spanAnnotations = spanAnnotationMatrix.fetch3DMap(begin, end);
            final SpanTextLabel oldSpanAnnotation = spanAnnotations.put(label, spanAnnotation);
            if (oldSpanAnnotation != null) {
                LOG.warn(String.format("Annotation label \"%s\" already exists for span [%d, %d]; Overwriting.",
                        label, begin, end));
            }
            spanAnnotationVector.add(spanAnnotation);
        }
    }

    final Collection<ArgumentRelation> argumentRelations = JCasUtil.select(jCas, ArgumentRelation.class);
    final Object2IntMap<SpanTextLabel> spanAnnotationIds = spanAnnotationVector.getReverseLookupMap();
    LOG.info(String.format("Processing %d argument relations.", argumentRelations.size()));

    final int initialTableRelationValue = -1;
    final Supplier<int[]> transitionTableArraySupplier = () -> {
        final int[] result = new int[spanAnnotationIds.size()];
        // Pre-fill the array in the case that there is no transition for a
        // given annotation
        Arrays.fill(result, initialTableRelationValue);
        return result;
    };
    final ArgumentTransitionTableCollector argTransitionTableCollector = new ArgumentTransitionTableCollector(
            transitionTableArraySupplier, initialTableRelationValue,
            annot -> getAnnotationId(annot, spanAnnotationMatrix, spanAnnotationIds));

    final Stream<ArgumentRelation> argumentRelationStream = argumentRelations.stream().map(argumentRelation -> {
        final ArgumentUnit source = argumentRelation.getSource();
        final Map<Attribute, Object> sourceAnnotAttrs = getSpanTextLabel(source, spanAnnotationMatrix)
                .getAttributes();
        // If the source annotation doesn't have its own category already set, set it to
        // the type label of the relation between it and its target
        sourceAnnotAttrs.putIfAbsent(Attribute.CATEGORY, argumentRelation.getType().getShortName());
        return argumentRelation;
    });
    final int[] argumentTransitionTable = argumentRelationStream.collect(argTransitionTableCollector);

    return new SpanAnnotationGraph<>(spanAnnotationVector, argumentTransitionTable);
}

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

public static Map<String, List<String>> findEvidence(Path dir, List<String> words) {
    LOGGER.info("?" + dir);
    Map<String, List<String>> data = new HashMap<>();
    try {//w  w w.  j  a va2  s  .co  m
        Files.walkFileTree(dir, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                String fileName = file.toFile().getAbsolutePath();
                if (file.toFile().getName().startsWith(".")) {
                    return FileVisitResult.CONTINUE;
                }
                if (!fileName.endsWith(".txt")) {
                    LOGGER.info("??txt" + fileName);
                    return FileVisitResult.CONTINUE;
                }

                LOGGER.info("?" + fileName);
                List<String> lines = Files.readAllLines(file);
                for (int i = 0; i < lines.size(); i++) {
                    final String line = lines.get(i);
                    final int index = i;
                    words.forEach(word -> {
                        if (line.toLowerCase().contains(word)) {
                            data.putIfAbsent(word, new ArrayList<>());
                            data.get(word).add(line + " <u><i>" + file.toFile().getName().replace(".txt", "")
                                    + "</i></u>");
                        }
                    });
                }

                return FileVisitResult.CONTINUE;
            }

        });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return data;
}

From source file:org.dllearner.algorithms.qtl.experiments.BenchmarkDescriptionGenerator.java

private void exportGraph(Query query, File file) {
    mxGraph graph = new mxGraph();
    Object parent = graph.getDefaultParent();
    // Adds cells to the model in a single step
    graph.getModel().beginUpdate();/*from w  ww. j a  v a 2s.co  m*/
    try {
        Set<Triple> tps = utils.extractTriplePattern(query);

        Map<Node, Object> mapping = new HashMap<>();
        tps.forEach(tp -> {
            Object val1 = mapping.putIfAbsent(tp.getSubject(), graph.insertVertex(parent, null,
                    tp.getSubject().toString(query.getPrefixMapping()), 20, 20, 40, 30));
            Object val2 = mapping.putIfAbsent(tp.getObject(), graph.insertVertex(parent, null,
                    tp.getObject().toString(query.getPrefixMapping()), 20, 20, 40, 30));
        });
        tps.forEach(tp -> {
            graph.insertEdge(parent, null, tp.getPredicate().toString(query.getPrefixMapping()),
                    mapping.get(tp.getSubject()), mapping.get(tp.getObject()));
        });

    } finally {
        // Updates the display
        graph.getModel().endUpdate();
    }
    mxGraphComponent graphComponent = new mxGraphComponent(graph);

    // positioning via jgraphx layouts
    //      mxHierarchicalLayout layout = new mxHierarchicalLayout(graph);
    //      layout.setParallelEdgeSpacing(20d);
    //      layout.setIntraCellSpacing(40d);
    mxGraphLayout layout = new mxOrthogonalLayout(graph);
    layout.execute(graph.getDefaultParent());

    Map<String, Object> edgeStyle = new HashMap<String, Object>();
    //edgeStyle.put(mxConstants.STYLE_EDGE, mxConstants.EDGESTYLE_ORTHOGONAL);
    edgeStyle.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_CONNECTOR);
    edgeStyle.put(mxConstants.STYLE_ENDARROW, mxConstants.ARROW_CLASSIC);
    edgeStyle.put(mxConstants.STYLE_STROKECOLOR, "#000000");
    edgeStyle.put(mxConstants.STYLE_FONTCOLOR, "#000000");
    edgeStyle.put(mxConstants.STYLE_LABEL_BACKGROUNDCOLOR, "#ffffff");

    Map<String, Object> nodeStyle = new HashMap<>();
    nodeStyle.put(mxConstants.STYLE_SHAPE, mxConstants.SHAPE_ELLIPSE);
    nodeStyle.put(mxConstants.STYLE_VERTICAL_ALIGN, mxConstants.ALIGN_BOTTOM);

    mxStylesheet stylesheet = new mxStylesheet();
    stylesheet.setDefaultEdgeStyle(edgeStyle);
    stylesheet.setDefaultVertexStyle(nodeStyle);

    graph.setStylesheet(stylesheet);

    //      JFrame frame = new JFrame();
    //      frame.getContentPane().add(new mxGraphComponent(adapter));
    //      frame.pack();
    //      frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    //      frame.setVisible(true);

    BufferedImage image = mxCellRenderer.createBufferedImage(graph, null, 1, Color.WHITE, true, null);
    mxPngEncodeParam param = mxPngEncodeParam.getDefaultEncodeParam(image);

    try {
        FileOutputStream outputStream = new FileOutputStream(file);
        mxPngImageEncoder encoder = new mxPngImageEncoder(outputStream, param);
        if (image != null) {
            encoder.encode(image);
        }
        outputStream.close();
        //         ImageIO.write(image, "PNG", file);
    } catch (IOException e) {
        e.printStackTrace();
    }
}