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.globocom.grou.report.ReportService.java

private HashMap<String, Double> sanitizeKeyName(Map<String, Double> report) {
    HashMap<String, Double> reportSanitized = new HashMap<>();
    report.forEach((key, value) -> reportSanitized.put(key.replaceAll("[.\\s\\\\()%/:\\-]", "_")
            .replaceAll("_{2,}", "_").replaceAll("_$", "").toLowerCase(), value));
    return reportSanitized;
}

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

private void buildDefinitionsSection(MarkupDocBuilder markupDocBuilder, Map<String, Model> definitions) {
    Map<String, Model> sortedMap = toSortedMap(definitions, config.getDefinitionOrdering());
    sortedMap.forEach((String definitionName, Model model) -> {
        if (isNotBlank(definitionName) && checkThatDefinitionIsNotInIgnoreList(definitionName)) {
            buildDefinition(markupDocBuilder, definitionName, model);
        }//from w w  w  . j a va 2s .c o  m
    });
}

From source file:org.apache.pulsar.io.kafka.connect.PulsarOffsetBackingStore.java

@Override
public Future<Void> set(Map<ByteBuffer, ByteBuffer> values, Callback<Void> callback) {
    values.forEach((key, value) -> {
        ByteBuf bb = Unpooled.wrappedBuffer(key);
        byte[] keyBytes = ByteBufUtil.getBytes(bb);
        bb = Unpooled.wrappedBuffer(value);
        byte[] valBytes = ByteBufUtil.getBytes(bb);
        producer.newMessage().key(new String(keyBytes, UTF_8)).value(valBytes).sendAsync();
    });//from w  w w .  j a va2s .c o  m
    return producer.flushAsync().whenComplete((ignored, cause) -> {
        if (null != callback) {
            callback.onCompletion(cause, ignored);
        }
        if (null == cause) {
            readToEnd(new CompletableFuture<>());
        }
    });
}

From source file:org.trellisldp.test.MementoResourceTests.java

/**
 * Test the content of memento resources.
 *///from  w  ww  .  j  ava2  s.co  m
@Test
@DisplayName("Test the content of memento resources")
default void testMementoContent() {
    final RDF rdf = getInstance();
    final Dataset dataset = rdf.createDataset();
    final Map<String, String> mementos = getMementos();
    mementos.forEach((memento, date) -> {
        try (final Response res = target(memento).request().get()) {
            assertEquals(SUCCESSFUL, res.getStatusInfo().getFamily(), "Check for a successful request");
            readEntityAsGraph(res.getEntity(), getBaseURL(), TURTLE).stream()
                    .forEach(triple -> dataset.add(rdf.createIRI(memento), triple.getSubject(),
                            triple.getPredicate(), triple.getObject()));
        }
    });

    final IRI subject = rdf.createIRI(getResourceLocation());
    final List<IRI> urls = mementos.keySet().stream().sorted().map(rdf::createIRI).collect(toList());
    assertEquals(3L, urls.size(), "Check that three mementos were found");
    assertTrue(dataset.getGraph(urls.get(0)).isPresent(), "Check that the first graph is present");
    dataset.getGraph(urls.get(0)).ifPresent(g -> {
        assertTrue(g.contains(subject, type, SKOS.Concept), "Check for a skos:Concept type");
        assertTrue(g.contains(subject, SKOS.prefLabel, rdf.createLiteral("Resource Name", "eng")),
                "Check for a skos:prefLabel property");
        assertTrue(g.contains(subject, DC.subject, rdf.createIRI("http://example.org/subject/1")),
                "Check for a dc:subject property");
        assertEquals(3L, g.size(), "Check for three triples");
    });

    assertTrue(dataset.getGraph(urls.get(1)).isPresent(), "Check that the second graph is present");
    dataset.getGraph(urls.get(1)).ifPresent(g -> {
        assertTrue(g.contains(subject, type, SKOS.Concept), "Check for a skos:Concept type");
        assertTrue(g.contains(subject, SKOS.prefLabel, rdf.createLiteral("Resource Name", "eng")),
                "Check for a skos:prefLabel property");
        assertTrue(g.contains(subject, DC.subject, rdf.createIRI("http://example.org/subject/1")),
                "Check for a dc:subject property");
        assertTrue(g.contains(subject, DC.title, rdf.createLiteral("Title")), "Check for a dc:title property");
        assertEquals(4L, g.size(), "Check for four triples");
    });

    assertTrue(dataset.getGraph(urls.get(2)).isPresent(), "Check that the third graph is present");
    dataset.getGraph(urls.get(2)).ifPresent(g -> {
        assertTrue(g.contains(subject, type, SKOS.Concept), "Check for a skos:Concept type");
        assertTrue(g.contains(subject, SKOS.prefLabel, rdf.createLiteral("Resource Name", "eng")),
                "Check for a skos:prefLabel property");
        assertTrue(g.contains(subject, DC.subject, rdf.createIRI("http://example.org/subject/1")),
                "Check for a dc:subject property");
        assertTrue(g.contains(subject, DC.title, rdf.createLiteral("Title")), "Check for a dc:title property");
        assertTrue(g.contains(subject, DC.alternative, rdf.createLiteral("Alternative Title")),
                "Check for a dc:alternative property");
        assertEquals(5L, g.size(), "Check for five triples");
    });
}

From source file:org.springframework.core.SimpleAliasRegistry.java

/**
 * Resolve all alias target names and aliases registered in this
 * factory, applying the given StringValueResolver to them.
 * <p>The value resolver may for example resolve placeholders
 * in target bean names and even in alias names.
 * @param valueResolver the StringValueResolver to apply
 *//*from ww  w.j av a 2  s  .com*/
public void resolveAliases(StringValueResolver valueResolver) {
    Assert.notNull(valueResolver, "StringValueResolver must not be null");
    synchronized (this.aliasMap) {
        Map<String, String> aliasCopy = new HashMap<>(this.aliasMap);
        aliasCopy.forEach((alias, registeredName) -> {
            String resolvedAlias = valueResolver.resolveStringValue(alias);
            String resolvedName = valueResolver.resolveStringValue(registeredName);
            if (resolvedAlias == null || resolvedName == null || resolvedAlias.equals(resolvedName)) {
                this.aliasMap.remove(alias);
            } else if (!resolvedAlias.equals(alias)) {
                String existingName = this.aliasMap.get(resolvedAlias);
                if (existingName != null) {
                    if (existingName.equals(resolvedName)) {
                        // Pointing to existing alias - just remove placeholder
                        this.aliasMap.remove(alias);
                        return;
                    }
                    throw new IllegalStateException("Cannot register resolved alias '" + resolvedAlias
                            + "' (original: '" + alias + "') for name '" + resolvedName
                            + "': It is already registered for name '" + registeredName + "'.");
                }
                checkForAliasCircle(resolvedName, resolvedAlias);
                this.aliasMap.remove(alias);
                this.aliasMap.put(resolvedAlias, resolvedName);
            } else if (!registeredName.equals(resolvedName)) {
                this.aliasMap.put(alias, resolvedName);
            }
        });
    }
}

From source file:tech.beshu.ror.integration.JwtAuthTests.java

private Optional<String> makeToken(String key, Map<String, Object> claims) {
    JwtBuilder builder = Jwts.builder().setSubject(SUBJECT).signWith(SignatureAlgorithm.valueOf(ALGO),
            key.getBytes());//from   w  w  w . j  a v a 2 s .c o m
    claims.forEach(builder::claim);
    return Optional.of(builder.compact());
}

From source file:org.fcrepo.kernel.modeshape.rdf.impl.RootRdfContext.java

private void concatRepositoryTriples() {
    LOGGER.trace("Creating RDF triples for repository description");
    final Repository repository = session().getRepository();

    final ImmutableSet.Builder<Triple> b = builder();
    stream(repository.getDescriptorKeys()).forEach(key -> {
        final String descriptor = repository.getDescriptor(key);
        if (descriptor != null) {
            // Create a URI from the jcr.Repository constant values,
            // converting them from dot notation (identifier.stability)
            // to the camel case that is more common in RDF properties.
            final String uri = stream(key.split("\\.")).map(StringUtils::capitalize)
                    .collect(joining("", REPOSITORY_NAMESPACE + "repository", ""));
            b.add(create(subject(), createURI(uri), createLiteral(descriptor)));
        }//from   w w w . j ava  2s . c  om
    });

    /*
    FIXME: removing due to performance problems, esp. w/ many files on federated filesystem
    see: https://www.pivotaltracker.com/story/show/78647248
            
    b.add(create(subject(), HAS_OBJECT_COUNT.asNode(), createLiteral(String
            .valueOf(getRepositoryCount(repository)))));
    b.add(create(subject(), HAS_OBJECT_SIZE.asNode(), createLiteral(String
            .valueOf(getRepositorySize(repository)))));
    */

    // Get the cluster configuration, if available
    // this ugly test checks to see whether this is an ordinary JCR
    // repository or a ModeShape repo, which will possess the extra info
    if (JcrRepository.class.isAssignableFrom(repository.getClass())) {
        final Map<String, String> config = new GetClusterConfiguration().apply(repository);
        assert (config != null);
        config.forEach(
                (k, v) -> b.add(create(subject(), createURI(REPOSITORY_NAMESPACE + k), createLiteral(v))));
    }

    // retrieve the metrics from the service
    final Map<String, Counter> counters = registryService.getMetrics().getCounters();
    // and add the repository metrics to the RDF model
    if (counters.containsKey(FIXITY_CHECK_COUNTER)) {
        b.add(create(subject(), HAS_FIXITY_CHECK_COUNT.asNode(),
                createTypedLiteral(counters.get(PREFIX + FIXITY_CHECK_COUNTER).getCount()).asNode()));
    }

    if (counters.containsKey(FIXITY_ERROR_COUNTER)) {
        b.add(create(subject(), HAS_FIXITY_ERROR_COUNT.asNode(),
                createTypedLiteral(counters.get(PREFIX + FIXITY_ERROR_COUNTER).getCount()).asNode()));
    }

    if (counters.containsKey(FIXITY_REPAIRED_COUNTER)) {
        b.add(create(subject(), HAS_FIXITY_REPAIRED_COUNT.asNode(),
                createTypedLiteral(counters.get(PREFIX + FIXITY_REPAIRED_COUNTER).getCount()).asNode()));
    }

    // offer all these accumulated triples
    concat(b.build());
}

From source file:com.evolveum.midpoint.model.impl.lens.EvaluationOrderImpl.java

@Override
public EvaluationOrder applyDifference(Map<QName, Integer> difference) {
    EvaluationOrderImpl clone = clone();
    difference.forEach((relation, count) -> clone.advanceThis(relation, count));
    clone.checkConsistence();/*from w  ww  . ja  v  a2  s  .  c o  m*/
    return clone;
}

From source file:org.codice.alliance.libs.stanag4609.Stanag4609TransportStreamParserTest.java

private void verifyDecodedMetadataPacket(final DecodedKLVMetadataPacket packet) {
    final KlvContext outerContext = packet.getDecodedKLV();
    assertThat(outerContext.getDataElements().size(), is(1));

    assertThat(outerContext.hasDataElement(Stanag4609TransportStreamParser.UAS_DATALINK_LOCAL_SET), is(true));
    final KlvContext localSetContext = ((KlvLocalSet) outerContext
            .getDataElementByName(Stanag4609TransportStreamParser.UAS_DATALINK_LOCAL_SET)).getValue();
    final Map<String, KlvDataElement> localSetDataElements = localSetContext.getDataElements();

    assertThat(localSetDataElements.size(), is(EXPECTED_VALUES.size()));

    localSetDataElements.forEach((name, dataElement) -> {
        final Object expectedValue = EXPECTED_VALUES.get(name);
        final Object actualValue = dataElement.getValue();

        if (actualValue instanceof Double) {
            assertThat(String.format("%s is not close to %s", name, expectedValue), (Double) actualValue,
                    is(closeTo((Double) expectedValue, 1e-6)));
        } else {/*from   w  w  w . j ava  2  s  .  c  o m*/
            assertThat(String.format("%s is not %s", name, expectedValue), actualValue, is(expectedValue));
        }
    });
}

From source file:cognition.pipeline.service.anonymisation.TemplateFiller.java

public String getFilledTemplate(String path, Map<String, Object> objectMap) {
    Template template = velocityEngine.getTemplate(path);
    VelocityContext context = new VelocityContext();

    StringWriter stringWriter = new StringWriter();
    addCommonToolsToMap(objectMap);//from   w ww.jav  a2  s.co  m
    objectMap.forEach((key, value) -> context.put(key, value));

    template.merge(context, stringWriter);

    return stringWriter.toString();
}