use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.
the class QueryProjects method apply.
public List<ProjectInfo> apply() throws BadRequestException, MethodNotAllowedException {
if (Strings.isNullOrEmpty(query)) {
throw new BadRequestException("missing query field");
}
ProjectIndex searchIndex = indexes.getSearchIndex();
if (searchIndex == null) {
throw new MethodNotAllowedException("no project index");
}
ProjectQueryProcessor queryProcessor = queryProcessorProvider.get();
if (start != 0) {
queryProcessor.setStart(start);
}
if (limit != 0) {
queryProcessor.setUserProvidedLimit(limit);
}
try {
QueryResult<ProjectData> result = queryProcessor.query(queryBuilder.parse(query));
List<ProjectData> pds = result.entities();
ArrayList<ProjectInfo> projectInfos = Lists.newArrayListWithCapacity(pds.size());
for (ProjectData pd : pds) {
projectInfos.add(json.format(pd.getProject()));
}
return projectInfos;
} catch (QueryParseException e) {
throw new BadRequestException(e.getMessage());
}
}
use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.
the class DeleteEmail method apply.
public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
Account.Id accountId = user.getAccountId();
if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
throw new MethodNotAllowedException("realm does not allow deleting emails");
}
Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
if (extIds.isEmpty()) {
throw new ResourceNotFoundException(email);
}
if (realm.accountBelongsToRealm(extIds)) {
String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
throw new ResourceConflictException(errorMsg);
}
try {
accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
} catch (AccountException e) {
throw new ResourceConflictException(e.getMessage());
}
return Response.none();
}
use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.
the class QueryAccounts method apply.
@Override
public Response<List<AccountInfo>> apply(TopLevelResource rsrc) throws RestApiException, PermissionBackendException {
if (Strings.isNullOrEmpty(query)) {
throw new BadRequestException("missing query field");
}
if (suggest && (!suggestConfig || query.length() < suggestFrom)) {
return Response.ok(Collections.emptyList());
}
Set<FillOptions> fillOptions = EnumSet.of(FillOptions.ID);
if (options.contains(ListAccountsOption.DETAILS)) {
fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
}
boolean modifyAccountCapabilityChecked = false;
if (options.contains(ListAccountsOption.ALL_EMAILS)) {
permissionBackend.currentUser().check(GlobalPermission.MODIFY_ACCOUNT);
modifyAccountCapabilityChecked = true;
fillOptions.add(FillOptions.EMAIL);
fillOptions.add(FillOptions.SECONDARY_EMAILS);
}
if (suggest) {
fillOptions.addAll(AccountLoader.DETAILED_OPTIONS);
fillOptions.add(FillOptions.EMAIL);
if (modifyAccountCapabilityChecked) {
fillOptions.add(FillOptions.SECONDARY_EMAILS);
} else {
if (permissionBackend.currentUser().test(GlobalPermission.MODIFY_ACCOUNT)) {
fillOptions.add(FillOptions.SECONDARY_EMAILS);
}
}
}
accountLoader = accountLoaderFactory.create(fillOptions);
AccountQueryProcessor queryProcessor = queryProcessorProvider.get();
if (queryProcessor.isDisabled()) {
throw new MethodNotAllowedException("query disabled");
}
if (limit != null) {
queryProcessor.setUserProvidedLimit(limit);
}
if (start != null) {
queryProcessor.setStart(start);
}
Map<Account.Id, AccountInfo> matches = new LinkedHashMap<>();
try {
Predicate<AccountState> queryPred;
if (suggest) {
queryPred = queryBuilder.defaultQuery(query);
queryProcessor.setUserProvidedLimit(suggestLimit);
} else {
queryPred = queryBuilder.parse(query);
}
if (!AccountPredicates.hasActive(queryPred)) {
// if neither 'is:active' nor 'is:inactive' appears in the query only
// active accounts should be queried
queryPred = AccountPredicates.andActive(queryPred);
}
QueryResult<AccountState> result = queryProcessor.query(queryPred);
for (AccountState accountState : result.entities()) {
Account.Id id = accountState.account().id();
matches.put(id, accountLoader.get(id));
}
accountLoader.fill();
List<AccountInfo> sorted = AccountInfoComparator.ORDER_NULLS_LAST.sortedCopy(matches.values());
if (!sorted.isEmpty() && result.more()) {
sorted.get(sorted.size() - 1)._moreAccounts = true;
}
return Response.ok(sorted);
} catch (QueryParseException e) {
if (suggest) {
return Response.ok(ImmutableList.of());
}
throw new BadRequestException(e.getMessage());
}
}
use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.
the class CreateChange method checkAndSanitizeChangeInput.
/**
* Checks and sanitizes the user input, e.g. check whether the input is legal; clean the input so
* that it meets the requirement for creating a change; set a field based on the global configs,
* etc.
*
* @param input the {@code ChangeInput} from the request. Note this method modify the {@code
* ChangeInput} object so that it can be reused directly by follow-up code.
* @param me the user who sent the current request to create a change.
* @throws BadRequestException if the input is not legal.
*/
private void checkAndSanitizeChangeInput(ChangeInput input, IdentifiedUser me) throws RestApiException, PermissionBackendException, IOException {
if (Strings.isNullOrEmpty(input.branch)) {
throw new BadRequestException("branch must be non-empty");
}
input.branch = RefNames.fullName(input.branch);
if (!isBranchAllowed(input.branch)) {
throw new BadRequestException("Cannot create a change on ref " + input.branch + ". Gerrit internal refs and refs/tags/* are not allowed.");
}
String subject = Strings.nullToEmpty(input.subject);
subject = subject.replaceAll("(?m)^#.*$\n?", "").trim();
if (subject.isEmpty()) {
throw new BadRequestException("commit message must be non-empty");
}
input.subject = subject;
Optional<String> changeId = getChangeIdFromMessage(input.subject);
if (changeId.isPresent()) {
if (!queryProvider.get().setLimit(1).byBranchKey(BranchNameKey.create(input.project, input.branch), Change.key(changeId.get())).isEmpty()) {
throw new ResourceConflictException(String.format("A change with Change-Id %s already exists for this branch.", changeId.get()));
}
}
if (input.topic != null) {
input.topic = Strings.emptyToNull(input.topic.trim());
}
if (input.status != null && input.status != ChangeStatus.NEW) {
throw new BadRequestException("unsupported change status");
}
if (input.baseChange != null && input.baseCommit != null) {
throw new BadRequestException("only provide one of base_change or base_commit");
}
ProjectResource projectResource = projectsCollection.parse(input.project);
// Checks whether the change to be created should be a private change.
boolean privateByDefault = projectResource.getProjectState().is(BooleanProjectConfig.PRIVATE_BY_DEFAULT);
boolean isPrivate = input.isPrivate == null ? privateByDefault : input.isPrivate;
if (isPrivate && disablePrivateChanges) {
throw new MethodNotAllowedException("private changes are disabled");
}
input.isPrivate = isPrivate;
ProjectState projectState = projectResource.getProjectState();
if (input.workInProgress == null) {
if (projectState.is(BooleanProjectConfig.WORK_IN_PROGRESS_BY_DEFAULT)) {
input.workInProgress = true;
} else {
input.workInProgress = firstNonNull(me.state().generalPreferences().workInProgressByDefault, false);
}
}
if (input.merge != null) {
if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
throw new BadRequestException("Submit type: " + submitType + " is not supported");
}
}
if (input.author != null && (Strings.isNullOrEmpty(input.author.email) || Strings.isNullOrEmpty(input.author.name))) {
throw new BadRequestException("Author must specify name and email");
}
}
use of com.google.gerrit.extensions.restapi.MethodNotAllowedException in project gerrit by GerritCodeReview.
the class DeleteVote method apply.
@Override
public Response<Object> apply(VoteResource rsrc, DeleteVoteInput input) throws RestApiException, UpdateException, IOException, ConfigInvalidException {
if (input == null) {
input = new DeleteVoteInput();
}
if (input.label != null && !rsrc.getLabel().equals(input.label)) {
throw new BadRequestException("label must match URL");
}
if (input.notify == null) {
input.notify = NotifyHandling.ALL;
}
ReviewerResource r = rsrc.getReviewer();
Change change = r.getChange();
if (r.getRevisionResource() != null && !r.getRevisionResource().isCurrent()) {
throw new MethodNotAllowedException("Cannot delete vote on non-current patch set");
}
try (BatchUpdate bu = updateFactory.create(change.getProject(), r.getChangeResource().getUser(), TimeUtil.now())) {
bu.setNotify(notifyResolver.resolve(firstNonNull(input.notify, NotifyHandling.ALL), input.notifyDetails));
bu.addOp(change.getId(), new Op(projectCache.get(r.getChange().getProject()).orElseThrow(illegalState(r.getChange().getProject())), r.getReviewerUser().state(), rsrc.getLabel(), input));
if (!input.ignoreAutomaticAttentionSetRules && !r.getReviewerUser().getAccountId().equals(currentUserProvider.get().getAccountId())) {
bu.addOp(change.getId(), attentionSetOpFactory.create(r.getReviewerUser().getAccountId(), /* reason= */
"Their vote was deleted", /* notify= */
false));
}
if (input.ignoreAutomaticAttentionSetRules) {
bu.addOp(change.getId(), new AttentionSetUnchangedOp());
}
bu.execute();
}
return Response.none();
}
Aggregations