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.lanternpowered.server.data.MemoryDataView.java

@SuppressWarnings("rawtypes")
private ImmutableMap<?, ?> ensureSerialization(Map<?, ?> map) {
    final ImmutableMap.Builder<Object, Object> builder = ImmutableMap.builder();
    map.forEach((key, value) -> {
        if (value instanceof Map) {
            builder.put(key, ensureSerialization((Map) value));
        } else if (value instanceof DataSerializable) {
            builder.put(key, ((DataSerializable) value).toContainer());
        } else if (value instanceof Collection) {
            builder.put(key, ensureSerialization((Collection) value));
        } else {/*from ww  w  .  j  a  va 2  s .  c  o  m*/
            builder.put(key, value);
        }
    });
    return builder.build();
}

From source file:io.atomix.protocols.gossip.map.AntiEntropyMapDelegate.java

@Override
public void putAll(Map<? extends K, ? extends V> m) {
    checkState(!closed, destroyedMessage);
    m.forEach(this::put);
}

From source file:com.oneops.transistor.service.BomManagerImpl.java

protected void check4Secondary(CmsCI platform, List<CmsCIRelation> platformCloudRels, String nsPath) {
    //get manifest clouds and priority; what is intended
    Map<Long, Integer> intendedCloudpriority = platformCloudRels.stream().filter(cloudUtil::isCloudActive)
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> i));
    //are there any secondary clouds for deployment
    long numberOfSecondaryClouds = intendedCloudpriority.entrySet().stream()
            .filter(entry -> (entry.getValue().equals(SECONDARY_CLOUD_STATUS))).count();
    if (numberOfSecondaryClouds == 0) {
        return;/*from  w  ww. ja  v  a 2s  .  c om*/
    }

    String finalNsPath = nsPath;
    //what is deployed currently.
    String entryPoint = getEntryPoint(platform);
    if (entryPoint == null) {
        //for platforms which dont have entry points, like schema.
        logger.info("Skipping secondary check , as entry point is absent for this " + nsPath + " platform ciId "
                + platform.getCiId());
        return;
    }

    Map<Long, Integer> existingCloudPriority = platformCloudRels.stream().map(CmsCIRelationBasic::getToCiId)
            .flatMap(cloudId -> cmProcessor
                    .getToCIRelationsByNs(cloudId, CmsConstants.DEPLOYED_TO, null, entryPoint, finalNsPath)
                    .stream())
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> {
                return Math.max(i, j);
            }));

    HashMap<Long, Integer> computedCloudPriority = new HashMap<>(existingCloudPriority);
    computedCloudPriority.putAll(intendedCloudpriority);

    //Now, take  all offline clouds from
    Map<Long, Integer> offlineClouds = platformCloudRels.stream().filter(cloudUtil::isCloudOffline)
            .collect(toMap(CmsCIRelationBasic::getToCiId, this::getPriority, (i, j) -> i));
    if (!offlineClouds.isEmpty()) {
        offlineClouds.forEach((k, v) -> {
            if (computedCloudPriority.containsKey(k)) {
                computedCloudPriority.remove(k);
            }
        });
    }

    long count = computedCloudPriority.entrySet().stream()
            .filter(entry -> (entry.getValue().equals(CmsConstants.SECONDARY_CLOUD_STATUS))).count();
    if (computedCloudPriority.size() == count) {
        //throw transistor exception
        String message = "";
        String clouds = platformCloudRels.stream().filter(rel -> !cloudUtil.isCloudActive(rel))
                .filter(rel -> (getPriority(rel) == PRIMARY_CLOUD_STATUS)).map(rel -> rel.getToCi().getCiName())
                .collect(joining(","));

        if (StringUtils.isNotEmpty(clouds)) {
            message = String.format(
                    "The deployment will result in no instances in primary clouds for platform %s. Primary clouds <%s>  are not in active state for this platform.  ",
                    nsPath, clouds);
        } else {
            message = String.format(
                    "The deployment will result in no instances in primary clouds for platform %s. Please check the cloud priority of the clouds. .  ",
                    nsPath);
        }

        throw new TransistorException(TRANSISTOR_ALL_INSTANCES_SECONDARY, message);
    }
}

From source file:com.hurence.logisland.processor.webAnalytics.setSourceOfTraffic.java

public void processSession(ProcessContext context, Record record) {
    final String utm_source_field = context.getPropertyValue(UTM_SOURCE_FIELD).asString();
    final String utm_medium_field = context.getPropertyValue(UTM_MEDIUM_FIELD).asString();
    final String utm_campaign_field = context.getPropertyValue(UTM_CAMPAIGN_FIELD).asString();
    final String utm_content_field = context.getPropertyValue(UTM_CONTENT_FIELD).asString();
    final String utm_term_field = context.getPropertyValue(UTM_TERM_FIELD).asString();
    final String first_visited_page_field = context.getPropertyValue(FIRST_VISITED_PAGE_FIELD).asString();
    final String SOURCE_OF_TRAFFIC_SUFFIX = context.getPropertyValue(SOURCE_OF_TRAFFIC_SUFFIX_FIELD).asString();
    final String FLAT_SEPARATOR = "_";
    final String referer_field = context.getPropertyValue(REFERER_FIELD).asString();
    final boolean hierarchical = context.getPropertyValue(HIERARCHICAL).asBoolean();

    SourceOfTrafficMap sourceOfTraffic = new SourceOfTrafficMap();

    // Check if location contains the parameter ?gclid= (adwords) or ?gclsrc= (DoubleClick).
    final Field locationField = record.getField(first_visited_page_field);
    final String location = locationField != null ? locationField.asString() : null;

    final Field referenceField = record.getField(referer_field);
    final String referer = referenceField != null ? referenceField.asString() : null;

    if (adwords(location, sourceOfTraffic) || adwords(referer, sourceOfTraffic)) {
        // Already processed.
    }//from  ww  w  .  j  av a 2 s . c o  m
    // Check if this is a custom campaign
    else if (record.getField(utm_source_field) != null) {
        String utm_source = null;
        try {
            utm_source = URLDecoder.decode(record.getField(utm_source_field).asString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            getLogger().error("UnsupportedEncodingException", e);
            utm_source = record.getField(utm_source_field).asString();
        }
        sourceOfTraffic.setSource(utm_source);
        if (record.getField(utm_campaign_field) != null) {
            String utm_campaign = null;
            try {
                utm_campaign = URLDecoder.decode(record.getField(utm_campaign_field).asString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                getLogger().error("UnsupportedEncodingException", e);
                utm_campaign = record.getField(utm_campaign_field).asString();
            }
            sourceOfTraffic.setCampaign(utm_campaign);
        }
        if (record.getField(utm_medium_field) != null) {
            String utm_medium = null;
            try {
                utm_medium = URLDecoder.decode(record.getField(utm_medium_field).asString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                getLogger().error("UnsupportedEncodingException", e);
                utm_medium = record.getField(utm_medium_field).asString();
            }
            sourceOfTraffic.setMedium(utm_medium);
        }
        if (record.getField(utm_content_field) != null) {
            String utm_content = null;
            try {
                utm_content = URLDecoder.decode(record.getField(utm_content_field).asString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                getLogger().error("UnsupportedEncodingException", e);
                utm_content = record.getField(utm_content_field).asString();
            }
            sourceOfTraffic.setContent(utm_content);
        }
        if (record.getField(utm_term_field) != null) {
            String utm_term = null;
            try {
                utm_term = URLDecoder.decode(record.getField(utm_term_field).asString(), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                getLogger().error("UnsupportedEncodingException", e);
                utm_term = record.getField(utm_term_field).asString();
            }
            sourceOfTraffic.setKeyword(utm_term);
        }
    } else if (referer != null) {
        String hostname;
        try {
            hostname = new URL(referer).getHost();
        } catch (MalformedURLException e) {
            // Avoid error in logs in case scheme is android-app.
            try {
                if ("android-app".equals(new URI(referer).getScheme())) {
                    return;
                }
            } catch (URISyntaxException e2) {
                getLogger().error("URISyntaxException for referer", e2);
                return;
            }
            getLogger().error("MalformedURLException for referer", e);
            return;
        }
        String[] hostname_splitted = hostname.split("\\.");
        String domain = null;
        if (hostname_splitted.length > 1) {
            domain = hostname_splitted[hostname_splitted.length - 2];
        } else if (hostname_splitted.length == 1) {
            domain = hostname_splitted[0];
        } else {
            return;
        }
        // Is referer under the webshop domain ?
        if (is_refer_under_site_domain(domain, context, record)) {
            // This is a direct access
            sourceOfTraffic.setSource(DIRECT_TRAFFIC);
            sourceOfTraffic.setMedium("");
            sourceOfTraffic.setCampaign(DIRECT_TRAFFIC);

        } else {
            // Is the referer a known search engine ?
            if (is_search_engine(domain, context, record)) {
                // This is an organic search engine
                sourceOfTraffic.setSource(domain);
                sourceOfTraffic.setMedium(SEARCH_ENGINE_SITE);
                sourceOfTraffic.setOrganic_searches(Boolean.TRUE);
            } else if (is_social_network(domain, context, record)) {
                // This is social network
                sourceOfTraffic.setSource(domain);
                sourceOfTraffic.setMedium(SOCIAL_NETWORK_SITE);
            } else {
                // If the referer is not in the website domain, neither a search engine nor a social network,
                // then it is a referring site
                sourceOfTraffic.setSource(domain);
                sourceOfTraffic.setMedium(REFERRING_SITE);
                String referral_path = null;
                try {
                    referral_path = URLDecoder.decode(referer, "UTF-8");
                } catch (UnsupportedEncodingException e) {
                    getLogger().error("UnsupportedEncodingException", e);
                    referral_path = referer;
                }
                sourceOfTraffic.setReferral_path(referral_path);
            }
        }
    } else {
        // Direct access
        sourceOfTraffic.setSource(DIRECT_TRAFFIC);
        sourceOfTraffic.setMedium("");
        sourceOfTraffic.setCampaign(DIRECT_TRAFFIC);
    }
    if (hierarchical) {
        record.setField(SOURCE_OF_TRAFFIC_SUFFIX, FieldType.MAP, sourceOfTraffic.getSourceOfTrafficMap());
    } else {
        Map<String, Object> sot = sourceOfTraffic.getSourceOfTrafficMap();
        sot.forEach((k, v) -> {
            record.setField(SOURCE_OF_TRAFFIC_SUFFIX + FLAT_SEPARATOR + k,
                    supportedSourceOfTrafficFieldNames.get(k), v);
        });
    }
}

From source file:org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.java

@Override
public void afterPropertiesSet() throws PersistenceException {
    JpaVendorAdapter jpaVendorAdapter = getJpaVendorAdapter();
    if (jpaVendorAdapter != null) {
        if (this.persistenceProvider == null) {
            this.persistenceProvider = jpaVendorAdapter.getPersistenceProvider();
        }//from w  ww .ja  v a  2  s .  co  m
        PersistenceUnitInfo pui = getPersistenceUnitInfo();
        Map<String, ?> vendorPropertyMap = (pui != null ? jpaVendorAdapter.getJpaPropertyMap(pui)
                : jpaVendorAdapter.getJpaPropertyMap());
        if (!CollectionUtils.isEmpty(vendorPropertyMap)) {
            vendorPropertyMap.forEach((key, value) -> {
                if (!this.jpaPropertyMap.containsKey(key)) {
                    this.jpaPropertyMap.put(key, value);
                }
            });
        }
        if (this.entityManagerFactoryInterface == null) {
            this.entityManagerFactoryInterface = jpaVendorAdapter.getEntityManagerFactoryInterface();
            if (!ClassUtils.isVisible(this.entityManagerFactoryInterface, this.beanClassLoader)) {
                this.entityManagerFactoryInterface = EntityManagerFactory.class;
            }
        }
        if (this.entityManagerInterface == null) {
            this.entityManagerInterface = jpaVendorAdapter.getEntityManagerInterface();
            if (!ClassUtils.isVisible(this.entityManagerInterface, this.beanClassLoader)) {
                this.entityManagerInterface = EntityManager.class;
            }
        }
        if (this.jpaDialect == null) {
            this.jpaDialect = jpaVendorAdapter.getJpaDialect();
        }
    }

    AsyncTaskExecutor bootstrapExecutor = getBootstrapExecutor();
    if (bootstrapExecutor != null) {
        this.nativeEntityManagerFactoryFuture = bootstrapExecutor.submit(this::buildNativeEntityManagerFactory);
    } else {
        this.nativeEntityManagerFactory = buildNativeEntityManagerFactory();
    }

    // Wrap the EntityManagerFactory in a factory implementing all its interfaces.
    // This allows interception of createEntityManager methods to return an
    // application-managed EntityManager proxy that automatically joins
    // existing transactions.
    this.entityManagerFactory = createEntityManagerFactoryProxy(this.nativeEntityManagerFactory);
}

From source file:com.thoughtworks.go.agent.AgentProcessParentImpl.java

private String[] agentInvocationCommand(String agentMD5, String launcherMd5, String agentPluginsZipMd5,
        String tfsImplMd5, Map<String, String> env, Map context,
        // the port is kept for backward compatibility to ensure that old bootstrappers are able to launch new agents
        Map<String, String> extraProperties) {
    AgentBootstrapperArgs bootstrapperArgs = AgentBootstrapperArgs.fromProperties(context);

    String startupArgsString = env.get(AGENT_STARTUP_ARGS);
    List<String> commandSnippets = new ArrayList<>();
    commandSnippets.add(javaCmd());//  w w w .  j a  va2s.c  om
    if (!isEmpty(startupArgsString)) {
        String[] startupArgs = startupArgsString.split(" ");
        for (String startupArg : startupArgs) {
            String decodedStartupArg = startupArg.trim().replace("%20", " ");
            if (!isEmpty(decodedStartupArg)) {
                commandSnippets.add(decodedStartupArg);
            }
        }
    }

    extraProperties.forEach((key, value) -> commandSnippets.add(property(key, value)));

    commandSnippets.add(property(GoConstants.AGENT_PLUGINS_MD5, agentPluginsZipMd5));
    commandSnippets.add(property(GoConstants.AGENT_JAR_MD5, agentMD5));
    commandSnippets.add(property(GoConstants.GIVEN_AGENT_LAUNCHER_JAR_MD5, launcherMd5));
    commandSnippets.add(property(GoConstants.TFS_IMPL_MD5, tfsImplMd5));
    commandSnippets.add("-jar");

    commandSnippets.add(Downloader.AGENT_BINARY);

    commandSnippets.add("-serverUrl");
    commandSnippets.add(bootstrapperArgs.getServerUrl().toString());

    if (bootstrapperArgs.getSslMode() != null) {
        commandSnippets.add("-sslVerificationMode");
        commandSnippets.add(bootstrapperArgs.getSslMode().toString());
    }

    if (bootstrapperArgs.getRootCertFile() != null) {
        commandSnippets.add("-rootCertFile");
        commandSnippets.add(bootstrapperArgs.getRootCertFile().getAbsolutePath());
    }

    return commandSnippets.toArray(new String[] {});
}

From source file:org.codice.ddf.admin.core.impl.SystemPropertiesAdmin.java

@Override
public void writeSystemProperties(Map<String, String> updatedSystemProperties) {
    if (updatedSystemProperties == null) {
        return;/*from w ww. j av  a 2s .co m*/
    }

    Properties systemDotProperties;
    try {
        systemDotProperties = new Properties(systemPropertiesFile);

    } catch (IOException e) {
        LOGGER.warn("Exception reading system.properties file.", e);
        return;
    }

    // save off the current/old hostname before we make any changes
    oldHostName = systemDotProperties.getProperty(SystemBaseUrl.INTERNAL_HOST);
    updatedSystemProperties.forEach((key, value) -> {
        // Clears out the property value before setting it
        //
        // We have to do this because when we read in the properties, the values are
        // expanded which can lead to a state where the value is erroneously not updated
        // after being checked.
        systemDotProperties.put(key, "");
        systemDotProperties.put(key, value);
    });

    callInterceptors(systemDotProperties);

    try {
        systemDotProperties.save();
    } catch (IOException e) {
        LOGGER.warn("Exception writing to system.properties file.", e);
    }

    writeOutUsersDotPropertiesFile(userPropertiesFile);
    writeOutUsersDotAttributesFile(userAttributesFile);
}

From source file:org.talend.dataprep.schema.xls.XlsSchemaParser.java

/**
 *
 *
 * @param colId the column id./*from  w  w  w  .  ja v  a2 s.co  m*/
 * @param columnRows all rows with previously guessed type: key=row number, value= guessed type
 * @param averageHeaderSize
 * @return
 */
private Type guessColumnType(Integer colId, SortedMap<Integer, String> columnRows, int averageHeaderSize) {

    // calculate number per type

    Map<String, Long> perTypeNumber = columnRows.tailMap(averageHeaderSize).values() //
            .stream() //
            .collect(Collectors.groupingBy(w -> w, Collectors.counting()));

    OptionalLong maxOccurrence = perTypeNumber.values().stream().mapToLong(Long::longValue).max();

    if (!maxOccurrence.isPresent()) {
        return ANY;
    }

    List<String> duplicatedMax = new ArrayList<>();

    perTypeNumber.forEach((type1, aLong) -> {
        if (aLong >= maxOccurrence.getAsLong()) {
            duplicatedMax.add(type1);
        }
    });

    String guessedType;
    if (duplicatedMax.size() == 1) {
        guessedType = duplicatedMax.get(0);
    } else {
        // as we have more than one type we guess ANY
        guessedType = ANY.getName();
    }

    LOGGER.debug("guessed type for column #{} is {}", colId, guessedType);
    return Type.get(guessedType);
}

From source file:net.di2e.ecdr.describe.commands.GenerateDescribeCommand.java

@Override
public Object execute() throws Exception {
    try {//from  w ww  .  ja  v a  2  s  .co  m
        Map<String, Metacard> describeRecords = new HashMap<>();
        if (CollectionUtils.isNotEmpty(ids)) {

            ids.forEach(sourceId -> {
                console.println("Generating Describe record for " + sourceId);
                Metacard card = describeGenerator.generate(sourceId);
                describeRecords.put(sourceId, card);
            });
        } else {
            this.framework.getSourceIds().forEach((sourceId) -> {
                console.println("Generating Describe record for " + sourceId);
                Metacard card = describeGenerator.generate(sourceId);
                describeRecords.put(sourceId, card);
            });
        }

        if (!doNotWrite) {
            describeRecords.forEach((id, card) -> {
                writeToFile(id, card.getMetadata());
            });
        }

        if (publishDescribe) {
            DescribePublisher publisher = new DescribePublisher(framework);
            publisher.publish(describeRecords.values());
            console.println(
                    "Succesfully published " + describeRecords.size() + " describe records to catalog.");
        }

        if (print) {
            describeRecords.forEach((id, card) -> {
                console.println("------------------- " + id + " -------------------");
                console.println(card.getMetadata());
                console.println("---------------------------------------------------------");
            });

        }

    } catch (Exception e) {
        console.println("Encountered error while trying to perform command. Check log for more details.");
        LOGGER.warn("Error while performing command.", e);
    }
    return null;
}

From source file:com.streamsets.pipeline.stage.processor.jdbclookup.JdbcLookupProcessor.java

/** {@inheritDoc} */
@Override//  w w  w .  ja va 2 s .com
protected void process(Record record, SingleLaneBatchMaker batchMaker) throws StageException {
    try {
        ELVars elVars = getContext().createELVars();
        RecordEL.setRecordInContext(elVars, record);
        String preparedQuery = queryEval.eval(elVars, query, String.class);
        Optional<List<Map<String, Field>>> entry = cache.get(preparedQuery);

        if (!entry.isPresent()) {
            // No results
            switch (missingValuesBehavior) {
            case SEND_TO_ERROR:
                LOG.error(JdbcErrors.JDBC_04.getMessage(), preparedQuery);
                errorRecordHandler
                        .onError(new OnRecordErrorException(record, JdbcErrors.JDBC_04, preparedQuery));
                break;
            case PASS_RECORD_ON:
                batchMaker.addRecord(record);
                break;
            default:
                throw new IllegalStateException("Unknown missing value behavior: " + missingValuesBehavior);
            }
        } else {
            List<Map<String, Field>> values = entry.get();
            switch (multipleValuesBehavior) {
            case FIRST_ONLY:
                setFieldsInRecord(record, values.get(0));
                batchMaker.addRecord(record);
                break;
            case SPLIT_INTO_MULTIPLE_RECORDS:
                for (Map<String, Field> lookupItem : values) {
                    Record newRecord = getContext().cloneRecord(record);
                    setFieldsInRecord(newRecord, lookupItem);
                    batchMaker.addRecord(newRecord);
                }
                break;
            case ALL_AS_LIST:
                Map<String, List<Field>> valuesMap = new HashMap<>();
                for (Map<String, Field> lookupItem : values) {
                    lookupItem.forEach((k, v) -> {
                        if (valuesMap.get(k) == null) {
                            List<Field> lookupValue = new ArrayList<>();
                            valuesMap.put(k, lookupValue);
                        }
                        valuesMap.get(k).add(v);
                    });
                }
                Map<String, Field> valueMap = new HashMap<>();
                valuesMap.forEach((k, v) -> valueMap.put(k, Field.create(v)));
                setFieldsInRecord(record, valueMap);
                batchMaker.addRecord(record);
                break;
            default:
                throw new IllegalStateException("Unknown multiple value behavior: " + multipleValuesBehavior);
            }

        }

    } catch (ELEvalException e) {
        LOG.error(JdbcErrors.JDBC_01.getMessage(), query, e);
        throw new OnRecordErrorException(record, JdbcErrors.JDBC_01, query);
    } catch (ExecutionException e) {
        Throwables.propagateIfPossible(e.getCause(), StageException.class);
        throw new IllegalStateException(e); // The cache loader shouldn't throw anything that isn't a StageException.
    } catch (OnRecordErrorException error) { // NOSONAR
        errorRecordHandler.onError(new OnRecordErrorException(record, error.getErrorCode(), error.getParams()));
    }
}