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.lightjason.agentspeak.action.buildin.graph.CAdjacencyMatrix.java

/**
 * converts a graph into an adjacency matrix
 *
 * @param p_graph graph/*  ww w. j  a va 2s. c o  m*/
 * @param p_cost map with edges and costs
 * @param p_defaultcost default cost value (on non-existing map values)
 * @param p_type matrix type
 * @return pair of double matrix and vertices
 */
private static Pair<DoubleMatrix2D, Collection<?>> apply(final AbstractGraph<Object, Object> p_graph,
        final Map<?, Number> p_cost, final double p_defaultcost, final EType p_type) {
    // index map for matching vertex to index position within matrix
    final Map<Object, Integer> l_index = new HashMap<>();

    // extract vertices from edges
    p_graph.getEdges().stream().map(p_graph::getEndpoints).flatMap(i -> Stream.of(i.getFirst(), i.getSecond()))
            .forEach(i -> l_index.putIfAbsent(i, 0));

    // define for each vertex an index number in [0, size)
    StreamUtils.zip(l_index.keySet().stream(), IntStream.range(0, l_index.size()).boxed(), ImmutablePair::new)
            .forEach(i -> l_index.put(i.getKey(), i.getValue()));

    final DoubleMatrix2D l_matrix;
    switch (p_type) {
    case SPARSE:
        l_matrix = new SparseDoubleMatrix2D(l_index.size(), l_index.size());
        break;

    default:
        l_matrix = new DenseDoubleMatrix2D(l_index.size(), l_index.size());
    }

    // map costs to matrix
    p_graph.getEdges().stream()
            .map(i -> new ImmutablePair<>(p_graph.getEndpoints(i),
                    p_cost.getOrDefault(i, p_defaultcost).doubleValue()))
            .forEach(i -> l_matrix.setQuick(l_index.get(i.getLeft().getFirst()),
                    l_index.get(i.getLeft().getSecond()),
                    i.getRight() + l_matrix.getQuick(l_index.get(i.getLeft().getFirst()),
                            l_index.get(i.getLeft().getSecond()))));

    return new ImmutablePair<>(l_matrix, new ArrayList<>(l_index.keySet()));
}

From source file:blusunrize.immersiveengineering.client.render.ItemRendererIEOBJ.java

private void renderQuadsForGroups(String[] groups, IOBJModelCallback<ItemStack> callback, IESmartObjModel model,
        List<Pair<BakedQuad, ShaderLayer>> quadsForGroup, ItemStack stack, ShaderCase sCase, ItemStack shader,
        BufferBuilder bb, Tessellator tes, Map<String, Boolean> visible, float partialTicks) {
    quadsForGroup.clear();// ww w .  ja v a  2  s .  co  m
    for (String g : groups) {
        if (visible.getOrDefault(g, Boolean.FALSE) && callback.shouldRenderGroup(stack, g))
            quadsForGroup.addAll(model.addQuadsForGroup(callback, stack, g, sCase, shader).stream()
                    .filter(Objects::nonNull).collect(Collectors.toList()));
        visible.remove(g);
    }
    if (!callback.areGroupsFullbright(stack, groups))
        bb.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);
    else
        bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
    VertexBufferConsumer vbc = new VertexBufferConsumer(bb);
    ShaderLayer lastShaderLayer = null;
    for (Pair<BakedQuad, ShaderLayer> pair : quadsForGroup) {
        BakedQuad bq = pair.getKey();
        ShaderLayer layer = pair.getValue();
        //Switch to or between dynamic layers
        boolean switchDynamic = layer != lastShaderLayer;
        if (switchDynamic) {
            //interrupt batch
            tes.draw();

            if (lastShaderLayer != null)//finish dynamic call on last layer
                lastShaderLayer.modifyRender(false, partialTicks);

            //set new layer
            lastShaderLayer = layer;

            if (lastShaderLayer != null)//start dynamic call on layer
                lastShaderLayer.modifyRender(true, partialTicks);
            //start new batch
            if (!callback.areGroupsFullbright(stack, groups))
                bb.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);
            else
                bb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);

        }
        bq.pipe(vbc);
    }
    tes.draw();
    if (lastShaderLayer != null)//finish dynamic call on final layer
        lastShaderLayer.modifyRender(false, partialTicks);

}

From source file:org.apache.metron.profiler.client.stellar.GetProfile.java

/**
 * Create an HBase table used when accessing HBase.
 * @param global The global configuration.
 * @return/*from   w w  w  .ja  v  a 2  s  .c  om*/
 */
private HTableInterface getTable(Map<String, Object> global) {

    String tableName = (String) global.getOrDefault(PROFILER_HBASE_TABLE, "profiler");
    TableProvider provider = getTableProvider(global);

    try {
        return provider.getTable(HBaseConfiguration.create(), tableName);

    } catch (IOException e) {
        throw new IllegalArgumentException(String.format("Unable to access table: %s", tableName));
    }
}

From source file:org.apache.metron.profiler.client.stellar.GetProfile.java

/**
 * Create the TableProvider to use when accessing HBase.
 * @param global The global configuration.
 *///from   ww w.  ja  v  a2 s  . c o m
private TableProvider getTableProvider(Map<String, Object> global) {
    String clazzName = (String) global.getOrDefault(PROFILER_HBASE_TABLE_PROVIDER,
            HTableProvider.class.getName());

    TableProvider provider;
    try {
        Class<? extends TableProvider> clazz = (Class<? extends TableProvider>) Class.forName(clazzName);
        provider = clazz.newInstance();

    } catch (Exception e) {
        provider = new HTableProvider();
    }

    return provider;
}

From source file:org.apache.metron.parsers.json.JSONMapParser.java

@Override
public void configure(Map<String, Object> config) {
    String strategyStr = (String) config.getOrDefault(MAP_STRATEGY_CONFIG, MapStrategy.DROP.name());
    mapStrategy = MapStrategy.valueOf(strategyStr);
    if (config.containsKey(JSONP_QUERY)) {
        typeRef = new TypeRef<List<Map<String, Object>>>() {
        };/*from   w  w  w. j a va2  s . c o  m*/
        jsonpQuery = (String) config.get(JSONP_QUERY);

        if (!StringUtils.isBlank(jsonpQuery) && config.containsKey(WRAP_JSON)) {
            Object wrapObject = config.get(WRAP_JSON);
            if (wrapObject instanceof String) {
                wrapJson = Boolean.valueOf((String) wrapObject);
            } else if (wrapObject instanceof Boolean) {
                wrapJson = (Boolean) config.get(WRAP_JSON);
            }
            String entityName = (String) config.get(WRAP_ENTITY_NAME);
            if (!StringUtils.isBlank(entityName)) {
                wrapEntityName = entityName;
            }
        }

        Configuration.setDefaults(new Configuration.Defaults() {

            private final JsonProvider jsonProvider = new JacksonJsonProvider();
            private final MappingProvider mappingProvider = new JacksonMappingProvider();

            @Override
            public JsonProvider jsonProvider() {
                return jsonProvider;
            }

            @Override
            public MappingProvider mappingProvider() {
                return mappingProvider;
            }

            @Override
            public Set<Option> options() {
                return EnumSet.of(Option.SUPPRESS_EXCEPTIONS);
            }
        });

        if (CacheProvider.getCache() == null) {
            CacheProvider.setCache(new LRUCache(100));
        }
    }
}

From source file:com.couchbase.beersample.BeerController.java

@RequestMapping(value = "/beer/edit", method = RequestMethod.GET)
String editGet(Model model, @RequestParam(value = "beer", required = true) String beer) {
    JsonDocument response = ConnectionManager.getItem(beer);
    if (response != null) {
        Map<String, Object> map = response.content().toMap();
        model.addAttribute("beer", map);
        BeerModel beerModel = new BeerModel();

        beerModel.setId(response.id());//w w  w .  j a va  2 s  .  com
        beerModel.setName(map.getOrDefault("name", "").toString());
        beerModel.setStyle(map.getOrDefault("style", "").toString());
        beerModel.setDescription(map.getOrDefault("description", "").toString());
        beerModel.setCategory(map.getOrDefault("category", "").toString());
        beerModel.setAbv(map.getOrDefault("abv", "").toString());
        beerModel.setSrm(map.getOrDefault("srm", "").toString());
        beerModel.setIbu(map.getOrDefault("ibu", "").toString());
        beerModel.setUpc(map.getOrDefault("upc", "").toString());
        beerModel.setBrewery(map.getOrDefault("brewery_id", "").toString());

        model.addAttribute("beerModel", beerModel);
    }
    return "beerEdit";
}

From source file:org.lightjason.agentspeak.action.builtin.graph.CAdjacencyMatrix.java

/**
 * converts a graph into an adjacency matrix
 *
 * @param p_graph graph//w ww.  j a  v  a 2s .  co m
 * @param p_cost map with edges and costs
 * @param p_defaultcost default cost value (on non-existing map values)
 * @param p_type matrix type
 * @return pair of double matrix and vertices
 */
private static Pair<DoubleMatrix2D, Collection<?>> apply(@Nonnull final Graph<Object, Object> p_graph,
        @Nonnull final Map<?, Number> p_cost, final double p_defaultcost, @Nonnull final EType p_type) {
    // index map for matching vertex to index position within matrix
    final Map<Object, Integer> l_index = new HashMap<>();

    // extract vertices from edges
    p_graph.getEdges().stream().map(p_graph::getEndpoints).flatMap(i -> Stream.of(i.getFirst(), i.getSecond()))
            .forEach(i -> l_index.putIfAbsent(i, 0));

    // define for each vertex an index number in [0, size)
    StreamUtils.zip(l_index.keySet().stream(), IntStream.range(0, l_index.size()).boxed(), ImmutablePair::new)
            .forEach(i -> l_index.put(i.getKey(), i.getValue()));

    final DoubleMatrix2D l_matrix;
    switch (p_type) {
    case SPARSE:
        l_matrix = new SparseDoubleMatrix2D(l_index.size(), l_index.size());
        break;

    default:
        l_matrix = new DenseDoubleMatrix2D(l_index.size(), l_index.size());
    }

    // map costs to matrix
    p_graph.getEdges().stream()
            .map(i -> new ImmutablePair<>(p_graph.getEndpoints(i),
                    p_cost.getOrDefault(i, p_defaultcost).doubleValue()))
            .forEach(i -> l_matrix.setQuick(l_index.get(i.getLeft().getFirst()),
                    l_index.get(i.getLeft().getSecond()),
                    i.getRight() + l_matrix.getQuick(l_index.get(i.getLeft().getFirst()),
                            l_index.get(i.getLeft().getSecond()))));

    // on undirected graphs, add the transposefor cost duplicating
    if (p_graph instanceof UndirectedGraph<?, ?>)
        l_matrix.assign(IAlgebra.ALGEBRA.transpose(l_matrix).copy(), Functions.plus);

    return new ImmutablePair<>(l_matrix, new ArrayList<>(l_index.keySet()));
}

From source file:com.couchbase.storm.examples.SentimentBolt.java

@Override
public void execute(Tuple tuple, BasicOutputCollector collector) {
    String content = (String) tuple.getValueByField("content");
    ObjectMapper mapper = new ObjectMapper();
    try {/*  ww  w  . j a  v a 2  s  .c o  m*/
        Map<String, Object> jsonMap = mapper.readValue(content, new TypeReference<Map<String, Object>>() {
        });
        if (!jsonMap.containsKey("sentiment") || !jsonMap.containsKey("sentimentScore")) {
            String tweet = (String) jsonMap.getOrDefault("text", "");
            int sentiment = NLP.findSentiment(tweet);
            jsonMap.put("sentimentScore", sentiment);
            jsonMap.put("sentiment", scores.get(sentiment));
            String json = mapper.writeValueAsString(jsonMap);

            collector.emit(new Values(tuple.getValueByField("type"), tuple.getValueByField("key"), json));
        }

    } catch (IOException e) {

    }
}

From source file:io.stallion.restfulEndpoints.QueryToPager.java

protected void process() {
    // ?filters=&search=&page=&sort=&filter_by...
    Map<String, String> params = this.request.getQueryParams();
    String search = params.getOrDefault("search", null);
    if (!empty(search)) {
        if (!empty(_searchFields)) {
            this.chain = chain.search(search, asArray(_searchFields, String.class));
        } else {/*from  w w w.ja v  a 2s .  c  om*/
            Log.warn("Search included, but no search fields defined");
        }
    }
    String filters = params.getOrDefault("filters", null);
    if (!empty(filters)) {
        List<LinkedHashMap> filterObjects = JSON.parseList(filters);
        for (LinkedHashMap<String, Object> o : filterObjects) {
            String field = o.get("name").toString();
            if (!_allFilters && !_allowedFilters.contains(field)) {
                Log.warn("Filter not allowed: " + field);
                continue;
            }

            Object value = o.get("value");
            if (value instanceof Collection) {
                value = new ArrayList((Collection) value);
            }
            String operation = (String) o.getOrDefault("op", "=");
            this.chain = chain.filter(field, value, operation);
        }
    }
    String sort = or(params.getOrDefault("sort", null), defaultSort);
    if (!empty(sort)) {
        SortDirection dir = SortDirection.ASC;
        if (sort.startsWith("-")) {
            sort = sort.substring(1);
            dir = SortDirection.DESC;
        }
        if (!_allSorts && !_allowedSortable.contains(sort)) {
            Log.warn("Sort not allowed: " + sort);
        } else {
            this.chain = chain.sortBy(sort, dir);
        }
    }

    for (String filter : request.getQueryParamAsList("filter_by")) {
        if (empty(filter) || !filter.contains(":")) {
            continue;
        }
        String[] parts = StringUtils.split(filter, ":", 3);
        String key = parts[0];
        if (_allFilters && !_allowedFilters.contains(key)) {
            Log.warn("Filter not allowed: " + key);
            continue;
        }
        String val;
        String op = "eq";
        if (parts.length > 2) {
            op = parts[1];
            val = parts[2];
        } else {
            val = parts[1];
        }
        this.chain = chain.filter(key, val, op);

    }

}

From source file:com.netflix.spectator.controllers.MetricsController.java

/**
 * Endpoint for querying current metric values.
 *
 * The result is a JSON document describing the metrics and their values.
 * The result can be filtered using query parameters or configuring the
 * controller instance itself./*from w  w w . j  a va  2  s  . co  m*/
 */
@RequestMapping(method = RequestMethod.GET)
public ApplicationRegistry getMetrics(@RequestParam Map<String, String> filters) throws IOException {
    boolean all = filters.get("all") != null;
    String filterMeterNameRegex = filters.getOrDefault("meterNameRegex", "");
    String filterTagNameRegex = filters.getOrDefault("tagNameRegex", "");
    String filterTagValueRegex = filters.getOrDefault("tagValueRegex", "");
    TagMeasurementFilter queryFilter = new TagMeasurementFilter(filterMeterNameRegex, filterTagNameRegex,
            filterTagValueRegex);
    Predicate<Measurement> filter;
    if (all) {
        filter = queryFilter;
    } else {
        filter = queryFilter.and(getDefaultMeasurementFilter());
    }

    ApplicationRegistry response = new ApplicationRegistry();
    response.setApplicationName(applicationName);
    response.setApplicationVersion(applicationVersion);
    response.setMetrics(encodeRegistry(registry, filter));
    return response;
}