Example usage for com.google.common.collect Maps filterValues

List of usage examples for com.google.common.collect Maps filterValues

Introduction

In this page you can find the example usage for com.google.common.collect Maps filterValues.

Prototype

@CheckReturnValue
public static <K, V> BiMap<K, V> filterValues(BiMap<K, V> unfiltered,
        final Predicate<? super V> valuePredicate) 

Source Link

Document

Returns a bimap containing the mappings in unfiltered whose values satisfy a predicate.

Usage

From source file:com.google.devtools.build.skyframe.SimpleCycleDetector.java

/**
 * The algorithm for this cycle detector is as follows. We visit the graph depth-first, keeping
 * track of the path we are currently on. We skip any DONE nodes (they are transitively
 * error-free). If we come to a node already on the path, we immediately construct a cycle. If we
 * are in the noKeepGoing case, we return ErrorInfo with that cycle to the caller. Otherwise, we
 * continue. Once all of a node's children are done, we construct an error value for it, based on
 * those children. Finally, when the original root's node is constructed, we return its ErrorInfo.
 *//*w w  w .j av a 2  s  .  c  o m*/
private static ErrorInfo checkForCycles(SkyKey root, ParallelEvaluatorContext evaluatorContext)
        throws InterruptedException {
    // The number of cycles found. Do not keep on searching for more cycles after this many were
    // found.
    int cyclesFound = 0;
    // The path through the graph currently being visited.
    List<SkyKey> graphPath = new ArrayList<>();
    // Set of nodes on the path, to avoid expensive searches through the path for cycles.
    Set<SkyKey> pathSet = new HashSet<>();

    // Maintain a stack explicitly instead of recursion to avoid stack overflows
    // on extreme graphs (with long dependency chains).
    Deque<SkyKey> toVisit = new ArrayDeque<>();

    toVisit.push(root);

    // The procedure for this check is as follows: we visit a node, push it onto the graph path,
    // push a marker value onto the toVisit stack, and then push all of its children onto the
    // toVisit stack. Thus, when the marker node comes to the top of the toVisit stack, we have
    // visited the downward transitive closure of the value. At that point, all of its children must
    // be finished, and so we can build the definitive error info for the node, popping it off the
    // graph path.
    while (!toVisit.isEmpty()) {
        SkyKey key = toVisit.pop();

        NodeEntry entry;
        if (key == CHILDREN_FINISHED) {
            // We have reached the marker node - that means all children of a node have been visited.
            // Since all nodes have errors, we must have found errors in the children at this point.
            key = graphPath.remove(graphPath.size() - 1);
            entry = Preconditions
                    .checkNotNull(evaluatorContext.getGraph().get(null, Reason.CYCLE_CHECKING, key), key);
            pathSet.remove(key);
            // Skip this node if it was first/last node of a cycle, and so has already been processed.
            if (entry.isDone()) {
                continue;
            }
            if (!evaluatorContext.keepGoing()) {
                // in the --nokeep_going mode, we would have already returned if we'd found a cycle below
                // this node. We haven't, so there are no cycles below this node; skip further evaluation
                continue;
            }
            Set<SkyKey> removedDeps = ImmutableSet.of();
            if (cyclesFound < MAX_CYCLES) {
                // Value must be ready, because all of its children have finished, so we can build its
                // error.
                Preconditions.checkState(entry.isReady(), "%s not ready. ValueEntry: %s", key, entry);
            } else if (!entry.isReady()) {
                removedDeps = removeIncompleteChildrenForCycle(key, entry,
                        Iterables.concat(entry.getTemporaryDirectDeps()), evaluatorContext);
            }
            maybeMarkRebuilding(entry);
            GroupedList<SkyKey> directDeps = entry.getTemporaryDirectDeps();
            // Find out which children have errors. Similar logic to that in Evaluate#run().
            List<ErrorInfo> errorDeps = getChildrenErrorsForCycle(key, Iterables.concat(directDeps),
                    evaluatorContext);
            Preconditions.checkState(!errorDeps.isEmpty(),
                    "Node %s was not successfully evaluated, but had no child errors. NodeEntry: %s", key,
                    entry);
            SkyFunctionEnvironment env = new SkyFunctionEnvironment(key, directDeps,
                    Sets.difference(entry.getAllRemainingDirtyDirectDeps(), removedDeps), evaluatorContext);
            env.setError(entry, ErrorInfo.fromChildErrors(key, errorDeps), /*isDirectlyTransient=*/ false);
            env.commit(entry, EnqueueParentBehavior.SIGNAL);
        } else {
            entry = evaluatorContext.getGraph().get(null, Reason.CYCLE_CHECKING, key);
        }

        Preconditions.checkNotNull(entry, key);
        // Nothing to be done for this node if it already has an entry.
        if (entry.isDone()) {
            continue;
        }
        if (cyclesFound == MAX_CYCLES) {
            // Do not keep on searching for cycles indefinitely, to avoid excessive runtime/OOMs.
            continue;
        }

        if (pathSet.contains(key)) {
            int cycleStart = graphPath.indexOf(key);
            // Found a cycle!
            cyclesFound++;
            Iterable<SkyKey> cycle = graphPath.subList(cycleStart, graphPath.size());
            logger.info("Found cycle : " + cycle + " from " + graphPath);
            // Put this node into a consistent state for building if it is dirty.
            if (entry.isDirty() && entry.getDirtyState() == NodeEntry.DirtyState.CHECK_DEPENDENCIES) {
                // In the check deps state, entry has exactly one child not done yet. Note that this node
                // must be part of the path to the cycle we have found (since done nodes cannot be in
                // cycles, and this is the only missing one). Thus, it will not be removed below in
                // removeDescendantsOfCycleValue, so it is safe here to signal that it is done.
                entry.signalDep();
                maybeMarkRebuilding(entry);
            }
            if (evaluatorContext.keepGoing()) {
                // Any children of this node that we haven't already visited are not worth visiting,
                // since this node is about to be done. Thus, the only child worth visiting is the one in
                // this cycle, the cycleChild (which may == key if this cycle is a self-edge).
                SkyKey cycleChild = selectCycleChild(key, graphPath, cycleStart);
                Set<SkyKey> removedDeps = removeDescendantsOfCycleValue(key, entry, cycleChild, toVisit,
                        graphPath.size() - cycleStart, evaluatorContext);
                ValueWithMetadata dummyValue = ValueWithMetadata.wrapWithMetadata(new SkyValue() {
                });

                SkyFunctionEnvironment env = new SkyFunctionEnvironment(key, entry.getTemporaryDirectDeps(),
                        ImmutableMap.of(cycleChild, dummyValue),
                        Sets.difference(entry.getAllRemainingDirtyDirectDeps(), removedDeps), evaluatorContext);

                // Construct error info for this node. Get errors from children, which are all done
                // except possibly for the cycleChild.
                List<ErrorInfo> allErrors = getChildrenErrorsForCycleChecking(
                        Iterables.concat(entry.getTemporaryDirectDeps()), /*unfinishedChild=*/ cycleChild,
                        evaluatorContext);
                CycleInfo cycleInfo = new CycleInfo(cycle);
                // Add in this cycle.
                allErrors.add(ErrorInfo.fromCycle(cycleInfo));
                env.setError(entry, ErrorInfo.fromChildErrors(key, allErrors), /*isTransient=*/ false);
                env.commit(entry, EnqueueParentBehavior.SIGNAL);
                continue;
            } else {
                // We need to return right away in the noKeepGoing case, so construct the cycle (with the
                // path) and return.
                Preconditions.checkState(graphPath.get(0).equals(root),
                        "%s not reached from %s. ValueEntry: %s", key, root, entry);
                return ErrorInfo.fromCycle(new CycleInfo(graphPath.subList(0, cycleStart), cycle));
            }
        }

        // This node is not yet known to be in a cycle. So process its children.
        Iterable<SkyKey> children = Iterables.concat(entry.getTemporaryDirectDeps());
        if (Iterables.isEmpty(children)) {
            continue;
        }
        // Prefetch all children, in case our graph performs better with a primed cache. No need to
        // recurse into done nodes. The fields of done nodes aren't necessary, since we'll filter them
        // out.
        // TODO(janakr): If graph implementations start using these hints for not-done nodes, we may
        // have to change this.
        Map<SkyKey, ? extends NodeEntry> childrenNodes = evaluatorContext.getGraph().getBatch(key,
                Reason.EXISTENCE_CHECKING, children);
        Preconditions.checkState(childrenNodes.size() == Iterables.size(children), childrenNodes);
        children = Maps.filterValues(childrenNodes, new Predicate<NodeEntry>() {
            @Override
            public boolean apply(NodeEntry nodeEntry) {
                return !nodeEntry.isDone();
            }
        }).keySet();

        // This marker flag will tell us when all this node's children have been processed.
        toVisit.push(CHILDREN_FINISHED);
        // This node is now part of the path through the graph.
        graphPath.add(key);
        pathSet.add(key);
        for (SkyKey nextValue : children) {
            toVisit.push(nextValue);
        }
    }
    return evaluatorContext.keepGoing() ? getAndCheckDoneForCycle(root, evaluatorContext).getErrorInfo() : null;
}

From source file:com.gnapse.common.math.Factorization.java

/**
 * A map view of this factorization, containing only those factors with positive exponents.
 *
 * <p>If one interprets a factorization as a fraction, the numerator consists of those factors
 * that have a positive exponent.</p>
 *///w w w. j a  v  a2s  .c  om
private Map<T, Integer> numeratorEntries() {
    if (numerator == null) {
        numerator = Maps.filterValues(factors, new Predicate<Integer>() {
            @Override
            public boolean apply(Integer exponent) {
                return exponent.intValue() > 0;
            }
        });
    }
    return numerator;
}

From source file:org.jfrog.teamcity.agent.util.ArtifactoryClientConfigurationBuilder.java

private static void gatherBuildInfoParams(Map<String, String> allParamMap,
        ArtifactoryClientConfiguration.PublisherHandler configuration, final String propPrefix,
        final String... propTypes) {
    Map<String, String> filteredProperties = Maps.filterKeys(allParamMap, new Predicate<String>() {
        public boolean apply(String key) {
            if (StringUtils.isNotBlank(key)) {
                if (key.startsWith(propPrefix)) {
                    return true;
                }/*  w  ww. j  a  v a2s  . c om*/
                for (String propType : propTypes) {
                    if (key.startsWith(propType + propPrefix)) {
                        return true;
                    }
                }
            }
            return false;
        }
    });
    filteredProperties = Maps.filterValues(filteredProperties, new Predicate<String>() {
        public boolean apply(String value) {
            return StringUtils.isNotBlank(value);
        }
    });

    for (Map.Entry<String, String> entryToAdd : filteredProperties.entrySet()) {
        String key = entryToAdd.getKey();
        for (String propType : propTypes) {
            key = StringUtils.remove(key, propType);
        }
        key = StringUtils.remove(key, propPrefix);
        configuration.addMatrixParam(key, entryToAdd.getValue());
    }
}

From source file:ninja.leaping.permissionsex.backend.memory.MemoryOptionSubjectData.java

@Override
public Map<Set<Entry<String, String>>, List<Entry<String, String>>> getAllParents() {
    return Maps.filterValues(
            Maps.transformValues(contexts, new Function<DataEntry, List<Map.Entry<String, String>>>() {
                @Nullable/*from   w  w w  .  j  av  a2s. c o  m*/
                @Override
                public List<Map.Entry<String, String>> apply(@Nullable DataEntry dataEntry) {
                    return dataEntry == null ? null
                            : dataEntry.parents == null ? null
                                    : Lists.transform(dataEntry.parents, PARENT_TRANSFORM_FUNC);
                }
            }), Predicates.notNull());
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.impl.DifferenceFilterManager.java

/**
 * Store value in preferences.//from   w ww.j a va2 s .  c  o m
 * 
 * @param currentValue
 *            Value to store.
 * @param defaultConf
 *            Default value.
 */
private void storeInPreferences(Set<? extends IDifferenceFilter> currentValue,
        Set<? extends IDifferenceFilter> defaultConf, String prefKey) {
    if (currentValue != null && !currentValue.equals(defaultConf)) {
        Map<String, IDifferenceFilter> toStore = Maps.filterValues(Maps.transformValues(map, TO_FILTER),
                Predicates.in(currentValue));
        String preferenceValue = Joiner.on(ItemUtil.PREFERENCE_DELIMITER).join(toStore.keySet());
        preferenceStore.put(prefKey, preferenceValue);
    } else {
        preferenceStore.remove(prefKey);
    }
}

From source file:com.gnapse.common.math.Factorization.java

/**
 * A map view of this factorization, containing only those factors with negative exponents.
 *
 * <p>If one interprets a factorization as a fraction, the denominator consists of those factors
 * that have a negative exponent.</p>
 *///  w  w w.  j a va 2  s .  c  om
private Map<T, Integer> denominatorEntries() {
    if (denominator == null) {
        denominator = Maps.filterValues(factors, new Predicate<Integer>() {
            @Override
            public boolean apply(Integer exponent) {
                return exponent.intValue() < 0;
            }
        });
    }
    return denominator;
}

From source file:com.puppycrawl.tools.checkstyle.AbstractModuleTestSupport.java

/**
 * Performs verification of the given files.
 * @param checker {@link Checker} instance
 * @param processedFiles files to process.
 * @param expectedViolations a map of expected violations per files.
 * @throws Exception if exception occurs during verification process.
 */// ww w . j a v a2 s .c  o  m
protected final void verify(Checker checker, File[] processedFiles,
        Map<String, List<String>> expectedViolations) throws Exception {
    stream.flush();
    final List<File> theFiles = new ArrayList<>();
    Collections.addAll(theFiles, processedFiles);
    final int errs = checker.process(theFiles);

    // process each of the lines
    final Map<String, List<String>> actualViolations = getActualViolations(errs);
    final Map<String, List<String>> realExpectedViolations = Maps.filterValues(expectedViolations,
            input -> !input.isEmpty());
    final MapDifference<String, List<String>> violationDifferences = Maps.difference(realExpectedViolations,
            actualViolations);

    final Map<String, List<String>> missingViolations = violationDifferences.entriesOnlyOnLeft();
    final Map<String, List<String>> unexpectedViolations = violationDifferences.entriesOnlyOnRight();
    final Map<String, MapDifference.ValueDifference<List<String>>> differingViolations = violationDifferences
            .entriesDiffering();

    final StringBuilder message = new StringBuilder(256);
    if (!missingViolations.isEmpty()) {
        message.append("missing violations: ").append(missingViolations);
    }
    if (!unexpectedViolations.isEmpty()) {
        if (message.length() > 0) {
            message.append('\n');
        }
        message.append("unexpected violations: ").append(unexpectedViolations);
    }
    if (!differingViolations.isEmpty()) {
        if (message.length() > 0) {
            message.append('\n');
        }
        message.append("differing violations: ").append(differingViolations);
    }

    assertTrue(message.toString(),
            missingViolations.isEmpty() && unexpectedViolations.isEmpty() && differingViolations.isEmpty());

    checker.destroy();
}

From source file:com.b2international.snowowl.snomed.datastore.id.cis.CisSnomedIdentifierService.java

@Override
public void release(final Set<String> componentIds) {
    LOGGER.debug("Releasing {} component IDs.", componentIds.size());

    final Map<String, SctId> sctIds = getSctIds(componentIds);
    final Map<String, SctId> problemSctIds = ImmutableMap.copyOf(Maps.filterValues(sctIds,
            Predicates.<SctId>not(Predicates.or(SctId::isAssigned, SctId::isReserved, SctId::isAvailable))));

    if (!problemSctIds.isEmpty()) {
        throw new SctIdStatusException(
                "Cannot release %s component IDs because they are not assigned, reserved, or already available.",
                problemSctIds);/*w  w w  . j  a v  a 2 s .  c om*/
    }

    final Map<String, SctId> assignedOrReservedSctIds = ImmutableMap
            .copyOf(Maps.filterValues(sctIds, Predicates.or(SctId::isAssigned, SctId::isReserved)));

    if (assignedOrReservedSctIds.isEmpty()) {
        return;
    }

    HttpPut releaseRequest = null;
    String currentNamespace = null;

    try {

        if (assignedOrReservedSctIds.size() > 1) {
            final Multimap<String, String> componentIdsByNamespace = toNamespaceMultimap(
                    assignedOrReservedSctIds.keySet());
            for (final Entry<String, Collection<String>> entry : componentIdsByNamespace.asMap().entrySet()) {
                currentNamespace = entry.getKey();

                for (final Collection<String> bulkIds : Iterables.partition(entry.getValue(), BULK_LIMIT)) {
                    LOGGER.debug(String.format("Sending bulk release request for namespace %s with size %d.",
                            currentNamespace, bulkIds.size()));
                    releaseRequest = httpPut(String.format("sct/bulk/release?token=%s", getToken()),
                            createBulkReleaseData(currentNamespace, bulkIds));
                    execute(releaseRequest);
                }
            }

        } else {

            final String componentId = Iterables.getOnlyElement(assignedOrReservedSctIds.keySet());
            currentNamespace = SnomedIdentifiers.getNamespace(componentId);
            releaseRequest = httpPut(String.format("sct/release?token=%s", getToken()),
                    createReleaseData(componentId));
            execute(releaseRequest);
        }

    } catch (IOException e) {
        throw new SnowowlRuntimeException(
                String.format("Exception while releasing IDs for namespace %s.", currentNamespace), e);
    } finally {
        release(releaseRequest);
    }
}

From source file:org.eclipse.sirius.ui.business.internal.viewpoint.ViewpointSelectionDialog.java

/**
 * Get missing dependencies from the current selection
 * /* w w  w  . j ava  2  s  .com*/
 * @return missing dependencies
 */
private Map<String, Collection<String>> getMissingDependencies() {
    Set<Viewpoint> selected = Maps.filterValues(selection, Predicates.equalTo(Boolean.TRUE)).keySet();

    Multimap<String, String> result = HashMultimap.create();
    for (Viewpoint viewpoint : selected) {
        for (RepresentationExtensionDescription extension : new ViewpointQuery(viewpoint)
                .getAllRepresentationExtensionDescriptions()) {
            String extended = extension.getViewpointURI();
            final Pattern pattern = Pattern.compile(extended);

            // Is there at least one available selected viewpoint URI ?
            if (!Iterables.any(selected, new Predicate<Viewpoint>() {
                @Override
                public boolean apply(Viewpoint vp) {
                    Option<URI> uri = new ViewpointQuery(vp).getViewpointURI();
                    if (uri.some()) {
                        Matcher matcher = pattern.matcher(uri.get().toString());
                        return matcher.matches();
                    } else {
                        return false;
                    }
                }
            })) {
                result.put(viewpoint.getName(), extended.trim().replaceFirst("^viewpoint:/[^/]+/", "")); //$NON-NLS-1$ //$NON-NLS-2$
            }
        }
    }
    return result.asMap();
}

From source file:com.b2international.snowowl.snomed.datastore.request.DescriptionRequestHelper.java

private static <T> Map<String, SnomedDescription> extractBest(
        Multimap<String, SnomedDescription> descriptionsByConceptId, List<T> orderedValues,
        Function<SnomedDescription, T> predicateFactory) {

    Map<String, SnomedDescription> uniqueMap = Maps.transformValues(descriptionsByConceptId.asMap(),
            new ExtractBestFunction<T>(orderedValues, predicateFactory));
    return ImmutableMap.copyOf(Maps.filterValues(uniqueMap, Predicates.notNull()));
}