Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

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

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:org.apache.tinkerpop.gremlin.spark.process.computer.traversal.strategy.optimization.SparkSingleIterationStrategyTest.java

private static <R> void test(boolean singleIteration, R expectedResult, final Traversal<?, R> traversal) {
    traversal.asAdmin().applyStrategies();
    final Map<String, Object> configuration = TraversalHelper
            .getFirstStepOfAssignableClass(TraversalVertexProgramStep.class, traversal.asAdmin()).get()
            .getComputer().getConfiguration();
    assertEquals(singleIteration, configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_PARTITIONER, false));
    assertEquals(singleIteration, configuration.getOrDefault(Constants.GREMLIN_SPARK_SKIP_GRAPH_CACHE, false));
    final List<R> result = traversal.toList();
    if (null != expectedResult)
        assertEquals(expectedResult, result.get(0));
}

From source file:com.haulmont.cuba.core.entity.LocaleHelper.java

public static String getEnumLocalizedValue(String enumValue, String localeBundle) {
    if (enumValue == null) {
        return null;
    }/*from   w ww  . ja  v a2s.co  m*/

    if (localeBundle == null) {
        return enumValue;
    }

    Map<String, String> map = getLocalizedValuesMap(localeBundle);

    Locale locale = AppBeans.get(UserSessionSource.class).getLocale();
    String key = locale.getLanguage();
    if (StringUtils.isNotEmpty(locale.getCountry())) {
        key += "_" + locale.getCountry();
    }

    String result = map.getOrDefault(key + "/" + enumValue, "");

    return Objects.equals(result, "") ? enumValue : result;
}

From source file:org.trellisldp.auth.oauth.JwksAuthenticator.java

private static Map<String, Key> buildKeys(final String location) {
    final Map<String, Key> keys = new HashMap<>();
    // TODO eventually, this will become part of the JJWT library
    final Deserializer<Map<String, List<Map<String, String>>>> deserializer = new JacksonDeserializer<>();
    final Map<String, List<Map<String, String>>> data = new HashMap<>();
    try (final InputStream input = new URL(location).openConnection().getInputStream()) {
        deserializer.deserialize(IOUtils.toByteArray(input)).forEach(data::put);
    } catch (final IOException ex) {
        LOGGER.error("Error fetching/parsing jwk document", ex);
    }/*from   w  w w.  j  a  v  a  2 s  .c  o  m*/

    for (final Map<String, String> jwk : data.getOrDefault("keys", emptyList())) {
        final BigInteger modulus = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.get("n")));
        final BigInteger exponent = new BigInteger(1, Base64.getUrlDecoder().decode(jwk.get("e")));
        OAuthUtils.buildRSAPublicKey("RSA", modulus, exponent).ifPresent(key -> keys.put(jwk.get("kid"), key));
    }
    return keys;
}

From source file:com.netflix.spinnaker.halyard.deploy.spinnaker.v1.service.distributed.kubernetes.v2.KubernetesV2Utils.java

static public boolean exists(KubernetesAccount account, String manifest) {
    Map<String, Object> parsedManifest = parseManifest(manifest);
    String kind = (String) parsedManifest.get("kind");
    Map<String, Object> metadata = (Map<String, Object>) parsedManifest.getOrDefault("metadata",
            new HashMap<>());
    String name = (String) metadata.get("name");
    String namespace = (String) metadata.get("namespace");

    return exists(account, namespace, kind, name);
}

From source file:com.act.lcms.v2.MZCollisionCounter.java

public static <T> Map<T, Long> histogram(Stream<T> stream) {
    Map<T, Long> hist = new HashMap<>();
    // This could be done with reduce (fold) or collector cleverness, but this invocation makes the intention clear.
    //stream.forEach(x -> hist.merge(x, 1l, (acc, one) -> one + acc));
    stream.forEach(x -> {// w  w w.  jav a 2s. c om
        try {
            hist.put(x, hist.getOrDefault(x, 0l) + 1);
        } catch (NoSuchElementException e) {
            LOGGER.error("Caught no such element exception for %s: %s", x.toString(), e.getMessage());
            throw e;
        }
    });

    return hist;
}

From source file:org.apache.metron.enrichment.integration.EnrichmentIntegrationTest.java

private static void simpleEnrichmentValidation(Map<String, Object> indexedDoc) {
    if (indexedDoc.getOrDefault(SRC_IP, "").equals("10.0.2.3")
            || indexedDoc.getOrDefault(DST_IP, "").equals("10.0.2.3")) {
        Assert.assertTrue(keyPatternExists("enrichments.hbaseEnrichment", indexedDoc));
        if (indexedDoc.getOrDefault(SRC_IP, "").equals("10.0.2.3")) {
            Assert.assertEquals(indexedDoc.get("enrichments.hbaseEnrichment." + SRC_IP + "."
                    + PLAYFUL_CLASSIFICATION_TYPE + ".orientation"), PLAYFUL_ENRICHMENT.get("orientation"));
            Assert.assertEquals(indexedDoc.get("src_classification.orientation"),
                    PLAYFUL_ENRICHMENT.get("orientation"));
            Assert.assertEquals(indexedDoc.get("is_src_malicious"), true);
        } else if (indexedDoc.getOrDefault(DST_IP, "").equals("10.0.2.3")) {
            Assert.assertEquals(indexedDoc.get("enrichments.hbaseEnrichment." + DST_IP + "."
                    + PLAYFUL_CLASSIFICATION_TYPE + ".orientation"), PLAYFUL_ENRICHMENT.get("orientation"));
            Assert.assertEquals(indexedDoc.get("dst_classification.orientation"),
                    PLAYFUL_ENRICHMENT.get("orientation"));

        }/*from  w  ww  .j  av  a 2 s  . c o  m*/
        if (!indexedDoc.getOrDefault(SRC_IP, "").equals("10.0.2.3")) {
            Assert.assertEquals(indexedDoc.get("is_src_malicious"), false);
        }
    } else {
        Assert.assertEquals(indexedDoc.get("is_src_malicious"), false);
    }
}

From source file:org.apache.metron.enrichment.integration.EnrichmentIntegrationTest.java

private static void threatIntelValidation(Map<String, Object> indexedDoc) {
    if (indexedDoc.getOrDefault(SRC_IP, "").equals("10.0.2.3")
            || indexedDoc.getOrDefault(DST_IP, "").equals("10.0.2.3")) {

        //if we have any threat intel messages, we want to tag is_alert to true
        Assert.assertTrue(keyPatternExists("threatintels.", indexedDoc));
        Assert.assertEquals(indexedDoc.getOrDefault("is_alert", ""), "true");

        // validate threat triage score
        Assert.assertTrue(indexedDoc.containsKey(THREAT_TRIAGE_SCORE_KEY));
        Double score = (Double) indexedDoc.get(THREAT_TRIAGE_SCORE_KEY);
        Assert.assertEquals(score, 10d, 1e-7);

        // validate threat triage rules
        Joiner joiner = Joiner.on(".");
        Stream.of(joiner.join(THREAT_TRIAGE_RULES_KEY, 0, THREAT_TRIAGE_RULE_NAME),
                joiner.join(THREAT_TRIAGE_RULES_KEY, 0, THREAT_TRIAGE_RULE_COMMENT),
                joiner.join(THREAT_TRIAGE_RULES_KEY, 0, THREAT_TRIAGE_RULE_REASON),
                joiner.join(THREAT_TRIAGE_RULES_KEY, 0, THREAT_TRIAGE_RULE_SCORE))
                .forEach(key -> Assert.assertTrue(String.format("Missing expected key: '%s'", key),
                        indexedDoc.containsKey(key)));
    } else {// w  w w .  j  ava 2 s  . c  om
        //For YAF this is the case, but if we do snort later on, this will be invalid.
        Assert.assertNull(indexedDoc.get("is_alert"));
        Assert.assertFalse(keyPatternExists("threatintels.", indexedDoc));
    }

    //ip threat intels
    if (keyPatternExists("threatintels.hbaseThreatIntel.", indexedDoc)) {
        if (indexedDoc.getOrDefault(SRC_IP, "").equals("10.0.2.3")) {
            Assert.assertEquals(
                    indexedDoc.get("threatintels.hbaseThreatIntel." + SRC_IP + "." + MALICIOUS_IP_TYPE),
                    "alert");
        } else if (indexedDoc.getOrDefault(DST_IP, "").equals("10.0.2.3")) {
            Assert.assertEquals(
                    indexedDoc.get("threatintels.hbaseThreatIntel." + DST_IP + "." + MALICIOUS_IP_TYPE),
                    "alert");
        } else {
            Assert.fail("There was a threat intels that I did not expect: " + indexedDoc);
        }
    }

}

From source file:org.briljantframework.data.dataframe.DataFrames.java

public static DataFrame table(Vector a, Vector b) {
    Check.dimension(a.size(), b.size());
    Map<Object, Map<Object, Integer>> counts = new HashMap<>();
    Set<Object> aUnique = new HashSet<>();
    Set<Object> bUnique = new HashSet<>();
    for (int i = 0; i < a.size(); i++) {
        Object va = a.loc().get(i);
        Object vb = b.loc().get(i);
        Map<Object, Integer> countVb = counts.get(va);
        if (countVb == null) {
            countVb = new HashMap<>();
            counts.put(va, countVb);/*from  w  ww. j a va2 s . c  o  m*/
        }
        countVb.compute(vb, (key, value) -> value == null ? 1 : value + 1);
        aUnique.add(va);
        bUnique.add(vb);
    }

    DataFrame.Builder df = DataFrame.builder();
    for (Object i : aUnique) {
        Map<Object, Integer> row = counts.get(i);
        if (row == null) {
            for (Object j : bUnique) {
                df.set(i, j, 0);
            }
        } else {
            for (Object j : bUnique) {
                df.set(i, j, row.getOrDefault(j, 0));
            }
        }
    }
    return df.build();
}

From source file:org.apache.nifi.processors.hl7.ExtractHL7Attributes.java

private static void addSegments(final Segment segment, final Map<String, Segment> segments,
        final Map<String, Integer> segmentIndexes) throws HL7Exception {
    if (!isEmpty(segment)) {
        final String segmentName = segment.getName();
        final StringBuilder sb = new StringBuilder().append(segmentName);
        if (isRepeating(segment)) {
            final int segmentIndex = segmentIndexes.getOrDefault(segmentName, 1);
            sb.append("_").append(segmentIndex);
        }/*from www . ja  v a  2  s. c  om*/
        final String segmentKey = sb.toString();
        segments.put(segmentKey, segment);
    }
}

From source file:com.formkiq.core.form.bean.ObjectBuilder.java

/**
 * Get Field Value Map from Object.//from  w w  w  .ja  va  2  s .co  m
 * @param bean {@link BeanUtilsBean}
 * @param obj {@link Object}
 * @param fieldNames {@link Collection} of {@link String}
 * @return {@link Map}
 * @throws IllegalAccessException IllegalAccessException
 * @throws InvocationTargetException InvocationTargetException
 * @throws NoSuchMethodException NoSuchMethodException
 */
private static Map<String, String> getFieldValueMap(final BeanUtilsBean bean, final Object obj,
        final Collection<String> fieldNames)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    Map<String, String> m = bean.describe(obj);

    if (!isEmpty(fieldNames)) {

        Map<String, String> r = new HashMap<>(fieldNames.size());

        for (String fieldname : fieldNames) {
            r.put(fieldname, m.getOrDefault(fieldname, ""));
        }

        m = r;

    } else {
        m.remove("class");
    }

    return m;
}