Search in sources :

Example 1 with ValidationException

use of com.google.gerrit.server.validators.ValidationException in project gerrit by GerritCodeReview.

the class AbstractSubmit method submitWithValidation.

@Test
public void submitWithValidation() throws Exception {
    AtomicBoolean called = new AtomicBoolean(false);
    this.addOnSubmitValidationListener(new OnSubmitValidationListener() {

        @Override
        public void preBranchUpdate(Arguments args) throws ValidationException {
            called.set(true);
            HashSet<String> refs = Sets.newHashSet(args.getCommands().keySet());
            assertThat(refs).contains("refs/heads/master");
            refs.remove("refs/heads/master");
            if (!refs.isEmpty()) {
                // Some submit strategies need to insert new patchset.
                assertThat(refs).hasSize(1);
                assertThat(refs.iterator().next()).startsWith(RefNames.REFS_CHANGES);
            }
        }
    });
    PushOneCommit.Result change = createChange();
    approve(change.getChangeId());
    submit(change.getChangeId());
    assertThat(called.get()).isTrue();
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) OnSubmitValidationListener(com.google.gerrit.server.git.validators.OnSubmitValidationListener) ValidationException(com.google.gerrit.server.validators.ValidationException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) HashSet(java.util.HashSet) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 2 with ValidationException

use of com.google.gerrit.server.validators.ValidationException in project gerrit by GerritCodeReview.

the class AbstractSubmit method submitWithValidationMultiRepo.

@Test
public void submitWithValidationMultiRepo() throws Exception {
    assume().that(isSubmitWholeTopicEnabled()).isTrue();
    String topic = "test-topic";
    // Create test projects
    TestRepository<?> repoA = createProjectWithPush("project-a", null, getSubmitType());
    TestRepository<?> repoB = createProjectWithPush("project-b", null, getSubmitType());
    // Create changes on project-a
    PushOneCommit.Result change1 = createChange(repoA, "master", "Change 1", "a.txt", "content", topic);
    PushOneCommit.Result change2 = createChange(repoA, "master", "Change 2", "b.txt", "content", topic);
    // Create changes on project-b
    PushOneCommit.Result change3 = createChange(repoB, "master", "Change 3", "a.txt", "content", topic);
    PushOneCommit.Result change4 = createChange(repoB, "master", "Change 4", "b.txt", "content", topic);
    List<PushOneCommit.Result> changes = Lists.newArrayList(change1, change2, change3, change4);
    for (PushOneCommit.Result change : changes) {
        approve(change.getChangeId());
    }
    // Construct validator which will throw on a second call.
    // Since there are 2 repos, first submit attempt will fail, the second will
    // succeed.
    List<String> projectsCalled = new ArrayList<>(4);
    this.addOnSubmitValidationListener(new OnSubmitValidationListener() {

        @Override
        public void preBranchUpdate(Arguments args) throws ValidationException {
            String master = "refs/heads/master";
            assertThat(args.getCommands()).containsKey(master);
            ReceiveCommand cmd = args.getCommands().get(master);
            ObjectId newMasterId = cmd.getNewId();
            try (Repository repo = repoManager.openRepository(args.getProject())) {
                assertThat(repo.exactRef(master).getObjectId()).isEqualTo(cmd.getOldId());
                assertThat(args.getRef(master)).hasValue(newMasterId);
                args.getRevWalk().parseBody(args.getRevWalk().parseCommit(newMasterId));
            } catch (IOException e) {
                throw new AssertionError("failed checking new ref value", e);
            }
            projectsCalled.add(args.getProject().get());
            if (projectsCalled.size() == 2) {
                throw new ValidationException("time to fail");
            }
        }
    });
    submitWithConflict(change4.getChangeId(), "time to fail");
    assertThat(projectsCalled).containsExactly(name("project-a"), name("project-b"));
    for (PushOneCommit.Result change : changes) {
        change.assertChange(Change.Status.NEW, name(topic), admin);
    }
    submit(change4.getChangeId());
    assertThat(projectsCalled).containsExactly(name("project-a"), name("project-b"), name("project-a"), name("project-b"));
    for (PushOneCommit.Result change : changes) {
        change.assertChange(Change.Status.MERGED, name(topic), admin);
    }
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) ValidationException(com.google.gerrit.server.validators.ValidationException) ObjectId(org.eclipse.jgit.lib.ObjectId) ArrayList(java.util.ArrayList) IOException(java.io.IOException) PushOneCommit(com.google.gerrit.acceptance.PushOneCommit) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) TestRepository(org.eclipse.jgit.junit.TestRepository) Repository(org.eclipse.jgit.lib.Repository) OnSubmitValidationListener(com.google.gerrit.server.git.validators.OnSubmitValidationListener) AbstractDaemonTest(com.google.gerrit.acceptance.AbstractDaemonTest) Test(org.junit.Test)

Example 3 with ValidationException

use of com.google.gerrit.server.validators.ValidationException in project gerrit by GerritCodeReview.

the class OutgoingEmail method send.

/**
   * Format and enqueue the message for delivery.
   *
   * @throws EmailException
   */
public void send() throws EmailException {
    if (NotifyHandling.NONE.equals(notify) && accountsToNotify.isEmpty()) {
        return;
    }
    if (!args.emailSender.isEnabled()) {
        //
        return;
    }
    init();
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("HeaderHtml"));
    }
    format();
    appendText(textTemplate("Footer"));
    if (useHtml()) {
        appendHtml(soyHtmlTemplate("FooterHtml"));
    }
    Set<Address> smtpRcptToPlaintextOnly = new HashSet<>();
    if (shouldSendMessage()) {
        if (fromId != null) {
            final Account fromUser = args.accountCache.get(fromId).getAccount();
            GeneralPreferencesInfo senderPrefs = fromUser.getGeneralPreferencesInfo();
            if (senderPrefs != null && senderPrefs.getEmailStrategy() == CC_ON_OWN_COMMENTS) {
                // If we are impersonating a user, make sure they receive a CC of
                // this message so they can always review and audit what we sent
                // on their behalf to others.
                //
                add(RecipientType.CC, fromId);
            } else if (!accountsToNotify.containsValue(fromId) && rcptTo.remove(fromId)) {
                // If they don't want a copy, but we queued one up anyway,
                // drop them from the recipient lists.
                //
                removeUser(fromUser);
            }
        }
        // In addition, check if users only want to receive plaintext email.
        for (Account.Id id : rcptTo) {
            Account thisUser = args.accountCache.get(id).getAccount();
            GeneralPreferencesInfo prefs = thisUser.getGeneralPreferencesInfo();
            if (prefs == null || prefs.getEmailStrategy() == DISABLED) {
                removeUser(thisUser);
            } else if (useHtml() && prefs.getEmailFormat() == EmailFormat.PLAINTEXT) {
                removeUser(thisUser);
                smtpRcptToPlaintextOnly.add(new Address(thisUser.getFullName(), thisUser.getPreferredEmail()));
            }
            if (smtpRcptTo.isEmpty() && smtpRcptToPlaintextOnly.isEmpty()) {
                return;
            }
        }
        // inbound email replies.
        if (!headers.containsKey("Reply-To")) {
            StringJoiner j = new StringJoiner(", ");
            if (fromId != null) {
                Address address = toAddress(fromId);
                if (address != null) {
                    j.add(address.getEmail());
                }
            }
            smtpRcptTo.stream().forEach(a -> j.add(a.getEmail()));
            smtpRcptToPlaintextOnly.stream().forEach(a -> j.add(a.getEmail()));
            setHeader("Reply-To", j.toString());
        }
        String textPart = textBody.toString();
        OutgoingEmailValidationListener.Args va = new OutgoingEmailValidationListener.Args();
        va.messageClass = messageClass;
        va.smtpFromAddress = smtpFromAddress;
        va.smtpRcptTo = smtpRcptTo;
        va.headers = headers;
        va.body = textPart;
        if (useHtml()) {
            va.htmlBody = htmlBody.toString();
        } else {
            va.htmlBody = null;
        }
        for (OutgoingEmailValidationListener validator : args.outgoingEmailValidationListeners) {
            try {
                validator.validateOutgoingEmail(va);
            } catch (ValidationException e) {
                return;
            }
        }
        if (!smtpRcptTo.isEmpty()) {
            // Send multipart message
            args.emailSender.send(va.smtpFromAddress, va.smtpRcptTo, va.headers, va.body, va.htmlBody);
        }
        if (!smtpRcptToPlaintextOnly.isEmpty()) {
            // Send plaintext message
            Map<String, EmailHeader> shallowCopy = new HashMap<>();
            shallowCopy.putAll(headers);
            // Remove To and Cc
            shallowCopy.remove(HDR_TO);
            shallowCopy.remove(HDR_CC);
            for (Address a : smtpRcptToPlaintextOnly) {
                // Add new To
                EmailHeader.AddressList to = new EmailHeader.AddressList();
                to.add(a);
                shallowCopy.put(HDR_TO, to);
            }
            args.emailSender.send(va.smtpFromAddress, smtpRcptToPlaintextOnly, shallowCopy, va.body);
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ValidationException(com.google.gerrit.server.validators.ValidationException) Address(com.google.gerrit.server.mail.Address) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) OutgoingEmailValidationListener(com.google.gerrit.server.validators.OutgoingEmailValidationListener) AddressList(com.google.gerrit.server.mail.send.EmailHeader.AddressList) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) AddressList(com.google.gerrit.server.mail.send.EmailHeader.AddressList) StringJoiner(java.util.StringJoiner) HashSet(java.util.HashSet)

Example 4 with ValidationException

use of com.google.gerrit.server.validators.ValidationException in project gerrit by GerritCodeReview.

the class CreateGroup method apply.

@Override
public GroupInfo apply(TopLevelResource resource, GroupInput input) throws AuthException, BadRequestException, UnprocessableEntityException, ResourceConflictException, OrmException, IOException {
    if (input == null) {
        input = new GroupInput();
    }
    if (input.name != null && !name.equals(input.name)) {
        throw new BadRequestException("name must match URL");
    }
    AccountGroup.Id ownerId = owner(input);
    CreateGroupArgs args = new CreateGroupArgs();
    args.setGroupName(name);
    args.groupDescription = Strings.emptyToNull(input.description);
    args.visibleToAll = MoreObjects.firstNonNull(input.visibleToAll, defaultVisibleToAll);
    args.ownerGroupId = ownerId;
    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.getId());
        }
        args.initialMembers = members;
    } else {
        args.initialMembers = ownerId == null ? Collections.singleton(self.get().getAccountId()) : Collections.<Account.Id>emptySet();
    }
    for (GroupCreationValidationListener l : groupCreationValidationListeners) {
        try {
            l.validateNewGroup(args);
        } catch (ValidationException e) {
            throw new ResourceConflictException(e.getMessage(), e);
        }
    }
    return json.format(GroupDescriptions.forAccountGroup(createGroup(args)));
}
Also used : GroupInput(com.google.gerrit.extensions.api.groups.GroupInput) Account(com.google.gerrit.reviewdb.client.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ValidationException(com.google.gerrit.server.validators.ValidationException) GroupCreationValidationListener(com.google.gerrit.server.validators.GroupCreationValidationListener) ArrayList(java.util.ArrayList) CreateGroupArgs(com.google.gerrit.server.account.CreateGroupArgs) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 5 with ValidationException

use of com.google.gerrit.server.validators.ValidationException in project gerrit by GerritCodeReview.

the class SetHashtagsOp method updateChange.

@Override
public boolean updateChange(ChangeContext ctx) throws AuthException, BadRequestException, MethodNotAllowedException, OrmException, IOException {
    if (!notesMigration.readChanges()) {
        throw new MethodNotAllowedException("Cannot add hashtags; NoteDb is disabled");
    }
    if (input == null || (input.add == null && input.remove == null)) {
        updatedHashtags = ImmutableSortedSet.of();
        return false;
    }
    change = ctx.getChange();
    ChangeUpdate update = ctx.getUpdate(change.currentPatchSetId());
    ChangeNotes notes = update.getNotes().load();
    Set<String> existingHashtags = notes.getHashtags();
    Set<String> updated = new HashSet<>();
    toAdd = new HashSet<>(extractTags(input.add));
    toRemove = new HashSet<>(extractTags(input.remove));
    try {
        for (HashtagValidationListener validator : validationListeners) {
            validator.validateHashtags(update.getChange(), toAdd, toRemove);
        }
    } catch (ValidationException e) {
        throw new BadRequestException(e.getMessage());
    }
    updated.addAll(existingHashtags);
    toAdd.removeAll(existingHashtags);
    toRemove.retainAll(existingHashtags);
    if (updated()) {
        updated.addAll(toAdd);
        updated.removeAll(toRemove);
        update.setHashtags(updated);
        addMessage(ctx, update);
    }
    updatedHashtags = ImmutableSortedSet.copyOf(updated);
    return true;
}
Also used : HashtagValidationListener(com.google.gerrit.server.validators.HashtagValidationListener) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ValidationException(com.google.gerrit.server.validators.ValidationException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) HashSet(java.util.HashSet)

Aggregations

ValidationException (com.google.gerrit.server.validators.ValidationException)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)3 HashSet (java.util.HashSet)3 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)2 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)2 Account (com.google.gerrit.reviewdb.client.Account)2 OnSubmitValidationListener (com.google.gerrit.server.git.validators.OnSubmitValidationListener)2 ChangeUpdate (com.google.gerrit.server.notedb.ChangeUpdate)2 ArrayList (java.util.ArrayList)2 Test (org.junit.Test)2 GroupInput (com.google.gerrit.extensions.api.groups.GroupInput)1 ConfigInput (com.google.gerrit.extensions.api.projects.ConfigInput)1 ProjectInput (com.google.gerrit.extensions.api.projects.ProjectInput)1 GeneralPreferencesInfo (com.google.gerrit.extensions.client.GeneralPreferencesInfo)1 BinaryResult (com.google.gerrit.extensions.restapi.BinaryResult)1 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)1 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)1 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)1 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)1