Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

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

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:com.cloudera.oryx.example.serving.ExampleServingModelManager.java

@Override
public void consumeKeyMessage(String key, String message, Configuration hadoopConf) throws IOException {
    switch (key) {
    case "MODEL":
        @SuppressWarnings("unchecked")
        Map<String, Integer> model = (Map<String, Integer>) new ObjectMapper().readValue(message, Map.class);
        synchronized (distinctOtherWords) {
            distinctOtherWords.clear();//w  w w .j  a v a 2s.  co  m
            model.forEach(distinctOtherWords::put);
        }
        break;
    case "UP":
        String[] wordCount = message.split(",");
        synchronized (distinctOtherWords) {
            distinctOtherWords.put(wordCount[0], Integer.valueOf(wordCount[1]));
        }
        break;
    default:
        throw new IllegalArgumentException("Bad key " + key);
    }
}

From source file:com.networknt.graphql.validator.ValidatorHandler.java

@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    String path = exchange.getRequestPath();
    if (!path.equals(GraphqlUtil.config.getPath()) && !path.equals(GraphqlUtil.config.getSubscriptionsPath())) {
        // invalid GraphQL path
        logger.warn("Invalid graphql path requested: " + path);
        Status status = new Status(STATUS_GRAPHQL_INVALID_PATH, path, GraphqlUtil.config.getPath());
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseSender().send(status.toString());
        return;/*  ww w.ja va  2  s.  c  o m*/
    }
    // verify the method is get or post.
    HttpString method = exchange.getRequestMethod();
    if (Methods.GET.equals(method)) {
        // validate query parameter exists
        Map<String, Deque<String>> queryParameters = exchange.getQueryParameters();
        final Map<String, Object> requestParameters = new HashMap<>();
        queryParameters.forEach((k, v) -> requestParameters.put(k, v.getFirst()));
        exchange.putAttachment(GraphqlUtil.GRAPHQL_PARAMS, requestParameters);
        next.handleRequest(exchange);
    } else if (Methods.POST.equals(method) || Methods.OPTIONS.equals(method)) {
        exchange.getRequestReceiver().receiveFullString((exchange1, s) -> {
            try {
                logger.debug("s = " + s);
                if (s != null && s.length() > 0) {
                    Map<String, Object> requestParameters = Config.getInstance().getMapper().readValue(s,
                            new TypeReference<HashMap<String, Object>>() {
                            });
                    logger.debug("requestParameters = " + requestParameters);
                    exchange1.putAttachment(GraphqlUtil.GRAPHQL_PARAMS, requestParameters);
                }
                next.handleRequest(exchange1);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    } else {
        // invalid GraphQL method
        Status status = new Status(STATUS_GRAPHQL_INVALID_METHOD, method);
        exchange.setStatusCode(status.getStatusCode());
        exchange.getResponseHeaders().put(Headers.ALLOW, "GET, POST, OPTIONS");
        exchange.getResponseSender().send(status.toString());
    }

}

From source file:com.cloudera.oryx.example.speed.ExampleSpeedModelManager.java

@Override
public void consumeKeyMessage(String key, String message, Configuration hadoopConf) throws IOException {
    switch (key) {
    case "MODEL":
        @SuppressWarnings("unchecked")
        Map<String, Integer> model = (Map<String, Integer>) new ObjectMapper().readValue(message, Map.class);
        synchronized (distinctOtherWords) {
            distinctOtherWords.clear();/*from  w ww. j a  va2  s.com*/
            model.forEach(distinctOtherWords::put);
        }
        break;
    case "UP":
        // ignore
        break;
    default:
        throw new IllegalArgumentException("Bad key " + key);
    }
}

From source file:com.baidu.rigel.biplatform.ac.util.HttpRequest.java

/**
 * ?URL??POST//from ww w . j a va2s .  c  o m
 * 
 * @param client httpclient
 * @param url ??URL
 * @param param ?? name1=value1&name2=value2 ?
 * @return URL ??
 */
public static String sendPost(HttpClient client, String url, Map<String, String> params) {
    if (client == null) {
        throw new IllegalArgumentException("client is null");
    }

    if (params == null) {
        params = new HashMap<String, String>(1);
    }
    String requestUrl = processPlaceHolder(url, params);

    String cookie = params.remove(COOKIE_PARAM_NAME);
    if (requestUrl.contains("?")) {
        String[] urls = requestUrl.split("?");
        requestUrl = urls[0];
        String[] urlParams = urls[1].split("&");
        for (String param : urlParams) {
            String[] paramSplit = param.split("=");
            params.put(paramSplit[0], paramSplit[1]);
        }
    }

    List<NameValuePair> nameValues = new ArrayList<NameValuePair>();
    params.forEach((k, v) -> {
        NameValuePair nameValuePair = new BasicNameValuePair(k, v);
        nameValues.add(nameValuePair);
    });

    String prefix = "", suffix = "";
    String[] addresses = new String[] { requestUrl };
    if (requestUrl.contains("[") && requestUrl.contains("]")) {
        addresses = requestUrl.substring(requestUrl.indexOf("[") + 1, requestUrl.indexOf("]")).split(" ");
        prefix = requestUrl.substring(0, requestUrl.indexOf("["));
        suffix = requestUrl.substring(requestUrl.indexOf("]") + 1);
    }
    LOGGER.info("start to send post:" + requestUrl);
    long current = System.currentTimeMillis();
    for (String address : addresses) {
        String postUrl = prefix + address + suffix;
        LOGGER.info("post url is : " + postUrl);
        try {
            HttpUriRequest request = RequestBuilder.post().setUri(postUrl) // .addParameters(nameValues.toArray(new NameValuePair[0]))
                    .setEntity(new UrlEncodedFormEntity(nameValues, "utf-8")).build();
            if (StringUtils.isNotBlank(cookie)) {
                // ?cookie
                request.addHeader(new BasicHeader(COOKIE_PARAM_NAME, cookie));
            }
            //                client.
            HttpResponse response = client.execute(request);
            String content = processHttpResponse(client, response, params, false);
            StringBuilder sb = new StringBuilder();
            sb.append("end send post :").append(postUrl).append(" params:").append(nameValues).append(" cost:")
                    .append(System.currentTimeMillis() - current);
            LOGGER.info(sb.toString());
            return content;
        } catch (Exception e) {
            LOGGER.warn("send post error " + requestUrl + ",retry next one", e);
        }
    }
    throw new RuntimeException("send post failed[" + requestUrl + "]. params :" + nameValues);

}

From source file:org.opendatakit.briefcase.model.BriefcasePreferences.java

/**
 * Associates the specified key/value map in this preference node.
 *
 * @param keyValues/*from w ww .  j  a  va  2 s .  com*/
 *          map of keys and values to ve associated.
 */
public void putAll(Map<String, String> keyValues) {
    keyValues.forEach(this::put);
}

From source file:org.springframework.transaction.interceptor.MethodMapTransactionAttributeSource.java

/**
 * Initialize the specified {@link #setMethodMap(java.util.Map) "methodMap"}, if any.
 * @param methodMap Map from method names to {@code TransactionAttribute} instances
 * @see #setMethodMap//from   w w w .j  a va  2 s. com
 */
protected void initMethodMap(@Nullable Map<String, TransactionAttribute> methodMap) {
    if (methodMap != null) {
        methodMap.forEach(this::addTransactionalMethod);
    }
}

From source file:org.janusgraph.diskstorage.common.LocalStoreManagerTest.java

public LocalStoreManager getStoreManager(Map<ConfigOption, String> map) throws BackendException {
    final ModifiableConfiguration mc = new ModifiableConfiguration(ROOT_NS,
            new CommonsConfiguration(new BaseConfiguration()), NONE);
    map.forEach(mc::set);
    return new LocalStoreManagerSampleImplementation(mc);
}

From source file:org.basinmc.irc.bridge.github.GitHubServerHandler.java

/**
 * Converts a nested map into a flat map consisting of dot separated property keys.
 *
 * @param original a nested map./*from   ww  w.j av  a2 s .  com*/
 * @return a flat map.
 */
@Nonnull
@SuppressWarnings("unchecked")
private Map flatMap(@Nonnull Map original) {
    Map flat = new HashMap<>();

    original.forEach((k, v) -> {
        if (v instanceof Map) {
            this.flatMap((Map) v).forEach((j, t) -> flat.put(k + "." + j, t));
        } else {
            flat.put(k, v);
        }
    });

    return flat;
}

From source file:com.uber.hoodie.io.strategy.TestHoodieCompactionStrategy.java

private List<HoodieCompactionOperation> createCompactionOperations(HoodieWriteConfig config,
        Map<Long, List<Long>> sizesMap, Map<Long, String> keyToPartitionMap) {
    List<HoodieCompactionOperation> operations = Lists.newArrayList(sizesMap.size());

    sizesMap.forEach((k, v) -> {
        HoodieDataFile df = TestHoodieDataFile.newDataFile(k);
        String partitionPath = keyToPartitionMap.get(k);
        List<HoodieLogFile> logFiles = v.stream().map(TestHoodieLogFile::newLogFile)
                .collect(Collectors.toList());
        operations.add(new HoodieCompactionOperation(df.getCommitTime(),
                logFiles.stream().map(s -> s.getPath().toString()).collect(Collectors.toList()), df.getPath(),
                df.getFileId(), partitionPath, config.getCompactionStrategy().captureMetrics(config,
                        Optional.of(df), partitionPath, logFiles)));
    });/*from www.j av  a2s. c  o  m*/
    return operations;
}

From source file:org.apache.james.mailrepository.cassandra.CassandraMailRepositoryMailDAO.java

private PerRecipientHeaders fromHeaderMap(Map<String, UDTValue> rawMap) {
    PerRecipientHeaders result = new PerRecipientHeaders();

    rawMap.forEach((key,
            value) -> result.addHeaderForRecipient(PerRecipientHeaders.Header.builder()
                    .name(value.getString(HEADER_NAME)).value(value.getString(HEADER_VALUE)).build(),
                    toMailAddress(key)));
    return result;
}