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.github.mavogel.ilias.printer.VelocityOutputPrinter.java

/**
 * Prints the header, content and output to the given print stream with the default template from the classpath.
 *
 * @param outputType the desired output type. @see {@link OutputType}
 * @param contextMap the context for velocity
 * @throws Exception in case of a error, so the caller can handle it
 *//*from  w w  w . j  a va 2  s  .  c  o m*/
private static void printWithDefaultTemplate(final OutputType outputType, final Map<String, Object> contextMap)
        throws Exception {
    VelocityEngine ve = new VelocityEngine();
    ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    ve.init();

    Writer writer = null;
    final String templateName = outputType.getDefaultTemplateLocation();
    try {
        VelocityContext context = new VelocityContext();
        contextMap.forEach((k, v) -> context.put(k, v));
        Template template = ve.getTemplate(templateName, "UTF-8");
        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());
        LOG.error("Cause: " + e.getCause());
        Arrays.stream(e.getStackTrace()).forEach(LOG::error);
        throw e;
    } finally {
        if (writer != null)
            writer.close();
    }
}

From source file:com.khartec.waltz.jobs.sample.MeasurablesGenerator.java

private static void generateRegions(DSLContext dsl) throws IOException {
    List<String> lines = readLines(OrgUnitGenerator.class.getResourceAsStream("/regions.csv"));

    System.out.println("Deleting existing Regions & Countries ...");
    int deletedCount = dsl.deleteFrom(MEASURABLE)
            .where(MEASURABLE.MEASURABLE_CATEGORY_ID
                    .in(DSL.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
                            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID))))
            .and(MEASURABLE.PROVENANCE.eq("demo")).execute();
    System.out.println("Deleted: " + deletedCount + " existing Regions & Countries");

    Map<String, Map<String, Set<String>>> regionHierarchy = lines.stream().skip(1)
            .map(line -> StringUtils.splitPreserveAllTokens(line, ","))
            .filter(cells -> notEmpty(cells[0]) && notEmpty(cells[6]) && notEmpty(cells[5]))
            .map(cells -> Tuple.tuple(cells[0], cells[6], cells[5]))
            .collect(groupingBy(t -> t.v3, groupingBy(t -> t.v2, mapping(t -> t.v1, toSet()))));

    final long measurableCategoryId = dsl.select(MEASURABLE_CATEGORY.ID).from(MEASURABLE_CATEGORY)
            .where(MEASURABLE_CATEGORY.EXTERNAL_ID.eq(REGION_CATEGORY_EXTERNAL_ID)).fetchAny().value1();

    AtomicInteger insertCount = new AtomicInteger(0);
    regionHierarchy.forEach((region, subRegionMap) -> {
        final long regionId = dsl.insertInto(MEASURABLE)
                .set(createRegion(null, region, measurableCategoryId, false)).returning(MEASURABLE.ID)
                .fetchOne().getId();//from  w w  w.  j  a v  a2 s. c  o m
        insertCount.incrementAndGet();

        subRegionMap.forEach((subRegion, countries) -> {
            final long subRegionId = dsl.insertInto(MEASURABLE)
                    .set(createRegion(regionId, subRegion, measurableCategoryId, true)).returning(MEASURABLE.ID)
                    .fetchOne().getId();
            insertCount.incrementAndGet();

            insertCount.addAndGet(dsl.batchInsert(countries.stream()
                    .map(country -> createRegion(subRegionId, country, measurableCategoryId, true))
                    .collect(toList())).execute().length);
        });
    });

    System.out.println("Inserted: " + insertCount + " Regions & Countries");
}

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

public static double[] getFunctionPoints(Map<String, Double> parserConstants, String formula, String varX,
        double[] valuesX) throws ParseException {
    FunctionConf function = new FunctionConf(parserConstants, formula, varX, valuesX);
    double[] result = results.getIfPresent(function);

    if (result != null) {
        return result;
    }//  w w w  .j  a  va 2 s .  co m

    Parser parser = new Parser();

    parserConstants.forEach((constant, value) -> parser.setVarValue(constant, value));

    ASTNode f = parser.parse(formula);
    double[] valuesY = new double[valuesX.length];

    Arrays.fill(valuesY, Double.NaN);

    for (int i = 0; i < valuesX.length; i++) {
        parser.setVarValue(varX, valuesX[i]);
        valuesY[i] = parser.evaluate(f);
    }

    results.put(function, valuesY);

    return valuesY;
}

From source file:act.installer.brenda.BrendaChebiOntology.java

/**
 * This function fetches and construct the set of main and direct applications for each ontology that has a role.
 * @param ontologyMap map {chebi id -> ChebiOntology object}
 * @param isSubtypeOfRelationships map {chebi id -> set of chebi id for its subtypes}
 * @param hasRoleRelationships map {chebi id -> set of chebi id for its roles}
 * @return a map from ChebiOntology objects to a ChebiApplicationSet object
 *///from w ww.j  av  a2  s .  c  o m
public static Map<ChebiOntology, ChebiApplicationSet> getApplications(Map<String, ChebiOntology> ontologyMap,
        Map<String, Set<String>> isSubtypeOfRelationships, Map<String, Set<String>> hasRoleRelationships) {

    Map<String, Set<String>> applicationToMainApplicationsMap = getApplicationToMainApplicationsMap(
            isSubtypeOfRelationships, APPLICATION_CHEBI_ID);

    // Filter out the roles that are not applications
    Map<String, Set<String>> directApplicationMap = new HashMap<>();
    hasRoleRelationships.forEach((key, value) -> directApplicationMap.put(key,
            value.stream().filter(ontology -> applicationToMainApplicationsMap.keySet().contains(ontology))
                    .collect(Collectors.toSet())));

    // Compute the set of main applications for each ontology that has a role (aka is a chemical entity).
    Map<ChebiOntology, Set<ChebiOntology>> chemicalEntityToMainApplicationMap = new HashMap<>();
    for (String chemicalEntity : directApplicationMap.keySet()) {

        Set<ChebiOntology> mainApplicationsSet = chemicalEntityToMainApplicationMap
                .get(ontologyMap.get(chemicalEntity));
        if (mainApplicationsSet == null) {
            mainApplicationsSet = new HashSet<>();
            chemicalEntityToMainApplicationMap.put(ontologyMap.get(chemicalEntity), mainApplicationsSet);
        }
        for (String parentApplication : directApplicationMap.get(chemicalEntity)) {
            Set<String> mainApplications = applicationToMainApplicationsMap.get(parentApplication);
            if (mainApplications != null) {
                mainApplicationsSet.addAll(mainApplications.stream().map(ontologyMap::get)
                        .filter(Objects::nonNull).collect(Collectors.toSet()));
            }
        }
    }

    // Finally, construct a ChebiApplicationSet object containing direct and main applications for the molecules.
    Map<ChebiOntology, ChebiApplicationSet> chemicalEntityToApplicationsMap = new HashMap<>();
    for (String chemicalEntity : directApplicationMap.keySet()) {
        Set<ChebiOntology> directApplications = directApplicationMap.get(chemicalEntity).stream()
                .map(ontologyMap::get).filter(Objects::nonNull).collect(Collectors.toSet());
        Set<ChebiOntology> mainApplications = chemicalEntityToMainApplicationMap
                .get(ontologyMap.get(chemicalEntity));
        if (directApplications.size() > 0 || mainApplications.size() > 0) {
            ChebiApplicationSet applications = new ChebiApplicationSet(directApplications, mainApplications);
            chemicalEntityToApplicationsMap.put(ontologyMap.get(chemicalEntity), applications);
        }
    }

    return chemicalEntityToApplicationsMap;
}

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

public static FirstOrderDifferentialEquations createDiffEquations(Parser parser, List<ASTNode> functions,
        List<String> dependentVariables, String timeVariable,
        Map<String, UnivariateFunction> variableFunctions) {
    return new FirstOrderDifferentialEquations() {

        @Override//from  w ww  .  j  a va2 s  .  co m
        public int getDimension() {
            return functions.size();
        }

        @Override
        public void computeDerivatives(double t, double[] y, double[] yDot)
                throws MaxCountExceededException, DimensionMismatchException {
            parser.setVarValue(timeVariable, t);
            variableFunctions.forEach((var, function) -> parser.setVarValue(var, function.value(t)));

            for (int i = 0; i < functions.size(); i++) {
                parser.setVarValue(dependentVariables.get(i), y[i]);
            }

            for (int i = 0; i < functions.size(); i++) {
                try {
                    double value = parser.evaluate(functions.get(i));

                    yDot[i] = Double.isFinite(value) ? value : Double.NaN;
                } catch (ParseException e) {
                    e.printStackTrace();
                    yDot[i] = Double.NaN;
                }
            }
        }
    };
}

From source file:org.springframework.kafka.support.SeekUtils.java

/**
 * Seek records to earliest position, optionally skipping the first.
 * @param records the records./*from www. ja  v  a  2 s.c  om*/
 * @param consumer the consumer.
 * @param exception the exception
 * @param recoverable true if skipping the first record is allowed.
 * @param skipper function to determine whether or not to skip seeking the first.
 * @param logger a {@link Log} for seek errors.
 * @return true if the failed record was skipped.
 */
public static boolean doSeeks(List<ConsumerRecord<?, ?>> records, Consumer<?, ?> consumer, Exception exception,
        boolean recoverable, BiPredicate<ConsumerRecord<?, ?>, Exception> skipper, Log logger) {
    Map<TopicPartition, Long> partitions = new LinkedHashMap<>();
    AtomicBoolean first = new AtomicBoolean(true);
    AtomicBoolean skipped = new AtomicBoolean();
    records.forEach(record -> {
        if (recoverable && first.get()) {
            skipped.set(skipper.test(record, exception));
            if (skipped.get() && logger.isDebugEnabled()) {
                logger.debug("Skipping seek of: " + record);
            }
        }
        if (!recoverable || !first.get() || !skipped.get()) {
            partitions.computeIfAbsent(new TopicPartition(record.topic(), record.partition()),
                    offset -> record.offset());
        }
        first.set(false);
    });
    boolean tracing = logger.isTraceEnabled();
    partitions.forEach((topicPartition, offset) -> {
        try {
            if (tracing) {
                logger.trace("Seeking: " + topicPartition + " to: " + offset);
            }
            consumer.seek(topicPartition, offset);
        } catch (Exception e) {
            logger.error("Failed to seek " + topicPartition + " to " + offset, e);
        }
    });
    return skipped.get();
}

From source file:org.structr.util.StructrLicenseManager.java

private static String write(final Map<String, String> properties) {

    final StringBuilder buf = new StringBuilder();

    properties.forEach((key, value) -> {

        buf.append(key);/*from   w  w  w  .  ja  v a 2  s. c  o  m*/
        buf.append(" = ");
        buf.append(value);
        buf.append("\n");
    });

    return buf.toString();

}

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

public static TableRuntimeContext createNextPartition(final TableRuntimeContext lastPartition) {
    if (!lastPartition.isPartitioned()) {
        throw new IllegalStateException("lastPartition TableRuntimeContext was not partitioned");
    }/*from   w w  w  .  j a  v  a 2 s. c o  m*/

    final Set<String> offsetColumns = lastPartition.getSourceTableContext().getOffsetColumns();
    final Map<String, String> startingPartitionOffsets = lastPartition.getStartingPartitionOffsets();

    if (startingPartitionOffsets.size() < offsetColumns.size()) {
        // we have not yet captured an offset for every offset columns
        if (LOG.isTraceEnabled()) {
            LOG.trace("Cannot create next partition after {} since we are missing values for offset columns {}",
                    lastPartition.getPartitionSequence(),
                    Sets.difference(offsetColumns, startingPartitionOffsets.keySet()));
        }
        return null;
    }

    final Map<String, String> nextStartingOffsets = new HashMap<>();
    final Map<String, String> nextMaxOffsets = new HashMap<>();

    final int newPartitionSequence = lastPartition.partitionSequence > 0 ? lastPartition.partitionSequence + 1
            : 1;

    lastPartition.startingPartitionOffsets.forEach((col, off) -> {
        String basedOnStartOffset = lastPartition.generateNextPartitionOffset(col, off);
        nextStartingOffsets.put(col, basedOnStartOffset);
    });

    nextStartingOffsets.forEach(
            (col, off) -> nextMaxOffsets.put(col, lastPartition.generateNextPartitionOffset(col, off)));

    final TableRuntimeContext nextPartition = new TableRuntimeContext(lastPartition.sourceTableContext,
            lastPartition.usingNonIncrementalLoad, lastPartition.partitioned, newPartitionSequence,
            nextStartingOffsets, nextMaxOffsets);

    return nextPartition;
}

From source file:org.roda_project.commons_ip.utils.ZIPUtils.java

public static Map<String, String> calculateChecksums(Optional<ZipOutputStream> zos, InputStream inputStream,
        Set<String> checksumAlgorithms) throws NoSuchAlgorithmException, IOException {
    byte[] buffer = new byte[4096];
    Map<String, String> values = new HashMap<>();

    // instantiate different checksum algorithms
    Map<String, MessageDigest> algorithms = new HashMap<>();
    for (String alg : checksumAlgorithms) {
        algorithms.put(alg, MessageDigest.getInstance(alg));
    }//from  w w  w  .  j a v  a  2 s. c o m

    // calculate value for each one of the algorithms
    int numRead;
    do {
        numRead = inputStream.read(buffer);
        if (numRead > 0) {
            for (Entry<String, MessageDigest> alg : algorithms.entrySet()) {
                alg.getValue().update(buffer, 0, numRead);
            }

            if (zos.isPresent()) {
                zos.get().write(buffer, 0, numRead);
            }
        }
    } while (numRead != -1);

    // generate hex versions of the digests
    algorithms.forEach((alg, dig) -> values.put(alg, DatatypeConverter.printHexBinary(dig.digest())));

    return values;
}

From source file:org.wso2.carbon.identity.application.authentication.framework.config.model.graph.JsGraphBuilder.java

/**
 * Adds all the event listeners to the decision node.
 *
 * @param eventsMap Map of events and event handler functions, which is handled by this execution.
 * @return created Dynamic Decision node.
 *///from www  . j a  v  a2s. co  m
private static void addEventListeners(DynamicDecisionNode decisionNode, Map<String, Object> eventsMap) {

    if (eventsMap == null) {
        return;
    }
    eventsMap.forEach((key, value) -> {
        if (value instanceof ScriptObjectMirror) {
            SerializableJsFunction jsFunction = SerializableJsFunction
                    .toSerializableForm((ScriptObjectMirror) value);
            if (jsFunction != null) {
                decisionNode.addFunction(key, jsFunction);
            } else {
                log.error("Event handler : " + key + " is not a function : " + value);
            }
        } else if (value instanceof SerializableJsFunction) {
            decisionNode.addFunction(key, (SerializableJsFunction) value);
        }
    });
}