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:org.workspace7.moviestore.controller.SessionsController.java

@CrossOrigin
@RequestMapping(method = RequestMethod.GET, value = "/sessions", produces = "application/json")
public @ResponseBody String sessions(HttpServletRequest request) {

    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");

    ObjectMapper sessions = new ObjectMapper();

    ObjectNode rootNode = sessions.createObjectNode().put("hostName", hostname);

    String jsonResponse = "{\"message\":\"NO SESSIONS AVAILABLE\"}";

    try {//from   w  w w. j  a v  a2  s. c  o  m

        AdvancedCache<Object, Object> sessionCache = cacheManager.getCache("moviestore-sessions-cache")
                .getAdvancedCache();

        if (sessionCache != null && !sessionCache.isEmpty()) {

            ArrayNode sessionsArray = rootNode.arrayNode();

            Map<Object, Object> sessionsCacheMap = sessionCache.entrySet().stream().collect(CacheCollectors
                    .serializableCollector(() -> Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

            sessionsCacheMap.forEach((s, o) -> {

                MapSession mapSession = (MapSession) o;

                log.debug("Session Controller Map Session Id {} value : {}", s, mapSession);

                if (log.isDebugEnabled()) {
                    StringBuilder debugMessage = new StringBuilder();

                    mapSession.getAttributeNames().forEach(key -> {
                        debugMessage.append("Attribute :" + s + " Value: " + mapSession.getAttribute(key));
                    });

                    log.debug("Map Session Attributes : {}", debugMessage);
                }

                MovieCart movieCart = mapSession.getAttribute(ShoppingCartController.SESSION_ATTR_MOVIE_CART);

                if (movieCart != null) {

                    ObjectNode movieCartNode = sessions.createObjectNode();
                    movieCartNode.put("sessionId", mapSession.getId());
                    movieCartNode.put("orderId", movieCart.getOrderId());

                    ArrayNode movieItemsNode = movieCartNode.arrayNode();

                    movieCart.getMovieItems().forEach((movieId, qty) -> {
                        ObjectNode movieItem = movieItemsNode.addObject();
                        movieItem.put("movieId", movieId);
                        movieItem.put("orderQuantity", qty);
                    });

                    movieCartNode.set("movies", movieItemsNode);

                    sessionsArray.add(movieCartNode);
                }
            });
            rootNode.set("sessions", sessionsArray);
        }
        jsonResponse = sessions.writeValueAsString(rootNode);
    } catch (Exception e) {
        log.error("Error building JSON response for sesisons", e);
    }

    return jsonResponse;
}

From source file:org.apache.pulsar.broker.loadbalance.impl.LoadManagerShared.java

/**
 * It returns map of broker and count of namespace that are belong to the same anti-affinity group as given
 * {@param namespaceName}/*from   ww  w  .  j a va  2  s . c  o  m*/
 *
 * @param pulsar
 * @param namespaceName
 * @param brokerToNamespaceToBundleRange
 * @return
 */
public static CompletableFuture<Map<String, Integer>> getAntiAffinityNamespaceOwnedBrokers(
        final PulsarService pulsar, String namespaceName,
        Map<String, Map<String, Set<String>>> brokerToNamespaceToBundleRange) {

    CompletableFuture<Map<String, Integer>> antiAffinityNsBrokersResult = new CompletableFuture<>();
    ZooKeeperDataCache<Policies> policiesCache = pulsar.getConfigurationCache().policiesCache();

    policiesCache.getAsync(path(POLICIES, namespaceName)).thenAccept(policies -> {
        if (!policies.isPresent() || StringUtils.isBlank(policies.get().antiAffinityGroup)) {
            antiAffinityNsBrokersResult.complete(null);
            return;
        }
        final String antiAffinityGroup = policies.get().antiAffinityGroup;
        final Map<String, Integer> brokerToAntiAffinityNamespaceCount = new ConcurrentHashMap<>();
        final List<CompletableFuture<Void>> futures = Lists.newArrayList();
        brokerToNamespaceToBundleRange.forEach((broker, nsToBundleRange) -> {
            nsToBundleRange.forEach((ns, bundleRange) -> {
                CompletableFuture<Void> future = new CompletableFuture<>();
                futures.add(future);
                policiesCache.getAsync(path(POLICIES, ns)).thenAccept(nsPolicies -> {
                    if (nsPolicies.isPresent()
                            && antiAffinityGroup.equalsIgnoreCase(nsPolicies.get().antiAffinityGroup)) {
                        brokerToAntiAffinityNamespaceCount.compute(broker,
                                (brokerName, count) -> count == null ? 1 : count + 1);
                    }
                    future.complete(null);
                }).exceptionally(ex -> {
                    future.complete(null);
                    return null;
                });
            });
        });
        FutureUtil.waitForAll(futures)
                .thenAccept(r -> antiAffinityNsBrokersResult.complete(brokerToAntiAffinityNamespaceCount));
    }).exceptionally(ex -> {
        // namespace-policies has not been created yet
        antiAffinityNsBrokersResult.complete(null);
        return null;
    });
    return antiAffinityNsBrokersResult;
}

From source file:org.onosproject.imr.rest.ImrWebResource.java

/**
 * Build the Json Nodes from the intent stats retrieved from {@link IntentMonitorAndRerouteService}.
 *
 * @param mapKeyToStats Intent statistics
 * @return {@link ArrayNode} built from the statistics
 *//*from  w  w  w.j a  v  a 2  s.  com*/
private ArrayNode getJsonNodesIntentStats(Map<ApplicationId, Map<Key, List<FlowEntry>>> mapKeyToStats) {
    final ArrayNode rootArrayNode = mapper.createArrayNode();
    mapKeyToStats.forEach((appId, mapIntentKeyStats) -> {
        ObjectNode appObjNode = codec(ApplicationId.class).encode(appId, this);
        ArrayNode intentArrayNode = appObjNode.putArray("intents");
        mapIntentKeyStats.forEach((intentKey, lstStats) -> {
            ObjectNode intentKeyObjNode = mapper.createObjectNode();
            ArrayNode statsArrayNode = intentKeyObjNode.putArray(intentKey.toString());
            lstStats.forEach(stat -> {
                statsArrayNode.add(codec(FlowEntry.class).encode(stat, this));
            });

            intentArrayNode.add(intentKeyObjNode);
        });

        rootArrayNode.add(appObjNode);
    });
    return rootArrayNode;
}

From source file:com.streamsets.datacollector.pipeline.executor.spark.yarn.YarnAppLauncher.java

private void verifyKeyValueArgs(Stage.Context context, Map<String, String> params, String config,
        List<Stage.ConfigIssue> issues) {
    params.forEach((String k, String v) -> {
        if (!StringUtils.isEmpty(k) && StringUtils.isEmpty(v)) {
            issues.add(context.createConfigIssue(SPARK_GROUP, config, SPARK_EXEC_09, k));
        }//w w w .jav  a  2  s  .  c o  m
        if (StringUtils.isEmpty(k) && !StringUtils.isEmpty(v)) {
            issues.add(context.createConfigIssue(SPARK_GROUP, config, SPARK_EXEC_10, v));
        }
    });
}

From source file:org.mule.service.soap.client.SoapCxfClient.java

private Map<String, Attachment> transformToCxfAttachments(Map<String, SoapAttachment> attachments) {
    ImmutableMap.Builder<String, Attachment> builder = ImmutableMap.builder();
    attachments.forEach((name, value) -> {
        try {/*from w w w . ja v a2s  .c o  m*/
            builder.put(name,
                    new AttachmentImpl(name, toDataHandler(name, value.getContent(), value.getContentType())));
        } catch (IOException e) {
            throw new BadRequestException(format("Error while preparing attachment [%s] for upload", name), e);
        }
    });
    return builder.build();
}

From source file:org.apache.tinkerpop.gremlin.console.jsr223.DriverRemoteAcceptor.java

@Override
public Object configure(final List<String> args) throws RemoteException {
    final String option = args.size() == 0 ? "" : args.get(0);
    if (!POSSIBLE_TOKENS.contains(option))
        throw new RemoteException(String.format("The 'config' option expects one of ['%s'] as an argument",
                String.join(",", POSSIBLE_TOKENS)));

    final List<String> arguments = args.subList(1, args.size());

    if (option.equals(TOKEN_HELP)) {
        return ":remote config [timeout [<ms>|none]|alias [reset|show|<alias> <actual>]|help]";
    } else if (option.equals(TOKEN_TIMEOUT)) {
        final String errorMessage = "The timeout option expects a positive integer representing milliseconds or 'none' as an argument";
        if (arguments.size() != 1)
            throw new RemoteException(errorMessage);
        try {//w w w  .j a  v a2 s. c  o m
            // first check for MAX timeout then NONE and finally parse the config to int. "max" is now "deprecated"
            // in the sense that it will no longer be promoted. support for it will be removed at a later date
            timeout = arguments.get(0).equals(TOKEN_MAX) ? Integer.MAX_VALUE
                    : arguments.get(0).equals(TOKEN_NONE) ? NO_TIMEOUT : Integer.parseInt(arguments.get(0));
            if (timeout < NO_TIMEOUT)
                throw new RemoteException("The value for the timeout cannot be less than " + NO_TIMEOUT);
            return timeout == NO_TIMEOUT ? "Remote timeout is disabled"
                    : "Set remote timeout to " + timeout + "ms";
        } catch (Exception ignored) {
            throw new RemoteException(errorMessage);
        }
    } else if (option.equals(TOKEN_ALIAS)) {
        if (arguments.size() == 1 && arguments.get(0).equals(TOKEN_RESET)) {
            aliases.clear();
            return "Aliases cleared";
        }

        if (arguments.size() == 1 && arguments.get(0).equals(TOKEN_SHOW)) {
            return aliases;
        }

        if (arguments.size() % 2 != 0)
            throw new RemoteException(
                    "Arguments to alias must be 'reset' to clear any existing alias settings or key/value alias/binding pairs");

        final Map<String, Object> aliasMap = ElementHelper.asMap(arguments.toArray());
        aliases.clear();
        aliasMap.forEach((k, v) -> aliases.put(k, v.toString()));
        return aliases;
    }

    return this.toString();
}

From source file:org.commonjava.indy.httprox.NPMStyleSuccessiveRetrievalTest.java

@Test
public void run() throws Exception {
    final String testRepo = "test";
    String pkgPath = "test-me";
    String tgzPath = "test-me/-/test-me-1.0.0.tgz";

    final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("npm/test-me");

    byte[] pkg = IOUtils.toByteArray(is);

    byte[] tgz = new byte[32];
    new Random().nextBytes(tgz);

    final String pkgUrl = server.formatUrl(testRepo, pkgPath);
    final String tgzUrl = server.formatUrl(testRepo, tgzPath);

    Map<String, byte[]> contentMap = new LinkedHashMap<>();
    contentMap.put(pkgUrl, pkg);/*w  w  w. ja  va 2s .  c o m*/
    contentMap.put(tgzUrl, tgz);

    server.expect(pkgUrl, 200, new ByteArrayInputStream(pkg));
    server.expect(tgzUrl, 200, new ByteArrayInputStream(tgz));

    contentMap.forEach((url, expect) -> {
        CloseableHttpResponse response = null;
        InputStream stream = null;
        final HttpGet get = new HttpGet(url);
        CloseableHttpClient httpClient = null;
        try {
            httpClient = proxiedHttp();

            response = httpClient.execute(get);
            stream = response.getEntity().getContent();

            byte[] content = IOUtils.toByteArray(stream);

            assertThat(url + ": content was null!", content, notNullValue());
            assertThat(url + ": retrieved content was wrong!", content, equalTo(expect));
        } catch (Exception e) {
            e.printStackTrace();
            fail(url + ": Failed to retrieve file. Reason: " + e.getMessage());
        } finally {
            IOUtils.closeQuietly(stream);
            HttpResources.cleanupResources(get, response, httpClient);
        }
    });
}

From source file:com.streamsets.pipeline.stage.processor.parser.sql.SqlParserProcessor.java

private Field createUnparsedField(Map<String, String> unparsed) {
    Map<String, Field> fields = new HashMap<>();
    unparsed.forEach((k, v) -> fields.put(k, Field.create(v)));
    return Field.create(fields);
}

From source file:ijfx.ui.explorer.DefaultFolderManagerService.java

private synchronized void load() {
    Map<String, String> folderMap = jsonPrefService.loadMapFromJson(FOLDER_PREFERENCE_FILE, String.class,
            String.class);
    folderMap.forEach((name, folderPath) -> {
        DefaultFolder folder = new DefaultFolder(new File(folderPath));
        context.inject(folder);// w w  w .  j a va  2s .  c  o m
        folder.setName(name);
        folderList.add(folder);
    });
}

From source file:cc.redpen.formatter.JSONFormatter.java

@Override
public void format(PrintWriter pw, Map<Document, List<ValidationError>> docErrorsMap)
        throws RedPenException, IOException {
    BufferedWriter writer = new BufferedWriter(new PrintWriter(pw));
    JSONArray errors = new JSONArray();
    docErrorsMap.forEach((doc, errorList) -> errors.put(asJSON(doc, errorList)));
    writer.write(errors.toString());/* w  ww  .  j a  va  2 s  . c o m*/
    writer.flush();
}