Example usage for com.google.common.collect Multimap values

List of usage examples for com.google.common.collect Multimap values

Introduction

In this page you can find the example usage for com.google.common.collect Multimap values.

Prototype

Collection<V> values();

Source Link

Document

Returns a view collection containing the value from each key-value pair contained in this multimap, without collapsing duplicates (so values().size() == size() ).

Usage

From source file:org.eclipse.xtext.builder.standalone.incremental.ResourceURICollector.java

protected Set<URI> collectResources(final Iterable<URI> roots, final Set<String> fileExtensions) {
    Iterable<String> _plus = Iterables.<String>concat(fileExtensions,
            Collections.<String>unmodifiableList(CollectionLiterals.<String>newArrayList("java")));
    final Set<String> extensions = IterableExtensions.<String>toSet(_plus);
    PathTraverser _pathTraverser = new PathTraverser();
    final Function1<URI, String> _function = (URI it) -> {
        return it.toFileString();
    };/*from  w w  w  .  jav  a  2 s  .  c o m*/
    Iterable<String> _map = IterableExtensions.<URI, String>map(roots, _function);
    List<String> _list = IterableExtensions.<String>toList(_map);
    final Predicate<URI> _function_1 = (URI it) -> {
        String _fileExtension = it.fileExtension();
        return extensions.contains(_fileExtension);
    };
    final Multimap<String, URI> modelsFound = _pathTraverser.resolvePathes(_list, _function_1);
    Map<String, Collection<URI>> _asMap = modelsFound.asMap();
    final BiConsumer<String, Collection<URI>> _function_2 = (String path, Collection<URI> resource) -> {
        final File file = new File(path);
        if ((((resource != null) && (!file.isDirectory())) && file.getName().endsWith(".jar"))) {
            this.registerBundle(file);
        }
    };
    _asMap.forEach(_function_2);
    Collection<URI> _values = modelsFound.values();
    return IterableExtensions.<URI>toSet(_values);
}

From source file:com.facebook.buck.java.JavaSymbolFinder.java

/**
 * Figure out the build targets that provide a set of Java symbols.
 * @param symbols The set of symbols (e.g. "com.example.foo.Bar") to find defining targets for.
 *                This is taken as a collection, rather than as an individual string, because
 *                instantiating a ProjectBuildFileParser is expensive (it spawns a Python
 *                subprocess), and we don't want to encourage the caller to do it more than once.
 * @return A multimap of symbols to the targets that define them, of the form:
 *         {"com.example.a.A": set("//com/example/a:a", "//com/another/a:a")}
 *///from  w w  w  .j av a  2 s.com
public ImmutableSetMultimap<String, BuildTarget> findTargetsForSymbols(Set<String> symbols)
        throws InterruptedException {
    // TODO(jacko): Handle files that aren't included in any rule.

    // First find all the source roots in the current project.
    Collection<Path> srcRoots;
    try {
        srcRoots = srcRootsFinder.getAllSrcRootPaths(config.getSrcRoots());
    } catch (IOException e) {
        buckEventBus.post(ThrowableConsoleEvent.create(e, "Error while searching for source roots."));
        return ImmutableSetMultimap.of();
    }

    // Now collect all the code files that define our symbols.
    Multimap<String, Path> symbolsToSourceFiles = HashMultimap.create();
    for (String symbol : symbols) {
        symbolsToSourceFiles.putAll(symbol, getDefiningPaths(symbol, srcRoots));
    }

    // Now find all the targets that define all those code files. We do this in one pass because we
    // don't want to instantiate a new parser subprocess for every symbol.
    Set<Path> allSourceFilePaths = ImmutableSet.copyOf(symbolsToSourceFiles.values());
    Multimap<Path, BuildTarget> sourceFilesToTargets = getTargetsForSourceFiles(allSourceFilePaths);

    // Now build the map from from symbols to build targets.
    ImmutableSetMultimap.Builder<String, BuildTarget> symbolsToTargets = ImmutableSetMultimap.builder();
    for (String symbol : symbolsToSourceFiles.keySet()) {
        for (Path sourceFile : symbolsToSourceFiles.get(symbol)) {
            symbolsToTargets.putAll(symbol, sourceFilesToTargets.get(sourceFile));
        }
    }

    return symbolsToTargets.build();
}

From source file:com.facebook.buck.jvm.java.JavaSymbolFinder.java

/**
 * Figure out the build targets that provide a set of Java symbols.
 * @param symbols The set of symbols (e.g. "com.example.foo.Bar") to find defining targets for.
 *                This is taken as a collection, rather than as an individual string, because
 *                instantiating a ProjectBuildFileParser is expensive (it spawns a Python
 *                subprocess), and we don't want to encourage the caller to do it more than once.
 * @return A multimap of symbols to the targets that define them, of the form:
 *         {"com.example.a.A": set("//com/example/a:a", "//com/another/a:a")}
 *///from   w w w  .  jav a 2  s.  c  om
public ImmutableSetMultimap<String, BuildTarget> findTargetsForSymbols(Set<String> symbols)
        throws InterruptedException, IOException {
    // TODO(oconnor663): Handle files that aren't included in any rule.

    // First find all the source roots in the current project.
    Collection<Path> srcRoots;
    try {
        srcRoots = srcRootsFinder.getAllSrcRootPaths(config.getView(JavaBuckConfig.class).getSrcRoots());
    } catch (IOException e) {
        buckEventBus.post(ThrowableConsoleEvent.create(e, "Error while searching for source roots."));
        return ImmutableSetMultimap.of();
    }

    // Now collect all the code files that define our symbols.
    Multimap<String, Path> symbolsToSourceFiles = HashMultimap.create();
    for (String symbol : symbols) {
        symbolsToSourceFiles.putAll(symbol, getDefiningPaths(symbol, srcRoots));
    }

    // Now find all the targets that define all those code files. We do this in one pass because we
    // don't want to instantiate a new parser subprocess for every symbol.
    Set<Path> allSourceFilePaths = ImmutableSet.copyOf(symbolsToSourceFiles.values());
    Multimap<Path, BuildTarget> sourceFilesToTargets = getTargetsForSourceFiles(allSourceFilePaths);

    // Now build the map from from symbols to build targets.
    ImmutableSetMultimap.Builder<String, BuildTarget> symbolsToTargets = ImmutableSetMultimap.builder();
    for (String symbol : symbolsToSourceFiles.keySet()) {
        for (Path sourceFile : symbolsToSourceFiles.get(symbol)) {
            symbolsToTargets.putAll(symbol, sourceFilesToTargets.get(sourceFile));
        }
    }

    return symbolsToTargets.build();
}

From source file:com.ikanow.infinit.e.harvest.extraction.document.HarvestStatus_Integrated.java

/**
 * getLogMessages/*from   ww  w . j  ava2s  .  c  om*/
 * Returns a list of up to 5 errors (eg encountered when parsing JavaScript) for 
 * a source, sorted by frequency in ascending order
 * @return
 */
private StringBuffer getLogMessages(boolean bReset) {
    if ((null != _messages) && (_messages.size() > 0)) {
        StringBuffer messagesString = new StringBuffer();

        // Create multimap to store errors in, reverse the order of key (error message) and
        // value (count) to sort on error count
        Multimap<Integer, String> mm = TreeMultimap.create();
        for (java.util.Map.Entry<String, Integer> entry : _messages.entrySet()) {
            StringBuffer msg = new StringBuffer(entry.getKey()).append(" (Occurences: ")
                    .append(entry.getValue()).append(')');
            mm.put(-entry.getValue(), msg.toString());
        }

        // Write the error messages to a Collection<String>
        Collection<String> messages = mm.values();

        // Append up to the top five messages to our StringBuffer and return
        int messageCount = 1;
        for (String s : messages) {
            if (messageCount > 1) {
                messagesString.append('\n');
            }
            messagesString.append(s);
            messageCount++;
            if (messageCount > 5)
                break;
        }
        if (bReset) {
            _messages.clear();
        }
        return messagesString;
    } else {
        return null;
    }
}

From source file:pt.ist.maidSyncher.domain.activeCollab.ACMilestone.java

private SyncActionWrapper<GHMilestone> syncUpdateEvent(final SyncEvent syncEvent) {
    final Set<String> tickedDescriptors = new HashSet<>();
    boolean auxChangedName = false;
    boolean auxChangedDueOn = false;
    boolean auxChangedBody = false;

    for (String changedDescriptor : syncEvent.getChangedPropertyDescriptorNames().getUnmodifiableList()) {
        tickedDescriptors.add(changedDescriptor);
        switch (changedDescriptor) {
        case DSC_PERMALINK:
        case DSC_ID:
        case DSC_URL:
        case DSC_PRIORITY:
        case DSC_ASSIGNEEID:
        case DSC_PROJECTID:
            //non code related things to complete
            //only non relevant descriptors above
            break;
        case DSC_BODY:
            //we should update the bpdy
            auxChangedBody = true;// w  w  w.  j ava 2  s .com
            break;
        case DSC_DUEON:
            auxChangedDueOn = true;
            //the due date as well
            break;
        case DSC_NAME:
            //and the name
            auxChangedName = true;
            break;
        default:
            tickedDescriptors.remove(changedDescriptor); //if we did not fall on any of the above
            //cases, let's remove it from the ticked descriptors

        }
    }

    final boolean changedName = auxChangedName;
    final boolean changedBody = auxChangedBody;
    final boolean changedDueOn = auxChangedDueOn;

    return new SyncActionWrapper<GHMilestone>() {

        @Override
        public Set<SynchableObject> sync() throws SyncActionError {
            Multimap<GHRepository, Milestone> milestonesToEdit = null;
            Set<SynchableObject> ghMilestonesChanged = new HashSet<>();

            if (changedName) {
                milestonesToEdit = getNewPrefilledGHMilestonesToEdit(milestonesToEdit);
                //let's make sure we edit all of its names
                for (Milestone milestone : milestonesToEdit.values()) {
                    milestone.setTitle(getName());
                }

            }
            if (changedBody) {
                milestonesToEdit = getNewPrefilledGHMilestonesToEdit(milestonesToEdit);
                //let's make sure we edit all of its bodies
                for (Milestone milestone : milestonesToEdit.values()) {
                    milestone.setDescription(getBody());
                }

            }
            if (changedDueOn) {
                milestonesToEdit = getNewPrefilledGHMilestonesToEdit(milestonesToEdit);
                //let's make sure we edit all of its due on
                for (Milestone milestone : milestonesToEdit.values()) {
                    milestone.setDueOn(getDueOn().toDate());
                }

            }
            if (milestonesToEdit != null) {
                MilestoneService milestoneService = new MilestoneService(MaidRoot.getGitHubClient());
                try {
                    for (GHRepository ghRepository : milestonesToEdit.keySet()) {
                        for (Milestone milestone : milestonesToEdit.get(ghRepository)) {
                            ghMilestonesChanged.add(GHMilestone
                                    .process(milestoneService.editMilestone(ghRepository, milestone), true));

                        }
                    }
                } catch (IOException exception) {
                    throw new SyncActionError(exception, ghMilestonesChanged);
                }
            }

            return ghMilestonesChanged;
        }

        @Override
        public SyncEvent getOriginatingSyncEvent() {
            return syncEvent;
        }

        @Override
        public Collection<DSIObject> getSyncDependedDSIObjects() {
            return Collections.emptyList();
        }

        @Override
        public Set<Class> getSyncDependedTypesOfDSIObjects() {
            Set<Class> classesDependedOn = new HashSet<>();
            classesDependedOn.add(GHRepository.class);
            return classesDependedOn;
        }

        @Override
        public Collection<String> getPropertyDescriptorNamesTicked() {
            return tickedDescriptors;
        }
    };

}

From source file:ai.grakn.graql.internal.query.QueryAnswer.java

@Override
public Answer unify(Unifier unifier) {
    if (unifier.isEmpty())
        return this;
    Answer unified = new QueryAnswer();
    Multimap<Var, Concept> answerMultimap = HashMultimap.create();

    this.entrySet().forEach(e -> {
        Var var = e.getKey();
        Collection<Var> uvars = unifier.get(var);
        if (uvars.isEmpty()) {
            answerMultimap.put(var, e.getValue());
        } else {/*from w w w.  j a  v  a2  s  .  co  m*/
            uvars.forEach(uv -> answerMultimap.put(uv, e.getValue()));
        }
    });
    //non-ambiguous mapping
    if (answerMultimap.keySet().size() == answerMultimap.values().size()) {
        answerMultimap.entries().forEach(e -> unified.put(e.getKey(), e.getValue()));
    }

    return unified.setExplanation(this.getExplanation());
}

From source file:com.google.devtools.build.lib.query2.RdepsUnboundedVisitor.java

@Override
protected Visit getVisitResult(Iterable<DepAndRdep> depAndRdeps) throws InterruptedException {
    Collection<SkyKey> validRdeps = new ArrayList<>();

    // Multimap of dep to all the reverse deps in this visitation. Used to filter out the
    // disallowed deps.
    Multimap<SkyKey, SkyKey> reverseDepMultimap = ArrayListMultimap.create();
    for (DepAndRdep depAndRdep : depAndRdeps) {
        // The "roots" of our visitation (see #preprocessInitialVisit) have a null 'dep' field.
        if (depAndRdep.dep == null) {
            validRdeps.add(depAndRdep.rdep);
        } else {/*  w  w  w .  jav  a2s . co  m*/
            reverseDepMultimap.put(depAndRdep.dep, depAndRdep.rdep);
        }
    }

    Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = env
            .makePackageKeyToTargetKeyMap(Iterables.concat(reverseDepMultimap.values()));
    Set<PackageIdentifier> pkgIdsNeededForTargetification = packageKeyToTargetKeyMap.keySet().stream()
            .map(SkyQueryEnvironment.PACKAGE_SKYKEY_TO_PACKAGE_IDENTIFIER).collect(toImmutableSet());
    packageSemaphore.acquireAll(pkgIdsNeededForTargetification);

    try {
        // Filter out disallowed deps. We cannot defer the targetification any further as we do not
        // want to retrieve the rdeps of unwanted nodes (targets).
        if (!reverseDepMultimap.isEmpty()) {
            Collection<Target> filteredTargets = env.filterRawReverseDepsOfTransitiveTraversalKeys(
                    reverseDepMultimap.asMap(), packageKeyToTargetKeyMap);
            filteredTargets.stream().map(SkyQueryEnvironment.TARGET_TO_SKY_KEY).forEachOrdered(validRdeps::add);
        }
    } finally {
        packageSemaphore.releaseAll(pkgIdsNeededForTargetification);
    }

    ImmutableList<SkyKey> uniqueValidRdeps = validRdeps.stream().filter(validRdepUniquifier::unique)
            .collect(ImmutableList.toImmutableList());

    // Retrieve the reverse deps as SkyKeys and defer the targetification and filtering to next
    // recursive visitation.
    ImmutableList.Builder<DepAndRdep> depAndRdepsToVisitBuilder = ImmutableList.builder();
    env.graph
            .getReverseDeps(
                    uniqueValidRdeps)
            .entrySet()
            .forEach(reverseDepsEntry -> depAndRdepsToVisitBuilder.addAll(Iterables.transform(
                    Iterables.filter(reverseDepsEntry.getValue(),
                            Predicates.and(SkyQueryEnvironment.IS_TTV, universe)),
                    rdep -> new DepAndRdep(reverseDepsEntry.getKey(), rdep))));

    return new Visit(/*keysToUseForResult=*/ uniqueValidRdeps,
            /*keysToVisit=*/ depAndRdepsToVisitBuilder.build());
}

From source file:org.jboss.gwt.circuit.processor.StoreProcessor.java

private void validateDAG(final String graphVizFile) {
    boolean cyclesFound = false;
    for (Map.Entry<String, Multimap<String, String>> entry : dagValidation.entrySet()) {
        String actionType = entry.getKey();
        Multimap<String, String> dependencies = entry.getValue();
        debug("Check cyclic dependencies for action [%s]", actionType);
        DirectedGraph<String, DefaultEdge> dg = new DefaultDirectedGraph<>(DefaultEdge.class);

        // vertices
        for (String store : dependencies.keySet()) {
            dg.addVertex(store);/*from   www. j  a v a  2  s.  c  om*/
        }
        for (String store : dependencies.values()) {
            dg.addVertex(store);
        }

        // edges
        for (String store : dependencies.keySet()) {
            Collection<String> storeDependencies = dependencies.get(store);
            for (String storeDependency : storeDependencies) {
                dg.addEdge(store, storeDependency);
            }
        }

        // cycles?
        CycleDetector<String, DefaultEdge> detector = new CycleDetector<>(dg);
        List<String> cycles = new LinkedList<>(detector.findCycles());
        if (!cycles.isEmpty()) {
            cyclesFound = true;
            StringBuilder cycleInfo = new StringBuilder();
            for (String cycle : cycles) {
                cycleInfo.append(cycle).append(" -> ");
            }
            cycleInfo.append(cycles.get(0));
            error("Cyclic dependencies detected for action [%s]: %s. Please review [%s] for more details.",
                    actionType, cycleInfo, graphVizFile);
        }
        if (!cyclesFound) {
            debug("No cyclic dependencies found for action [%s]", actionType);
        }
    }
}

From source file:hu.bme.mit.trainbenchmark.benchmark.fourstore.driver.FourStoreDriver.java

private void insertEdgesWithVertexPartition(final Multimap<String, String> edges, final String edgeType,
        final String targetVertexType) throws IOException {
    final StringBuilder insertQueryBuilder = new StringBuilder(SPARQL_RDF_PREFIX);
    insertQueryBuilder.append("INSERT DATA {");
    edgesToTriples(edges, edgeType, insertQueryBuilder);
    for (final String targetVertex : edges.values()) {
        insertQueryBuilder// w w  w  .j  a v a 2 s .  co  m
                .append(String.format(". %s rdf:type %s", brackets(targetVertex), brackets(targetVertexType)));
    }
    insertQueryBuilder.append("}");

    // run the update
    runUpdate(insertQueryBuilder.toString());
}

From source file:com.google.errorprone.scanner.ScannerSupplier.java

/**
 * Applies options to this {@link ScannerSupplier}.
 *
 * <p>Command-line options to override check severities may do any of the following:
 * <ul>/*from www.  j  a v  a2  s  . c o m*/
 * <li>Enable a check that is currently off</li>
 * <li>Disable a check that is currently on</li>
 * <li>Change the severity of a check that is on, promoting a warning to an error or demoting
 * an error to a warning</li>
 * </ul>
 *
 * @param errorProneOptions an {@link ErrorProneOptions} object that encapsulates the overrides
 * for this compilation
 * @throws InvalidCommandLineOptionException if the override map attempts to disable a check
 * that may not be disabled
 */
@CheckReturnValue
public ScannerSupplier applyOverrides(ErrorProneOptions errorProneOptions)
        throws InvalidCommandLineOptionException {
    Map<String, Severity> severityOverrides = errorProneOptions.getSeverityMap();
    if (severityOverrides.isEmpty() && !errorProneOptions.isEnableAllChecks()
            && !errorProneOptions.isDropErrorsToWarnings()) {
        return this;
    }

    // Initialize result allChecks map and enabledChecks set with current state of this Supplier.
    ImmutableBiMap<String, BugCheckerInfo> checks = getAllChecks();
    Map<String, SeverityLevel> severities = new LinkedHashMap<>(severities());
    Set<String> disabled = new HashSet<>(disabled());

    // Create a map from names (canonical and alternate) to checks. We could do this when the
    // supplier is created, but applyOverrides() is unlikely to be called more than once per
    // scanner instance.
    Multimap<String, BugCheckerInfo> checksByAllNames = ArrayListMultimap.create();
    for (BugCheckerInfo checker : getAllChecks().values()) {
        for (String name : checker.allNames()) {
            checksByAllNames.put(name, checker);
        }
    }

    if (errorProneOptions.isEnableAllChecks()) {
        disabled.forEach(c -> severities.put(c, checks.get(c).defaultSeverity()));
        disabled.clear();
    }

    if (errorProneOptions.isDropErrorsToWarnings()) {
        checksByAllNames.values().stream()
                .filter(c -> c.defaultSeverity() == SeverityLevel.ERROR && c.suppressibility().disableable())
                .forEach(c -> severities.put(c.canonicalName(), SeverityLevel.WARNING));
    }

    // Process overrides
    severityOverrides.forEach((checkName, newSeverity) -> {
        Collection<BugCheckerInfo> checksWithName = checksByAllNames.get(checkName);
        if (checksWithName.isEmpty()) {
            if (errorProneOptions.ignoreUnknownChecks()) {
                return;
            }
            throw new InvalidCommandLineOptionException(checkName + " is not a valid checker name");
        }
        for (BugCheckerInfo check : checksWithName) {
            switch (newSeverity) {
            case OFF:
                if (!check.suppressibility().disableable()) {
                    throw new InvalidCommandLineOptionException(check.canonicalName() + " may not be disabled");
                }
                severities.remove(check.canonicalName());
                disabled.add(check.canonicalName());
                break;
            case DEFAULT:
                severities.put(check.canonicalName(), check.defaultSeverity());
                disabled.remove(check.canonicalName());
                break;
            case WARN:
                // Demoting an enabled check from an error to a warning is a form of disabling
                if (!disabled().contains(check.canonicalName()) && !check.suppressibility().disableable()
                        && check.defaultSeverity() == SeverityLevel.ERROR) {
                    throw new InvalidCommandLineOptionException(
                            check.canonicalName() + " is not disableable and may not be demoted to a warning");
                }
                severities.put(check.canonicalName(), SeverityLevel.WARNING);
                disabled.remove(check.canonicalName());
                break;
            case ERROR:
                severities.put(check.canonicalName(), SeverityLevel.ERROR);
                disabled.remove(check.canonicalName());
                break;
            default:
                throw new IllegalStateException("Unexpected severity level: " + newSeverity);
            }
        }
    });

    return new ScannerSupplierImpl(checks, ImmutableMap.copyOf(severities), ImmutableSet.copyOf(disabled));
}