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.jumlabs.jcr.oak.rpc.api.impl.JTreeServiceImpl.java

@Override
public void setPropertiesValue(Map<String, TPropertyState> values, TTree ttree) throws TException {
    try {//ww  w .java  2s.co  m
        Tree tree = RepositoryUtils.getTree(repository, ttree);
        values.forEach((key, propertyState) -> {
            TType type = propertyState.getType();
            switch (type) {
            case BINARIES:
                tree.setProperty(key, propertyState.getBinaryValues());
                break;
            case BINARY:
                tree.setProperty(key, propertyState.getBinaryValue());
                break;
            case BOOLEAN:
                tree.setProperty(key, propertyState.isBooleanValue());
                break;
            case BOOLEANS:
                tree.setProperty(key, propertyState.getBooleanValues());
                break;
            case DATE:
                tree.setProperty(key, propertyState.getDateValue());
                break;
            case DATES:
                tree.setProperty(key, propertyState.getDateValues());
                break;
            case DOUBLE:
                tree.setProperty(key, propertyState.getDoubleValue());
                break;
            case DOUBLES:
                tree.setProperty(key, propertyState.getDoubleValues());
                break;
            case LONG:
                tree.setProperty(key, propertyState.getLongValue());
                break;
            case LONGS:
                tree.setProperty(key, propertyState.getLongValues());
                break;

            case STRING:
                tree.setProperty(key, propertyState.getStringValue());
                break;
            case STRINGS:
                tree.setProperty(key, propertyState.getStringValues());
                break;
            default:
                tree.setProperty(key, propertyState.getStringValue());
                break;
            }

        });

    } catch (LoginException | NoSuchWorkspaceException ex) {
        logger.error(ex.getMessage(), ex);
    }
}

From source file:com.redhat.red.build.koji.it.ImportSimpleBuild_RelPathIT.java

/**
 * Something must have broken in latest Koji. When we call addPackageToTag -> ListPackagesRequest,
 * the args for kojihub.py listPackages(...) must have changed, and it does not accept a dict type now.
 *
 * We got error://from ww w.  ja va  2 s  .  c o m
 * ...
 * File "/usr/share/koji-hub/kojihub.py", line 2799, in lookup_name
 * raise koji.GenericError('invalid type for id lookup: %s' % type(info))
 * GenericError: invalid type for id lookup: &lt;type 'dict'&gt;
 *
 * The cause:
 *
 * Frame call_with_argcheck in /usr/lib/python2.7/site-packages/koji/util.py at line 212
 * args = {'pkgID': None, 'tagID': 1, 'userID': 2, 'prefix': None, 'inherited': None, 'event': None}
 * func = RootExports.listPackages
 *
 * It calls func(*args, **kwargs), pass the *args to listPackages. Bug the latter can not handle the args correctly.
 *
 * Frame listPackages in /usr/share/koji-hub/kojihub.py at line 10001
 * pkgID = None
 * userID = None
 * tagID = {'pkgID': None, 'tagID': 1, 'userID': 2, 'prefix': None, 'inherited': None, 'event': None}
 * ...
 *
 * Refer to the method signature:
 * def listPackages(self, tagID=None, userID=None, pkgID=None, prefix=None, inherited=False, with_dups=False, event=None, queryOpts=None)
 *
 * If I skip ListPackagesRequest in KojiClient addPackageToTag, this case can pass.
 *
 * I ignore this case for now. --henry 2017-8-22
 */
@Ignore
@Test
public void run() throws Exception {
    KojiClient client = newKojiClient();
    KojiSessionInfo session = client.login();

    String tagName = getClass().getSimpleName();
    CreateTagRequest req = new CreateTagRequest();
    req.setTagName(tagName);

    client.createTag(req, session);

    ProjectVersionRef gav = new SimpleProjectVersionRef("org.foo", "bar", "1.1");

    boolean packageAdded;
    try {
        packageAdded = client.addPackageToTag(tagName, gav, session);
    } catch (KojiClientException e) {
        if (e.getCause() != null) {
            e.getCause().printStackTrace();
        }
        throw e;
    }
    assertThat(packageAdded, equalTo(true));

    Map<String, KojiArchiveType> archiveTypes = client.getArchiveTypeMap(session);

    KojiArchiveType pomType = archiveTypes.get("pom");

    Date start = new Date(System.currentTimeMillis() - 86400);
    Date end = new Date(System.currentTimeMillis() - 43200);

    KojiImport.Builder importBuilder = new KojiImport.Builder();

    int brId = 1;
    String pomPath = "org/foo/bar/1.1/bar-1.1.pom";
    byte[] pomBytes = readTestResourceBytes("import-data/" + pomPath);

    KojiImport importMetadata = importBuilder.withNewBuildDescription(gav)
            //        KojiImport importMetadata = importBuilder.withNewBuildDescription( "org.foo-bar", "1.1", "1" )
            //                                                 .withBuildType( StandardBuildType.maven )
            .withExternalBuildId("foo-bar-1.1").withStartTime(start).withEndTime(end)
            .withBuildSource("http://build.foo.com").parent().withNewBuildRoot(brId)
            .withTool("apache-maven", "3.2.1").withContentGenerator("test-cg", "1.0")
            .withContainer(
                    new BuildContainer(StandardBuildType.maven.name(), StandardArchitecture.noarch.name()))
            .withHost("linux", StandardArchitecture.x86_64).parent()
            .withNewOutput(1, new File(pomPath).getName()).withFileSize(pomBytes.length)
            .withChecksum(StandardChecksum.md5.name(), DigestUtils.md5Hex(pomBytes))
            //                                                 .withOutputType( StandardOutputType.maven )
            .withMavenInfoAndType(gav).parent().build();

    List<Supplier<ImportFile>> fileSuppliers = Arrays
            .asList(() -> new ImportFile(pomPath, new ByteArrayInputStream(pomBytes), pomBytes.length));

    System.out.printf("Starting CGImport using client: %s\n metadata: %s\n fileSuppliers: %s\n session: %s",
            client, importMetadata, fileSuppliers, session);
    KojiImportResult result = client.importBuild(importMetadata, fileSuppliers, session);

    Map<String, KojijiErrorInfo> uploadErrors = result.getUploadErrors();

    if (uploadErrors != null && !uploadErrors.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        sb.append("The following upload errors occurred:\n\n");
        uploadErrors.forEach((k, v) -> sb.append(k).append(":\n\n  ").append(v).append("\n\n"));
        fail(sb.toString());
    }

    KojiBuildInfo buildInfo = result.getBuildInfo();
    assertThat(buildInfo, notNullValue());

    Integer taskId = client.tagBuild(tagName, buildInfo.getNvr(), session);
    assertThat(taskId, notNullValue());

    KojiTaskInfo taskInfo = client.getTaskInfo(taskId, session);

    System.out.println("State of tag operation: " + taskInfo.getState());
}

From source file:se.inera.intyg.intygstjanst.web.integration.stub.SendMessageToCareResponderStubRestApi.java

private String buildXMLResponse(boolean ok, long time, Map<String, String> additionalValues) {
    StringBuilder sb = new StringBuilder();
    sb.append("<pingdom_http_custom_check>");
    sb.append("<status>" + (ok ? "OK" : "FAIL") + "</status>");
    sb.append("<response_time>" + time + "</response_time>");
    if (additionalValues != null) {
        sb.append("<additional_data>");
        additionalValues.forEach((k, v) -> sb.append("<" + k + ">" + v + "</" + k + ">"));
        sb.append("</additional_data>");
    }/*from ww w.  j ava2s  .  com*/
    sb.append("</pingdom_http_custom_check>");
    return sb.toString();
}

From source file:com.redhat.red.build.koji.it.ImportSimpleBuildIT.java

/**
 * Something must have broken in latest Koji. When we call addPackageToTag -> ListPackagesRequest,
 * the args for kojihub.py listPackages(...) must have changed, and it does not accept a dict type now.
 *
 * We got error:/*  w  w w . jav a  2  s.co  m*/
 * ...
 * File "/usr/share/koji-hub/kojihub.py", line 2799, in lookup_name
 * raise koji.GenericError('invalid type for id lookup: %s' % type(info))
 * GenericError: invalid type for id lookup: &lt;type 'dict'&gt;
 *
 * The cause:
 *
 * Frame call_with_argcheck in /usr/lib/python2.7/site-packages/koji/util.py at line 212
 * args = {'pkgID': None, 'tagID': 1, 'userID': 2, 'prefix': None, 'inherited': None, 'event': None}
 * func = RootExports.listPackages
 *
 * It calls func(*args, **kwargs), pass the *args to listPackages. Bug the latter can not handle the args correctly.
 *
 * Frame listPackages in /usr/share/koji-hub/kojihub.py at line 10001
 * pkgID = None
 * userID = None
 * tagID = {'pkgID': None, 'tagID': 1, 'userID': 2, 'prefix': None, 'inherited': None, 'event': None}
 * ...
 *
 * Refer to the method signature:
 * def listPackages(self, tagID=None, userID=None, pkgID=None, prefix=None, inherited=False, with_dups=False, event=None, queryOpts=None)
 *
 * If I skip ListPackagesRequest in KojiClient addPackageToTag, this case can pass.
 *
 * I ignore this case for now. --henry 2017-8-22
 */
@Ignore
@Test
public void run() throws Exception {
    KojiClient client = newKojiClient();
    KojiSessionInfo session = client.login();

    String tagName = getClass().getSimpleName();
    CreateTagRequest req = new CreateTagRequest();
    req.setTagName(tagName);

    client.createTag(req, session);

    ProjectVersionRef gav = new SimpleProjectVersionRef("org.foo", "bar", "1.1");

    boolean packageAdded;
    try {
        packageAdded = client.addPackageToTag(tagName, gav, session);
    } catch (KojiClientException e) {
        if (e.getCause() != null) {
            e.getCause().printStackTrace();
        }
        throw e;
    }
    assertThat(packageAdded, equalTo(true));

    Map<String, KojiArchiveType> archiveTypes = client.getArchiveTypeMap(session);

    KojiArchiveType pomType = archiveTypes.get("pom");

    Date start = new Date(System.currentTimeMillis() - 86400);
    Date end = new Date(System.currentTimeMillis() - 43200);

    KojiImport.Builder importBuilder = new KojiImport.Builder();

    int brId = 1;
    String pomPath = "org/foo/bar/1.1/bar-1.1.pom";
    byte[] pomBytes = readTestResourceBytes("import-data/" + pomPath);

    KojiImport importMetadata = importBuilder.withNewBuildDescription(gav)
            //        KojiImport importMetadata = importBuilder.withNewBuildDescription( "org.foo-bar", "1.1", "1" )
            //                                                 .withBuildType( StandardBuildType.maven )
            .withExternalBuildId("foo-bar-1.1").withStartTime(start).withEndTime(end)
            .withBuildSource("http://build.foo.com").parent().withNewBuildRoot(brId)
            .withTool("apache-maven", "3.2.1").withContentGenerator("test-cg", "1.0")
            .withContainer(
                    new BuildContainer(StandardBuildType.maven.name(), StandardArchitecture.noarch.name()))
            .withHost("linux", StandardArchitecture.x86_64).parent()
            .withNewOutput(1, new File(pomPath).getName()).withFileSize(pomBytes.length)
            .withChecksum(StandardChecksum.md5.name(), DigestUtils.md5Hex(pomBytes))
            //                                                 .withOutputType( StandardOutputType.maven )
            .withMavenInfoAndType(gav).parent().build();

    List<Supplier<ImportFile>> fileSuppliers = Arrays.asList(() -> new ImportFile(new File(pomPath).getName(),
            new ByteArrayInputStream(pomBytes), pomBytes.length));

    System.out.printf("Starting CGImport using client: %s\n metadata: %s\n fileSuppliers: %s\n session: %s",
            client, importMetadata, fileSuppliers, session);
    KojiImportResult result = client.importBuild(importMetadata, fileSuppliers, session);

    Map<String, KojijiErrorInfo> uploadErrors = result.getUploadErrors();

    if (uploadErrors != null && !uploadErrors.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        sb.append("The following upload errors occurred:\n\n");
        uploadErrors.forEach((k, v) -> sb.append(k).append(":\n\n  ").append(v).append("\n\n"));
        fail(sb.toString());
    }

    KojiBuildInfo buildInfo = result.getBuildInfo();
    assertThat(buildInfo, notNullValue());

    Integer taskId = client.tagBuild(tagName, buildInfo.getNvr(), session);
    assertThat(taskId, notNullValue());

    KojiTaskInfo taskInfo = client.getTaskInfo(taskId, session);

    System.out.println("State of tag operation: " + taskInfo.getState());
}

From source file:be.boyenvaesen.scheduling.HumiditySchedules.java

@Scheduled(fixedRate = 2000)
public void updateIntervalDatabases() {
    log.info("Starting database cleanup");

    Calendar c = Calendar.getInstance();
    Calendar calForCalculations = Calendar.getInstance();
    //Clean records dating till :
    c.add(Calendar.HOUR, -5);/*from  w  w w .j  a  va 2  s  .c  om*/
    Date now = new Date();

    List<Humidity> allHumidities = service.getBetweenDates(c.getTime(), now);
    List<HumidityByMinute> humiditiesByMinute = service.getBetweenDatesByInterval(HumidityByMinute.class,
            c.getTime(), now);
    List<HumidityByHour> humidityByHour = service.getBetweenDatesByInterval(HumidityByHour.class, c.getTime(),
            now);

    //Group humidities by minute
    Map<Date, List<Humidity>> map = allHumidities.stream().collect(Collectors.groupingBy((t) -> {

        calForCalculations.setTime(t.getMeasured());
        calForCalculations.set(Calendar.SECOND, 0);
        calForCalculations.set(Calendar.MILLISECOND, 0);

        return calForCalculations.getTime();
    }));
    //CALCULATE MINUTES
    map.forEach((t, u) -> {
        HumidityByMinute toCalc = humiditiesByMinute.stream().filter((q) -> {
            return q.getAtTime().compareTo(t) == 0;
        }).findAny().orElse(new HumidityByMinute(t));
        float average = (float) u.stream().mapToDouble(Humidity::getPercentage).average().getAsDouble();
        toCalc.setAveragePercentage(average);
        service.saveByInterval(toCalc);
    });

    List<HumidityByMinute> newByMinute = service.getBetweenDatesByInterval(HumidityByMinute.class, c.getTime(),
            now);
    //Group HumidityByMinute By hour
    Map<Date, List<HumidityByMinute>> mapByHour = newByMinute.stream().collect(Collectors.groupingBy((t) -> {
        calForCalculations.setTime(t.getAtTime());
        calForCalculations.set(Calendar.MINUTE, 0);
        return calForCalculations.getTime();
    }));
    //CALCULATE HOURS
    mapByHour.forEach((t, u) -> {

        HumidityByHour toCalc = humidityByHour.stream().filter((q) -> {
            return q.getAtTime().compareTo(t) == 0;
        }).findAny().orElse(new HumidityByHour(t));
        float average = (float) u.stream().mapToDouble(HumidityByMinute::getAveragePercentage).average()
                .getAsDouble();
        toCalc.setAveragePercentage(average);
        service.saveByInterval(toCalc);

    });
    log.info("finished cleaning database");

}

From source file:org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.java

private void loadBeanDefinitionsFromRegistrars(
        Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
    registrars.forEach((registrar, metadata) -> registrar.registerBeanDefinitions(metadata, this.registry));
}

From source file:org.apache.hadoop.hbase.replication.ReplicationPeerConfig.java

private Map<TableName, List<String>> unmodifiableTableCFsMap(Map<TableName, List<String>> tableCFsMap) {
    Map<TableName, List<String>> newTableCFsMap = new HashMap<>();
    tableCFsMap.forEach(
            (table, cfs) -> newTableCFsMap.put(table, cfs != null ? Collections.unmodifiableList(cfs) : null));
    return Collections.unmodifiableMap(newTableCFsMap);
}

From source file:ws.salient.session.Session.java

private void setGlobals(Injector injector) {
    Map<String, Class<?>> globalDefintions = ((InternalKnowledgeBase) ksession.getKieBase()).getGlobals();
    globalDefintions.forEach((String key, Class type) -> {
        Object value = injector.getInstance(type);
        ksession.setGlobal(key, value);//from w ww  . j a  v a 2s .  co  m
    });
}

From source file:org.matonto.sparql.rest.impl.SparqlRestImplTest.java

@Test
public void downloadQueryTest() {
    Map<String, String> tests = new HashMap<>();
    tests.put("csv", "text/csv");
    tests.put("tsv", "text/tab-separated-values");
    tests.put("xls", "application/vnd.ms-excel");
    tests.put("xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    tests.forEach((type, mimeType) -> {
        Response response = target().path("sparql").queryParam("query", ALL_QUERY)
                .queryParam("fileName", "test").queryParam("fileType", type).request().get();
        assertEquals(response.getStatus(), 200);
        MultivaluedMap<String, Object> headers = response.getHeaders();
        assertEquals(headers.get("Content-Type").get(0), mimeType);
        assertEquals(headers.get("Content-Disposition").get(0), "attachment;filename=test." + type);
    });//from w w w  .j  a va  2  s .  c o m
}

From source file:org.talend.dataprep.dataset.StatisticsAdapter.java

private void injectDataFrequency(final ColumnMetadata column, final Analyzers.Result result) {
    if (result.exist(DataTypeFrequencyStatistics.class)) {
        final Statistics statistics = column.getStatistics();
        final DataTypeFrequencyStatistics dataFrequencyStatistics = result
                .get(DataTypeFrequencyStatistics.class);
        final Map<String, Long> topTerms = dataFrequencyStatistics.getTopK(15);
        if (topTerms != null) {
            statistics.getDataFrequencies().clear();
            topTerms.forEach((s, o) -> statistics.getDataFrequencies().add(new DataFrequency(s, o)));
        }/*  ww w .  j a v a2s. c  o  m*/
    }
}