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.adobe.acs.commons.adobeio.service.impl.EndpointServiceImpl.java

/**
 * Process the Adobe I/O action//  w  w  w  .  j  a v  a2s .  c o  m
 * 
 * @param actionUrl
 *            The url to be executed
 * @param queryParameters
 *            The query parameters to pass
 * @param method
 *            The method to be executed
 * @param payload
 *            The payload of the call
 * @return JsonObject containing the result of the action
 * @throws Exception
 *             Thrown when process-action throws an exception
 */
private JsonObject process(@NotNull final String actionUrl, @NotNull final Map<String, String> queryParameters,
        @NotNull final String method, final String[] headers, @NotNull final JsonObject payload) {
    if (isBlank(actionUrl) || isBlank(method)) {
        LOGGER.error("Method or url is null");
        return new JsonObject();
    }

    URI uri = null;

    try {
        URIBuilder builder = new URIBuilder(actionUrl);
        queryParameters.forEach((k, v) -> builder.addParameter(k, v));
        uri = builder.build();

    } catch (URISyntaxException uriexception) {
        LOGGER.error(uriexception.getMessage());
        return new JsonObject();
    }

    LOGGER.debug("Performing method = {}. queryParameters = {}. actionUrl = {}. payload = {}", method,
            queryParameters, uri, payload);

    try {
        if (StringUtils.equalsIgnoreCase(method, METHOD_POST)) {
            return processPost(uri, payload, headers);
        } else if (StringUtils.equalsIgnoreCase(method, METHOD_GET)) {
            return processGet(uri, headers);
        } else if (StringUtils.equalsIgnoreCase(method, "PATCH")) {
            return processPatch(uri, payload, headers);
        } else {
            return new JsonObject();
        }
    } catch (IOException ioexception) {
        LOGGER.error(ioexception.getMessage());
        return new JsonObject();

    }

}

From source file:org.opencb.opencga.app.cli.analysis.executors.VariantCommandExecutor.java

private void samples() throws Exception {

    VariantCommandOptions.VariantSamplesFilterCommandOptions cliOptions = variantCommandOptions.samplesFilterCommandOptions;

    //        Map<Long, String> studyIds = getStudyIds(sessionId);
    Query query = VariantQueryCommandUtils.parseBasicVariantQuery(cliOptions.variantQueryOptions, new Query());

    VariantStorageManager variantManager = new VariantStorageManager(catalogManager, storageEngineFactory);

    VariantSampleFilter variantSampleFilter = new VariantSampleFilter(variantManager.iterable(sessionId));

    if (StringUtils.isNotEmpty(cliOptions.samples)) {
        query.append(VariantDBAdaptor.VariantQueryParams.RETURNED_SAMPLES.key(),
                Arrays.asList(cliOptions.samples.split(",")));
    }/*from  w  w w .j a v a 2  s  .  c  o  m*/
    if (StringUtils.isNotEmpty(cliOptions.study)) {
        query.append(VariantDBAdaptor.VariantQueryParams.STUDIES.key(), cliOptions.study);
    }

    List<String> genotypes = Arrays.asList(cliOptions.genotypes.split(","));
    if (cliOptions.all) {
        Collection<String> samplesInAllVariants = variantSampleFilter.getSamplesInAllVariants(query, genotypes);
        System.out.println("##Samples in ALL variants with genotypes " + genotypes);
        for (String sample : samplesInAllVariants) {
            System.out.println(sample);
        }
    } else {
        Map<String, Set<Variant>> samplesInAnyVariants = variantSampleFilter.getSamplesInAnyVariants(query,
                genotypes);
        System.out.println("##Samples in ANY variants with genotypes " + genotypes);
        Set<Variant> variants = new TreeSet<>((v1, o2) -> v1.getStart().compareTo(o2.getStart()));
        samplesInAnyVariants.forEach((sample, v) -> variants.addAll(v));

        System.out.print(StringUtils.rightPad("#SAMPLE", 10));
        //            System.out.print("|");
        for (Variant variant : variants) {
            System.out.print(StringUtils.center(variant.toString(), 15));
            //                System.out.print("|");
        }
        System.out.println();
        samplesInAnyVariants.forEach((sample, v) -> {
            System.out.print(StringUtils.rightPad(sample, 10));
            //                System.out.print("|");
            for (Variant variant : variants) {
                if (v.contains(variant)) {
                    System.out.print(StringUtils.center("X", 15));
                } else {
                    System.out.print(StringUtils.center("-", 15));
                }
                //                    System.out.print("|");
            }
            System.out.println();
        });

    }
}

From source file:org.onosproject.cli.net.IntentsListCommand.java

@Override
protected void execute() {
    service = get(IntentService.class);
    contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);

    Iterable<Intent> intents;
    if (pending) {
        intents = service.getPending();// www . ja  va2s.co  m
    } else {
        intents = service.getIntents();
    }

    // Remove intents
    if (remove != null && !remove.isEmpty()) {
        filter.add(remove);
        contentFilter = new StringFilter(filter, StringFilter.Strategy.AND);
        IntentRemoveCommand intentRemoveCmd = new IntentRemoveCommand();
        if (!remove.isEmpty()) {
            intentRemoveCmd.purgeIntentsInteractive(filterIntents(service));
        }
        return;
    }

    // Show detailed intents
    if (!intentIds.isEmpty()) {
        IntentDetailsCommand intentDetailsCmd = new IntentDetailsCommand();
        intentDetailsCmd.detailIntents(intentIds);
        return;
    }

    // Show brief intents
    if (intentsSummary || miniSummary) {
        Map<String, IntentSummary> summarized = summarize(intents);
        if (outputJson()) {
            ObjectNode summaries = mapper().createObjectNode();
            summarized.forEach((n, s) -> summaries.set(uncapitalize(n), s.json(mapper())));
            print("%s", summaries);
        } else if (miniSummary) {
            StringBuilder builder = new StringBuilder();
            builder.append(summarized.remove("All").miniSummary());
            summarized.values().forEach(s -> builder.append(s.miniSummary()));
            print("%s", builder.toString());
        } else {
            StringBuilder builder = new StringBuilder();
            builder.append(SUMMARY_TITLES);
            builder.append('\n').append(SEPARATOR);
            builder.append(summarized.remove("All").summary());
            summarized.values().forEach(s -> builder.append(s.summary()));
            print("%s", builder.toString());
        }
        return;
    }

    // JSON or default output
    if (outputJson()) {
        print("%s", json(intents));
    } else {
        for (Intent intent : intents) {
            IntentState state = service.getIntentState(intent.key());
            StringBuilder intentFormat = fullFormat(intent, state);
            StringBuilder detailsIntentFormat = detailsFormat(intent, state);
            String formatted = intentFormat.append(detailsIntentFormat).toString();
            if (contentFilter.filter(formatted)) {
                print("%s\n", formatted);
            }
        }
    }
}

From source file:org.obiba.mica.core.service.MailService.java

private synchronized void sendEmail(String subject, String templateName, Map<String, String> context,
        String recipient) {// w  ww .  jav a 2 s.  co  m
    try {
        RestTemplate template = newRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth());
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        StringBuilder form = new StringBuilder(Strings.isNullOrEmpty(recipient) ? "" : recipient + "&");
        form.append("subject=").append(encode(subject, "UTF-8")).append("&template=")
                .append(encode(templateName, "UTF-8"));
        context.forEach((k, v) -> {
            try {
                form.append("&").append(k).append("=").append(encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException ignored) {
            }
        });
        HttpEntity<String> entity = new HttpEntity<>(form.toString(), headers);

        ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity,
                String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Email sent via Agate");
        } else {
            log.error("Sending email via Agate failed with status: {}", response.getStatusCode());
        }
    } catch (Exception e) {
        log.error("Agate connection failure: {}", e.getMessage());
    }
}

From source file:org.nanoframework.core.component.scan.ComponentScan.java

/**
 * RequestMapping/*  w w w.j av  a 2 s.  co m*/
 * @param obj 
 * @param methods 
 * @param annotationClass RequestMapping
 * @param componentURI URI
 * @return 
 */
public static Map<String, Map<RequestMethod, RequestMapper>> filter(Object obj, Method[] methods,
        Class<? extends RequestMapping> annotationClass, String componentURI) {
    if (methods == null)
        return Collections.emptyMap();

    Map<String, Map<RequestMethod, RequestMapper>> methodMaps = new HashMap<>();
    for (Iterator<Map<String, Map<RequestMethod, RequestMapper>>> iter = Arrays.asList(methods).stream()
            .filter(method -> method.isAnnotationPresent(annotationClass)).filter(method -> {
                RequestMapping mapping = method.getAnnotation(annotationClass);
                if (mapping != null && !"".equals(mapping.value()))
                    return true;
                else {
                    LOGGER.debug("Unknown component mapper define: {}.{}:{}", obj.getClass().getName(),
                            method.getName(), (componentURI + mapping.value()));
                    return false;
                }
            }).map(method -> {
                Map<String, Map<RequestMethod, RequestMapper>> methodMap = new HashMap<>();
                RequestMapping mapping = method.getAnnotation(annotationClass);
                RequestMapper mapper = RequestMapper.create().setObject(obj).setClz(obj.getClass())
                        .setMethod(method).setRequestMethods(mapping.method());
                Map<RequestMethod, RequestMapper> mappers = new HashMap<>();
                final RequestMethod[] mths = mapper.getRequestMethods();
                for (RequestMethod _method : mths) {
                    mappers.put(_method, mapper);
                }

                methodMap.put((componentURI + mapping.value()).toLowerCase(), mappers);
                if (LOGGER.isDebugEnabled())
                    LOGGER.debug("URI Mapper: " + obj.getClass().getName() + '.' + method.getName() + ':'
                            + (componentURI + mapping.value()));

                return methodMap;
            }).iterator();iter.hasNext();) {
        Map<String, Map<RequestMethod, RequestMapper>> methodMap = iter.next();
        String uri = null;
        if (!CollectionUtils.isEmpty(methodMap)
                && methodMaps.containsKey(uri = methodMap.keySet().iterator().next())) {
            Set<RequestMethod> before = methodMap.get(uri).keySet();
            Set<RequestMethod> after = methodMaps.get(uri).keySet();
            if (!isIntersectionRequestMethod(before, after)) {
                methodMap.forEach((_uri, _methodMapper) -> {
                    Map<RequestMethod, RequestMapper> methodMapper;
                    if ((methodMapper = methodMaps.get(_uri)) == null) {
                        methodMaps.put(_uri, _methodMapper);
                    } else {
                        methodMapper.putAll(_methodMapper);
                        methodMaps.put(_uri, methodMapper);
                    }
                });
            } else
                throw new ComponentServiceRepeatException(uri);

        } else {
            methodMap.forEach((_uri, _methodMapper) -> {
                Map<RequestMethod, RequestMapper> methodMapper;
                if ((methodMapper = methodMaps.get(_uri)) == null) {
                    methodMaps.put(_uri, _methodMapper);
                } else {
                    methodMapper.putAll(_methodMapper);
                    methodMaps.put(_uri, methodMapper);
                }
            });
        }
    }

    return methodMaps;
}

From source file:net.di2e.ecdr.describe.generator.DescribeGeneratorImpl.java

protected void setTemporalCoverage(List<TimePeriodType> timeList, Map<String, TemporalCoverageHolder> timeMap) {
    timeMap.forEach((k, v) -> {
        TimePeriodType tp = new TimePeriodType();
        TemporalCoverageHolder tcHolder = (TemporalCoverageHolder) v;
        tp.setName(tcHolder.getLabel());
        tp.setStart(Arrays.asList(new String[] { df.format(tcHolder.getStartDate()) }));
        tp.setEnd(Arrays.asList(new String[] { df.format(tcHolder.getEndDate()) }));
        timeList.add(tp);/*from  w  w  w.  j  av a 2  s. c o  m*/
    });
}

From source file:com.thinkbiganalytics.metadata.modeshape.support.JcrPropertyUtil.java

/**
 * Sets the specified user-defined properties on the specified node.
 *
 * @param node       the target node//from w ww .ja v a  2  s .c  o  m
 * @param fields     the predefined user fields
 * @param properties the map of user-defined property names to values
 * @throws IllegalStateException       if a property name is encoded incorrectly
 * @throws MetadataRepositoryException if the metadata repository is unavailable
 */
public static void setUserProperties(@Nonnull final Node node, @Nonnull final Set<UserFieldDescriptor> fields,
        @Nonnull final Map<String, String> properties) {
    // Verify required properties are not empty
    for (final UserFieldDescriptor field : fields) {
        if (field.isRequired() && StringUtils.isEmpty(properties.get(field.getSystemName()))) {
            throw new MissingUserPropertyException("Missing required property: " + field.getSystemName());
        }
    }

    // Set properties on node
    final Set<String> newProperties = new HashSet<>(properties.size());
    final String prefix = JcrMetadataAccess.USR_PREFIX + ":";

    properties.forEach((key, value) -> {
        try {
            final String name = prefix + URLEncoder.encode(key, USER_PROPERTY_ENCODING);
            newProperties.add(name);
            node.setProperty(name, value);
        } catch (AccessDeniedException e) {
            log.debug("Access denied", e);
            throw new AccessControlException(e.getMessage());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(
                    "Failed to set user property \"" + key + "\" on node: " + node, e);
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e.toString(), e);
        }
    });

    // Get node properties
    final PropertyIterator iterator;
    try {
        iterator = node.getProperties();
    } catch (AccessDeniedException e) {
        log.debug("Access denied", e);
        throw new AccessControlException(e.getMessage());
    } catch (RepositoryException e) {
        throw new MetadataRepositoryException("Failed to get properties for node: " + node, e);
    }

    // Remove properties from node
    while (iterator.hasNext()) {
        final Property property = iterator.nextProperty();
        try {
            final String name = property.getName();
            if (name.startsWith(prefix) && !newProperties.contains(name)) {
                property.remove();
            }
        } catch (AccessDeniedException e) {
            log.debug("Access denied", e);
            throw new AccessControlException(e.getMessage());
        } catch (RepositoryException e) {
            throw new MetadataRepositoryException(
                    "Failed to remove property \"" + property + "\" on node: " + node, e);
        }
    }
}

From source file:com.hurence.logisland.service.elasticsearch.Elasticsearch_2_4_0_ClientService.java

@Override
public List<MultiGetResponseRecord> multiGet(List<MultiGetQueryRecord> multiGetQueryRecords) {
    List<MultiGetResponseRecord> multiGetResponseRecords = new ArrayList<>();
    if (multiGetQueryRecords.isEmpty()) {
        getLogger().debug("MultiGet query called with empty list");
        return multiGetResponseRecords;
    }/*from   w  ww .  ja v  a  2  s . c o  m*/

    MultiGetRequestBuilder multiGetRequestBuilder = esClient.prepareMultiGet();

    for (MultiGetQueryRecord multiGetQueryRecord : multiGetQueryRecords) {
        String index = multiGetQueryRecord.getIndexName();
        String type = multiGetQueryRecord.getTypeName();
        List<String> documentIds = multiGetQueryRecord.getDocumentIds();
        String[] fieldsToInclude = multiGetQueryRecord.getFieldsToInclude();
        String[] fieldsToExclude = multiGetQueryRecord.getFieldsToExclude();
        if ((fieldsToInclude != null && fieldsToInclude.length > 0)
                || (fieldsToExclude != null && fieldsToExclude.length > 0)) {
            for (String documentId : documentIds) {
                MultiGetRequest.Item item = new MultiGetRequest.Item(index, type, documentId);
                item.fetchSourceContext(new FetchSourceContext(fieldsToInclude, fieldsToExclude));
                multiGetRequestBuilder.add(item);
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug(
                            "MultiGet query adding item\n" + "index : {}\n" + "type : {}\n" + "id : {}\n"
                                    + "fields : {}\n" + "excludes : {}\n" + "includes : {}\n"
                                    + "fetchSource : {}\n" + "transformSource : {}",
                            new Object[] { item.index(), item.type(), item.id(), item.fields(),
                                    item.fetchSourceContext().excludes(), item.fetchSourceContext().includes(),
                                    item.fetchSourceContext().fetchSource(),
                                    item.fetchSourceContext().transformSource(), });
                }
            }
        } else {
            multiGetRequestBuilder.add(index, type, documentIds);
            if (getLogger().isDebugEnabled()) {
                getLogger().debug("MultiGet query adding item\n" + "index : {}\n" + "type : {}\n" + "ids : {}",
                        new Object[] { index, type, documentIds });
            }
        }
    }

    MultiGetResponse multiGetItemResponses = null;
    try {
        multiGetItemResponses = multiGetRequestBuilder.get();
    } catch (ActionRequestValidationException e) {
        getLogger().error("MultiGet query failed \n: message {}\n cause : {}",
                new Object[] { e.getMessage(), e.getCause() });
    }

    if (multiGetItemResponses != null) {
        for (MultiGetItemResponse itemResponse : multiGetItemResponses) {
            GetResponse response = itemResponse.getResponse();
            if (response != null && response.isExists()) {
                Map<String, Object> responseMap = response.getSourceAsMap();
                Map<String, String> retrievedFields = new HashMap<>();
                responseMap.forEach((k, v) -> {
                    if (v != null)
                        retrievedFields.put(k, v.toString());
                });
                multiGetResponseRecords.add(new MultiGetResponseRecord(response.getIndex(), response.getType(),
                        response.getId(), retrievedFields));
            }
        }
    }

    return multiGetResponseRecords;
}

From source file:ddf.catalog.definition.impl.DefinitionParser.java

private void undoAttributeValidators(Map<String, Set<AttributeValidator>> attributeValidators) {
    attributeValidators.forEach((attributeName, validatorsToRemove) -> {
        Set<AttributeValidator> currentValidators = attributeValidatorRegistry.getValidators(attributeName);
        Set<AttributeValidator> resultingValidators = Sets.difference(currentValidators, validatorsToRemove);
        attributeValidatorRegistry.deregisterValidators(attributeName);

        if (!resultingValidators.isEmpty()) {
            attributeValidatorRegistry.registerValidators(attributeName, resultingValidators);
        }//from w w  w .ja  v a 2s.  c om
    });
}

From source file:org.springframework.messaging.handler.invocation.reactive.AbstractMethodMessageHandler.java

/**
 * Detect if the given handler has any methods that can handle messages and if
 * so register it with the extracted mapping information.
 * <p><strong>Note:</strong> This method is protected and can be invoked by
 * sub-classes, but this should be done on startup only as documented in
 * {@link #registerHandlerMethod}.//from  w w  w .j ava  2  s  . c  o  m
 * @param handler the handler to check, either an instance of a Spring bean name
 */
protected final void detectHandlerMethods(Object handler) {
    Class<?> handlerType;
    if (handler instanceof String) {
        ApplicationContext context = getApplicationContext();
        Assert.state(context != null, "ApplicationContext is required for resolving handler bean names");
        handlerType = context.getType((String) handler);
    } else {
        handlerType = handler.getClass();
    }
    if (handlerType != null) {
        final Class<?> userType = ClassUtils.getUserClass(handlerType);
        Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
                (MethodIntrospector.MetadataLookup<T>) method -> getMappingForMethod(method, userType));
        if (logger.isDebugEnabled()) {
            logger.debug(formatMappings(userType, methods));
        }
        methods.forEach((key, value) -> registerHandlerMethod(handler, key, value));
    }
}