Example usage for java.util.stream Collectors toMap

List of usage examples for java.util.stream Collectors toMap

Introduction

In this page you can find the example usage for java.util.stream Collectors toMap.

Prototype

public static <T, K, U> Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
        Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction) 

Source Link

Document

Returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

Usage

From source file:com.yahoo.bard.webservice.web.filters.QueryParameterNormalizationFilter.java

/**
 * Build a parameter map that searches for @QueryParam annotations on the jersey endpoints
 * and extract their names./*  w w  w . ja  v a  2 s.co m*/
 * This map enables us to perform case insensitive translations.
 *
 * Detail:
 *   This method extracts all classes contained within the packages specified as "jersey provider packages."
 *   It then conditions these methods by enumerating all methods and keeping only those that are annotated
 *   as JAX-RS endpoints (+ the bard @PATCH annotation). After harvesting this list of method, it then enumerates
 *   all of the parameters for each method and keeps a list of the @QueryParam values. It then extracts the values
 *   from these @QueryParam annotations to retain its codified casing while also constructing a map of lowercase'd
 *   values to map in a case insensitive way.
 *
 * NOTE: The ClassLoader provided with the ResourceConfig is used to find classes.
 *
 * @param providers Set of provider classes to seek for @QueryParam
 * @param classLoader Class loader to use while searching for specified packages
 * @return  Parameter map containing all of the case insensitive to case sensitive @QueryParam values
 */
private static Map<String, String> buildParameterMap(Set<Class<?>> providers, ClassLoader classLoader) {
    if (providers == null) {
        LOG.warn("No providers defined. Disabling QueryParameterNormalizationFilter.");
        return Collections.emptyMap();
    } else if (classLoader == null) {
        LOG.warn("No valid ClassLoader found from context. Disabling QueryParameterNormalizationFilter.");
        return Collections.emptyMap();
    }
    return providers.stream()
            // Extract all of the corresponding methods from these classes
            .flatMap(QueryParameterNormalizationFilter::extractMethods)
            // Determine which methods are annotated as a JAX-RS endpoint
            .filter(QueryParameterNormalizationFilter::isWebEndpoint)
            // For each of these methods, extract the @QueryParam annotations from the parameter list
            .flatMap(QueryParameterNormalizationFilter::extractQueryParameters)
            // Extract the parameter value
            .map(QueryParam::value).distinct()
            // Map the lower-case'd parameter value to its @QueryParam case'd counterpart
            .collect(Collectors.toMap(param -> param.toLowerCase(Locale.ENGLISH), Function.identity(),
                    QueryParameterNormalizationFilter::resolveMapConflicts));
}

From source file:org.fcrepo.apix.jena.impl.JenaServiceRegistry.java

@Override
public void update() {

    // For all resources in the registry, get the URIs of everything that calls itself a Service, or is explicitly
    // registered as a service

    final Set<URI> serviceURIs = Stream.concat(super.list().stream().map(this::get).map(Util::parse)
            .flatMap(m -> m.listSubjectsWithProperty(m.getProperty(RDF_TYPE), m.getResource(CLASS_SERVICE))
                    .mapWith(Resource::getURI).toSet().stream().map(URI::create)),
            objectResourcesOf(null, PROP_CONTAINS_SERVICE, parse(this.get(registryContainer))).stream())
            .collect(Collectors.toSet());

    // Map canonical URI to service resource. If multiple service resources
    // indicate the same canonical URI, pick one arbitrarily.
    final Map<URI, URI> canonical = serviceURIs.stream().flatMap(this::attemptLookupService)
            .collect(Collectors.toMap(s -> s.canonicalURI(), s -> s.uri(), (a, b) -> a));

    canonicalUriMap.putAll(canonical);/*from  ww  w  . j  ava  2  s  .c o m*/

    canonicalUriMap.keySet().removeIf(k -> !canonical.containsKey(k));
}

From source file:org.obiba.mica.search.csvexport.SpecificStudyReportGenerator.java

private Map<String, Locale> getCountries() {
    return Arrays.stream(Locale.getAvailableLocales()).collect(Collectors.toMap(locale -> {
        try {/*from   w w w . j  ava 2  s .c  o m*/
            return locale.getISO3Country();
        } catch (RuntimeException e) {
            return locale.getCountry();
        }
    }, Function.identity(), (a, b) -> a));
}

From source file:com.netflix.spinnaker.clouddriver.google.controllers.GoogleNamedImageLookupController.java

private static Map<String, String> extractTagFilters(HttpServletRequest httpServletRequest) {
    List<String> parameterNames = Collections.list(httpServletRequest.getParameterNames());

    return parameterNames.stream().filter(Objects::nonNull)
            .filter(parameter -> parameter.toLowerCase().startsWith("tag:"))
            .collect(Collectors.toMap(tagParameter -> tagParameter.replaceAll("tag:", "").toLowerCase(),
                    httpServletRequest::getParameter, (a, b) -> b));
}

From source file:ddf.catalog.history.Historian.java

/**
 * Versions updated {@link Metacard}s and {@link ContentItem}s.
 *
 * @param streamUpdateRequest Needed to pass {@link
 *     ddf.catalog.core.versioning.MetacardVersion#SKIP_VERSIONING} flag into downstream update
 * @param updateStorageResponse Versions this response's updated items
 * @return the update response originally passed in
 * @throws UnsupportedQueryException// w  ww  .j a va 2 s.  c  o m
 * @throws SourceUnavailableException
 * @throws IngestException
 */
public UpdateStorageResponse version(UpdateStorageRequest streamUpdateRequest,
        UpdateStorageResponse updateStorageResponse, UpdateResponse updateResponse)
        throws UnsupportedQueryException, SourceUnavailableException, IngestException {
    if (doSkip(updateStorageResponse)) {
        return updateStorageResponse;
    }
    setSkipFlag(streamUpdateRequest);
    setSkipFlag(updateStorageResponse);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning updated metacards and content: {}", updateStorageResponse);
    }

    List<Metacard> updatedMetacards = updateStorageResponse.getUpdatedContentItems().stream()
            .filter(ci -> StringUtils.isBlank(ci.getQualifier())).map(ContentItem::getMetacard)
            .filter(Objects::nonNull).filter(isNotVersionNorDeleted).collect(Collectors.toList());

    if (updatedMetacards.isEmpty()) {
        LOGGER.trace("No updated metacards applicable to versioning");
        SecurityLogger.audit("Skipping versioning updated metacards with ids: {}",
                updateStorageResponse.getUpdatedContentItems().stream().map(ContentItem::getMetacard)
                        .filter(Objects::nonNull).map(Metacard::getId).collect(TO_A_STRING));
        return updateStorageResponse;
    }

    Map<String, Metacard> originalMetacards = updateResponse.getUpdatedMetacards().stream()
            .map(Update::getOldMetacard)
            .collect(Collectors.toMap(Metacard::getId, Function.identity(), Historian::firstInWinsMerge));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Found current data for the following metacards: {}", getList(originalMetacards));
    }

    Collection<ReadStorageRequest> ids = getReadStorageRequests(updatedMetacards);
    Map<String, List<ContentItem>> content = getContent(ids);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Found resources for the following metacards: {}", getList(content));
    }

    Function<String, Action> getAction = id -> content.containsKey(id) ? Action.VERSIONED_CONTENT
            : Action.VERSIONED;

    Map<String, Metacard> versionMetacards = getVersionMetacards(originalMetacards.values(), getAction,
            (Subject) updateResponse.getProperties().get(SecurityConstants.SECURITY_SUBJECT));

    CreateStorageResponse createStorageResponse = versionContentItems(content, versionMetacards);

    if (createStorageResponse == null) {
        String message = "Could not version content items for: " + getList(originalMetacards);
        SecurityLogger.audit(message);
        LOGGER.debug(message);
        return updateStorageResponse;
    }

    setResourceUriForContent(/*mutable*/ versionMetacards, createStorageResponse);

    CreateResponse createResponse = storeVersionMetacards(versionMetacards);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created metacard versions under ids: {}",
                createResponse.getCreatedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    return updateStorageResponse;
}

From source file:ddf.security.SubjectUtils.java

/**
 * Retrieves the security attributes for the given subject.
 *
 * @param subject the Subject to check/*  www  . ja  v  a2 s  .  c  o m*/
 * @return Map of attributes with the collected values for each
 */
public static Map<String, SortedSet<String>> getSubjectAttributes(Subject subject) {
    if (subject == null) {
        return Collections.emptyMap();
    }

    return subject.getPrincipals().byType(SecurityAssertion.class).stream()
            .map(SecurityAssertion::getAttributeStatements).flatMap(Collection::stream)
            .map(AttributeStatement::getAttributes).flatMap(Collection::stream)
            .collect(Collectors.toMap(Attribute::getName, SubjectUtils::getAttributeValues, (acc, val) -> {
                acc.addAll(val);
                return acc;
            }));
}

From source file:ddf.catalog.history.Historian.java

/**
 * Versions deleted {@link Metacard}s./*ww w  .j  a va 2  s.  co  m*/
 *
 * @param deleteResponse Versions this responses deleted metacards
 */
public DeleteResponse version(DeleteResponse deleteResponse)
        throws SourceUnavailableException, IngestException {
    if (doSkip(deleteResponse)) {
        return deleteResponse;
    }
    setSkipFlag(deleteResponse);

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning Deleted Metacards {}", deleteResponse);
    }

    List<Metacard> originalMetacards = deleteResponse.getDeletedMetacards().stream()
            .filter(isNotVersionNorDeleted).collect(Collectors.toList());

    if (originalMetacards.isEmpty()) {
        LOGGER.trace("No deleted metacards applicable to versioning");
        SecurityLogger.audit("Skipping versioning deleted metacards with ids: {}",
                deleteResponse.getDeletedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
        return deleteResponse;
    }

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Versioning following deleted metacards: {}",
                originalMetacards.stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    // [OriginalMetacardId: Original Metacard]
    Map<String, Metacard> originalMetacardsMap = originalMetacards.stream()
            .collect(Collectors.toMap(Metacard::getId, Function.identity(), Historian::firstInWinsMerge));

    // [ContentItem.getId: content items]
    Map<String, List<ContentItem>> contentItems = getContent(getReadStorageRequests(originalMetacards));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Got content under the following ID's: {}",
                contentItems.keySet().stream().collect(TO_A_STRING));
    }

    Function<String, Action> getAction = id -> contentItems.containsKey(id) ? Action.DELETED_CONTENT
            : Action.DELETED;
    // VERSION_OF_ID is equivalent to the Original Metacard ID
    // [MetacardVersion.VERSION_OF_ID: versioned metacard]
    Map<String, Metacard> versionedMap = getVersionMetacards(originalMetacards, getAction,
            (Subject) deleteResponse.getRequest().getProperties().get(SecurityConstants.SECURITY_SUBJECT));

    if (LOGGER.isDebugEnabled() && !versionedMap.keySet().equals(originalMetacardsMap.keySet())) {
        LOGGER.debug("There is not a one to one mapping between original metacards and their versions!"
                + " (Some metacards may not have been versioned or too many versions may have been created). "
                + "More information regarding the IDs is available by setting log level to trace "
                + "(log:set trace ddf.catalog.history)");
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Original Metacards: {}",
                    originalMetacards.stream().map(Metacard::getId).collect(TO_A_STRING));
            LOGGER.trace("Version Metacards: {}", versionedMap.keySet().stream().collect(TO_A_STRING));
        }
    }

    CreateStorageResponse createStorageResponse = versionContentItems(contentItems, versionedMap);
    if (createStorageResponse != null) {
        setResourceUriForContent(/*Mutable*/ versionedMap, createStorageResponse);
        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Successfully stored content under ids: {}",
                    createStorageResponse.getCreatedContentItems());
        }
    }

    executeAsSystem(
            () -> catalogProvider().create(new CreateRequestImpl(new ArrayList<>(versionedMap.values()))));
    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created versioned metacards under ids: {}",
                versionedMap.values().stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    String userid = subjectIdentity.getUniqueIdentifier(
            (Subject) deleteResponse.getProperties().get(SecurityConstants.SECURITY_SUBJECT));
    List<Metacard> deletionMetacards = versionedMap
            .entrySet().stream().map(s -> new DeletedMetacardImpl(uuidGenerator.generateUuid(), s.getKey(),
                    userid, s.getValue().getId(), originalMetacardsMap.get(s.getKey())))
            .collect(Collectors.toList());

    CreateResponse deletionMetacardsCreateResponse = executeAsSystem(
            () -> catalogProvider().create(new CreateRequestImpl(deletionMetacards, new HashMap<>())));

    if (LOGGER.isTraceEnabled()) {
        LOGGER.trace("Successfully created deletion metacards under ids: {}", deletionMetacardsCreateResponse
                .getCreatedMetacards().stream().map(Metacard::getId).collect(TO_A_STRING));
    }

    return deleteResponse;
}

From source file:com.thinkbiganalytics.metadata.jobrepo.nifi.provenance.NifiStatsJmsReceiver.java

/**
 * Save the running totals for the feed/*from  w ww  .  java2  s . c  o  m*/
 */
private Map<String, JpaNifiFeedStats> saveFeedStats(AggregatedFeedProcessorStatisticsHolderV2 holder,
        List<NifiFeedProcessorStats> summaryStats) {
    Map<String, JpaNifiFeedStats> feedStatsMap = new HashMap<>();

    if (summaryStats != null) {
        Map<String, Long> feedLatestTimestamp = summaryStats.stream().collect(Collectors.toMap(
                NifiFeedProcessorStats::getFeedName, stats -> stats.getMinEventTime().getMillis(), Long::max));
        feedLatestTimestamp.entrySet().stream().forEach(e -> {
            String feedName = e.getKey();
            Long timestamp = e.getValue();
            JpaNifiFeedStats stats = feedStatsMap.computeIfAbsent(feedName,
                    name -> new JpaNifiFeedStats(feedName));
            stats.setLastActivityTimestamp(timestamp);
        });
    }
    if (holder.getProcessorIdRunningFlows() != null) {
        holder.getProcessorIdRunningFlows().entrySet().stream().forEach(e -> {
            String feedProcessorId = e.getKey();
            Long runningCount = e.getValue();
            String feedName = provenanceEventFeedUtil.getFeedName(feedProcessorId); //ensure not null
            if (StringUtils.isNotBlank(feedName)) {
                JpaNifiFeedStats stats = feedStatsMap.computeIfAbsent(feedName,
                        name -> new JpaNifiFeedStats(feedName));
                OpsManagerFeed opsManagerFeed = provenanceEventFeedUtil.getFeed(feedName);
                if (opsManagerFeed != null) {
                    stats.setFeedId(new JpaNifiFeedStats.OpsManagerFeedId(opsManagerFeed.getId().toString()));
                }
                stats.addRunningFeedFlows(runningCount);
                stats.setTime(DateTime.now().getMillis());
            }
        });
    }
    //group stats to save together by feed name
    if (!feedStatsMap.isEmpty()) {
        nifiFeedStatisticsProvider.saveLatestFeedStats(new ArrayList<>(feedStatsMap.values()));
    }
    return feedStatsMap;
}

From source file:nu.yona.server.analysis.service.ActivityService.java

private Map<ZonedDateTime, Set<DayActivityDto>> getDayActivitiesForUserAnonymizedIdsInInterval(
        Set<UUID> userAnonymizedIds, Set<UUID> relevantActivityCategoryIds, Interval interval,
        Set<IntervalInactivityDto> mia) {
    return userAnonymizedIds.stream()
            .map(id -> getDayActivitiesForCategories(userAnonymizedService.getUserAnonymized(id),
                    relevantActivityCategoryIds, interval, mia))
            .map(Map::entrySet).flatMap(Collection::stream)
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {
                Set<DayActivityDto> allActivities = new HashSet<>(a);
                allActivities.addAll(b);
                return allActivities;
            }));/*from   w  w  w  .  j  a  v  a  2s . co m*/
}

From source file:com.prepaird.objectgraphdb.ObjectGraphDb.java

private <RET> RET updateEdgeRelations(RET r, Map<Method, AnnotationFieldValueWrapper> savedRelations,
        boolean onDelete) {
    //in order to keep our pojo synched with the latest db version we first update all relations
    //then reload the pojo and then attach all new related objects
    savedRelations.entrySet().stream().forEach(e -> {
        try {//from   w  ww .  java  2 s. c  o m
            Field f = e.getValue().field;
            Object value = e.getValue().value;
            if (e.getValue().relation instanceof OEdgeRelation) {
                OEdgeRelation relation = (OEdgeRelation) e.getValue().relation;
                //First of all, get the existing edges for this field
                Map<String, EdgeVertexPair> oldRelations = getExistingEdgesAndVertices(r, f, relation).stream()
                        .collect(Collectors.toMap(o -> Utils.getRecordId(o.getVertex()), o -> o, (o1, o2) -> {
                            throw new OGDBException(100,
                                    "conflict, ids: " + Utils.getRecordId(o1.getVertex()) + ", "
                                            + Utils.getRecordId(o1.getEdge()) + " .. "
                                            + o2.getVertex().getClass().getSimpleName() + ", " + f.getName()
                                            + ", " + value.getClass().getSimpleName());
                        })), newRelations = new HashMap<>(oldRelations.size());
                Object setParam;
                if (relation.readOnly() || relation.accumulator() != OEdgeRelation.AccumulatorType.OBJECT) {
                    //don't do any updates whatsoever...
                    setParam = value;
                    //TODO maybe set to oldRealtions.values() instead?
                    newRelations = oldRelations;
                } else {
                    if (value == null) {
                        //no edge should be created.
                        //possible edges should be deleted though, but that will be taken care of below
                        setParam = null;
                    } else if (value instanceof Iterable) {
                        //create edges for every object and remove object which should be cascaded away
                        //save object
                        Collection coll = getCollection(f, relation);
                        Iterable iterable = (Iterable) value;
                        Iterator itt = iterable.iterator();
                        while (itt.hasNext()) {

                            coll.add(saveRelatedVertex(r, itt.next(), relation, oldRelations, newRelations));
                        }
                        //sort if necessary
                        sortCollectionIfNecessary(coll, relation);
                        setParam = coll;
                    } else {
                        setParam = saveRelatedVertex(r, value, relation, oldRelations, newRelations);
                    }
                }
                deleteOldVerticesAndEdges(r, relation, newRelations, oldRelations);
                e.getValue().value = setParam;
            } else { //OGRelation
                OGRelation rel = (OGRelation) e.getValue().relation;
                OGBinder ogb = (OGBinder) rel.binder().newInstance();
                Object setParam;
                if (onDelete) {
                    setParam = ogb.onDelete(this, getRecordByUserObject(r, false), value);
                } else {
                    setParam = ogb.onSave(this, getRecordByUserObject(r, false), value);
                }
                e.getKey().invoke(r, setParam);
                e.getValue().value = setParam;
            }
        } catch (RuntimeException ex) {
            Log.error(ex);
            throw ex;
        } catch (Exception ex) {
            Log.error(ex);
        }
    });
    //reload pojo from db
    RET ret = reloadNonRecursive(r);
    //set values
    setValues(ret, savedRelations);
    return ret;
}