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

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

Introduction

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

Prototype

Set<K> keySet();

Source Link

Document

Returns a view collection of all distinct keys contained in this multimap.

Usage

From source file:com.google.gapid.views.Formatter.java

/**
 * @return empty list if not a constant, single value for constants, more values, for bitfileds.
 *///from w  w  w .jav a2 s  .c o  m
public static Collection<Constant> findConstant(SnippetObject obj, Primitive type) {
    final ConstantSet constants = ConstantSet.lookup(type);
    if (constants == null || constants.getEntries().length == 0) {
        return Collections.emptyList();
    }

    // first, try and find exact match
    List<Constant> byValue = constants.getByValue(obj.getObject());
    if (byValue != null && byValue.size() != 0) {
        if (byValue.size() == 1) {
            // perfect, we have just 1 match
            return byValue;
        }
        // try and find the best match
        Labels labels = Labels.fromSnippets(obj.getSnippets());
        Constant result = disambiguate(byValue, labels);
        return result == null ? Collections.emptyList() : ImmutableList.of(result);
    }

    // we can not find any exact match,
    // but for a number, maybe we can find a combination of constants that match (bit flags)
    Object value = obj.getObject();
    if (!(value instanceof Number) || value instanceof Double || value instanceof Float) {
        return Collections.emptyList();
    }

    long valueNumber = ((Number) value).longValue();
    long leftToFind = valueNumber;
    Multimap<Number, Constant> resultMap = ArrayListMultimap.create();

    for (Constant constant : constants.getEntries()) {
        long constantValue = ((Number) constant.getValue()).longValue();
        if (Long.bitCount(constantValue) == 1 && (valueNumber & constantValue) != 0) {
            resultMap.put(constantValue, constant);
            leftToFind &= ~constantValue; // remove bit
        }
    }

    // we did not find enough flags to cover this constant
    if (leftToFind != 0) {
        return Collections.emptyList();
    }

    // we found exactly 1 of each constant to cover the whole value
    if (resultMap.keySet().size() == resultMap.size()) {
        return resultMap.values();
    }

    // we have more than 1 matching constant per flag to we need to disambiguate
    Labels labels = Labels.fromSnippets(obj.getSnippets());
    for (Number key : resultMap.keySet()) {
        Collection<Constant> flagConstants = resultMap.get(key);
        if (flagConstants.size() == 1) {
            // perfect, we only have 1 value for this
            continue;
        }

        Constant con = disambiguate(flagConstants, labels);
        if (con != null) {
            // we have several values, but we found 1 to use
            resultMap.replaceValues(key, ImmutableList.of(con));
        } else {
            // we have several values and we don't know what one to use
            return Collections.emptyList();
        }
    }
    // assert all constants are disambiguated now
    assert resultMap.keySet().size() == resultMap.size();
    return resultMap.values();
}

From source file:com.b2international.snowowl.datastore.index.BaseCDOChangeProcessor.java

private final void updateDocuments(ICDOCommitChangeSet commitChangeSet, RevisionSearcher index)
        throws IOException {
    log.info("Processing changes...");
    final ImmutableIndexCommitChangeSet.Builder indexCommitChangeSet = ImmutableIndexCommitChangeSet.builder();

    for (final CodeSystem newCodeSystem : newCodeSystems) {
        final CodeSystemEntry entry = CodeSystemEntry.builder(newCodeSystem).build();
        indexCommitChangeSet.putRawMappings(Long.toString(entry.getStorageKey()), entry);
        indexCommitChangeSet.putNewComponents(
                ComponentIdentifier.of(CodeSystemEntry.TERMINOLOGY_COMPONENT_ID, entry.getShortName()));
    }//from  w ww .  jav  a 2s . c  o  m

    for (final CodeSystemVersion newCodeSystemVersion : newCodeSystemVersions) {
        final CodeSystemVersionEntry entry = CodeSystemVersionEntry.builder(newCodeSystemVersion).build();
        indexCommitChangeSet.putRawMappings(Long.toString(entry.getStorageKey()), entry);
        indexCommitChangeSet.putNewComponents(
                ComponentIdentifier.of(CodeSystemVersionEntry.TERMINOLOGY_COMPONENT_ID, entry.getVersionId()));
    }

    for (final CodeSystem dirtyCodeSystem : dirtyCodeSystems) {
        final CodeSystemEntry entry = CodeSystemEntry.builder(dirtyCodeSystem).build();
        indexCommitChangeSet.putRawMappings(Long.toString(entry.getStorageKey()), entry);
        indexCommitChangeSet.putChangedComponents(
                ComponentIdentifier.of(CodeSystemEntry.TERMINOLOGY_COMPONENT_ID, entry.getShortName()));
    }

    for (final CodeSystemVersion dirtyCodeSystemVersion : dirtyCodeSystemVersions) {
        final CodeSystemVersionEntry entry = CodeSystemVersionEntry.builder(dirtyCodeSystemVersion).build();
        indexCommitChangeSet.putRawMappings(Long.toString(entry.getStorageKey()), entry);
        indexCommitChangeSet.putChangedComponents(
                ComponentIdentifier.of(CodeSystemVersionEntry.TERMINOLOGY_COMPONENT_ID, entry.getVersionId()));
    }

    // apply code system and version deletions
    List<String> detachedCodeSystemDocIds = LongToStringFunction.copyOf(detachedCodeSystemIds);
    indexCommitChangeSet.putRawDeletions(CodeSystemEntry.class, detachedCodeSystemDocIds);
    detachedCodeSystemDocIds.stream().map(
            componentId -> ComponentIdentifier.of(CodeSystemVersionEntry.TERMINOLOGY_COMPONENT_ID, componentId))
            .forEach(indexCommitChangeSet::putDeletedComponents);

    List<String> detachedCodeSystemVersionDocIds = LongToStringFunction.copyOf(detachedCodeSystemVersionIds);
    indexCommitChangeSet.putRawDeletions(CodeSystemVersionEntry.class, detachedCodeSystemVersionDocIds);
    detachedCodeSystemDocIds.stream().map(
            componentId -> ComponentIdentifier.of(CodeSystemVersionEntry.TERMINOLOGY_COMPONENT_ID, componentId))
            .forEach(indexCommitChangeSet::putDeletedComponents);

    preUpdateDocuments(commitChangeSet, index);

    for (ChangeSetProcessor processor : getChangeSetProcessors()) {
        log.trace("Collecting {}...", processor.description());
        processor.process(commitChangeSet, index);
        // register additions, deletions from the sub processor
        indexCommitChangeSet.putRevisionMappings(processor.getNewMappings());
        for (RevisionDocument revision : Iterables.filter(processor.getNewMappings().values(),
                RevisionDocument.class)) {
            indexCommitChangeSet.putNewComponents(getComponentIdentifier(revision));
        }
        indexCommitChangeSet.putRevisionMappings(processor.getChangedMappings());
        for (RevisionDocument revision : Iterables.filter(processor.getChangedMappings().values(),
                RevisionDocument.class)) {
            indexCommitChangeSet.putChangedComponents(getComponentIdentifier(revision));
        }

        final Multimap<Class<? extends Revision>, Long> deletions = processor.getDeletions();
        indexCommitChangeSet.putRevisionDeletions(deletions);
        for (Class<? extends Revision> type : deletions.keySet()) {
            for (RevisionDocument revision : Iterables.filter(index.get(type, deletions.get(type)),
                    RevisionDocument.class)) {
                indexCommitChangeSet.putDeletedComponents(getComponentIdentifier(revision));
            }
        }
    }

    indexChangeSet = indexCommitChangeSet.build();
    postUpdateDocuments(indexChangeSet);
    log.info("Processing changes successfully finished.");
}

From source file:com.github.jsdossier.RenderTaskExecutor.java

/**
 * Submits tasks to render documentation for the given types.
 *
 * @param types the types to generate documentation for.
 * @return a self reference.//w ww  . j  av a  2  s.  co m
 */
public RenderTaskExecutor renderDocumentation(Iterable<NominalType> types) {
    // First, group all types by output paths, forced to lower case strings.
    // Any types with a collision must be rendered together to ensure no data mysteriously
    // disappears when running on a case insensitive file system (OSX is case-insensitive,
    // but case-preserving).
    Multimap<String, NominalType> normalizedPathToTypes = MultimapBuilder.hashKeys().arrayListValues().build();
    for (NominalType type : types) {
        String normalized = dfs.getPath(type).toAbsolutePath().normalize().toString().toLowerCase();
        normalizedPathToTypes.put(normalized, type);
    }

    for (String path : normalizedPathToTypes.keySet()) {
        RenderDocumentationTaskSupplier supplier = documentationTaskSupplierFactory
                .create(ImmutableList.copyOf(normalizedPathToTypes.get(path)));
        for (Callable<Path> task : supplier.get()) {
            submit(task);
        }
    }

    return this;
}

From source file:com.datatorrent.common.metric.MetricsAggregator.java

@Override
public Map<String, Object> aggregate(long windowId,
        Collection<AutoMetric.PhysicalMetricsContext> physicalMetrics) {
    Multimap<String, Object> metricValues = ArrayListMultimap.create();

    for (AutoMetric.PhysicalMetricsContext pmCtx : physicalMetrics) {
        for (Map.Entry<String, Object> entry : pmCtx.getMetrics().entrySet()) {
            metricValues.put(entry.getKey(), entry.getValue());
        }//from   w ww  .  j  a  va  2 s . c  o m
    }

    Map<String, Object> aggregates = Maps.newHashMap();
    for (String metric : metricValues.keySet()) {
        List<LogicalMetricMeta> logicalMetricMetas = metricLogicalAggregates.get(metric);
        if (logicalMetricMetas != null) {
            for (LogicalMetricMeta logicalMetricMeta : logicalMetricMetas) {

                Object aggregatedVal = logicalMetricMeta.aggregator.aggregate(metricValues.get(metric));
                aggregates.put(logicalMetricMeta.name, aggregatedVal);
            }
        }
    }
    return aggregates;
}

From source file:org.sonarlint.intellij.trigger.MakeTrigger.java

private void submitFiles(VirtualFile[] files, String trigger) {
    Multimap<Module, VirtualFile> filesByModule = HashMultimap.create();

    for (VirtualFile file : files) {
        Module m = ModuleUtil.findModuleForFile(file, myProject);
        if (!SonarLintUtils.shouldAnalyzeAutomatically(file, m)) {
            continue;
        }// w  w  w. j  a va 2  s .c  o  m

        filesByModule.put(m, file);
    }

    if (!filesByModule.isEmpty()) {
        console.debug("Trigger: " + trigger);

        for (Module m : filesByModule.keySet()) {
            analyzer.submitAsync(m, filesByModule.get(m), TriggerType.COMPILATION);
        }
    }
}

From source file:org.jetbrains.jet.lang.resolve.DeclarationResolver.java

private void checkRedeclarationsInNamespaces() {
    for (NamespaceDescriptorImpl descriptor : context.getNamespaceDescriptors().values()) {
        Multimap<Name, DeclarationDescriptor> simpleNameDescriptors = descriptor.getMemberScope()
                .getDeclaredDescriptorsAccessibleBySimpleName();
        for (Name name : simpleNameDescriptors.keySet()) {
            // Keep only properties with no receiver
            Collection<DeclarationDescriptor> descriptors = Collections2.filter(simpleNameDescriptors.get(name),
                    new Predicate<DeclarationDescriptor>() {
                        @Override
                        public boolean apply(@Nullable DeclarationDescriptor descriptor) {
                            if (descriptor instanceof PropertyDescriptor) {
                                PropertyDescriptor propertyDescriptor = (PropertyDescriptor) descriptor;
                                return !propertyDescriptor.getReceiverParameter().exists();
                            }// w w  w . ja va  2  s  .  c  om
                            return true;
                        }
                    });
            if (descriptors.size() > 1) {
                for (DeclarationDescriptor declarationDescriptor : descriptors) {
                    for (PsiElement declaration : getDeclarationsByDescriptor(declarationDescriptor)) {
                        assert declaration != null : "Null declaration for descriptor: " + declarationDescriptor
                                + " "
                                + (declarationDescriptor != null
                                        ? DescriptorRenderer.TEXT.render(declarationDescriptor)
                                        : "");
                        trace.report(REDECLARATION.on(declaration, declarationDescriptor.getName().getName()));
                    }
                }
            }
        }
    }
}

From source file:ibis.constellation.impl.TimerImpl.java

private <T> List<TimerImpl> groupBy(Function<TimerEvent, T> f) {
    Multimap<T, TimerEvent> index = Multimaps.index(events, f);
    ArrayList<TimerImpl> timers = new ArrayList<TimerImpl>();
    for (T t : index.keySet()) {
        TimerImpl timer = new TimerImpl(hostId);
        timer.events.addAll(index.get(t));
        // Collections.sort(timer.events);
        timers.add(timer);//  w  ww  .  ja  v  a 2 s . c om
    }
    return timers;
}

From source file:com.miz.service.TraktTvShowsSyncService.java

private void updateWatchedTvShows() {
    int count = mLocalWatched.size();
    if (count > 0) {
        ArrayList<TraktTvShow> watched = new ArrayList<TraktTvShow>();

        for (int i = 0; i < count; i++) {
            if (!mTraktWatched.containsKey(mLocalWatched.get(i).getId())) {
                // This show isn't in the Trakt library, so we'll add everything
                watched.add(mLocalWatched.get(i));
            } else {

                TraktTvShow traktTemp = mTraktWatched.get(mLocalWatched.get(i).getId());
                TraktTvShow temp = new TraktTvShow(mLocalWatched.get(i).getId(),
                        mLocalWatched.get(i).getTitle());

                // This show is in the Trakt library, so we'll have to check each episode in each season
                Multimap<String, String> seasonsMap = mLocalWatched.get(i).getSeasons();
                Set<String> seasons = seasonsMap.keySet();
                for (String season : seasons) {
                    Collection<String> episodes = seasonsMap.get(season);
                    for (String episode : episodes) {
                        if (!traktTemp.contains(MizLib.removeIndexZero(season),
                                MizLib.removeIndexZero(episode))) {
                            temp.addEpisode(MizLib.removeIndexZero(season), MizLib.removeIndexZero(episode));
                        }/*from w  ww .  j a v  a  2s.co m*/
                    }
                }

                if (temp.getSeasons().size() > 0)
                    watched.add(temp);
            }
        }

        count = watched.size();
        for (int i = 0; i < count; i++) {
            Trakt.markTvShowAsWatched(watched.get(i), getApplicationContext());
        }

        // Clean up
        watched.clear();
        watched = null;

        mTraktWatched.clear();
        mTraktWatched = null;
    }
}

From source file:com.miz.service.TraktTvShowsSyncService.java

private void updateTvShowCollection() {
    int count = mLocalCollection.size();
    if (count > 0) {
        ArrayList<TraktTvShow> collection = new ArrayList<TraktTvShow>();

        for (int i = 0; i < count; i++) {
            if (!mTraktCollection.containsKey(mLocalCollection.get(i).getId())) {
                // This show isn't in the Trakt library, so we'll add everything
                collection.add(mLocalCollection.get(i));
            } else {

                TraktTvShow traktTemp = mTraktCollection.get(mLocalCollection.get(i).getId());
                TraktTvShow temp = new TraktTvShow(mLocalCollection.get(i).getId(),
                        mLocalCollection.get(i).getTitle());

                // This show is in the Trakt library, so we'll have to check each episode in each season
                Multimap<String, String> seasonsMap = mLocalCollection.get(i).getSeasons();
                Set<String> seasons = seasonsMap.keySet();
                for (String season : seasons) {
                    Collection<String> episodes = seasonsMap.get(season);
                    for (String episode : episodes) {
                        if (!traktTemp.contains(MizLib.removeIndexZero(season),
                                MizLib.removeIndexZero(episode))) {
                            temp.addEpisode(season, episode);
                        }//from  w  w w  . j a  v  a 2s.c  o m
                    }
                }

                if (temp.getSeasons().size() > 0)
                    collection.add(temp);
            }
        }

        count = collection.size();
        for (int i = 0; i < count; i++) {
            Trakt.addTvShowToLibrary(collection.get(i), getApplicationContext());
        }

        // Clean up
        collection.clear();
        collection = null;

        mTraktCollection.clear();
        mTraktCollection = null;
    }
}

From source file:com.facebook.buck.parser.TargetSpecResolver.java

/**
 * @return a list of sets of build targets where each set contains all build targets that match a
 *     corresponding {@link TargetNodeSpec}.
 *///  w ww  .jav  a 2s . c o  m
public <T extends HasBuildTarget> ImmutableList<ImmutableSet<BuildTarget>> resolveTargetSpecs(Cell rootCell,
        Iterable<? extends TargetNodeSpec> specs, TargetConfiguration targetConfiguration,
        FlavorEnhancer<T> flavorEnhancer, TargetNodeProviderForSpecResolver<T> targetNodeProvider,
        TargetNodeFilterForSpecResolver<T> targetNodeFilter)
        throws BuildFileParseException, InterruptedException {

    // Convert the input spec iterable into a list so we have a fixed ordering, which we'll rely on
    // when returning results.
    ImmutableList<TargetNodeSpec> orderedSpecs = ImmutableList.copyOf(specs);

    Multimap<Path, Integer> perBuildFileSpecs = groupSpecsByBuildFile(rootCell, orderedSpecs);

    // Kick off parse futures for each build file.
    ArrayList<ListenableFuture<Map.Entry<Integer, ImmutableSet<BuildTarget>>>> targetFutures = new ArrayList<>();
    for (Path buildFile : perBuildFileSpecs.keySet()) {
        Collection<Integer> buildFileSpecs = perBuildFileSpecs.get(buildFile);
        TargetNodeSpec firstSpec = orderedSpecs.get(Iterables.get(buildFileSpecs, 0));
        Cell cell = rootCell.getCell(firstSpec.getBuildFileSpec().getCellPath());

        // Format a proper error message for non-existent build files.
        if (!cell.getFilesystem().isFile(buildFile)) {
            throw new MissingBuildFileException(firstSpec.toString(),
                    cell.getFilesystem().getRootPath().relativize(buildFile));
        }

        for (int index : buildFileSpecs) {
            TargetNodeSpec spec = orderedSpecs.get(index);
            handleTargetNodeSpec(flavorEnhancer, targetNodeProvider, targetNodeFilter, targetFutures, cell,
                    buildFile, targetConfiguration, index, spec);
        }
    }

    return collectTargets(orderedSpecs.size(), targetFutures);
}