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();
}
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);
}
}
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);
}
}
}
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)));
}
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;
}
Aggregations