use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CreateChange method applyImpl.
@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
if (Strings.isNullOrEmpty(input.project)) {
throw new BadRequestException("project must be non-empty");
}
if (Strings.isNullOrEmpty(input.branch)) {
throw new BadRequestException("branch must be non-empty");
}
if (Strings.isNullOrEmpty(input.subject)) {
throw new BadRequestException("commit message must be non-empty");
}
if (input.status != null) {
if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
throw new BadRequestException("unsupported change status");
}
if (!allowDrafts && input.status == ChangeStatus.DRAFT) {
throw new MethodNotAllowedException("draft workflow is disabled");
}
}
String refName = RefNames.fullName(input.branch);
ProjectResource rsrc = projectsCollection.parse(input.project);
Capable r = rsrc.getControl().canPushToAtLeastOneRef();
if (r != Capable.OK) {
throw new AuthException(r.getMessage());
}
RefControl refControl = rsrc.getControl().controlForRef(refName);
if (!refControl.canUpload() || !refControl.isVisible()) {
throw new AuthException("cannot upload review");
}
Project.NameKey project = rsrc.getNameKey();
try (Repository git = gitManager.openRepository(project);
ObjectInserter oi = git.newObjectInserter();
ObjectReader reader = oi.newReader();
RevWalk rw = new RevWalk(reader)) {
ObjectId parentCommit;
List<String> groups;
if (input.baseChange != null) {
List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
if (ctls.size() != 1) {
throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
}
ChangeControl ctl = Iterables.getOnlyElement(ctls);
if (!ctl.isVisible(db.get())) {
throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
}
PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
parentCommit = ObjectId.fromString(ps.getRevision().get());
groups = ps.getGroups();
} else {
Ref destRef = git.getRefDatabase().exactRef(refName);
if (destRef != null) {
if (Boolean.TRUE.equals(input.newBranch)) {
throw new ResourceConflictException(String.format("Branch %s already exists.", refName));
}
parentCommit = destRef.getObjectId();
} else {
if (Boolean.TRUE.equals(input.newBranch)) {
parentCommit = null;
} else {
throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName));
}
}
groups = Collections.emptyList();
}
RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
Timestamp now = TimeUtil.nowTs();
IdentifiedUser me = user.get().asIdentifiedUser();
PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
AccountState account = accountCache.get(me.getAccountId());
GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
String commitMessage = ChangeIdUtil.insertId(input.subject, id);
if (Boolean.TRUE.equals(info.signedOffBy)) {
commitMessage += String.format("%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
}
RevCommit c;
if (input.merge != null) {
// create a merge commit
if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
throw new BadRequestException("Submit type: " + submitType + " is not supported");
}
c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
} else {
// create an empty commit
c = newCommit(oi, rw, author, mergeTip, commitMessage);
}
Change.Id changeId = new Change.Id(seq.nextChangeId());
ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
String topic = input.topic;
if (topic != null) {
topic = Strings.emptyToNull(topic.trim());
}
ins.setTopic(topic);
ins.setDraft(input.status == ChangeStatus.DRAFT);
ins.setPrivate(input.isPrivate != null && input.isPrivate);
ins.setWorkInProgress(input.workInProgress != null && input.workInProgress);
ins.setGroups(groups);
ins.setNotify(input.notify);
ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
bu.setRepository(git, rw, oi);
bu.insertChange(ins);
bu.execute();
}
ChangeJson json = jsonFactory.noOptions();
return Response.created(json.format(ins.getChange()));
} catch (IllegalArgumentException e) {
throw new BadRequestException(e.getMessage());
}
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CreateDraftComment method applyImpl.
@Override
protected Response<CommentInfo> applyImpl(BatchUpdate.Factory updateFactory, RevisionResource rsrc, DraftInput in) throws RestApiException, UpdateException, OrmException {
if (Strings.isNullOrEmpty(in.path)) {
throw new BadRequestException("path must be non-empty");
} else if (in.message == null || in.message.trim().isEmpty()) {
throw new BadRequestException("message must be non-empty");
} else if (in.line != null && in.line < 0) {
throw new BadRequestException("line must be >= 0");
} else if (in.line != null && in.range != null && in.line != in.range.endLine) {
throw new BadRequestException("range endLine must be on the same line as the comment");
}
try (BatchUpdate bu = updateFactory.create(db.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Op op = new Op(rsrc.getPatchSet().getId(), in);
bu.addOp(rsrc.getChange().getId(), op);
bu.execute();
return Response.created(commentJson.get().setFillAccounts(false).newCommentFormatter().format(op.comment));
}
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CreateEmail method apply.
public Response<EmailInfo> apply(IdentifiedUser user, EmailInput input) throws AuthException, BadRequestException, ResourceConflictException, ResourceNotFoundException, OrmException, EmailException, MethodNotAllowedException, IOException, ConfigInvalidException, PermissionBackendException {
if (input.email != null && !email.equals(input.email)) {
throw new BadRequestException("email address must match URL");
}
EmailInfo info = new EmailInfo();
info.email = email;
if (input.noConfirmation || isDevMode) {
if (isDevMode) {
log.warn("skipping email validation in developer mode");
}
try {
accountManager.link(user.getAccountId(), AuthRequest.forEmail(email));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
if (input.preferred) {
putPreferred.apply(new AccountResource.Email(user, email), null);
info.preferred = true;
}
} else {
try {
RegisterNewEmailSender sender = registerNewEmailFactory.create(email);
if (!sender.isAllowed()) {
throw new MethodNotAllowedException("Not allowed to add email address " + email);
}
sender.send();
info.pendingConfirmation = true;
} catch (EmailException | RuntimeException e) {
log.error("Cannot send email verification message to " + email, e);
throw e;
}
}
return Response.created(info);
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class PostReview method ensureRangesDoNotOverlap.
private static void ensureRangesDoNotOverlap(String commentPath, List<FixReplacementInfo> fixReplacementInfos) throws BadRequestException {
List<Range> sortedRanges = fixReplacementInfos.stream().map(fixReplacementInfo -> fixReplacementInfo.range).sorted().collect(toList());
int previousEndLine = 0;
int previousOffset = -1;
for (Range range : sortedRanges) {
if (range.startLine < previousEndLine || (range.startLine == previousEndLine && range.startCharacter < previousOffset)) {
throw new BadRequestException(String.format("Replacements overlap for the robot comment on %s", commentPath));
}
previousEndLine = range.endLine;
previousOffset = range.endCharacter;
}
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class PostReviewers method applyImpl.
@Override
protected AddReviewerResult applyImpl(BatchUpdate.Factory updateFactory, ChangeResource rsrc, AddReviewerInput input) throws IOException, OrmException, RestApiException, UpdateException, PermissionBackendException {
if (input.reviewer == null) {
throw new BadRequestException("missing reviewer field");
}
Addition addition = prepareApplication(rsrc, input, true);
if (addition.op == null) {
return addition.result;
}
try (BatchUpdate bu = updateFactory.create(dbProvider.get(), rsrc.getProject(), rsrc.getUser(), TimeUtil.nowTs())) {
Change.Id id = rsrc.getChange().getId();
bu.addOp(id, addition.op);
bu.execute();
addition.gatherResults();
}
return addition.result;
}
Aggregations