Search in sources :

Example 91 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class AccountIT method validateAccountActivation.

@Test
public void validateAccountActivation() throws Exception {
    Account.Id activatableAccountId = accountOperations.newAccount().inactive().preferredEmail("foo@activatable.com").create();
    Account.Id deactivatableAccountId = accountOperations.newAccount().preferredEmail("foo@deactivatable.com").create();
    AccountActivationValidationListener validationListener = new AccountActivationValidationListener() {

        @Override
        public void validateActivation(AccountState account) throws ValidationException {
            String preferredEmail = account.account().preferredEmail();
            if (preferredEmail == null || !preferredEmail.endsWith("@activatable.com")) {
                throw new ValidationException("not allowed to active account");
            }
        }

        @Override
        public void validateDeactivation(AccountState account) throws ValidationException {
            String preferredEmail = account.account().preferredEmail();
            if (preferredEmail == null || !preferredEmail.endsWith("@deactivatable.com")) {
                throw new ValidationException("not allowed to deactive account");
            }
        }
    };
    AccountActivationListener listener = mock(AccountActivationListener.class);
    try (Registration registration = extensionRegistry.newRegistration().add(validationListener).add(listener)) {
        /* Test account that can be activated, but not deactivated */
        // Deactivate account that is already inactive
        ResourceConflictException thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(activatableAccountId.get()).setActive(false));
        assertThat(thrown).hasMessageThat().isEqualTo("account not active");
        assertThat(accountOperations.account(activatableAccountId).get().active()).isFalse();
        verifyNoInteractions(listener);
        // Activate account that can be activated
        gApi.accounts().id(activatableAccountId.get()).setActive(true);
        assertThat(accountOperations.account(activatableAccountId).get().active()).isTrue();
        verify(listener).onAccountActivated(activatableAccountId.get());
        verifyNoMoreInteractions(listener);
        // Activate account that is already active
        gApi.accounts().id(activatableAccountId.get()).setActive(true);
        assertThat(accountOperations.account(activatableAccountId).get().active()).isTrue();
        verifyNoMoreInteractions(listener);
        // Try deactivating account that cannot be deactivated
        thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(activatableAccountId.get()).setActive(false));
        assertThat(thrown).hasMessageThat().isEqualTo("not allowed to deactive account");
        assertThat(accountOperations.account(activatableAccountId).get().active()).isTrue();
        verifyNoMoreInteractions(listener);
        /* Test account that can be deactivated, but not activated */
        // Activate account that is already inactive
        gApi.accounts().id(deactivatableAccountId.get()).setActive(true);
        assertThat(accountOperations.account(deactivatableAccountId).get().active()).isTrue();
        verifyNoMoreInteractions(listener);
        // Deactivate account that can be deactivated
        gApi.accounts().id(deactivatableAccountId.get()).setActive(false);
        assertThat(accountOperations.account(deactivatableAccountId).get().active()).isFalse();
        verify(listener).onAccountDeactivated(deactivatableAccountId.get());
        verifyNoMoreInteractions(listener);
        // Deactivate account that is already inactive
        thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(deactivatableAccountId.get()).setActive(false));
        assertThat(thrown).hasMessageThat().isEqualTo("account not active");
        assertThat(accountOperations.account(deactivatableAccountId).get().active()).isFalse();
        verifyNoMoreInteractions(listener);
        // Try activating account that cannot be activated
        thrown = assertThrows(ResourceConflictException.class, () -> gApi.accounts().id(deactivatableAccountId.get()).setActive(true));
        assertThat(thrown).hasMessageThat().isEqualTo("not allowed to active account");
        assertThat(accountOperations.account(deactivatableAccountId).get().active()).isFalse();
        verifyNoMoreInteractions(listener);
    }
}
Also used : TestAccount(com.google.gerrit.acceptance.TestAccount) Account(com.google.gerrit.entities.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ValidationException(com.google.gerrit.server.validators.ValidationException) AccountActivationListener(com.google.gerrit.extensions.events.AccountActivationListener) AccountActivationValidationListener(com.google.gerrit.server.validators.AccountActivationValidationListener) Registration(com.google.gerrit.acceptance.ExtensionRegistry.Registration) AccountState(com.google.gerrit.server.account.AccountState) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 92 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class AbstractDaemonTest method verifyNoAccountDetailsInChangeNotes.

/**
 * Verify that NoteDB commits do not persist user-sensitive information, by running checks for all
 * commits in {@link RefNames#changeMetaRef} for all changes, created during the test.
 *
 * <p>These tests prevent regression, assuming appropriate test coverage for new features. The
 * verification is disabled by default and can be enabled using {@link VerifyNoPiiInChangeNotes}
 * annotation either on test class or method.
 */
protected void verifyNoAccountDetailsInChangeNotes() throws RestApiException, IOException {
    List<ChangeInfo> allChanges = gApi.changes().query().get();
    List<AccountState> allAccounts = accounts.all();
    for (ChangeInfo change : allChanges) {
        try (Repository repo = repoManager.openRepository(Project.nameKey(change.project))) {
            String metaRefName = RefNames.changeMetaRef(Change.Id.tryParse(change._number.toString()).get());
            ObjectId metaTip = repo.getRefDatabase().exactRef(metaRefName).getObjectId();
            ChangeNotesRevWalk revWalk = ChangeNotesCommit.newRevWalk(repo);
            revWalk.reset();
            revWalk.markStart(revWalk.parseCommit(metaTip));
            ChangeNotesCommit commit;
            while ((commit = revWalk.next()) != null) {
                String fullMessage = commit.getFullMessage();
                for (AccountState accountState : allAccounts) {
                    Account account = accountState.account();
                    assertThat(fullMessage).doesNotContain(account.getName());
                    if (account.fullName() != null) {
                        assertThat(fullMessage).doesNotContain(account.fullName());
                    }
                    if (account.displayName() != null) {
                        assertThat(fullMessage).doesNotContain(account.displayName());
                    }
                    if (account.preferredEmail() != null) {
                        assertThat(fullMessage).doesNotContain(account.preferredEmail());
                    }
                    if (accountState.userName().isPresent()) {
                        assertThat(fullMessage).doesNotContain(accountState.userName().get());
                    }
                    List<String> allEmails = accountState.externalIds().stream().map(ExternalId::email).filter(Objects::nonNull).collect(toImmutableList());
                    for (String email : allEmails) {
                        assertThat(fullMessage).doesNotContain(email);
                    }
                }
            }
        }
    }
}
Also used : Account(com.google.gerrit.entities.Account) TestRepository(org.eclipse.jgit.junit.TestRepository) Repository(org.eclipse.jgit.lib.Repository) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ChangeNotesRevWalk(com.google.gerrit.server.notedb.ChangeNotesCommit.ChangeNotesRevWalk) AccountState(com.google.gerrit.server.account.AccountState) IdString(com.google.gerrit.extensions.restapi.IdString) ChangeNotesCommit(com.google.gerrit.server.notedb.ChangeNotesCommit)

Example 93 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    if (!accounts.hasAnyAccount()) {
        welcome();
    }
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    if (!accounts.hasAnyAccount()) {
        ui.header("Gerrit Administrator");
        if (ui.yesno(true, "Create administrator user")) {
            Account.Id id = Account.id(sequencesOnInit.nextAccountId());
            String username = ui.readString("admin", "username");
            String name = ui.readString("Administrator", "name");
            String httpPassword = ui.readString("secret", "HTTP password");
            AccountSshKey sshKey = readSshKey(id);
            String email = readEmail(sshKey);
            List<ExternalId> extIds = new ArrayList<>(2);
            extIds.add(externalIdFactory.createUsername(username, id, httpPassword));
            if (email != null) {
                extIds.add(externalIdFactory.createEmail(id, email));
            }
            externalIds.insert("Add external IDs for initial admin user", extIds);
            Account persistedAccount = accounts.insert(Account.builder(id, TimeUtil.now()).setFullName(name).setPreferredEmail(email));
            // Only two groups should exist at this point in time and hence iterating over all of them
            // is cheap.
            Optional<GroupReference> adminGroupReference = groupsOnInit.getAllGroupReferences().filter(group -> group.getName().equals("Administrators")).findAny();
            if (!adminGroupReference.isPresent()) {
                throw new NoSuchGroupException("Administrators");
            }
            GroupReference adminGroup = adminGroupReference.get();
            groupsOnInit.addGroupMember(adminGroup.getUUID(), persistedAccount);
            if (sshKey != null) {
                VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                authorizedKeys.addKey(sshKey.sshPublicKey());
                authorizedKeys.save("Add SSH key for initial admin user\n");
            }
            AccountState as = AccountState.forAccount(persistedAccount, extIds);
            for (AccountIndex accountIndex : accountIndexCollection.getWriteIndexes()) {
                accountIndex.replace(as);
            }
            InternalGroup adminInternalGroup = groupsOnInit.getExistingGroup(adminGroup);
            for (GroupIndex groupIndex : groupIndexCollection.getWriteIndexes()) {
                groupIndex.replace(adminInternalGroup);
            }
        }
    }
}
Also used : InternalGroup(com.google.gerrit.entities.InternalGroup) AuthType(com.google.gerrit.extensions.client.AuthType) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) Inject(com.google.inject.Inject) GroupIndexCollection(com.google.gerrit.server.index.group.GroupIndexCollection) InitStep(com.google.gerrit.pgm.init.api.InitStep) EmailValidator(org.apache.commons.validator.routines.EmailValidator) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) ConsoleUI(com.google.gerrit.pgm.init.api.ConsoleUI) Path(java.nio.file.Path) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Account(com.google.gerrit.entities.Account) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) IOException(java.io.IOException) GroupReference(com.google.gerrit.entities.GroupReference) List(java.util.List) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) Paths(java.nio.file.Paths) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) AccountState(com.google.gerrit.server.account.AccountState) SequencesOnInit(com.google.gerrit.pgm.init.api.SequencesOnInit) InitFlags(com.google.gerrit.pgm.init.api.InitFlags) Account(com.google.gerrit.entities.Account) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) InternalGroup(com.google.gerrit.entities.InternalGroup) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) AuthType(com.google.gerrit.extensions.client.AuthType) GroupReference(com.google.gerrit.entities.GroupReference)

Example 94 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class ChangeJson method removableReviewers.

private Collection<AccountInfo> removableReviewers(ChangeData cd, ChangeInfo out) throws PermissionBackendException {
    // Although this is called removableReviewers, this method also determines
    // which CCs are removable.
    // 
    // For reviewers, we need to look at each approval, because the reviewer
    // should only be considered removable if *all* of their approvals can be
    // removed. First, add all reviewers with *any* removable approval to the
    // "removable" set. Along the way, if we encounter a non-removable approval,
    // add the reviewer to the "fixed" set. Before we return, remove all members
    // of "fixed" from "removable", because not all of their approvals can be
    // removed.
    Collection<LabelInfo> labels = out.labels.values();
    Set<Account.Id> fixed = Sets.newHashSetWithExpectedSize(labels.size());
    Set<Account.Id> removable = new HashSet<>();
    // Add all reviewers, which will later be removed if they are in the "fixed" set.
    removable.addAll(out.reviewers.getOrDefault(ReviewerState.REVIEWER, Collections.emptySet()).stream().filter(a -> a._accountId != null).map(a -> Account.id(a._accountId)).collect(Collectors.toSet()));
    // Check if the user has the permission to remove a reviewer. This means we can bypass the
    // testRemoveReviewer check for a specific reviewer in the loop saving potentially many
    // permission checks.
    boolean canRemoveAnyReviewer = permissionBackend.user(userProvider.get()).change(cd).test(ChangePermission.REMOVE_REVIEWER);
    for (LabelInfo label : labels) {
        if (label.all == null) {
            continue;
        }
        for (ApprovalInfo ai : label.all) {
            Account.Id id = Account.id(ai._accountId);
            if (!canRemoveAnyReviewer && !removeReviewerControl.testRemoveReviewer(cd, userProvider.get(), id, MoreObjects.firstNonNull(ai.value, 0))) {
                fixed.add(id);
            }
        }
    }
    // CCs are simpler than reviewers. They are removable if the ChangeControl
    // would permit a non-negative approval by that account to be removed, in
    // which case add them to removable. We don't need to add unremovable CCs to
    // "fixed" because we only visit each CC once here.
    Collection<AccountInfo> ccs = out.reviewers.get(ReviewerState.CC);
    if (ccs != null) {
        for (AccountInfo ai : ccs) {
            if (ai._accountId != null) {
                Account.Id id = Account.id(ai._accountId);
                if (canRemoveAnyReviewer || removeReviewerControl.testRemoveReviewer(cd, userProvider.get(), id, 0)) {
                    removable.add(id);
                }
            }
        }
    }
    // Subtract any reviewers with non-removable approvals from the "removable"
    // set. This also subtracts any CCs that for some reason also hold
    // unremovable approvals.
    removable.removeAll(fixed);
    List<AccountInfo> result = Lists.newArrayListWithCapacity(removable.size());
    for (Account.Id id : removable) {
        result.add(accountLoader.get(id));
    }
    // Reviewers added by email are always removable
    for (Collection<AccountInfo> infos : out.reviewers.values()) {
        for (AccountInfo info : infos) {
            if (info._accountId == null) {
                result.add(info);
            }
        }
    }
    return result;
}
Also used : AttentionSetUtil.additionsOnly(com.google.gerrit.server.util.AttentionSetUtil.additionsOnly) REVIEWER_UPDATES(com.google.gerrit.extensions.client.ListChangesOption.REVIEWER_UPDATES) LabelInfo(com.google.gerrit.extensions.common.LabelInfo) ListMultimap(com.google.common.collect.ListMultimap) TrackingIdInfo(com.google.gerrit.extensions.common.TrackingIdInfo) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewerSet(com.google.gerrit.server.ReviewerSet) SubmitRequirementResult(com.google.gerrit.entities.SubmitRequirementResult) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) LABELS(com.google.gerrit.extensions.client.ListChangesOption.LABELS) AttentionSetUtil.removalsOnly(com.google.gerrit.server.util.AttentionSetUtil.removalsOnly) ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Timer0(com.google.gerrit.metrics.Timer0) Set(java.util.Set) ReviewerStatusUpdate(com.google.gerrit.server.ReviewerStatusUpdate) SubmitRecord(com.google.gerrit.entities.SubmitRecord) SUBMITTABLE(com.google.gerrit.extensions.client.ListChangesOption.SUBMITTABLE) SubmitTypeRecord(com.google.gerrit.entities.SubmitTypeRecord) ImmutableMap.toImmutableMap(com.google.common.collect.ImmutableMap.toImmutableMap) MESSAGES(com.google.gerrit.extensions.client.ListChangesOption.MESSAGES) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) DETAILED_ACCOUNTS(com.google.gerrit.extensions.client.ListChangesOption.DETAILED_ACCOUNTS) MetricMaker(com.google.gerrit.metrics.MetricMaker) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ArrayList(java.util.ArrayList) CURRENT_COMMIT(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_COMMIT) ChangeMessage(com.google.gerrit.entities.ChangeMessage) Lists(com.google.common.collect.Lists) Description(com.google.gerrit.metrics.Description) PatchSet(com.google.gerrit.entities.PatchSet) Address(com.google.gerrit.entities.Address) RefState(com.google.gerrit.index.RefState) CURRENT_ACTIONS(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_ACTIONS) StorageException(com.google.gerrit.exceptions.StorageException) Units(com.google.gerrit.metrics.Description.Units) MoreObjects(com.google.common.base.MoreObjects) Throwables(com.google.common.base.Throwables) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ReviewerUpdateInfo(com.google.gerrit.extensions.common.ReviewerUpdateInfo) SubmitRuleOptions(com.google.gerrit.server.project.SubmitRuleOptions) LegacySubmitRequirementInfo(com.google.gerrit.extensions.common.LegacySubmitRequirementInfo) Project(com.google.gerrit.entities.Project) TrackingFooters(com.google.gerrit.server.config.TrackingFooters) ReviewerByEmailSet(com.google.gerrit.server.ReviewerByEmailSet) RequestCancelledException(com.google.gerrit.server.cancellation.RequestCancelledException) ALL_REVISIONS(com.google.gerrit.extensions.client.ListChangesOption.ALL_REVISIONS) Inject(com.google.inject.Inject) RevisionInfo(com.google.gerrit.extensions.common.RevisionInfo) Assisted(com.google.inject.assistedinject.Assisted) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LegacySubmitRequirement(com.google.gerrit.entities.LegacySubmitRequirement) RemoveReviewerControl(com.google.gerrit.server.project.RemoveReviewerControl) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) GpgException(com.google.gerrit.server.GpgException) REVIEWED(com.google.gerrit.extensions.client.ListChangesOption.REVIEWED) RefNames(com.google.gerrit.entities.RefNames) SubmitRequirementResultInfo(com.google.gerrit.extensions.common.SubmitRequirementResultInfo) CHECK(com.google.gerrit.extensions.client.ListChangesOption.CHECK) ChangedLines(com.google.gerrit.server.query.change.ChangeData.ChangedLines) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) DETAILED_LABELS(com.google.gerrit.extensions.client.ListChangesOption.DETAILED_LABELS) Account(com.google.gerrit.entities.Account) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Url(com.google.gerrit.extensions.restapi.Url) Optional(java.util.Optional) AttentionSetUtil(com.google.gerrit.server.util.AttentionSetUtil) PatchListNotAvailableException(com.google.gerrit.server.patch.PatchListNotAvailableException) AccountLoader(com.google.gerrit.server.account.AccountLoader) FixInput(com.google.gerrit.extensions.api.changes.FixInput) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) CURRENT_REVISION(com.google.gerrit.extensions.client.ListChangesOption.CURRENT_REVISION) ChangeInfo(com.google.gerrit.extensions.common.ChangeInfo) SubmitRecordInfo(com.google.gerrit.extensions.common.SubmitRecordInfo) SKIP_DIFFSTAT(com.google.gerrit.extensions.client.ListChangesOption.SKIP_DIFFSTAT) ChangeMessagesUtil.createChangeMessageInfo(com.google.gerrit.server.ChangeMessagesUtil.createChangeMessageInfo) Change(com.google.gerrit.entities.Change) ListChangesOption(com.google.gerrit.extensions.client.ListChangesOption) PluginDefinedInfo(com.google.gerrit.extensions.common.PluginDefinedInfo) TRACKING_IDS(com.google.gerrit.extensions.client.ListChangesOption.TRACKING_IDS) ProblemInfo(com.google.gerrit.extensions.common.ProblemInfo) CurrentUser(com.google.gerrit.server.CurrentUser) QueryResult(com.google.gerrit.index.query.QueryResult) Status(com.google.gerrit.entities.SubmitRecord.Status) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) AccountInfoComparator(com.google.gerrit.server.account.AccountInfoComparator) ChangeMessageInfo(com.google.gerrit.extensions.common.ChangeMessageInfo) CHANGE_ACTIONS(com.google.gerrit.extensions.client.ListChangesOption.CHANGE_ACTIONS) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) ChangeField(com.google.gerrit.server.index.change.ChangeField) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) SUBMIT_REQUIREMENTS(com.google.gerrit.extensions.client.ListChangesOption.SUBMIT_REQUIREMENTS) COMMIT_FOOTERS(com.google.gerrit.extensions.client.ListChangesOption.COMMIT_FOOTERS) ALL_COMMITS(com.google.gerrit.extensions.client.ListChangesOption.ALL_COMMITS) Collections(java.util.Collections) StarredChangesUtil(com.google.gerrit.server.StarredChangesUtil) Account(com.google.gerrit.entities.Account) LabelInfo(com.google.gerrit.extensions.common.LabelInfo) ApprovalInfo(com.google.gerrit.extensions.common.ApprovalInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) AccountInfo(com.google.gerrit.extensions.common.AccountInfo) HashSet(java.util.HashSet)

Example 95 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class ChangeQueryBuilder method destination.

@Operator
public Predicate<ChangeData> destination(String value) throws QueryParseException {
    // [name=]<name>[,user=<user>] || [user=<user>,][name=]<name>
    PredicateArgs inputArgs = new PredicateArgs(value);
    String name = null;
    Account.Id account = null;
    try (Repository git = args.repoManager.openRepository(args.allUsersName)) {
        // [name=]<name>
        if (inputArgs.keyValue.containsKey(ARG_ID_NAME)) {
            name = inputArgs.keyValue.get(ARG_ID_NAME).value();
        } else if (inputArgs.positional.size() == 1) {
            name = Iterables.getOnlyElement(inputArgs.positional);
        } else if (inputArgs.positional.size() > 1) {
            throw new QueryParseException("Error parsing named destination: " + value);
        }
        // [,user=<user>]
        if (inputArgs.keyValue.containsKey(ARG_ID_USER)) {
            Set<Account.Id> accounts = parseAccount(inputArgs.keyValue.get(ARG_ID_USER).value());
            if (accounts != null && accounts.size() > 1) {
                throw error(String.format("\"%s\" resolves to multiple accounts", inputArgs.keyValue.get(ARG_ID_USER)));
            }
            account = (accounts == null ? self() : Iterables.getOnlyElement(accounts));
        } else {
            account = self();
        }
        VersionedAccountDestinations d = VersionedAccountDestinations.forUser(account);
        d.load(args.allUsersName, git);
        Set<BranchNameKey> destinations = d.getDestinationList().getDestinations(name);
        if (destinations != null && !destinations.isEmpty()) {
            return new DestinationPredicate(destinations, value);
        }
    } catch (RepositoryNotFoundException e) {
        throw new QueryParseException("Unknown named destination (no " + args.allUsersName + " repo): " + name, e);
    } catch (IOException | ConfigInvalidException e) {
        throw new QueryParseException("Error parsing named destination: " + value, e);
    }
    throw new QueryParseException("Unknown named destination: " + name);
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) VersionedAccountDestinations(com.google.gerrit.server.account.VersionedAccountDestinations) QueryParseException(com.google.gerrit.index.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository) BranchNameKey(com.google.gerrit.entities.BranchNameKey)

Aggregations

Account (com.google.gerrit.entities.Account)124 Test (org.junit.Test)59 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)37 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)35 AccountState (com.google.gerrit.server.account.AccountState)35 IOException (java.io.IOException)31 Repository (org.eclipse.jgit.lib.Repository)31 Change (com.google.gerrit.entities.Change)28 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 Inject (com.google.inject.Inject)25 PersonIdent (org.eclipse.jgit.lib.PersonIdent)25 List (java.util.List)24 ArrayList (java.util.ArrayList)23 HashSet (java.util.HashSet)23 Set (java.util.Set)22 RefNames (com.google.gerrit.entities.RefNames)21 AuthRequest (com.google.gerrit.server.account.AuthRequest)21 Map (java.util.Map)21 ObjectId (org.eclipse.jgit.lib.ObjectId)21 ImmutableList (com.google.common.collect.ImmutableList)20