Example usage for com.google.common.collect MultimapBuilder hashKeys

List of usage examples for com.google.common.collect MultimapBuilder hashKeys

Introduction

In this page you can find the example usage for com.google.common.collect MultimapBuilder hashKeys.

Prototype

public static MultimapBuilderWithKeys<Object> hashKeys() 

Source Link

Document

Uses a HashMap to map keys to value collections.

Usage

From source file:com.googlesource.gerrit.plugins.serverconfig.ServerConfigServlet.java

private void audit(String what, String path, String diff) {
    String sessionId = webSession.get().getSessionId();
    CurrentUser who = webSession.get().getUser();
    long when = TimeUtil.nowMs();
    ListMultimap<String, Object> params = MultimapBuilder.hashKeys().arrayListValues().build();
    params.put("plugin", pluginName);
    params.put("class", ServerConfigServlet.class);
    params.put("diff", diff);
    params.put("file", path);
    auditService.dispatch(new AuditEvent(sessionId, who, what, when, params, null));
}

From source file:com.google.gerrit.server.notedb.DraftCommentNotes.java

@Override
protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
    ObjectId rev = handle.id();//w  ww. ja  v a2s  .c om
    if (rev == null) {
        loadDefaults();
        return;
    }

    RevCommit tipCommit = handle.walk().parseCommit(rev);
    ObjectReader reader = handle.walk().getObjectReader();
    revisionNoteMap = RevisionNoteMap.parse(args.noteUtil, getChangeId(), reader,
            NoteMap.read(reader, tipCommit), PatchLineComment.Status.DRAFT);
    ListMultimap<RevId, Comment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
    for (ChangeRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
        for (Comment c : rn.getComments()) {
            cs.put(new RevId(c.revId), c);
        }
    }
    comments = ImmutableListMultimap.copyOf(cs);
}

From source file:com.google.gerrit.server.git.GroupCollector.java

private GroupCollector(ListMultimap<ObjectId, PatchSet.Id> patchSetsBySha, Lookup groupLookup) {
    this.patchSetsBySha = patchSetsBySha;
    this.groupLookup = groupLookup;
    groups = MultimapBuilder.hashKeys().arrayListValues().build();
    groupAliases = MultimapBuilder.hashKeys().hashSetValues().build();
}

From source file:com.google.gerrit.server.schema.Schema_108.java

private SetMultimap<Project.NameKey, Change.Id> getOpenChangesByProject(ReviewDb db, UpdateUI ui)
        throws OrmException {
    SortedSet<NameKey> projects = repoManager.list();
    SortedSet<NameKey> nonExistentProjects = Sets.newTreeSet();
    SetMultimap<Project.NameKey, Change.Id> openByProject = MultimapBuilder.hashKeys().hashSetValues().build();
    for (Change c : db.changes().all()) {
        Status status = c.getStatus();/*  w w w . ja  va2  s  .c  o  m*/
        if (status != null && status.isClosed()) {
            continue;
        }

        NameKey projectKey = c.getProject();
        if (!projects.contains(projectKey)) {
            nonExistentProjects.add(projectKey);
        } else {
            // The old "submitted" state is not supported anymore
            // (thus status is null) but it was an opened state and needs
            // to be migrated as such
            openByProject.put(projectKey, c.getId());
        }
    }

    if (!nonExistentProjects.isEmpty()) {
        ui.message("Detected open changes referring to the following non-existent projects:");
        ui.message(Joiner.on(", ").join(nonExistentProjects));
        ui.message("It is highly recommended to remove\n"
                + "the obsolete open changes, comments and patch-sets from your DB.\n");
    }
    return openByProject;
}

From source file:org.gradle.api.internal.changedetection.state.OrderInsensitiveTaskFilePropertyCompareStrategy.java

private Iterator<TaskStateChange> iterateChangesForRelativePaths(
        final Map<String, NormalizedFileSnapshot> current, Map<String, NormalizedFileSnapshot> previous,
        final String fileType) {
    final ListMultimap<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshots = MultimapBuilder
            .hashKeys().linkedListValues().build();
    for (Entry<String, NormalizedFileSnapshot> entry : previous.entrySet()) {
        String absolutePath = entry.getKey();
        NormalizedFileSnapshot previousSnapshot = entry.getValue();
        unaccountedForPreviousSnapshots.put(previousSnapshot,
                new IncrementalFileSnapshotWithAbsolutePath(absolutePath, previousSnapshot.getSnapshot()));
    }/*ww w .  ja v  a 2  s.  com*/
    final Iterator<Entry<String, NormalizedFileSnapshot>> currentEntries = current.entrySet().iterator();
    return new AbstractIterator<TaskStateChange>() {
        private Iterator<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> unaccountedForPreviousSnapshotsIterator;
        private final ListMultimap<String, IncrementalFileSnapshotWithAbsolutePath> addedFiles = MultimapBuilder
                .hashKeys().linkedListValues().build();
        private Iterator<IncrementalFileSnapshotWithAbsolutePath> addedFilesIterator;

        @Override
        protected TaskStateChange computeNext() {
            while (currentEntries.hasNext()) {
                Entry<String, NormalizedFileSnapshot> entry = currentEntries.next();
                String currentAbsolutePath = entry.getKey();
                NormalizedFileSnapshot currentNormalizedSnapshot = entry.getValue();
                IncrementalFileSnapshot currentSnapshot = currentNormalizedSnapshot.getSnapshot();
                List<IncrementalFileSnapshotWithAbsolutePath> previousSnapshotsForNormalizedPath = unaccountedForPreviousSnapshots
                        .get(currentNormalizedSnapshot);
                if (previousSnapshotsForNormalizedPath.isEmpty()) {
                    IncrementalFileSnapshotWithAbsolutePath currentSnapshotWithAbsolutePath = new IncrementalFileSnapshotWithAbsolutePath(
                            currentAbsolutePath, currentSnapshot);
                    addedFiles.put(currentNormalizedSnapshot.getNormalizedPath(),
                            currentSnapshotWithAbsolutePath);
                } else {
                    IncrementalFileSnapshotWithAbsolutePath previousSnapshotWithAbsolutePath = previousSnapshotsForNormalizedPath
                            .remove(0);
                    IncrementalFileSnapshot previousSnapshot = previousSnapshotWithAbsolutePath.getSnapshot();
                    if (!currentSnapshot.isContentUpToDate(previousSnapshot)) {
                        return new FileChange(currentAbsolutePath, ChangeType.MODIFIED, fileType);
                    }
                }
            }

            // Create a single iterator to use for all of the still unaccounted files
            if (unaccountedForPreviousSnapshotsIterator == null) {
                if (unaccountedForPreviousSnapshots.isEmpty()) {
                    unaccountedForPreviousSnapshotsIterator = Iterators.emptyIterator();
                } else {
                    List<Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath>> entries = Lists
                            .newArrayList(unaccountedForPreviousSnapshots.entries());
                    Collections.sort(entries, ENTRY_COMPARATOR);
                    unaccountedForPreviousSnapshotsIterator = entries.iterator();
                }
            }

            if (unaccountedForPreviousSnapshotsIterator.hasNext()) {
                Entry<NormalizedFileSnapshot, IncrementalFileSnapshotWithAbsolutePath> unaccountedForPreviousSnapshotEntry = unaccountedForPreviousSnapshotsIterator
                        .next();
                String normalizedPath = unaccountedForPreviousSnapshotEntry.getKey().getNormalizedPath();
                List<IncrementalFileSnapshotWithAbsolutePath> addedFilesForNormalizedPath = addedFiles
                        .get(normalizedPath);
                if (!addedFilesForNormalizedPath.isEmpty()) {
                    // There might be multiple files with the same normalized path, here we choose one of them
                    IncrementalFileSnapshotWithAbsolutePath modifiedSnapshot = addedFilesForNormalizedPath
                            .remove(0);
                    return new FileChange(modifiedSnapshot.getAbsolutePath(), ChangeType.MODIFIED, fileType);
                } else {
                    IncrementalFileSnapshotWithAbsolutePath removedSnapshot = unaccountedForPreviousSnapshotEntry
                            .getValue();
                    return new FileChange(removedSnapshot.getAbsolutePath(), ChangeType.REMOVED, fileType);
                }
            }

            if (includeAdded) {
                // Create a single iterator to use for all of the added files
                if (addedFilesIterator == null) {
                    addedFilesIterator = addedFiles.values().iterator();
                }

                if (addedFilesIterator.hasNext()) {
                    IncrementalFileSnapshotWithAbsolutePath addedFile = addedFilesIterator.next();
                    return new FileChange(addedFile.getAbsolutePath(), ChangeType.ADDED, fileType);
                }
            }

            return endOfData();
        }
    };
}

From source file:com.google.gerrit.server.index.change.StalenessChecker.java

public static ListMultimap<Project.NameKey, RefStatePattern> parsePatterns(Iterable<byte[]> patterns) {
    RefStatePattern.check(patterns != null, null);
    ListMultimap<Project.NameKey, RefStatePattern> result = MultimapBuilder.hashKeys().arrayListValues()
            .build();/*from w  w w.jav a  2s. co m*/
    for (byte[] b : patterns) {
        RefStatePattern.check(b != null, null);
        String s = new String(b, UTF_8);
        List<String> parts = Splitter.on(':').splitToList(s);
        RefStatePattern.check(parts.size() == 2, s);
        result.put(new Project.NameKey(parts.get(0)), RefStatePattern.create(parts.get(1)));
    }
    return result;
}

From source file:com.facebook.buck.apple.ApplePackageDescription.java

/**
 * Get the correct package configuration based on the platform flavors of this build target.
 *
 * Validates that all named platforms yields the identical package config.
 *
 * @return If found, a package config for this target.
 * @throws HumanReadableException if there are multiple possible package configs.
 *//*from  w ww  .  j  a v  a2s . c  o m*/
private Optional<ApplePackageConfigAndPlatformInfo> getApplePackageConfig(BuildTarget target,
        Function<String, com.facebook.buck.rules.args.Arg> macroExpander) {
    Set<Flavor> platformFlavors = getPlatformFlavorsOrDefault(target);

    // Ensure that different platforms generate the same config.
    // The value of this map is just for error reporting.
    Multimap<Optional<ApplePackageConfigAndPlatformInfo>, Flavor> packageConfigs = MultimapBuilder.hashKeys()
            .arrayListValues().build();

    for (Flavor flavor : platformFlavors) {
        AppleCxxPlatform platform = appleCxxPlatformFlavorDomain.getValue(flavor);
        Optional<ApplePackageConfig> packageConfig = config
                .getPackageConfigForPlatform(platform.getAppleSdk().getApplePlatform());
        packageConfigs.put(packageConfig.isPresent()
                ? Optional
                        .of(ApplePackageConfigAndPlatformInfo.of(packageConfig.get(), macroExpander, platform))
                : Optional.empty(), flavor);
    }

    if (packageConfigs.isEmpty()) {
        return Optional.empty();
    } else if (packageConfigs.keySet().size() == 1) {
        return Iterables.getOnlyElement(packageConfigs.keySet());
    } else {
        throw new HumanReadableException(
                "In target %s: Multi-architecture package has different package configs for targets: %s",
                target.getFullyQualifiedName(), packageConfigs.asMap().values());
    }
}

From source file:com.google.gerrit.server.git.SubmoduleOp.java

@Inject
public SubmoduleOp(GitModules.Factory gitmodulesFactory, @GerritPersonIdent PersonIdent myIdent,
        @GerritServerConfig Config cfg, ProjectCache projectCache, ProjectState.Factory projectStateFactory,
        BatchUpdate.Factory batchUpdateFactory, @Assisted Set<Branch.NameKey> updatedBranches,
        @Assisted MergeOpRepoManager orm) throws SubmoduleException {
    this.gitmodulesFactory = gitmodulesFactory;
    this.myIdent = myIdent;
    this.projectCache = projectCache;
    this.projectStateFactory = projectStateFactory;
    this.batchUpdateFactory = batchUpdateFactory;
    this.verboseSuperProject = cfg.getEnum("submodule", null, "verboseSuperprojectUpdate",
            VerboseSuperprojectUpdate.TRUE);
    this.enableSuperProjectSubscriptions = cfg.getBoolean("submodule", "enableSuperProjectSubscriptions", true);
    this.orm = orm;
    this.updatedBranches = updatedBranches;
    this.targets = MultimapBuilder.hashKeys().hashSetValues().build();
    this.affectedBranches = new HashSet<>();
    this.branchTips = new HashMap<>();
    this.branchGitModules = new HashMap<>();
    this.branchesByProject = MultimapBuilder.hashKeys().hashSetValues().build();
    this.sortedBranches = calculateSubscriptionMap();
}

From source file:com.google.gerrit.server.change.WalkSorter.java

private List<PatchSetData> sortProject(Project.NameKey project, Collection<ChangeData> in)
        throws OrmException, IOException {
    try (Repository repo = repoManager.openRepository(project); RevWalk rw = new RevWalk(repo)) {
        rw.setRetainBody(retainBody);/*from   w w  w .  j a va2s .  co m*/
        ListMultimap<RevCommit, PatchSetData> byCommit = byCommit(rw, in);
        if (byCommit.isEmpty()) {
            return ImmutableList.of();
        } else if (byCommit.size() == 1) {
            return ImmutableList.of(byCommit.values().iterator().next());
        }

        // Walk from all patch set SHA-1s, and terminate as soon as we've found
        // everything we're looking for. This is equivalent to just sorting the
        // list of commits by the RevWalk's configured order.
        //
        // Partially topo sort the list, ensuring no parent is emitted before a
        // direct child that is also in the input set. This preserves the stable,
        // expected sort in the case where many commits share the same timestamp,
        // e.g. a quick rebase. It also avoids JGit's topo sort, which slurps all
        // interesting commits at the beginning, which is a problem since we don't
        // know which commits to mark as uninteresting. Finding a reasonable set
        // of commits to mark uninteresting (the "rootmost" set) is at least as
        // difficult as just implementing this partial topo sort ourselves.
        //
        // (This is slightly less efficient than JGit's topo sort, which uses a
        // private in-degree field in RevCommit rather than multimaps. We assume
        // the input size is small enough that this is not an issue.)

        Set<RevCommit> commits = byCommit.keySet();
        ListMultimap<RevCommit, RevCommit> children = collectChildren(commits);
        ListMultimap<RevCommit, RevCommit> pending = MultimapBuilder.hashKeys().arrayListValues().build();
        Deque<RevCommit> todo = new ArrayDeque<>();

        RevFlag done = rw.newFlag("done");
        markStart(rw, commits);
        int expected = commits.size();
        int found = 0;
        RevCommit c;
        List<PatchSetData> result = new ArrayList<>(expected);
        while (found < expected && (c = rw.next()) != null) {
            if (!commits.contains(c)) {
                continue;
            }
            todo.clear();
            todo.add(c);
            int i = 0;
            while (!todo.isEmpty()) {
                // Sanity check: we can't pop more than N pending commits, otherwise
                // we have an infinite loop due to programmer error or something.
                checkState(++i <= commits.size(), "Too many pending steps while sorting %s", commits);
                RevCommit t = todo.removeFirst();
                if (t.has(done)) {
                    continue;
                }
                boolean ready = true;
                for (RevCommit child : children.get(t)) {
                    if (!child.has(done)) {
                        pending.put(child, t);
                        ready = false;
                    }
                }
                if (ready) {
                    found += emit(t, byCommit, result, done);
                    todo.addAll(pending.get(t));
                }
            }
        }
        return result;
    }
}

From source file:com.google.gerrit.server.change.WalkSorter.java

private static ListMultimap<RevCommit, RevCommit> collectChildren(Set<RevCommit> commits) {
    ListMultimap<RevCommit, RevCommit> children = MultimapBuilder.hashKeys().arrayListValues().build();
    for (RevCommit c : commits) {
        for (RevCommit p : c.getParents()) {
            if (commits.contains(p)) {
                children.put(p, c);/*  w ww.j  a  v  a 2 s .  c o m*/
            }
        }
    }
    return children;
}