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.intuit.wasabi.assignment.cache.impl.AssignmentsMetadataCacheImpl.java

/**
 * Make elements list which is specific to the ehcache format..
 *
 * @param elementsMap/*from   w w  w  .j a va  2s  .c  om*/
 * @param <K>
 * @param <V>
 * @return Elements list
 */
private <K, V> List<Element> makeElementsList(Map<K, V> elementsMap) {
    List<Element> elementsList = new ArrayList<>();
    elementsMap.forEach((key, value) -> {
        elementsList.add(new Element(key, value));
    });
    return elementsList;
}

From source file:org.onosproject.cpman.impl.DefaultMetricsDatabase.java

@Override
public void updateMetrics(Map<String, Double> metrics, long time) {
    try {//from w  w w  .j a  v  a  2 s.c  om
        sample = rrdDb.createSample(time);
        metrics.forEach((k, v) -> {
            try {
                checkArgument(rrdDb.containsDs(k), NON_EXIST_METRIC);
                sample.setValue(k, v);
            } catch (IOException e) {
                log.error("Failed to update metric value due to {}", e);
            }
        });
        sample.update();
    } catch (IOException e) {
        log.error("Failed to update metric values due to {}", e);
    }
}

From source file:io.github.swagger2markup.internal.document.PathsDocument.java

/**
 * Builds the paths section. Groups the paths either as-is, by tags or using regex.
 *
 * @param paths the Swagger paths//from   w w  w  .ja v a  2 s  . c o  m
 */
private void buildsPathsSection(MarkupDocBuilder markupDocBuilder, Map<String, Path> paths) {
    List<PathOperation> pathOperations = PathUtils.toPathOperationsList(paths, getBasePath(),
            config.getOperationOrdering());
    if (CollectionUtils.isNotEmpty(pathOperations)) {
        if (config.getPathsGroupedBy() == GroupBy.AS_IS) {
            pathOperations.forEach(operation -> buildOperation(markupDocBuilder, operation, config));
        } else if (config.getPathsGroupedBy() == GroupBy.TAGS) {
            Validate.notEmpty(context.getSwagger().getTags(),
                    "Tags must not be empty, when operations are grouped by tags");
            // Group operations by tag
            Multimap<String, PathOperation> operationsGroupedByTag = TagUtils
                    .groupOperationsByTag(pathOperations, config.getOperationOrdering());

            Map<String, Tag> tagsMap = TagUtils.toSortedMap(context.getSwagger().getTags(),
                    config.getTagOrdering());

            tagsMap.forEach((String tagName, Tag tag) -> {
                markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(tagName),
                        tagName + "_resource");
                String description = tag.getDescription();
                if (StringUtils.isNotBlank(description)) {
                    markupDocBuilder.paragraph(description);
                }
                operationsGroupedByTag.get(tagName)
                        .forEach(operation -> buildOperation(markupDocBuilder, operation, config));

            });
        } else if (config.getPathsGroupedBy() == GroupBy.REGEX) {
            Validate.notNull(config.getHeaderPattern(),
                    "Header regex pattern must not be empty when operations are grouped using regex");

            Pattern headerPattern = config.getHeaderPattern();
            Multimap<String, PathOperation> operationsGroupedByRegex = RegexUtils
                    .groupOperationsByRegex(pathOperations, headerPattern);
            Set<String> keys = operationsGroupedByRegex.keySet();
            String[] sortedHeaders = RegexUtils.toSortedArray(keys);

            for (String header : sortedHeaders) {
                markupDocBuilder.sectionTitleWithAnchorLevel2(WordUtils.capitalize(header),
                        header + "_resource");
                operationsGroupedByRegex.get(header)
                        .forEach(operation -> buildOperation(markupDocBuilder, operation, config));
            }
        }
    }
}

From source file:io.github.swagger2markup.internal.component.PropertiesTableComponent.java

public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, Parameters params) {
    //TODO: This method is too complex, split it up in smaller methods to increase readability
    StringColumn.Builder nameColumnBuilder = StringColumn
            .builder(ColumnIds.StringColumnId.of(labels.getLabel(NAME_COLUMN)))
            .putMetaData(TableComponent.WIDTH_RATIO, "3");

    StringColumn.Builder descriptionColumnBuilder = StringColumn
            .builder(ColumnIds.StringColumnId.of(labels.getLabel(DESCRIPTION_COLUMN)))
            .putMetaData(TableComponent.WIDTH_RATIO, "11").putMetaData(TableComponent.HEADER_COLUMN, "true");

    StringColumn.Builder schemaColumnBuilder = StringColumn
            .builder(ColumnIds.StringColumnId.of(labels.getLabel(SCHEMA_COLUMN)))
            .putMetaData(TableComponent.WIDTH_RATIO, "4").putMetaData(TableComponent.HEADER_COLUMN, "true");

    Map<String, Property> properties = params.properties;
    if (MapUtils.isNotEmpty(properties)) {
        Map<String, Property> sortedProperties = toSortedMap(properties, config.getPropertyOrdering());
        sortedProperties.forEach((String propertyName, Property property) -> {
            PropertyAdapter propertyAdapter = new PropertyAdapter(property);
            Type propertyType = propertyAdapter.getType(definitionDocumentResolver);

            if (config.isInlineSchemaEnabled()) {
                propertyType = createInlineType(propertyType, propertyName,
                        params.parameterName + " " + propertyName, params.inlineDefinitions);
            }/*from   w  ww.j av  a 2s.co m*/

            Optional<Object> optionalExample = propertyAdapter.getExample(config.isGeneratedExamplesEnabled(),
                    markupDocBuilder);
            Optional<Object> optionalDefaultValue = propertyAdapter.getDefaultValue();
            Optional<Integer> optionalMaxLength = propertyAdapter.getMaxlength();
            Optional<Integer> optionalMinLength = propertyAdapter.getMinlength();
            Optional<String> optionalPattern = propertyAdapter.getPattern();
            Optional<Number> optionalMinValue = propertyAdapter.getMin();
            boolean exclusiveMin = propertyAdapter.getExclusiveMin();
            Optional<Number> optionalMaxValue = propertyAdapter.getMax();
            boolean exclusiveMax = propertyAdapter.getExclusiveMax();

            MarkupDocBuilder propertyNameContent = copyMarkupDocBuilder(markupDocBuilder);
            propertyNameContent.boldTextLine(propertyName, true);
            if (property.getRequired())
                propertyNameContent.italicText(labels.getLabel(FLAGS_REQUIRED).toLowerCase());
            else
                propertyNameContent.italicText(labels.getLabel(FLAGS_OPTIONAL).toLowerCase());
            if (propertyAdapter.getReadOnly()) {
                propertyNameContent.newLine(true);
                propertyNameContent.italicText(labels.getLabel(FLAGS_READ_ONLY).toLowerCase());
            }

            MarkupDocBuilder descriptionContent = copyMarkupDocBuilder(markupDocBuilder);
            String description = markupDescription(config.getSwaggerMarkupLanguage(), markupDocBuilder,
                    property.getDescription());
            if (isNotBlank(description))
                descriptionContent.text(description);

            if (optionalDefaultValue.isPresent()) {
                if (isNotBlank(descriptionContent.toString())) {
                    descriptionContent.newLine(true);
                }
                descriptionContent.boldText(labels.getLabel(DEFAULT_COLUMN)).text(COLON)
                        .literalText(Json.pretty(optionalDefaultValue.get()));
            }

            if (optionalMinLength.isPresent() && optionalMaxLength.isPresent()) {
                // combination of minlength/maxlength
                Integer minLength = optionalMinLength.get();
                Integer maxLength = optionalMaxLength.get();

                if (isNotBlank(descriptionContent.toString())) {
                    descriptionContent.newLine(true);
                }

                String lengthRange = minLength + " - " + maxLength;
                if (minLength.equals(maxLength)) {
                    lengthRange = minLength.toString();
                }

                descriptionContent.boldText(labels.getLabel(LENGTH_COLUMN)).text(COLON)
                        .literalText(lengthRange);

            } else {
                if (optionalMinLength.isPresent()) {
                    if (isNotBlank(descriptionContent.toString())) {
                        descriptionContent.newLine(true);
                    }
                    descriptionContent.boldText(labels.getLabel(MINLENGTH_COLUMN)).text(COLON)
                            .literalText(optionalMinLength.get().toString());
                }

                if (optionalMaxLength.isPresent()) {
                    if (isNotBlank(descriptionContent.toString())) {
                        descriptionContent.newLine(true);
                    }
                    descriptionContent.boldText(labels.getLabel(MAXLENGTH_COLUMN)).text(COLON)
                            .literalText(optionalMaxLength.get().toString());
                }
            }

            if (optionalPattern.isPresent()) {
                if (isNotBlank(descriptionContent.toString())) {
                    descriptionContent.newLine(true);
                }
                descriptionContent.boldText(labels.getLabel(PATTERN_COLUMN)).text(COLON)
                        .literalText(Json.pretty(optionalPattern.get()));
            }

            if (optionalMinValue.isPresent()) {
                if (isNotBlank(descriptionContent.toString())) {
                    descriptionContent.newLine(true);
                }
                String minValueColumn = exclusiveMin ? labels.getLabel(MINVALUE_EXCLUSIVE_COLUMN)
                        : labels.getLabel(MINVALUE_COLUMN);
                descriptionContent.boldText(minValueColumn).text(COLON)
                        .literalText(optionalMinValue.get().toString());
            }

            if (optionalMaxValue.isPresent()) {
                if (isNotBlank(descriptionContent.toString())) {
                    descriptionContent.newLine(true);
                }
                String maxValueColumn = exclusiveMax ? labels.getLabel(MAXVALUE_EXCLUSIVE_COLUMN)
                        : labels.getLabel(MAXVALUE_COLUMN);
                descriptionContent.boldText(maxValueColumn).text(COLON)
                        .literalText(optionalMaxValue.get().toString());
            }

            if (optionalExample.isPresent()) {
                if (isNotBlank(description) || optionalDefaultValue.isPresent()) {
                    descriptionContent.newLine(true);
                }
                descriptionContent.boldText(labels.getLabel(EXAMPLE_COLUMN)).text(COLON)
                        .literalText(Json.pretty(optionalExample.get()));
            }

            nameColumnBuilder.add(propertyNameContent.toString());
            descriptionColumnBuilder.add(descriptionContent.toString());
            schemaColumnBuilder.add(propertyType.displaySchema(markupDocBuilder));
        });
    }

    return tableComponent.apply(markupDocBuilder, TableComponent.parameters(nameColumnBuilder.build(),
            descriptionColumnBuilder.build(), schemaColumnBuilder.build()));
}

From source file:org.commonjava.indy.metrics.IndyMetricsManager.java

@PostConstruct
public void init() {
    if (!config.isMetricsEnabled()) {
        logger.info("Indy metrics subsystem not enabled");
        return;// w ww.j a v  a  2 s. c o  m
    }

    logger.info("Init metrics subsystem...");

    registerJvmMetric(config.getNodePrefix(), metricRegistry);

    // Health checks
    indyHealthChecks.forEach(hc -> {
        logger.info("Registering health check: {}", hc.getName());
        healthCheckRegistry.register(hc.getName(), hc);
    });

    indyCompoundHealthChecks.forEach(cc -> {
        Map<String, HealthCheck> healthChecks = cc.getHealthChecks();
        logger.info("Registering {} health checks from set: {}", healthChecks.size(),
                cc.getClass().getSimpleName());
        healthChecks.forEach((name, check) -> {
            logger.info("Registering health check: {}", name);
            healthCheckRegistry.register(name, check);
        });
    });

    metricSetProviderInstances.forEach((provider) -> provider.registerMetricSet(metricRegistry));

    if (config.isMeasureTransport()) {
        setUpTransportMetricConfig();
    }
}

From source file:org.apache.gobblin.cluster.GobblinHelixJobTask.java

@VisibleForTesting
protected void setResultToUserContent(Map<String, String> keyValues) throws IOException {
    WorkUnitState wus = new WorkUnitState();
    wus.setProp(ConfigurationKeys.JOB_ID_KEY, this.planningJobId);
    wus.setProp(ConfigurationKeys.TASK_ID_KEY, this.planningJobId);
    wus.setProp(ConfigurationKeys.TASK_KEY_KEY, this.planningJobId);
    keyValues.forEach((key, value) -> wus.setProp(key, value));
    TaskState taskState = new TaskState(wus);

    this.stateStores.getTaskStateStore().put(this.planningJobId, this.planningJobId, taskState);
}

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

public static double[] getDiffPoints(Map<String, Double> parserConstants, Map<String, String> functions,
        Map<String, Double> initValues, Map<String, String> initParameters,
        Map<String, List<Double>> conditionLists, String dependentVariable,
        Map<String, Double> independentVariables, String varX, double[] valuesX, IntegratorFactory integrator,
        InterpolationFactory interpolator) throws ParseException {
    DiffFunctionConf function = new DiffFunctionConf(parserConstants, functions, initValues, initParameters,
            conditionLists, dependentVariable, independentVariables, varX, valuesX, integrator, interpolator);
    double[] result = diffResults.getIfPresent(function);

    if (result != null) {
        return result;
    }/*from   www .  j  a v  a2  s  .c  om*/

    List<ASTNode> fs = new ArrayList<>();
    List<String> valueVariables = new ArrayList<>();
    double[] values = new double[functions.size()];
    Parser parser = new Parser();

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

    int index = 0;

    for (Map.Entry<String, String> entry : functions.entrySet()) {
        String var = entry.getKey();

        fs.add(parser.parse(entry.getValue()));
        valueVariables.add(var);
        values[index++] = initValues.containsKey(var) ? initValues.get(var)
                : parserConstants.get(initParameters.get(var));
    }

    Map<String, UnivariateFunction> variableFunctions = MathUtils.createInterpolationFunctions(conditionLists,
            varX, interpolator);
    FirstOrderDifferentialEquations f = MathUtils.createDiffEquations(parser, fs, valueVariables, varX,
            variableFunctions);
    FirstOrderIntegrator instance = integrator.createIntegrator();
    double diffValue = conditionLists.get(varX).get(0);
    int depIndex = valueVariables.indexOf(dependentVariable);
    double[] valuesY = new double[valuesX.length];

    for (int i = 0; i < valuesX.length; i++) {
        if (valuesX[i] == diffValue) {
            valuesY[i] = values[depIndex];
        } else if (valuesX[i] > diffValue) {
            instance.integrate(f, diffValue, values, valuesX[i], values);
            diffValue = valuesX[i];
            valuesY[i] = values[depIndex];
        } else {
            valuesY[i] = Double.NaN;
        }
    }

    diffResults.put(function, valuesY);

    return valuesY;
}

From source file:io.mandrel.common.schema.SchemaTest.java

public void inspect(int level, Type clazz, String name) {

    if (level > 6)
        return;// w  ww. j a v  a 2  s.  c o m
    if (clazz instanceof Class && clazz.equals(LinkFilter.class))
        return;

    if (clazz instanceof Class && !((Class<?>) clazz).isEnum() && ((Class<?>) clazz).getPackage() != null
            && ((Class<?>) clazz).getPackage().getName().startsWith("io.mandrel")) {
        int newLevel = level + 1;

        List<Field> fields = new ArrayList<Field>();
        Class<?> i = ((Class<?>) clazz);
        while (i != null && i != Object.class) {
            fields.addAll(Arrays.asList(i.getDeclaredFields()));
            i = i.getSuperclass();
        }

        for (Field field : fields) {
            Class<?> fieldType = field.getType();
            String text;
            if (!field.isAnnotationPresent(JsonIgnore.class) && !Modifier.isStatic(field.getModifiers())) {
                if (List.class.equals(fieldType) || Map.class.equals(fieldType)) {
                    Type type = field.getGenericType();
                    if (type instanceof ParameterizedType) {
                        ParameterizedType pType = (ParameterizedType) type;
                        for (Type paramType : pType.getActualTypeArguments()) {
                            if (paramType instanceof Class
                                    && NamedDefinition.class.isAssignableFrom((Class) paramType)) {
                                text = field.getName() + "(container of " + paramType + " oneOf)";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                        .getType();
                                Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                map.forEach((k, v) -> {
                                    String text2 = k;
                                    System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5,
                                            "\t-   "));
                                    inspect(newLevel, v.getClass(), field.getName());
                                });
                            } else if (paramType instanceof ParameterizedType && NamedDefinition.class
                                    .isAssignableFrom((Class) ((ParameterizedType) paramType).getRawType())) {
                                text = field.getName() + "(container of " + paramType + " oneOf2)";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) paramType)
                                        .getRawType();
                                Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                map.forEach((k, v) -> {
                                    String text2 = k;
                                    System.err.println(StringUtils.leftPad(text2, text2.length() + newLevel * 5,
                                            "\t-   "));
                                    inspect(newLevel, v.getClass(), field.getName());
                                });
                            } else if (paramType instanceof WildcardType) {
                                for (Type wildType : ((WildcardType) paramType).getUpperBounds()) {
                                    if (wildType instanceof Class
                                            && NamedDefinition.class.isAssignableFrom((Class) wildType)) {
                                        text = field.getName() + "(container of " + wildType + " oneOf)";
                                        System.err.println(StringUtils.leftPad(text,
                                                text.length() + newLevel * 5, "\t-   "));
                                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                                .getType();
                                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                        map.forEach((k, v) -> {
                                            String text2 = k;
                                            System.err.println(StringUtils.leftPad(text2,
                                                    text2.length() + newLevel * 5, "\t-   "));
                                            inspect(newLevel, v.getClass(), field.getName());
                                        });
                                    } else if (wildType instanceof ParameterizedType
                                            && NamedDefinition.class.isAssignableFrom(
                                                    (Class) ((ParameterizedType) wildType).getRawType())) {
                                        text = field.getName() + "(container of " + wildType + " oneOf2)";
                                        System.err.println(StringUtils.leftPad(text,
                                                text.length() + newLevel * 5, "\t-   "));
                                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) ((ParameterizedType) wildType)
                                                .getRawType();
                                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                                        map.forEach((k, v) -> {
                                            String text2 = k;
                                            System.err.println(StringUtils.leftPad(text2,
                                                    text2.length() + newLevel * 5, "\t-   "));
                                            inspect(newLevel, v.getClass(), field.getName());
                                        });
                                    }
                                }
                            } else {
                                text = field.getName() + "(container of " + paramType + ")";
                                System.err.println(
                                        StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                                inspect(newLevel, paramType, "");
                            }
                        }
                    }
                } else {
                    if (NamedDefinition.class.isAssignableFrom(field.getType())) {
                        text = field.getName() + " oneOf";
                        System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                        Class<? extends NamedDefinition> nd = (Class<? extends NamedDefinition>) field
                                .getType();
                        Map<String, ? extends NamedDefinition> map = NamedProviders.get(nd);
                        map.forEach((k, v) -> {
                            String text2 = k;
                            System.err.println(
                                    StringUtils.leftPad(text2, text2.length() + newLevel * 5, "\t-   "));
                            inspect(newLevel, v.getClass(), field.getName());
                        });
                    } else {
                        text = field.getName()
                                + (field.getType().isPrimitive() || field.getType().equals(String.class)
                                        || field.getType().equals(LocalDateTime.class)
                                                ? " (" + field.getType().getName() + ")"
                                                : "");
                        System.err.println(StringUtils.leftPad(text, text.length() + newLevel * 5, "\t-   "));
                        inspect(newLevel, fieldType, field.getName());
                    }
                }

                // JsonSubTypes subtype =
                // fieldType.getAnnotation(JsonSubTypes.class);
                // if (subtype != null) {
                // int subLevel = level + 2;
                // text = "subtypes:";
                // System.err.println(StringUtils.leftPad(text,
                // text.length() + subLevel * 5, "\t-   "));
                // for (JsonSubTypes.Type type : subtype.value()) {
                // text = "subtype:" + type.name();
                // System.err.println(StringUtils.leftPad(text,
                // text.length() + (subLevel + 1) * 5, "\t-   "));
                // inspect((subLevel + 1), type.value(), type.name());
                // }
                // }
            }
        }

        JsonSubTypes subtype = ((Class<?>) clazz).getAnnotation(JsonSubTypes.class);
        if (subtype != null) {
            int subLevel = level + 1;
            String text = "subtypes:";
            System.err.println(StringUtils.leftPad(text, text.length() + subLevel * 5, "\t-   "));
            for (JsonSubTypes.Type type : subtype.value()) {
                text = "subtype:" + type.name();
                System.err.println(StringUtils.leftPad(text, text.length() + (subLevel + 1) * 5, "\t-   "));
                inspect((subLevel + 1), type.value(), type.name());
            }
        }
    }
}

From source file:org.janusgraph.graphdb.management.ConfigurationManagementGraph.java

/**
 * Create a configuration according to the supplied {@link Configuration}; you must include
 * the property "graph.graphname" with a value in the configuration; you can then
 * open your graph using graph.graphname without having to supply the
 * Configuration or File each time using the {@link org.janusgraph.core.ConfiguredGraphFactory}.
 *//*  w  w w. ja v  a  2s.com*/
public void createConfiguration(final Configuration config) {
    Preconditions.checkArgument(config.containsKey(PROPERTY_GRAPH_NAME),
            String.format("Please include the property \"%s\" in your configuration.", PROPERTY_GRAPH_NAME));
    final Map<Object, Object> map = ConfigurationConverter.getMap(config);
    final Vertex v = graph.addVertex(T.label, VERTEX_LABEL);
    map.forEach((key, value) -> v.property((String) key, value));
    v.property(PROPERTY_TEMPLATE, false);
    graph.tx().commit();
}

From source file:org.onosproject.influxdbmetrics.DefaultInfluxDbMetricsRetriever.java

@Override
public Map<NodeId, Map<String, InfluxMetric>> allMetrics() {
    Map<NodeId, Set<String>> nameMap = allMetricNames();
    Map<NodeId, Map<String, InfluxMetric>> metricsMap = Maps.newHashMap();

    nameMap.forEach((nodeId, metricNames) -> metricsMap.putIfAbsent(nodeId, metricsByNodeId(nodeId)));

    return metricsMap;
}