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.adobe.ags.curly.controller.ActionRunner.java

private void applyMultiVariablesToMap(Map<String, String> variables, Map<String, List<String>> target) {
    Set<String> variableTokens = ActionUtils.getVariableNames(action);

    Map<String, List<String>> newValues = new HashMap<>();
    Set removeSet = new HashSet<>();

    target.forEach((paramName, paramValues) -> {
        StringProperty paramNameProperty = new SimpleStringProperty(paramName);
        variableTokens.forEach((String originalName) -> {
            String[] variableNameParts = originalName.split("\\|");
            String variableName = variableNameParts[0];
            String variableNameMatchPattern = Pattern.quote("${" + originalName + "}");
            String val = variables.get(variableName);
            if (val == null) {
                val = "";
            }//from w  w  w . j  a  v  a2 s .  c o  m
            String variableValue = Matcher.quoteReplacement(val);
            String newParamName = paramNameProperty.get().replaceAll(variableNameMatchPattern, variableValue);
            removeSet.add(paramNameProperty.get());
            removeSet.add(paramName);
            if (newValues.get(paramNameProperty.get()) == null) {
                newValues.put(paramNameProperty.get(), new ArrayList<>(paramValues.size()));
            }
            if (newValues.get(newParamName) == null) {
                newValues.put(newParamName, new ArrayList<>(paramValues.size()));
            }
            List<String> newParamValues = newValues.get(paramNameProperty.get());
            for (int i = 0; i < paramValues.size(); i++) {
                String newParamValue = newParamValues != null && newParamValues.size() > i
                        && newParamValues.get(i) != null ? newParamValues.get(i) : paramValues.get(i);

                // fix for removing JCR values (setting them to an empty
                // string deletes them from the JCR)
                if (null == newParamValue) {
                    newParamValue = "";
                }

                newParamValue = newParamValue.replaceAll(variableNameMatchPattern, variableValue);
                if (newParamName.contains("/") && newParamValue.equals("@" + newParamName)) {
                    // The upload name should actually be the file name, not the full path of the file.
                    removeSet.add(newParamName);
                    newValues.remove(newParamName);
                    newParamName = newParamName.substring(newParamName.lastIndexOf("/") + 1);
                    newValues.put(newParamName, newParamValues);
                }
                if (newValues.get(newParamName).size() == i) {
                    newValues.get(newParamName).add(newParamValue);
                } else {
                    newValues.get(newParamName).set(i, newParamValue);
                }
            }
            if (!paramNameProperty.get().equals(newParamName)) {
                newValues.remove(paramNameProperty.get());
            }
            paramNameProperty.set(newParamName);
        });
    });
    target.keySet().removeAll(removeSet);
    target.putAll(newValues);
}

From source file:org.springframework.security.web.method.ResolvableMethod.java

private String formatAnnotation(Annotation annotation) {
    Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
    map.forEach((key, value) -> {
        if (value.equals(ValueConstants.DEFAULT_NONE)) {
            map.put(key, "NONE");
        }//w w  w  .  jav a  2 s. co m
    });
    return annotation.annotationType().getName() + map;
}

From source file:edu.ucsd.sbrg.escher.model.EscherMap.java

@JsonProperty("reactions")
public void setReactions(Map<String, EscherReaction> reactions) {
    reactions.forEach((k, v) -> v.setId(k));
    this.reactions = reactions;
}

From source file:com.baidu.rigel.biplatform.tesseract.meta.impl.CallbackDimensionMemberServiceImpl.java

@Override
public MiniCubeMember getMemberFromLevelByName(DataSourceInfo dataSourceInfo, Cube cube, Level level,
        String name, MiniCubeMember parent, Map<String, String> params)
        throws MiniCubeQueryException, MetaException {
    //        MetaDataService.checkCube(cube);
    //        MetaDataService.checkDataSourceInfo(dataSourceInfo);
    //        List<CallBackTreeNode> posTree = fetchCallBack(level, params);
    CallbackLevel callbackLevel = (CallbackLevel) level;
    Map<String, String> callbackParams = Maps.newHashMap(callbackLevel.getCallbackParams());
    if (MapUtils.isNotEmpty(params)) {
        params.forEach((k, v) -> {
            if (callbackParams.containsKey(k)) {
                callbackParams.put(k, v);
            }//w  w w  .  ja  v  a2 s.co  m
        });
        //            callbackParams.putAll(params);
    }
    CallbackResponse response = CallbackServiceInvoker.invokeCallback(callbackLevel.getCallbackUrl(),
            callbackParams, CallbackType.DIM);
    if (response.getStatus() == ResponseStatus.SUCCESS) {
        @SuppressWarnings("unchecked")
        List<CallbackDimTreeNode> posTree = (List<CallbackDimTreeNode>) response.getData();
        if (posTree.size() != 1) {
            CallbackDimTreeNode node = findTreeNodeByName(posTree, name);
            return createMemberByPosTreeNode(node, level, null);
        }
        // TODO 

        return createMemberByPosTreeNode(posTree.get(0), level, null);

    } else {
        throw new RuntimeException(response.getMessage());
    }
}

From source file:org.springframework.messaging.handler.invocation.ResolvableMethod.java

private String formatAnnotation(Annotation annotation) {
    Map<String, Object> map = AnnotationUtils.getAnnotationAttributes(annotation);
    map.forEach((key, value) -> {
        if (value.equals(DEFAULT_VALUE_NONE)) {
            map.put(key, "NONE");
        }// w w  w . j a  va 2 s. c om
    });
    return annotation.annotationType().getName() + map;
}

From source file:com.evolveum.midpoint.model.impl.scripting.actions.ScriptExecutor.java

private Object executeScript(ScriptExpression scriptExpression, Object input,
        Map<String, Object> externalVariables, ExecutionContext context, OperationResult result)
        throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    ExpressionVariables variables = new ExpressionVariables();
    variables.addVariableDefinition(ExpressionConstants.VAR_INPUT, input);
    variables.addVariableDefinition(ExpressionConstants.VAR_PRISM_CONTEXT, prismContext);
    ExpressionUtil.addActorVariable(variables, securityContextManager);
    externalVariables
            .forEach((k, v) -> variables.addVariableDefinition(new QName(NS_C, k), cloneIfNecessary(k, v)));

    List<?> rv = Utils.evaluateScript(scriptExpression, null, variables, true, "in '" + NAME + "' action",
            context.getTask(), result);//from  www .  jav  a 2  s  .co m

    if (rv == null || rv.size() == 0) {
        return null;
    } else if (rv.size() == 1) {
        return rv.get(0);
    } else {
        return rv; // shouldn't occur; would cause problems
    }
}

From source file:ch.ifocusit.livingdoc.plugin.PublishMojo.java

/**
 * @return html pages//from w  w  w.  j  a v  a 2  s  . co  m
 * @throws IOException
 */
private List<Page> readHtmlPages() throws IOException {

    List<Page> pages = new ArrayList<>();

    Files.walk(Paths.get(generatedDocsDirectory.getAbsolutePath()))
            .filter(path -> FilenameUtils.isExtension(path.getFileName().toString(),
                    new String[] { Format.adoc.name(), Format.asciidoc.name(), Format.html.name() }))
            .forEach(path -> {
                try {
                    Map<String, String> attachmentCollector = new HashMap<>();

                    HtmlPostProcessor htmlProcessor = getPostProcessor();

                    Page page = new Page();
                    page.setSpaceKey(publish.getSpaceKey());
                    page.setParentId(publish.getAncestorId());
                    page.setTitle(htmlProcessor.getPageTitle(path));
                    page.setFile(path);
                    String content = htmlProcessor.process(path, attachmentCollector);
                    page.setContent(content);

                    attachmentCollector.forEach(page::addAttachement);

                    pages.add(page);
                } catch (IOException e) {
                    throw new IllegalArgumentException("error reading file", e);
                }
            });

    return pages;
}

From source file:io.gravitee.management.service.impl.ApiKeyServiceImpl.java

@Override
public Map<String, List<ApiKeyEntity>> findByApi(String apiId) {
    try {/*from w  w  w .jav a2 s.  c o m*/
        LOGGER.debug("Find all API keys for API {}", apiId);

        Set<ApiKey> keys = apiKeyRepository.findByApi(apiId);

        Map<String, Set<ApiKey>> keysByApplication = new HashMap<>();
        keys.forEach(apiKey -> {
            Set<ApiKey> values = keysByApplication.getOrDefault(apiKey.getApplication(), new HashSet<>());
            values.add(apiKey);
            keysByApplication.put(apiKey.getApplication(), values);
        });

        Map<String, List<ApiKeyEntity>> keysByApplicationResult = new HashMap<>(keysByApplication.size());

        keysByApplication.forEach((api, apiKeys) -> keysByApplicationResult.put(api,
                apiKeys.stream().sorted((key1, key2) -> key2.getCreatedAt().compareTo(key1.getCreatedAt()))
                        .map(ApiKeyServiceImpl::convert).collect(Collectors.toList())));

        return keysByApplicationResult;
    } catch (TechnicalException ex) {
        LOGGER.error("An error occurs while getting all API keys for API {}", apiId, ex);
        throw new TechnicalManagementException("An error occurs while getting all API keys for API " + apiId,
                ex);
    }
}

From source file:com.github.totyumengr.minicubes.cluster.BootTimeSeriesMiniCubeController.java

@RequestMapping(value = "/distinct", method = { RequestMethod.POST, RequestMethod.GET })
public @ResponseBody Map<Integer, Set<Integer>> distinct(@NotBlank @RequestParam String indName,
        @NotBlank @RequestParam(required = false) Boolean isDim,
        @RequestParam(required = false) String filterDims, @RequestParam String groupbyDim,
        @NotBlank @RequestParam String... timeSeries) throws Throwable {

    LOGGER.info("Try to distinct {} on {} with filter {}.", indName, ObjectUtils.getDisplayString(timeSeries),
            filterDims);//ww w.j  av a 2  s. c  om
    long timing = System.currentTimeMillis();
    Map<String, List<Integer>> filter = (filterDims == null || "".equals(filterDims)) ? null
            : objectMapper.readValue(filterDims, new TypeReference<Map<String, List<Integer>>>() {
            });
    Map<Integer, RoaringBitmap> distinct = manager.aggs(timeSeries).distinct(indName,
            isDim == null ? true : isDim, groupbyDim, filter);
    LOGGER.info("Sucess to distinct {} on {} result size is {} using {}ms.", indName, timeSeries,
            distinct.size(), System.currentTimeMillis() - timing);
    LOGGER.debug("Sucess to distinct {} on {} result is {}.", indName, timeSeries, distinct);

    Map<Integer, Set<Integer>> result = new HashMap<Integer, Set<Integer>>();
    distinct.forEach(new BiConsumer<Integer, RoaringBitmap>() {
        @Override
        public void accept(Integer t, RoaringBitmap u) {
            result.put(t, Arrays.stream(u.toArray()).collect(HashSet<Integer>::new, Set::add, (l, r) -> {
            }));
        }
    });

    return result;
}

From source file:org.apache.solr.cloud.autoscaling.sim.TestLargeCluster.java

@Test
//@AwaitsFix(bugUrl = "https://issues.apache.org/jira/browse/SOLR-11714")
public void testSearchRate() throws Exception {
    SolrClient solrClient = cluster.simGetSolrClient();
    String setTriggerCommand = "{" + "'set-trigger' : {" + "'name' : 'search_rate_trigger',"
            + "'event' : 'searchRate'," + "'waitFor' : '" + waitForSeconds + "s'," + "'rate' : 1.0,"
            + "'enabled' : true," + "'actions' : [" + "{'name':'compute','class':'"
            + ComputePlanAction.class.getName() + "'}," + "{'name':'execute','class':'"
            + ExecutePlanAction.class.getName() + "'}," + "{'name':'test','class':'"
            + TestTriggerAction.class.getName() + "'}" + "]" + "}}";
    SolrRequest req = createAutoScalingRequest(SolrRequest.METHOD.POST, setTriggerCommand);
    NamedList<Object> response = solrClient.request(req);
    assertEquals(response.get("result").toString(), "success");
    String setListenerCommand1 = "{" + "'set-listener' : " + "{" + "'name' : 'srt',"
            + "'trigger' : 'search_rate_trigger'," + "'stage' : ['FAILED','SUCCEEDED']," + "'class' : '"
            + TestTriggerListener.class.getName() + "'" + "}" + "}";
    req = createAutoScalingRequest(SolrRequest.METHOD.POST, setListenerCommand1);
    response = solrClient.request(req);//  w ww.  ja  v  a 2  s.co  m
    assertEquals(response.get("result").toString(), "success");

    String collectionName = "testSearchRate";
    CollectionAdminRequest.Create create = CollectionAdminRequest.createCollection(collectionName, "conf", 2,
            10);
    create.process(solrClient);

    log.info("Ready after " + waitForState(collectionName, 300, TimeUnit.SECONDS, clusterShape(2, 10)) + " ms");

    // collect the node names for shard1
    Set<String> nodes = new HashSet<>();
    cluster.getSimClusterStateProvider().getClusterState().getCollection(collectionName).getSlice("shard1")
            .getReplicas().forEach(r -> nodes.add(r.getNodeName()));

    String metricName = "QUERY./select.requestTimes:1minRate";
    // simulate search traffic
    cluster.getSimClusterStateProvider().simSetShardValue(collectionName, "shard1", metricName, 40, true);

    boolean await = triggerFiredLatch.await(20000 / SPEED, TimeUnit.MILLISECONDS);
    assertTrue("The trigger did not fire at all", await);
    // wait for listener to capture the SUCCEEDED stage
    cluster.getTimeSource().sleep(2000);
    assertEquals(listenerEvents.toString(), 1, listenerEvents.get("srt").size());
    CapturedEvent ev = listenerEvents.get("srt").get(0);
    assertEquals(TriggerEventType.SEARCHRATE, ev.event.getEventType());
    Map<String, Number> m = (Map<String, Number>) ev.event.getProperty("node");
    assertNotNull(m);
    assertEquals(nodes.size(), m.size());
    assertEquals(nodes, m.keySet());
    m.forEach((k, v) -> assertEquals(4.0, v.doubleValue(), 0.01));
    List<TriggerEvent.Op> ops = (List<TriggerEvent.Op>) ev.event.getProperty(TriggerEvent.REQUESTED_OPS);
    assertNotNull(ops);
    assertEquals(3, ops.size());
    ops.forEach(op -> {
        assertEquals(CollectionParams.CollectionAction.ADDREPLICA, op.getAction());
        assertEquals(1, op.getHints().size());
        Pair<String, String> hint = (Pair<String, String>) op.getHints().get(Suggester.Hint.COLL_SHARD);
        assertNotNull(hint);
        assertEquals(collectionName, hint.first());
        assertEquals("shard1", hint.second());
    });
}