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.wso2.carbon.identity.recovery.util.Utils.java

public static void updateChallengeQuestionsYAML(List<ChallengeQuestion> challengeQuestions)
        throws IdentityRecoveryException {

    final boolean[] error = { false };
    Map<String, List<ChallengeQuestion>> groupedByLocale = challengeQuestions.stream()
            .collect(Collectors.groupingBy(challengeQuestion -> challengeQuestion.getLocale()));
    groupedByLocale.forEach((key, value) -> {
        try {//  ww  w.j a  va  2 s  .  c  o  m
            updateChallengeQuestionsYAML(value, key);
        } catch (IdentityRecoveryException e) {
            log.error(String.format("Error while updating challenge questions from locale file %s", key));
            error[0] = true;
        }
    });

    if (error[0]) {
        throw new IdentityRecoveryException("Error while updating challenge questions");
    }

}

From source file:org.apache.fluo.recipes.core.combine.it.CombineQueueTreeIT.java

private static Map<String, Long> rollup(Map<String, Long> m, String rollupFields) {
    boolean useX = rollupFields.contains("x");
    boolean useY = rollupFields.contains("y");
    boolean useTime = rollupFields.contains("t");

    Map<String, Long> ret = new HashMap<>();
    m.forEach((k, v) -> {
        String[] fields = k.split(":");
        String nk = (useX ? fields[0] : "") + (useY ? ((useX ? ":" : "") + fields[1]) : "")
                + (useTime ? ((useX || useY ? ":" : "") + fields[2]) : "");

        ret.merge(nk, v, Long::sum);
    });/*from  ww  w. j  a v  a 2 s  .  c  o  m*/
    return ret;
}

From source file:com.linecorp.armeria.server.docs.ThriftDocString.java

@VisibleForTesting
static Map<String, String> getDocStringsFromJsonResource(ClassLoader classLoader, String jsonResourcePath) {
    ImmutableMap.Builder<String, String> docStrings = ImmutableMap.builder();
    try (InputStream in = classLoader.getResourceAsStream(jsonResourcePath)) {
        if (in == null) {
            throw new IllegalStateException("not found: " + jsonResourcePath);
        }// w  ww .  j av a2s  . c  o  m

        final Map<String, Object> json = new ObjectMapper().readValue(in, JSON_VALUE_TYPE);
        @SuppressWarnings("unchecked")
        final Map<String, Object> namespaces = (Map<String, Object>) json.getOrDefault("namespaces",
                ImmutableMap.of());
        final String packageName = (String) namespaces.get("java");
        json.forEach((key, children) -> {
            if (children instanceof Collection) {
                ((Collection) children).forEach(grandChild -> {
                    traverseChildren(docStrings, packageName, FQCN_DELIM, grandChild);
                });
            }
        });

        return docStrings.build();
    } catch (IOException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java

/**
 * Prints the header, content and output to the given print stream with a custom template.
 *
 * @param outputType   the desired output type. @see {@link OutputType}
 * @param templateName the name of the template
 * @param contextMap   the context for velocity
 * @throws Exception in case of a error, so the caller can handle it
 *///from  ww  w.  ja  va  2s .c o m
private static void printWithCustomTemplate(final OutputType outputType, final String templateName,
        final Map<String, Object> contextMap) throws Exception {
    Velocity.init();
    Writer writer = null;
    try {
        final Template template = Velocity.getTemplate(templateName);
        final VelocityContext context = new VelocityContext();
        contextMap.forEach((k, v) -> context.put(k, v));
        writer = new BufferedWriter(createFileWriter(outputType, templateName));

        template.merge(context, writer);
        writer.flush();
    } catch (ResourceNotFoundException rnfe) {
        LOG.error("Couldn't find the template with name '" + templateName + "'");
        throw new Exception(rnfe.getMessage());
    } catch (ParseErrorException pee) {
        LOG.error("Syntax error: problem parsing the template ' " + templateName + "': " + pee.getMessage());
        throw new Exception(pee.getMessage());
    } catch (MethodInvocationException mie) {
        LOG.error(
                "An invoked method on the template '" + templateName + "' threw an error: " + mie.getMessage());
        throw new Exception(mie.getMessage());
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage());
        throw e;
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:org.gerzog.jstataggr.core.collector.impl.StatisticsCollector.java

protected static CollectorClassInfo generateClassInfo(final Class<?> clazz,
        final Map<IStatisticsField, FieldInfo> fieldInfo) {
    final CollectorClassInfo result = new CollectorClassInfo(clazz);
    final Map<String, Class<?>> methodInfo = new HashMap<>();

    fieldInfo.forEach((statisticsInfo, bucketInfo) -> {
        propogate(() -> {//from w w  w  . ja  va 2 s.  co m
            final MethodHandle accessMethod = statisticsInfo.getAccessMethodHandle(clazz);

            bucketInfo.setAccessor(accessMethod);

            if (statisticsInfo.isAggregator()) {
                result.getUpdaters().add(bucketInfo);
            } else {
                result.getKeys().put(bucketInfo.getName(), bucketInfo);
            }

            methodInfo.put(statisticsInfo.getFieldName(), statisticsInfo.getMethodType());
        });
    });

    final BeanGenerator externalBeanGenerator = new BeanGenerator();
    BeanGenerator.addProperties(externalBeanGenerator, methodInfo);

    result.setExternalEntityClass((Class<?>) externalBeanGenerator.createClass());

    return result;
}

From source file:de.bund.bfr.math.MathUtils.java

public static Map<String, UnivariateFunction> createInterpolationFunctions(
        Map<String, List<Double>> variableValues, String timeVariable, InterpolationFactory interpolator) {
    Map<String, UnivariateFunction> variableFunctions = new LinkedHashMap<>();

    variableValues.forEach((var, values) -> {
        if (!var.equals(timeVariable)) {
            variableFunctions.put(var, interpolator.createInterpolationFunction(
                    Doubles.toArray(variableValues.get(timeVariable)), Doubles.toArray(values)));
        }//  www.j  a  va  2 s.c o m
    });

    return variableFunctions;
}

From source file:com.streamsets.pipeline.lib.jdbc.multithread.util.OffsetQueryUtil.java

public static String getOffsetFormat(Map<String, ?> columnsToOffsets) {
    List<String> offsetColumnFormat = new ArrayList<>();
    if (columnsToOffsets != null) {
        columnsToOffsets.forEach(
                (col, off) -> offsetColumnFormat.add(String.format(OFFSET_COLUMN_NAME_VALUE, col, off)));
    }/*w w  w  .j  av a  2  s .c  om*/
    return OFFSET_COLUMN_JOINER.join(offsetColumnFormat);
}

From source file:com.hurence.logisland.plugin.PluginManager.java

private static void listPlugins() {
    Map<ModuleInfo, List<String>> moduleMapping = findPluginMeta();

    System.out.println();/*from www  .  j  ava  2s  . c o  m*/
    System.out.println("Listing details for " + moduleMapping.size() + " installed modules.");
    System.out.println("==============================================================");
    System.out.println();
    moduleMapping.forEach((c, l) -> {
        System.out.println("Artifact: " + c.getArtifact());
        System.out.println("Name: " + c.getName());
        System.out.println("Version: " + c.getVersion());
        System.out.println("Location: " + c.getSourceArchive());
        System.out.println("Components provided:");
        l.forEach(ll -> System.out.println("\t" + ll));
        System.out.println("\n-----------------------------------------------------------\n");
    });
}

From source file:core.Web.java

public static String httpRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {//from   w  w w  .  j a v a  2s .  c o  m
        // Create connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            //                connection.setRequestProperty("Accept", "application/json");
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            System.err.println("Error " + responseCode + ":" + url);
            return null;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return content;
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:core.Web.java

public static JSONObject httpsRequest(URL url, Map<String, String> properties, JSONObject message) {
    //        System.out.println(url);
    try {/*w ww  . j  a v a 2s.c  o m*/
        // Create connection
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        //connection.addRequestProperty("Authorization", API_KEY);
        // Set properties if needed
        if (properties != null && !properties.isEmpty()) {
            properties.forEach(connection::setRequestProperty);
        }
        // Post message
        if (message != null) {
            // Maybe somewhere
            connection.setDoOutput(true);
            try (BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(connection.getOutputStream()))) {
                writer.write(message.toString());
            }
        }
        // Establish connection
        connection.connect();
        int responseCode = connection.getResponseCode();

        if (responseCode != 200) {
            throw new RuntimeException("Response code was not 200. Detected response was " + responseCode);
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            String content = "";
            while ((line = reader.readLine()) != null) {
                content += line;
            }
            return new JSONObject(content);
        }

    } catch (IOException ex) {
        Logger.getLogger(Web.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}