use of com.google.gerrit.extensions.restapi.BadRequestException 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))));
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CheckMergeability method apply.
@Override
public Response<MergeableInfo> apply(BranchResource resource) throws IOException, BadRequestException, ResourceNotFoundException, ResourceConflictException {
if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
throw new BadRequestException("Submit type: " + submitType + " is not supported");
}
MergeableInfo result = new MergeableInfo();
result.submitType = submitType;
result.strategy = strategy;
try (Repository git = gitManager.openRepository(resource.getNameKey());
RevWalk rw = new RevWalk(git);
ObjectInserter inserter = new InMemoryInserter(git)) {
Merger m = MergeUtil.newMerger(inserter, git.getConfig(), strategy);
Ref destRef = git.getRefDatabase().exactRef(resource.getRef());
if (destRef == null) {
throw new ResourceNotFoundException(resource.getRef());
}
RevCommit targetCommit = rw.parseCommit(destRef.getObjectId());
RevCommit sourceCommit = null;
try {
sourceCommit = MergeUtil.resolveCommit(git, rw, source);
if (!commits.canRead(resource.getProjectState(), git, sourceCommit)) {
throw new BadRequestException("do not have read permission for: " + source);
}
} catch (BadRequestException e) {
// Throw a unified exception for permission denied and unresolvable commits.
throw new BadRequestException("Error resolving: '" + source + "'. Do not have read permission, or failed to resolve to a commit.", e);
}
if (rw.isMergedInto(sourceCommit, targetCommit)) {
result.mergeable = true;
result.commitMerged = true;
result.contentMerged = true;
return Response.ok(result);
}
if (m.merge(false, targetCommit, sourceCommit)) {
result.mergeable = true;
result.commitMerged = false;
result.contentMerged = m.getResultTreeId().equals(targetCommit.getTree());
} else {
result.mergeable = false;
if (m instanceof ResolveMerger) {
result.conflicts = ((ResolveMerger) m).getUnmergedPaths();
}
}
} catch (InvalidMergeStrategyException e) {
throw new BadRequestException(e.getMessage());
} catch (NoMergeBaseException e) {
// adapted to show the message to the user.
throw new ResourceConflictException(String.format("Change cannot be merged: %s", e.getMessage()), e);
}
return Response.ok(result);
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class LabelDefinitionInputParser method parseValues.
public static List<LabelValue> parseValues(Map<String, String> values) throws BadRequestException {
List<LabelValue> valueList = new ArrayList<>();
Set<Short> allValues = new HashSet<>();
for (Map.Entry<String, String> e : values.entrySet()) {
short value;
try {
value = Shorts.checkedCast(PermissionRule.parseInt(e.getKey().trim()));
} catch (NumberFormatException ex) {
throw new BadRequestException("invalid value: " + e.getKey(), ex);
}
if (!allValues.add(value)) {
throw new BadRequestException("duplicate value: " + value);
}
String valueDescription = e.getValue().trim();
if (valueDescription.isEmpty()) {
throw new BadRequestException("description for value '" + e.getKey() + "' cannot be empty");
}
valueList.add(LabelValue.create(value, valueDescription));
}
return valueList;
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CreateTag method apply.
@Override
public Response<TagInfo> apply(ProjectResource resource, IdString id, TagInput input) throws RestApiException, IOException, PermissionBackendException, NoSuchProjectException {
String ref = id.get();
if (input == null) {
input = new TagInput();
}
if (input.ref != null && !ref.equals(input.ref)) {
throw new BadRequestException("ref must match URL");
}
if (input.revision != null) {
input.revision = input.revision.trim();
}
if (Strings.isNullOrEmpty(input.revision)) {
input.revision = Constants.HEAD;
}
ref = RefUtil.normalizeTagRef(ref);
PermissionBackend.ForRef perm = permissionBackend.currentUser().project(resource.getNameKey()).ref(ref);
try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
RevWalk rw = RefUtil.verifyConnected(repo, revid);
// Reachability through tags does not influence a commit's visibility, so no need to check for
// visibility.
RevObject object = rw.parseAny(revid);
rw.reset();
boolean isAnnotated = Strings.emptyToNull(input.message) != null;
boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
if (isSigned) {
throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
} else if (isAnnotated) {
if (!check(perm, RefPermission.CREATE_TAG)) {
throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
}
} else {
perm.check(RefPermission.CREATE);
}
if (repo.getRefDatabase().exactRef(ref) != null) {
throw new ResourceConflictException("tag \"" + ref + "\" already exists");
}
try (Git git = new Git(repo)) {
TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())).setAnnotated(isAnnotated).setSigned(isSigned);
if (isAnnotated) {
tag.setMessage(input.message).setTagger(resource.getUser().asIdentifiedUser().newCommitterIdent(TimeUtil.now(), TimeZone.getDefault()));
}
Ref result = tag.call();
tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), resource.getUser().asIdentifiedUser().state());
try (RevWalk w = new RevWalk(repo)) {
return Response.created(ListTags.createTagInfo(perm, result, w, resource.getProjectState(), links));
}
}
} catch (InvalidRevisionException e) {
throw new BadRequestException("Invalid base revision", e);
} catch (GitAPIException e) {
logger.atSevere().withCause(e).log("Cannot create tag \"%s\"", ref);
throw new IOException(e);
}
}
use of com.google.gerrit.extensions.restapi.BadRequestException in project gerrit by GerritCodeReview.
the class CreateProject method apply.
@Override
public Response<ProjectInfo> apply(TopLevelResource resource, IdString id, ProjectInput input) throws RestApiException, IOException, ConfigInvalidException, PermissionBackendException {
String name = id.get();
if (input == null) {
input = new ProjectInput();
}
if (input.name != null && !name.equals(input.name)) {
throw new BadRequestException("name must match URL");
}
CreateProjectArgs args = new CreateProjectArgs();
args.setProjectName(ProjectUtil.sanitizeProjectName(name));
String parentName = MoreObjects.firstNonNull(Strings.emptyToNull(input.parent), allProjects.get());
args.newParent = projectsCollection.get().parse(parentName, false).getNameKey();
if (args.newParent.equals(allUsers)) {
throw new ResourceConflictException(String.format("Cannot inherit from '%s' project", allUsers.get()));
}
args.createEmptyCommit = input.createEmptyCommit;
args.permissionsOnly = input.permissionsOnly;
args.projectDescription = Strings.emptyToNull(input.description);
args.submitType = input.submitType;
args.branch = normalizeBranchNames(input.branches);
if (input.owners == null || input.owners.isEmpty()) {
args.ownerIds = new ArrayList<>(projectOwnerGroups.create(args.getProject()).get());
} else {
args.ownerIds = Lists.newArrayListWithCapacity(input.owners.size());
for (String owner : input.owners) {
args.ownerIds.add(groupResolver.get().parse(owner).getGroupUUID());
}
}
args.contributorAgreements = MoreObjects.firstNonNull(input.useContributorAgreements, InheritableBoolean.INHERIT);
args.signedOffBy = MoreObjects.firstNonNull(input.useSignedOffBy, InheritableBoolean.INHERIT);
args.contentMerge = input.submitType == SubmitType.FAST_FORWARD_ONLY ? InheritableBoolean.FALSE : MoreObjects.firstNonNull(input.useContentMerge, InheritableBoolean.INHERIT);
args.newChangeForAllNotInTarget = MoreObjects.firstNonNull(input.createNewChangeForAllNotInTarget, InheritableBoolean.INHERIT);
args.changeIdRequired = MoreObjects.firstNonNull(input.requireChangeId, InheritableBoolean.INHERIT);
args.rejectEmptyCommit = MoreObjects.firstNonNull(input.rejectEmptyCommit, InheritableBoolean.INHERIT);
args.enableSignedPush = MoreObjects.firstNonNull(input.enableSignedPush, InheritableBoolean.INHERIT);
args.requireSignedPush = MoreObjects.firstNonNull(input.requireSignedPush, InheritableBoolean.INHERIT);
try {
args.maxObjectSizeLimit = ProjectConfig.validMaxObjectSizeLimit(input.maxObjectSizeLimit);
} catch (ConfigInvalidException e) {
throw new BadRequestException(e.getMessage());
}
Lock nameLock = lockManager.call(lockManager -> lockManager.getLock(args.getProject()));
nameLock.lock();
try {
try {
projectCreationValidationListeners.runEach(l -> l.validateNewProject(args), ValidationException.class);
} catch (ValidationException e) {
throw new ResourceConflictException(e.getMessage(), e);
}
ProjectState projectState = projectCreator.createProject(args);
requireNonNull(projectState, () -> String.format("failed to create project %s", args.getProject().get()));
if (input.pluginConfigValues != null) {
ConfigInput in = new ConfigInput();
in.pluginConfigValues = input.pluginConfigValues;
in.description = args.projectDescription;
putConfig.get().apply(projectState, in);
}
return Response.created(json.format(projectState));
} finally {
nameLock.unlock();
}
}
Aggregations