Search in sources :

Example 11 with Account

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

the class AbstractChangeNotesTest method setUpTestEnvironment.

// TODO(issue-15517): Fix the JdkObsolete issue with Date once JGit's PersonIdent class supports
// Instants
@SuppressWarnings("JdkObsolete")
@Before
public void setUpTestEnvironment() throws Exception {
    setTimeForTesting();
    serverIdent = new PersonIdent("Gerrit Server", "noreply@gerrit.com", Date.from(TimeUtil.now()), TZ);
    project = Project.nameKey("test-project");
    repoManager = new InMemoryRepositoryManager();
    repo = repoManager.createRepository(project);
    tr = new TestRepository<>(repo);
    rw = tr.getRevWalk();
    accountCache = new FakeAccountCache();
    Account.Builder co = Account.builder(Account.id(1), TimeUtil.now());
    co.setFullName("Change Owner");
    co.setPreferredEmail("change@owner.com");
    accountCache.put(co.build());
    Account.Builder ou = Account.builder(Account.id(2), TimeUtil.now());
    ou.setFullName("Other Account");
    ou.setPreferredEmail("other@account.com");
    accountCache.put(ou.build());
    assertableFanOutExecutor = new AssertableExecutorService();
    injector = Guice.createInjector(new FactoryModule() {

        @Override
        public void configure() {
            install(new GitModule());
            install(new DefaultUrlFormatterModule());
            install(NoteDbModule.forTest());
            bind(AllUsersName.class).toProvider(AllUsersNameProvider.class);
            bind(String.class).annotatedWith(GerritServerId.class).toInstance("gerrit");
            bind(GitRepositoryManager.class).toInstance(repoManager);
            bind(ProjectCache.class).to(NullProjectCache.class);
            bind(Config.class).annotatedWith(GerritServerConfig.class).toInstance(testConfig);
            bind(String.class).annotatedWith(AnonymousCowardName.class).toProvider(AnonymousCowardNameProvider.class);
            bind(String.class).annotatedWith(CanonicalWebUrl.class).toInstance("http://localhost:8080/");
            bind(Boolean.class).annotatedWith(EnablePeerIPInReflogRecord.class).toInstance(Boolean.FALSE);
            bind(Realm.class).to(FakeRealm.class);
            bind(GroupBackend.class).to(SystemGroupBackend.class).in(SINGLETON);
            bind(AccountCache.class).toInstance(accountCache);
            bind(PersonIdent.class).annotatedWith(GerritPersonIdent.class).toInstance(serverIdent);
            bind(GitReferenceUpdated.class).toInstance(GitReferenceUpdated.DISABLED);
            bind(MetricMaker.class).to(DisabledMetricMaker.class);
            bind(ExecutorService.class).annotatedWith(FanOutExecutor.class).toInstance(assertableFanOutExecutor);
            bind(ServiceUserClassifier.class).to(ServiceUserClassifier.NoOp.class);
            bind(InternalChangeQuery.class).toProvider(() -> {
                throw new UnsupportedOperationException();
            });
            bind(PatchSetApprovalUuidGenerator.class).to(TestPatchSetApprovalUuidGenerator.class);
        }
    });
    injector.injectMembers(this);
    repoManager.createRepository(allUsers);
    changeOwner = userFactory.create(co.id());
    otherUser = userFactory.create(ou.id());
    otherUserId = otherUser.getAccountId();
    internalUser = new InternalUser();
}
Also used : MetricMaker(com.google.gerrit.metrics.MetricMaker) DisabledMetricMaker(com.google.gerrit.metrics.DisabledMetricMaker) Account(com.google.gerrit.entities.Account) InMemoryRepositoryManager(com.google.gerrit.testing.InMemoryRepositoryManager) AssertableExecutorService(com.google.gerrit.testing.AssertableExecutorService) InternalUser(com.google.gerrit.server.InternalUser) GerritServerId(com.google.gerrit.server.config.GerritServerId) GitReferenceUpdated(com.google.gerrit.server.extensions.events.GitReferenceUpdated) FakeAccountCache(com.google.gerrit.testing.FakeAccountCache) SystemGroupBackend(com.google.gerrit.server.group.SystemGroupBackend) FakeRealm(com.google.gerrit.server.account.FakeRealm) Realm(com.google.gerrit.server.account.Realm) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) EnablePeerIPInReflogRecord(com.google.gerrit.server.config.EnablePeerIPInReflogRecord) AnonymousCowardName(com.google.gerrit.server.config.AnonymousCowardName) CanonicalWebUrl(com.google.gerrit.server.config.CanonicalWebUrl) FactoryModule(com.google.gerrit.extensions.config.FactoryModule) GitModule(com.google.gerrit.server.git.GitModule) FanOutExecutor(com.google.gerrit.server.FanOutExecutor) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) DefaultUrlFormatterModule(com.google.gerrit.server.config.DefaultUrlFormatter.DefaultUrlFormatterModule) PatchSetApprovalUuidGenerator(com.google.gerrit.server.approval.PatchSetApprovalUuidGenerator) TestPatchSetApprovalUuidGenerator(com.google.gerrit.server.approval.testing.TestPatchSetApprovalUuidGenerator) FakeAccountCache(com.google.gerrit.testing.FakeAccountCache) AccountCache(com.google.gerrit.server.account.AccountCache) ProjectCache(com.google.gerrit.server.project.ProjectCache) NullProjectCache(com.google.gerrit.server.project.NullProjectCache) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) AllUsersName(com.google.gerrit.server.config.AllUsersName) Before(org.junit.Before)

Example 12 with Account

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

the class ChangeNotesTest method patchLineCommentNotesFormatWeirdUser.

@Test
public void patchLineCommentNotesFormatWeirdUser() throws Exception {
    Account.Builder account = Account.builder(Account.id(3), TimeUtil.now());
    account.setFullName("Weird\n\u0002<User>\n");
    account.setPreferredEmail(" we\r\nird@ex>ample<.com");
    accountCache.put(account.build());
    IdentifiedUser user = userFactory.create(Account.id(3));
    Change c = newChange();
    ChangeUpdate update = newUpdate(c, user);
    String uuid = "uuid";
    CommentRange range = new CommentRange(1, 1, 2, 1);
    Instant time = TimeUtil.now();
    PatchSet.Id psId = c.currentPatchSetId();
    HumanComment comment = newComment(psId, "file1", uuid, range, range.getEndLine(), user, null, time, "comment", (short) 1, ObjectId.fromString("abcd1234abcd1234abcd1234abcd1234abcd1234"), false);
    update.setPatchSetId(psId);
    update.putComment(HumanComment.Status.PUBLISHED, comment);
    update.commit();
    ChangeNotes notes = newNotes(c);
    assertThat(notes.getHumanComments()).isEqualTo(ImmutableListMultimap.of(comment.getCommitId(), comment));
}
Also used : Account(com.google.gerrit.entities.Account) Instant(java.time.Instant) CommentRange(com.google.gerrit.entities.CommentRange) PatchSet(com.google.gerrit.entities.PatchSet) Change(com.google.gerrit.entities.Change) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) HumanComment(com.google.gerrit.entities.HumanComment) Test(org.junit.Test)

Example 13 with Account

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

the class ChangeUpdate method updateAttentionSet.

/**
 * Any updates to the attention set must be done in {@link #addToPlannedAttentionSetUpdates}. This
 * method is called after all the updates are finished to do the updates once and for real.
 *
 * <p>Changing the behaviour of this method might affect the way a ChangeUpdate is considered to
 * be an "Attention Set Change Only". Make sure the {@link #isAttentionSetChangeOnly} logic is
 * amended as well if needed.
 */
private void updateAttentionSet(StringBuilder msg) {
    if (plannedAttentionSetUpdates == null) {
        plannedAttentionSetUpdates = new HashMap<>();
    }
    Set<Account.Id> currentUsersInAttentionSet = AttentionSetUtil.additionsOnly(getNotes().getAttentionSet()).stream().map(AttentionSetUpdate::account).collect(Collectors.toSet());
    // Current reviewers/ccs are the reviewers/ccs before the update + the new reviewers/ccs - the
    // deleted reviewers/ccs.
    Set<Account.Id> currentReviewers = Stream.concat(getNotes().getReviewers().all().stream(), reviewers.entrySet().stream().filter(r -> r.getValue().asReviewerState() != ReviewerState.REMOVED).map(r -> r.getKey())).collect(Collectors.toSet());
    currentReviewers.removeAll(reviewers.entrySet().stream().filter(r -> r.getValue().asReviewerState() == ReviewerState.REMOVED).map(r -> r.getKey()).collect(ImmutableSet.toImmutableSet()));
    removeInactiveUsersFromAttentionSet(currentReviewers);
    for (AttentionSetUpdate attentionSetUpdate : plannedAttentionSetUpdates.values()) {
        if (attentionSetUpdate.operation() == AttentionSetUpdate.Operation.ADD && currentUsersInAttentionSet.contains(attentionSetUpdate.account())) {
            // Skip users that are already in the attention set: no need to re-add them.
            continue;
        }
        if (attentionSetUpdate.operation() == AttentionSetUpdate.Operation.REMOVE && !currentUsersInAttentionSet.contains(attentionSetUpdate.account())) {
            // Skip users that are not in the attention set: no need to remove them.
            continue;
        }
        if (attentionSetUpdate.operation() == AttentionSetUpdate.Operation.ADD && serviceUserClassifier.isServiceUser(attentionSetUpdate.account())) {
            // Skip adding robots to the attention set.
            continue;
        }
        if (attentionSetUpdate.operation() == AttentionSetUpdate.Operation.ADD && approvals.rowKeySet().contains(LabelId.legacySubmit().get())) {
            // This ensures we don't add users to the attention set on submit.
            continue;
        }
        // Don't add accounts that are not active in the change to the attention set.
        if (attentionSetUpdate.operation() == AttentionSetUpdate.Operation.ADD && !isActiveOnChange(currentReviewers, attentionSetUpdate.account())) {
            continue;
        }
        addFooter(msg, FOOTER_ATTENTION, noteUtil.attentionSetUpdateToJson(attentionSetUpdate));
    }
}
Also used : RefNames.changeMetaRef(com.google.gerrit.entities.RefNames.changeMetaRef) Comparator.naturalOrder(java.util.Comparator.naturalOrder) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) FOOTER_SUBMITTED_WITH(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_SUBMITTED_WITH) OBJ_BLOB(org.eclipse.jgit.lib.Constants.OBJ_BLOB) ProjectCache(com.google.gerrit.server.project.ProjectCache) FOOTER_HASHTAGS(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_HASHTAGS) Comment(com.google.gerrit.entities.Comment) HumanComment(com.google.gerrit.entities.HumanComment) SubmissionId(com.google.gerrit.entities.SubmissionId) SubmitRequirementResult(com.google.gerrit.entities.SubmitRequirementResult) Assisted(com.google.inject.assistedinject.Assisted) FooterKey(org.eclipse.jgit.revwalk.FooterKey) RevWalk(org.eclipse.jgit.revwalk.RevWalk) FOOTER_ASSIGNEE(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_ASSIGNEE) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) FOOTER_PATCH_SET_DESCRIPTION(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_PATCH_SET_DESCRIPTION) AttentionSetUpdate(com.google.gerrit.entities.AttentionSetUpdate) Map(java.util.Map) AssistedInject(com.google.inject.assistedinject.AssistedInject) NoteDbUtil.sanitizeFooter(com.google.gerrit.server.notedb.NoteDbUtil.sanitizeFooter) NoteMap(org.eclipse.jgit.notes.NoteMap) FOOTER_ATTENTION(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_ATTENTION) FOOTER_WORK_IN_PROGRESS(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_WORK_IN_PROGRESS) ImmutableSet(com.google.common.collect.ImmutableSet) FOOTER_SUBJECT(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_SUBJECT) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Set(java.util.Set) Instant(java.time.Instant) SubmitRecord(com.google.gerrit.entities.SubmitRecord) Collectors(java.util.stream.Collectors) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Objects(java.util.Objects) PersonIdent(org.eclipse.jgit.lib.PersonIdent) List(java.util.List) FOOTER_STATUS(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_STATUS) Stream(java.util.stream.Stream) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) FOOTER_LABEL(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_LABEL) Cell(com.google.common.collect.Table.Cell) FOOTER_SUBMISSION_ID(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_SUBMISSION_ID) Joiner(com.google.common.base.Joiner) AttentionSetUtil(com.google.gerrit.server.util.AttentionSetUtil) FOOTER_COMMIT(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_COMMIT) FOOTER_CHANGE_ID(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_CHANGE_ID) FOOTER_REVERT_OF(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_REVERT_OF) Iterables(com.google.common.collect.Iterables) LabelId(com.google.gerrit.entities.LabelId) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) FOOTER_TAG(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TAG) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) FOOTER_REAL_USER(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_REAL_USER) ImmutableList(com.google.common.collect.ImmutableList) PatchSetApprovalUuidGenerator(com.google.gerrit.server.approval.PatchSetApprovalUuidGenerator) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) Objects.requireNonNull(java.util.Objects.requireNonNull) RobotComment(com.google.gerrit.entities.RobotComment) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Address(com.google.gerrit.entities.Address) FOOTER_BRANCH(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_BRANCH) FOOTER_PATCH_SET(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_PATCH_SET) Operation(com.google.gerrit.entities.AttentionSetUpdate.Operation) FOOTER_GROUPS(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_GROUPS) FOOTER_COPIED_LABEL(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_COPIED_LABEL) FOOTER_PRIVATE(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_PRIVATE) FOOTER_TOPIC(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_TOPIC) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) CurrentUser(com.google.gerrit.server.CurrentUser) ValidationException(com.google.gerrit.server.validators.ValidationException) StorageException(com.google.gerrit.exceptions.StorageException) FOOTER_CURRENT(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_CURRENT) IOException(java.io.IOException) TreeBasedTable(com.google.common.collect.TreeBasedTable) ObjectId(org.eclipse.jgit.lib.ObjectId) FOOTER_CHERRY_PICK_OF(com.google.gerrit.server.notedb.ChangeNoteUtil.FOOTER_CHERRY_PICK_OF) Project(com.google.gerrit.entities.Project) LabelVote(com.google.gerrit.server.util.LabelVote) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Comparator(java.util.Comparator) Table(com.google.common.collect.Table) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) AttentionSetUpdate(com.google.gerrit.entities.AttentionSetUpdate) SubmissionId(com.google.gerrit.entities.SubmissionId) LabelId(com.google.gerrit.entities.LabelId) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 14 with Account

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

the class CreateGroup method apply.

@Override
public Response<GroupInfo> apply(TopLevelResource resource, IdString id, GroupInput input) throws AuthException, BadRequestException, UnprocessableEntityException, ResourceConflictException, IOException, ConfigInvalidException, ResourceNotFoundException, PermissionBackendException {
    String name = id.get();
    if (input == null) {
        input = new GroupInput();
    }
    if (input.name != null && !name.equals(input.name)) {
        throw new BadRequestException("name must match URL");
    }
    AccountGroup.UUID ownerUuid = owner(input);
    CreateGroupArgs args = new CreateGroupArgs();
    args.setGroupName(name);
    args.uuid = Strings.isNullOrEmpty(input.uuid) ? null : AccountGroup.UUID.parse(input.uuid);
    if (args.uuid != null) {
        if (!args.uuid.isInternalGroup()) {
            throw new BadRequestException(String.format("invalid group UUID '%s'", args.uuid.get()));
        }
        if (groupCache.get(args.uuid).isPresent()) {
            throw new ResourceConflictException(String.format("group with UUID '%s' already exists", args.uuid.get()));
        }
    }
    args.groupDescription = Strings.emptyToNull(input.description);
    args.visibleToAll = MoreObjects.firstNonNull(input.visibleToAll, defaultVisibleToAll);
    args.ownerGroupUuid = ownerUuid;
    if (input.members != null && !input.members.isEmpty()) {
        List<Account.Id> members = new ArrayList<>();
        for (String nameOrEmailOrId : input.members) {
            Account a = addMembers.findAccount(nameOrEmailOrId);
            if (!a.isActive()) {
                throw new UnprocessableEntityException(String.format("Account Inactive: %s", nameOrEmailOrId));
            }
            members.add(a.id());
        }
        args.initialMembers = members;
    } else {
        args.initialMembers = ownerUuid == null ? Collections.singleton(self.get().getAccountId()) : Collections.emptySet();
    }
    try {
        groupCreationValidationListeners.runEach(l -> l.validateNewGroup(args), ValidationException.class);
    } catch (ValidationException e) {
        throw new ResourceConflictException(e.getMessage(), e);
    }
    return Response.created(json.format(new InternalGroupDescription(createGroup(args))));
}
Also used : GroupInput(com.google.gerrit.extensions.api.groups.GroupInput) Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) InternalGroupDescription(com.google.gerrit.server.group.InternalGroupDescription) ValidationException(com.google.gerrit.server.validators.ValidationException) ArrayList(java.util.ArrayList) IdString(com.google.gerrit.extensions.restapi.IdString) CreateGroupArgs(com.google.gerrit.server.account.CreateGroupArgs) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountGroup(com.google.gerrit.entities.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 15 with Account

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

the class MailUtil method getRecipientsFromFooters.

public static MailRecipients getRecipientsFromFooters(AccountResolver accountResolver, List<FooterLine> footerLines) throws IOException, ConfigInvalidException {
    MailRecipients recipients = new MailRecipients();
    for (FooterLine footerLine : footerLines) {
        try {
            if (isReviewer(footerLine)) {
                Account.Id accountId = toAccountId(accountResolver, footerLine.getValue().trim());
                recipients.reviewers.add(accountId);
                logger.atFine().log("Added account %d from footer line \"%s\" as reviewer", accountId.get(), footerLine);
            } else if (footerLine.matches(FooterKey.CC)) {
                Account.Id accountId = toAccountId(accountResolver, footerLine.getValue().trim());
                recipients.cc.add(accountId);
                logger.atFine().log("Added account %d from footer line \"%s\" as cc", accountId.get(), footerLine);
            }
        } catch (UnprocessableEntityException e) {
            logger.atFine().log("Skip adding reviewer/cc from footer line \"%s\": %s", footerLine, e.getMessage());
            continue;
        }
    }
    return recipients;
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) FooterLine(org.eclipse.jgit.revwalk.FooterLine)

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