use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.
the class ChangeQueryBuilder method reviewerByState.
public Predicate<ChangeData> reviewerByState(String who, ReviewerStateInternal state, boolean forDefaultField) throws QueryParseException, IOException, ConfigInvalidException {
Predicate<ChangeData> reviewerByEmailPredicate = null;
Address address = Address.tryParse(who);
if (address != null) {
reviewerByEmailPredicate = ReviewerByEmailPredicate.forState(address, state);
}
Predicate<ChangeData> reviewerPredicate = null;
try {
Set<Account.Id> accounts = parseAccount(who);
if (!forDefaultField || accounts.size() <= MAX_ACCOUNTS_PER_DEFAULT_FIELD) {
reviewerPredicate = Predicate.or(accounts.stream().map(id -> ReviewerPredicate.forState(id, state)).collect(toList()));
} else {
logger.atFine().log("Skipping reviewer predicate for %s in default field query" + " because the number of matched accounts (%d) exceeds the limit of %d", who, accounts.size(), MAX_ACCOUNTS_PER_DEFAULT_FIELD);
}
} catch (QueryParseException e) {
logger.atFine().log("Parsing %s as account failed: %s", who, e.getMessage());
// Propagate this exception only if we can't use 'who' to query by email
if (reviewerByEmailPredicate == null) {
throw e;
}
}
if (reviewerPredicate != null && reviewerByEmailPredicate != null) {
return Predicate.or(reviewerPredicate, reviewerByEmailPredicate);
} else if (reviewerPredicate != null) {
return reviewerPredicate;
} else if (reviewerByEmailPredicate != null) {
return reviewerByEmailPredicate;
} else {
return Predicate.any();
}
}
use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.
the class ChangeQueryBuilder method query.
@Operator
public Predicate<ChangeData> query(String value) throws QueryParseException {
// [name=]<name>[,user=<user>] || [user=<user>,][name=]<name>
PredicateArgs inputArgs = new PredicateArgs(value);
String name = null;
Account.Id account = null;
try (Repository git = args.repoManager.openRepository(args.allUsersName)) {
// [name=]<name>
if (inputArgs.keyValue.containsKey(ARG_ID_NAME)) {
name = inputArgs.keyValue.get(ARG_ID_NAME).value();
} else if (inputArgs.positional.size() == 1) {
name = Iterables.getOnlyElement(inputArgs.positional);
} else if (inputArgs.positional.size() > 1) {
throw new QueryParseException("Error parsing named query: " + value);
}
// [,user=<user>]
if (inputArgs.keyValue.containsKey(ARG_ID_USER)) {
Set<Account.Id> accounts = parseAccount(inputArgs.keyValue.get(ARG_ID_USER).value());
if (accounts != null && accounts.size() > 1) {
throw error(String.format("\"%s\" resolves to multiple accounts", inputArgs.keyValue.get(ARG_ID_USER)));
}
account = (accounts == null ? self() : Iterables.getOnlyElement(accounts));
} else {
account = self();
}
VersionedAccountQueries q = VersionedAccountQueries.forUser(account);
q.load(args.allUsersName, git);
String query = q.getQueryList().getQuery(name);
if (query != null) {
return parse(query);
}
} catch (RepositoryNotFoundException e) {
throw new QueryParseException("Unknown named query (no " + args.allUsersName + " repo): " + name, e);
} catch (IOException | ConfigInvalidException e) {
throw new QueryParseException("Error parsing named query: " + value, e);
}
throw new QueryParseException("Unknown named query: " + name);
}
use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.
the class CreateAccount method apply.
public Response<AccountInfo> apply(IdString id, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, IOException, ConfigInvalidException, PermissionBackendException {
String username = applyCaseOfUsername(id.get());
if (input.username != null && !username.equals(applyCaseOfUsername(input.username))) {
throw new BadRequestException("username must match URL");
}
if (!ExternalId.isValidUsername(username)) {
throw new BadRequestException("Invalid username '" + username + "'");
}
if (input.name == null) {
input.name = input.username;
}
Set<AccountGroup.UUID> groups = parseGroups(input.groups);
Account.Id accountId = Account.id(seq.nextAccountId());
List<ExternalId> extIds = new ArrayList<>();
if (input.email != null) {
if (!validator.isValid(input.email)) {
throw new BadRequestException("invalid email address");
}
extIds.add(externalIdFactory.createEmail(accountId, input.email));
}
extIds.add(externalIdFactory.createUsername(username, accountId, input.httpPassword));
externalIdCreators.runEach(c -> extIds.addAll(c.create(accountId, username, input.email)));
try {
accountsUpdateProvider.get().insert("Create Account via API", accountId, u -> u.setFullName(input.name).setPreferredEmail(input.email).addExternalIds(extIds));
} catch (DuplicateExternalIdKeyException e) {
if (e.getDuplicateKey().isScheme(SCHEME_USERNAME)) {
throw new ResourceConflictException("username '" + e.getDuplicateKey().id() + "' already exists");
} else if (e.getDuplicateKey().isScheme(SCHEME_MAILTO)) {
throw new UnprocessableEntityException("email '" + e.getDuplicateKey().id() + "' already exists");
} else {
// AccountExternalIdCreator returned an external ID that already exists
throw e;
}
}
for (AccountGroup.UUID groupUuid : groups) {
try {
addGroupMember(groupUuid, accountId);
} catch (NoSuchGroupException e) {
throw new UnprocessableEntityException(String.format("Group %s not found", groupUuid), e);
}
}
if (input.sshKey != null) {
try {
authorizedKeys.addKey(accountId, input.sshKey);
sshKeyCache.evict(username);
} catch (InvalidSshKeyException e) {
throw new BadRequestException(e.getMessage());
}
}
AccountLoader loader = infoLoader.create(true);
AccountInfo info = loader.get(accountId);
loader.fill();
return Response.created(info);
}
use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.
the class PostReview method apply.
public Response<ReviewResult> apply(RevisionResource revision, ReviewInput input, Instant ts) throws RestApiException, UpdateException, IOException, PermissionBackendException, ConfigInvalidException, PatchListNotAvailableException {
// Respect timestamp, but truncate at change created-on time.
ts = Ordering.natural().max(ts, revision.getChange().getCreatedOn());
if (revision.getEdit().isPresent()) {
throw new ResourceConflictException("cannot post review on edit");
}
ProjectState projectState = projectCache.get(revision.getProject()).orElseThrow(illegalState(revision.getProject()));
LabelTypes labelTypes = projectState.getLabelTypes(revision.getNotes());
logger.atFine().log("strict label checking is %s", (strictLabels ? "enabled" : "disabled"));
metrics.draftHandling.increment(input.drafts == null ? "N/A" : input.drafts.name());
input.drafts = firstNonNull(input.drafts, DraftHandling.KEEP);
logger.atFine().log("draft handling = %s", input.drafts);
if (input.onBehalfOf != null) {
revision = onBehalfOf(revision, labelTypes, input);
}
if (input.labels != null) {
checkLabels(revision, labelTypes, input.labels);
}
if (input.comments != null) {
input.comments = cleanUpComments(input.comments);
checkComments(revision, input.comments);
}
if (input.draftIdsToPublish != null) {
checkDraftIds(revision, input.draftIdsToPublish, input.drafts);
}
if (input.robotComments != null) {
input.robotComments = cleanUpComments(input.robotComments);
checkRobotComments(revision, input.robotComments);
}
if (input.notify == null) {
input.notify = defaultNotify(revision.getChange(), input);
}
logger.atFine().log("notify handling = %s", input.notify);
Map<String, ReviewerResult> reviewerJsonResults = null;
List<ReviewerModification> reviewerResults = Lists.newArrayList();
boolean hasError = false;
boolean confirm = false;
if (input.reviewers != null) {
reviewerJsonResults = Maps.newHashMap();
for (ReviewerInput reviewerInput : input.reviewers) {
ReviewerModification result = reviewerModifier.prepare(revision.getNotes(), revision.getUser(), reviewerInput, true);
reviewerJsonResults.put(reviewerInput.reviewer, result.result);
if (result.result.error != null) {
logger.atFine().log("Adding %s as reviewer failed: %s", reviewerInput.reviewer, result.result.error);
hasError = true;
continue;
}
if (result.result.confirm != null) {
logger.atFine().log("Adding %s as reviewer requires confirmation", reviewerInput.reviewer);
confirm = true;
continue;
}
logger.atFine().log("Adding %s as reviewer was prepared", reviewerInput.reviewer);
reviewerResults.add(result);
}
}
ReviewResult output = new ReviewResult();
output.reviewers = reviewerJsonResults;
if (hasError || confirm) {
output.error = ERROR_ADDING_REVIEWER;
return Response.withStatusCode(SC_BAD_REQUEST, output);
}
output.labels = input.labels;
try (BatchUpdate bu = updateFactory.create(revision.getChange().getProject(), revision.getUser(), ts)) {
Account account = revision.getUser().asIdentifiedUser().getAccount();
boolean ccOrReviewer = false;
if (input.labels != null && !input.labels.isEmpty()) {
ccOrReviewer = input.labels.values().stream().anyMatch(v -> v != 0);
if (ccOrReviewer) {
logger.atFine().log("calling user is cc/reviewer on the change due to voting on a label");
}
}
if (!ccOrReviewer) {
// Check if user was already CCed or reviewing prior to this review.
ReviewerSet currentReviewers = approvalsUtil.getReviewers(revision.getChangeResource().getNotes());
ccOrReviewer = currentReviewers.all().contains(account.id());
if (ccOrReviewer) {
logger.atFine().log("calling user is already cc/reviewer on the change");
}
}
// Apply reviewer changes first. Revision emails should be sent to the
// updated set of reviewers. Also keep track of whether the user added
// themselves as a reviewer or to the CC list.
logger.atFine().log("adding reviewer additions");
for (ReviewerModification reviewerResult : reviewerResults) {
// Send a single batch email below.
reviewerResult.op.suppressEmail();
// Send events below, if possible as batch.
reviewerResult.op.suppressEvent();
bu.addOp(revision.getChange().getId(), reviewerResult.op);
if (!ccOrReviewer && reviewerResult.reviewers.contains(account)) {
logger.atFine().log("calling user is explicitly added as reviewer or CC");
ccOrReviewer = true;
}
}
if (!ccOrReviewer) {
// User posting this review isn't currently in the reviewer or CC list,
// isn't being explicitly added, and isn't voting on any label.
// Automatically CC them on this change so they receive replies.
logger.atFine().log("CCing calling user");
ReviewerModification selfAddition = reviewerModifier.ccCurrentUser(revision.getUser(), revision);
selfAddition.op.suppressEmail();
selfAddition.op.suppressEvent();
bu.addOp(revision.getChange().getId(), selfAddition.op);
}
// Add WorkInProgressOp if requested.
if ((input.ready || input.workInProgress) && didWorkInProgressChange(revision.getChange().isWorkInProgress(), input)) {
if (input.ready && input.workInProgress) {
output.error = ERROR_WIP_READY_MUTUALLY_EXCLUSIVE;
return Response.withStatusCode(SC_BAD_REQUEST, output);
}
revision.getChangeResource().permissions().check(ChangePermission.TOGGLE_WORK_IN_PROGRESS_STATE);
if (input.ready) {
output.ready = true;
}
logger.atFine().log("setting work-in-progress to %s", input.workInProgress);
WorkInProgressOp wipOp = workInProgressOpFactory.create(input.workInProgress, new WorkInProgressOp.Input());
wipOp.suppressEmail();
bu.addOp(revision.getChange().getId(), wipOp);
}
// Add the review op.
logger.atFine().log("posting review");
bu.addOp(revision.getChange().getId(), new Op(projectState, revision.getPatchSet().id(), input));
// Notify based on ReviewInput, ignoring the notify settings from any ReviewerInputs.
NotifyResolver.Result notify = notifyResolver.resolve(input.notify, input.notifyDetails);
bu.setNotify(notify);
// Adjust the attention set based on the input
replyAttentionSetUpdates.updateAttentionSet(bu, revision.getNotes(), input, revision.getUser());
bu.execute();
// Re-read change to take into account results of the update.
ChangeData cd = changeDataFactory.create(revision.getProject(), revision.getChange().getId());
for (ReviewerModification reviewerResult : reviewerResults) {
reviewerResult.gatherResults(cd);
}
// Sending emails and events from ReviewersOps was suppressed so we can send a single batch
// email/event here.
batchEmailReviewers(revision.getUser(), revision.getChange(), reviewerResults, notify);
batchReviewerEvents(revision.getUser(), cd, revision.getPatchSet(), reviewerResults, ts);
}
return Response.ok(output);
}
use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.
the class ReviewerRecommender method baseRanking.
/**
* @param baseWeight The weight applied to the ordering of the reviewers.
* @param query Query to match. For example, it can try to match all users that start with "Ab".
* @param candidateList The list of candidates based on the query. If query is empty, this list is
* also empty.
* @return Map of account ids that match the query and their appropriate ranking (the better the
* ranking, the better it is to suggest them as reviewers).
* @throws IOException Can't find owner="self" account.
* @throws ConfigInvalidException Can't find owner="self" account.
*/
private Map<Account.Id, MutableDouble> baseRanking(double baseWeight, String query, List<Account.Id> candidateList) throws IOException, ConfigInvalidException {
int numberOfRelevantChanges = config.getInt("suggest", "relevantChanges", 50);
// Get the user's last numberOfRelevantChanges changes, check reviewers
try {
List<ChangeData> result = queryProvider.get().setLimit(numberOfRelevantChanges).setRequestedFields(ChangeField.REVIEWER).query(changeQueryBuilder.owner("self"));
Map<Account.Id, MutableDouble> suggestions = new LinkedHashMap<>();
// Put those candidates at the bottom of the list
candidateList.stream().forEach(id -> suggestions.put(id, new MutableDouble(0)));
for (ChangeData cd : result) {
for (Account.Id reviewer : cd.reviewers().all()) {
if (accountMatchesQuery(reviewer, query)) {
suggestions.computeIfAbsent(reviewer, (ignored) -> new MutableDouble(0)).add(baseWeight);
}
}
}
return suggestions;
} catch (QueryParseException e) {
// Unhandled, because owner:self will never provoke a QueryParseException
logger.atSevere().withCause(e).log("Exception while suggesting reviewers");
return new HashMap<>();
}
}
Aggregations