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:org.gradle.api.internal.changedetection.state.ClasspathEntrySnapshotBuilder.java

public ClasspathEntrySnapshotBuilder(ResourceHasher classpathResourceHasher, StringInterner stringInterner) {
    this.classpathResourceHasher = classpathResourceHasher;
    this.stringInterner = stringInterner;
    this.normalizedSnapshots = MultimapBuilder.hashKeys().arrayListValues().build();
}

From source file:org.chaston.oakfunds.storage.mgmt.SchemaBuilder.java

private Multimap<RecordType, RecordType> groupBySuperType(Set<? extends RecordType> recordTypes) {
    Multimap<RecordType, RecordType> typesBySuperType = MultimapBuilder.hashKeys().arrayListValues().build();
    for (RecordType recordType : recordTypes) {
        typesBySuperType.put(recordType.getRootType(), recordType);
    }/* w w  w .j a va 2  s.  c om*/
    return typesBySuperType;
}

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

public IncludedInInfo apply(Project.NameKey project, String revisionId) throws RestApiException, IOException {
    try (Repository r = repoManager.openRepository(project); RevWalk rw = new RevWalk(r)) {
        rw.setRetainBody(false);//from   w w  w.  j a  va 2 s .  c om
        RevCommit rev;
        try {
            rev = rw.parseCommit(ObjectId.fromString(revisionId));
        } catch (IncorrectObjectTypeException err) {
            throw new BadRequestException(err.getMessage());
        } catch (MissingObjectException err) {
            throw new ResourceConflictException(err.getMessage());
        }

        IncludedInResolver.Result d = IncludedInResolver.resolve(r, rw, rev);
        ListMultimap<String, String> external = MultimapBuilder.hashKeys().arrayListValues().build();
        for (ExternalIncludedIn ext : externalIncludedIn) {
            ListMultimap<String, String> extIncludedIns = ext.getIncludedIn(project.get(), rev.name(),
                    d.getTags(), d.getBranches());
            if (extIncludedIns != null) {
                external.putAll(extIncludedIns);
            }
        }
        return new IncludedInInfo(d.getBranches(), d.getTags(),
                (!external.isEmpty() ? external.asMap() : null));
    }
}

From source file:com.google.gerrit.server.plugins.JarScanner.java

@Override
public Map<Class<? extends Annotation>, Iterable<ExtensionMetaData>> scan(String pluginName,
        Iterable<Class<? extends Annotation>> annotations) throws InvalidPluginException {
    Set<String> descriptors = new HashSet<>();
    ListMultimap<String, JarScanner.ClassData> rawMap = MultimapBuilder.hashKeys().arrayListValues().build();
    Map<Class<? extends Annotation>, String> classObjToClassDescr = new HashMap<>();

    for (Class<? extends Annotation> annotation : annotations) {
        String descriptor = Type.getType(annotation).getDescriptor();
        descriptors.add(descriptor);//from ww  w  .j  a v a2  s. c om
        classObjToClassDescr.put(annotation, descriptor);
    }

    Enumeration<JarEntry> e = jarFile.entries();
    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        if (skip(entry)) {
            continue;
        }

        ClassData def = new ClassData(descriptors);
        try {
            new ClassReader(read(jarFile, entry)).accept(def, SKIP_ALL);
        } catch (IOException err) {
            throw new InvalidPluginException("Cannot auto-register", err);
        } catch (RuntimeException err) {
            PluginLoader.log.warn(String.format("Plugin %s has invalid class file %s inside of %s", pluginName,
                    entry.getName(), jarFile.getName()), err);
            continue;
        }

        if (!Strings.isNullOrEmpty(def.annotationName)) {
            if (def.isConcrete()) {
                rawMap.put(def.annotationName, def);
            } else {
                PluginLoader.log.warn(String.format("Plugin %s tries to @%s(\"%s\") abstract class %s",
                        pluginName, def.annotationName, def.annotationValue, def.className));
            }
        }
    }

    ImmutableMap.Builder<Class<? extends Annotation>, Iterable<ExtensionMetaData>> result = ImmutableMap
            .builder();

    for (Class<? extends Annotation> annotoation : annotations) {
        String descr = classObjToClassDescr.get(annotoation);
        Collection<ClassData> discoverdData = rawMap.get(descr);
        Collection<ClassData> values = firstNonNull(discoverdData, Collections.<ClassData>emptySet());

        result.put(annotoation,
                transform(values, cd -> new ExtensionMetaData(cd.className, cd.annotationValue)));
    }

    return result.build();
}

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

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    ListMultimap<Account.Id, AccountSshKey> imports = MultimapBuilder.hashKeys().arrayListValues().build();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
            ResultSet rs = stmt.executeQuery("SELECT " + "account_id, " + "seq, " + "ssh_public_key, "
                    + "valid " + "FROM account_ssh_keys")) {
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt(1));
            int seq = rs.getInt(2);
            String sshPublicKey = rs.getString(3);
            AccountSshKey key = new AccountSshKey(new AccountSshKey.Id(accountId, seq), sshPublicKey);
            boolean valid = toBoolean(rs.getString(4));
            if (!valid) {
                key.setInvalid();//from w w w  .jav  a2  s  .  c  o  m
            }
            imports.put(accountId, key);
        }
    }

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

    try (Repository git = repoManager.openRepository(allUsersName); RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();

        for (Map.Entry<Account.Id, Collection<AccountSshKey>> e : imports.asMap().entrySet()) {
            try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
                md.getCommitBuilder().setAuthor(serverUser);
                md.getCommitBuilder().setCommitter(serverUser);

                VersionedAuthorizedKeys authorizedKeys = new VersionedAuthorizedKeys(new SimpleSshKeyCreator(),
                        e.getKey());
                authorizedKeys.load(md);
                authorizedKeys.setKeys(fixInvalidSequenceNumbers(e.getValue()));
                authorizedKeys.commit(md);
            }
        }

        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (ConfigInvalidException | IOException ex) {
        throw new OrmException(ex);
    }
}

From source file:com.google.gerrit.server.account.externalids.ExternalIdsConsistencyChecker.java

private List<ConsistencyProblemInfo> check(Repository repo, ObjectId commit) throws IOException {
    List<ConsistencyProblemInfo> problems = new ArrayList<>();

    ListMultimap<String, ExternalId.Key> emails = MultimapBuilder.hashKeys().arrayListValues().build();

    try (RevWalk rw = new RevWalk(repo)) {
        NoteMap noteMap = ExternalIdReader.readNoteMap(rw, commit);
        for (Note note : noteMap) {
            byte[] raw = rw.getObjectReader().open(note.getData(), OBJ_BLOB)
                    .getCachedBytes(ExternalIdReader.MAX_NOTE_SZ);
            try {
                ExternalId extId = ExternalId.parse(note.getName(), raw);
                problems.addAll(validateExternalId(extId));

                if (extId.email() != null) {
                    emails.put(extId.email(), extId.key());
                }/*from w w  w .  ja v  a 2s .  c o  m*/
            } catch (ConfigInvalidException e) {
                addError(String.format(e.getMessage()), problems);
            }
        }
    }

    emails.asMap().entrySet().stream().filter(e -> e.getValue().size() > 1).forEach(e -> addError(
            String.format("Email '%s' is not unique, it's used by the following external IDs: %s", e.getKey(),
                    e.getValue().stream().map(k -> "'" + k.get() + "'").sorted().collect(joining(", "))),
            problems));

    return problems;
}

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

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    ListMultimap<Account.Id, ProjectWatch> imports = MultimapBuilder.hashKeys().arrayListValues().build();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
            ResultSet rs = stmt.executeQuery(
                    "SELECT " + "account_id, " + "project_name, " + "filter, " + "notify_abandoned_changes, "
                            + "notify_all_comments, " + "notify_new_changes, " + "notify_new_patch_sets, "
                            + "notify_submitted_changes " + "FROM account_project_watches")) {
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt(1));
            ProjectWatch.Builder b = ProjectWatch.builder().project(new Project.NameKey(rs.getString(2)))
                    .filter(rs.getString(3)).notifyAbandonedChanges(rs.getBoolean(4))
                    .notifyAllComments(rs.getBoolean(5)).notifyNewChanges(rs.getBoolean(6))
                    .notifyNewPatchSets(rs.getBoolean(7)).notifySubmittedChanges(rs.getBoolean(8));
            imports.put(accountId, b.build());
        }// ww  w .  j av  a 2s  .  c om
    }

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

    try (Repository git = repoManager.openRepository(allUsersName); RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        bru.setRefLogIdent(serverUser);
        bru.setRefLogMessage(MSG, false);

        for (Map.Entry<Account.Id, Collection<ProjectWatch>> e : imports.asMap().entrySet()) {
            Map<ProjectWatchKey, Set<NotifyType>> projectWatches = new HashMap<>();
            for (ProjectWatch projectWatch : e.getValue()) {
                ProjectWatchKey key = ProjectWatchKey.create(projectWatch.project(), projectWatch.filter());
                if (projectWatches.containsKey(key)) {
                    throw new OrmDuplicateKeyException("Duplicate key for watched project: " + key.toString());
                }
                Set<NotifyType> notifyValues = EnumSet.noneOf(NotifyType.class);
                if (projectWatch.notifyAbandonedChanges()) {
                    notifyValues.add(NotifyType.ABANDONED_CHANGES);
                }
                if (projectWatch.notifyAllComments()) {
                    notifyValues.add(NotifyType.ALL_COMMENTS);
                }
                if (projectWatch.notifyNewChanges()) {
                    notifyValues.add(NotifyType.NEW_CHANGES);
                }
                if (projectWatch.notifyNewPatchSets()) {
                    notifyValues.add(NotifyType.NEW_PATCHSETS);
                }
                if (projectWatch.notifySubmittedChanges()) {
                    notifyValues.add(NotifyType.SUBMITTED_CHANGES);
                }
                projectWatches.put(key, notifyValues);
            }

            try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
                md.getCommitBuilder().setAuthor(serverUser);
                md.getCommitBuilder().setCommitter(serverUser);
                md.setMessage(MSG);

                WatchConfig watchConfig = new WatchConfig(e.getKey());
                watchConfig.load(md);
                watchConfig.setProjectWatches(projectWatches);
                watchConfig.commit(md);
            }
        }
        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (IOException | ConfigInvalidException ex) {
        throw new OrmException(ex);
    }
}

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

public ListMultimap<Branch.NameKey, ChangeData> changesByBranch() throws OrmException {
    ListMultimap<Branch.NameKey, ChangeData> ret = MultimapBuilder.hashKeys().arrayListValues().build();
    for (ChangeData cd : changeData.values()) {
        ret.put(cd.change().getDest(), cd);
    }/*from  w  w  w  .j av  a 2s  .  com*/
    return ret;
}

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

@Override
protected void onLoad(LoadHandle handle) throws IOException, ConfigInvalidException {
    metaId = handle.id();/* w  w  w .  j  a  va2s  .c om*/
    if (metaId == null) {
        loadDefaults();
        return;
    }
    metaId = metaId.copy();

    RevCommit tipCommit = handle.walk().parseCommit(metaId);
    ObjectReader reader = handle.walk().getObjectReader();
    revisionNoteMap = RevisionNoteMap.parseRobotComments(args.noteUtil, reader,
            NoteMap.read(reader, tipCommit));
    ListMultimap<RevId, RobotComment> cs = MultimapBuilder.hashKeys().arrayListValues().build();
    for (RobotCommentsRevisionNote rn : revisionNoteMap.revisionNotes.values()) {
        for (RobotComment c : rn.getComments()) {
            cs.put(new RevId(c.revId), c);
        }
    }
    comments = ImmutableListMultimap.copyOf(cs);
}

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

public ListMultimap<RecipientType, Account.Id> resolveAccounts(
        @Nullable Map<RecipientType, NotifyInfo> notifyDetails) throws OrmException, BadRequestException {
    if (isNullOrEmpty(notifyDetails)) {
        return ImmutableListMultimap.of();
    }/*from   w  ww  .  j a va2s.  c om*/

    ListMultimap<RecipientType, Account.Id> m = null;
    for (Entry<RecipientType, NotifyInfo> e : notifyDetails.entrySet()) {
        List<String> accounts = e.getValue().accounts;
        if (accounts != null) {
            if (m == null) {
                m = MultimapBuilder.hashKeys().arrayListValues().build();
            }
            m.putAll(e.getKey(), find(dbProvider.get(), accounts));
        }
    }

    return m != null ? m : ImmutableListMultimap.of();
}