Search in sources :

Example 96 with Account

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();
    }
}
Also used : AllUsersName(com.google.gerrit.server.config.AllUsersName) GroupBackend(com.google.gerrit.server.account.GroupBackend) Arrays(java.util.Arrays) ProjectCache(com.google.gerrit.server.project.ProjectCache) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) Inject(com.google.inject.Inject) OperatorAliasConfig(com.google.gerrit.server.config.OperatorAliasConfig) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) Config(org.eclipse.jgit.lib.Config) ChangeTriplet(com.google.gerrit.server.change.ChangeTriplet) VersionedAccountQueries(com.google.gerrit.server.account.VersionedAccountQueries) Map(java.util.Map) RefNames(com.google.gerrit.entities.RefNames) ProvisionException(com.google.inject.ProvisionException) Splitter(com.google.common.base.Splitter) Collectors.toSet(java.util.stream.Collectors.toSet) FieldDef(com.google.gerrit.index.FieldDef) Schema(com.google.gerrit.index.Schema) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Collection(java.util.Collection) LimitPredicate(com.google.gerrit.index.query.LimitPredicate) Account(com.google.gerrit.entities.Account) Set(java.util.Set) SubmitRecord(com.google.gerrit.entities.SubmitRecord) BranchNameKey(com.google.gerrit.entities.BranchNameKey) GroupReference(com.google.gerrit.entities.GroupReference) Objects(java.util.Objects) List(java.util.List) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) CHANGE_ID_PATTERN(com.google.gerrit.entities.Change.CHANGE_ID_PATTERN) ChangeData.asChanges(com.google.gerrit.server.query.change.ChangeData.asChanges) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) SubmitDryRun(com.google.gerrit.server.submit.SubmitDryRun) Optional(java.util.Optional) Providers(com.google.inject.util.Providers) Pattern(java.util.regex.Pattern) SchemaUtil(com.google.gerrit.index.SchemaUtil) ValOp(com.google.gerrit.server.query.change.PredicateArgs.ValOp) FluentLogger(com.google.common.flogger.FluentLogger) QueryRequiresAuthException(com.google.gerrit.index.query.QueryRequiresAuthException) ChangeIndexRewriter(com.google.gerrit.server.index.change.ChangeIndexRewriter) AccountCache(com.google.gerrit.server.account.AccountCache) Iterables(com.google.common.collect.Iterables) IndexConfig(com.google.gerrit.index.IndexConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) MergeabilityComputationBehavior(com.google.gerrit.server.change.MergeabilityComputationBehavior) GroupBackends(com.google.gerrit.server.account.GroupBackends) HasOperandAliasConfig(com.google.gerrit.server.config.HasOperandAliasConfig) CommentsUtil(com.google.gerrit.server.CommentsUtil) Function(java.util.function.Function) Enums(com.google.common.base.Enums) GroupMembers(com.google.gerrit.server.account.GroupMembers) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Lists(com.google.common.collect.Lists) AccountResolver.isSelf(com.google.gerrit.server.account.AccountResolver.isSelf) GroupDescription(com.google.gerrit.entities.GroupDescription) QueryParseException(com.google.gerrit.index.query.QueryParseException) UnresolvableAccountException(com.google.gerrit.server.account.AccountResolver.UnresolvableAccountException) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Address(com.google.gerrit.entities.Address) Predicate(com.google.gerrit.index.query.Predicate) QueryBuilder(com.google.gerrit.index.query.QueryBuilder) AccountGroup(com.google.gerrit.entities.AccountGroup) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResolver(com.google.gerrit.server.account.AccountResolver) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) SubmitRule(com.google.gerrit.server.rules.SubmitRule) NotSignedInException(com.google.gerrit.exceptions.NotSignedInException) ExperimentFeatures(com.google.gerrit.server.experiments.ExperimentFeatures) PatchListCache(com.google.gerrit.server.patch.PatchListCache) StorageException(com.google.gerrit.exceptions.StorageException) IOException(java.io.IOException) VersionedAccountDestinations(com.google.gerrit.server.account.VersionedAccountDestinations) Ints(com.google.common.primitives.Ints) ChildProjects(com.google.gerrit.server.project.ChildProjects) ChangeField(com.google.gerrit.server.index.change.ChangeField) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.entities.Project) ChangeIndexCollection(com.google.gerrit.server.index.change.ChangeIndexCollection) VisibleForTesting(com.google.common.annotations.VisibleForTesting) AccountState(com.google.gerrit.server.account.AccountState) ChangeIndex(com.google.gerrit.server.index.change.ChangeIndex) Collections(java.util.Collections) GERRIT_BACKEND_REQUEST_FEATURE_COMPUTE_FROM_ALL_USERS_REPOSITORY(com.google.gerrit.server.experiments.ExperimentFeaturesConstants.GERRIT_BACKEND_REQUEST_FEATURE_COMPUTE_FROM_ALL_USERS_REPOSITORY) Repository(org.eclipse.jgit.lib.Repository) StarredChangesUtil(com.google.gerrit.server.StarredChangesUtil) Address(com.google.gerrit.entities.Address) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Example 97 with Account

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);
}
Also used : Account(com.google.gerrit.entities.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) VersionedAccountQueries(com.google.gerrit.server.account.VersionedAccountQueries) QueryParseException(com.google.gerrit.index.query.QueryParseException) Repository(org.eclipse.jgit.lib.Repository)

Example 98 with Account

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);
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) IdString(com.google.gerrit.extensions.restapi.IdString) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) InvalidSshKeyException(com.google.gerrit.exceptions.InvalidSshKeyException) AccountGroup(com.google.gerrit.entities.AccountGroup) AccountLoader(com.google.gerrit.server.account.AccountLoader) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 99 with Account

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);
}
Also used : ON_BEHALF_OF(com.google.gerrit.server.permissions.LabelPermission.ForUser.ON_BEHALF_OF) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Comment(com.google.gerrit.entities.Comment) FixSuggestion(com.google.gerrit.entities.FixSuggestion) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerSet(com.google.gerrit.server.ReviewerSet) DiffSummaryKey(com.google.gerrit.server.patch.DiffSummaryKey) Config(org.eclipse.jgit.lib.Config) Map(java.util.Map) FixReplacement(com.google.gerrit.entities.FixReplacement) DraftHandling(com.google.gerrit.extensions.api.changes.ReviewInput.DraftHandling) Side(com.google.gerrit.extensions.client.Side) Metadata(com.google.gerrit.server.logging.Metadata) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) TraceContext(com.google.gerrit.server.logging.TraceContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) Stream(java.util.stream.Stream) CommentAdded(com.google.gerrit.server.extensions.events.CommentAdded) AutoValue(com.google.auto.value.AutoValue) DiffSummary(com.google.gerrit.server.patch.DiffSummary) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) Counter1(com.google.gerrit.metrics.Counter1) MetricMaker(com.google.gerrit.metrics.MetricMaker) PatchListKey(com.google.gerrit.server.patch.PatchListKey) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) AccountCache(com.google.gerrit.server.account.AccountCache) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Collectors.groupingBy(java.util.stream.Collectors.groupingBy) CommentsUtil(com.google.gerrit.server.CommentsUtil) CommentForValidation(com.google.gerrit.extensions.validators.CommentForValidation) Response(com.google.gerrit.extensions.restapi.Response) ArrayList(java.util.ArrayList) PATCHSET_LEVEL(com.google.gerrit.entities.Patch.PATCHSET_LEVEL) Strings(com.google.common.base.Strings) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput) Lists(com.google.common.collect.Lists) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) Description(com.google.gerrit.metrics.Description) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) PatchSet(com.google.gerrit.entities.PatchSet) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) Address(com.google.gerrit.entities.Address) REVIEWER(com.google.gerrit.server.notedb.ReviewerStateInternal.REVIEWER) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) HashCode(com.google.common.hash.HashCode) Result(com.google.gerrit.server.change.ReviewerOp.Result) PatchListCache(com.google.gerrit.server.patch.PatchListCache) StorageException(com.google.gerrit.exceptions.StorageException) CommentValidationFailure(com.google.gerrit.extensions.validators.CommentValidationFailure) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) RobotCommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.RobotCommentInput) ChangeUpdate(com.google.gerrit.server.notedb.ChangeUpdate) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ReviewInput(com.google.gerrit.extensions.api.changes.ReviewInput) LabelVote(com.google.gerrit.server.util.LabelVote) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) CommentValidator(com.google.gerrit.extensions.validators.CommentValidator) AccountState(com.google.gerrit.server.account.AccountState) Patch(com.google.gerrit.entities.Patch) Inject(com.google.inject.Inject) HumanComment(com.google.gerrit.entities.HumanComment) UpdateException(com.google.gerrit.server.update.UpdateException) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) LabelTypes(com.google.gerrit.entities.LabelTypes) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) LabelType(com.google.gerrit.entities.LabelType) AuthException(com.google.gerrit.extensions.restapi.AuthException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) Collectors.toSet(java.util.stream.Collectors.toSet) Timestamp(java.sql.Timestamp) Collection(java.util.Collection) Account(com.google.gerrit.entities.Account) Streams(com.google.common.collect.Streams) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) Objects(java.util.Objects) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) FixSuggestionInfo(com.google.gerrit.extensions.common.FixSuggestionInfo) Url(com.google.gerrit.extensions.restapi.Url) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) LabelPermission(com.google.gerrit.server.permissions.LabelPermission) PatchListNotAvailableException(com.google.gerrit.server.patch.PatchListNotAvailableException) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) CommentValidationContext(com.google.gerrit.extensions.validators.CommentValidationContext) PublishCommentUtil(com.google.gerrit.server.PublishCommentUtil) ChangePermission(com.google.gerrit.server.permissions.ChangePermission) Hashing(com.google.common.hash.Hashing) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) HashSet(java.util.HashSet) CommentsRejectedException(com.google.gerrit.server.update.CommentsRejectedException) ImmutableList(com.google.common.collect.ImmutableList) ChangeResource(com.google.gerrit.server.change.ChangeResource) PostUpdateContext(com.google.gerrit.server.update.PostUpdateContext) CommentInput(com.google.gerrit.extensions.api.changes.ReviewInput.CommentInput) Range(com.google.gerrit.extensions.client.Comment.Range) RobotComment(com.google.gerrit.entities.RobotComment) Field(com.google.gerrit.metrics.Field) Change(com.google.gerrit.entities.Change) ChangeUtil(com.google.gerrit.server.ChangeUtil) ChangeContext(com.google.gerrit.server.update.ChangeContext) ModifyReviewersEmail(com.google.gerrit.server.change.ModifyReviewersEmail) FixReplacementInfo(com.google.gerrit.extensions.common.FixReplacementInfo) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResolver(com.google.gerrit.server.account.AccountResolver) Iterator(java.util.Iterator) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ReviewerAdded(com.google.gerrit.server.extensions.events.ReviewerAdded) ProjectState(com.google.gerrit.server.project.ProjectState) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) Collectors.toList(java.util.stream.Collectors.toList) Ordering(com.google.common.collect.Ordering) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RevisionResource(com.google.gerrit.server.change.RevisionResource) PatchSetUtil(com.google.gerrit.server.PatchSetUtil) EmailReviewComments(com.google.gerrit.server.change.EmailReviewComments) Collections(java.util.Collections) Account(com.google.gerrit.entities.Account) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) LabelTypes(com.google.gerrit.entities.LabelTypes) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) WorkInProgressOp(com.google.gerrit.server.change.WorkInProgressOp) ChangeData(com.google.gerrit.server.query.change.ChangeData) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ReviewerSet(com.google.gerrit.server.ReviewerSet) ProjectState(com.google.gerrit.server.project.ProjectState) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) ReviewerInput(com.google.gerrit.extensions.api.changes.ReviewerInput)

Example 100 with Account

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<>();
    }
}
Also used : AccountCache(com.google.gerrit.server.account.AccountCache) FanOutExecutor(com.google.gerrit.server.FanOutExecutor) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) MutableDouble(org.apache.commons.lang3.mutable.MutableDouble) Config(org.eclipse.jgit.lib.Config) Future(java.util.concurrent.Future) ImmutableList(com.google.common.collect.ImmutableList) QueryParseException(com.google.gerrit.index.query.QueryParseException) Map(java.util.Map) ExecutorService(java.util.concurrent.ExecutorService) SuggestedReviewer(com.google.gerrit.server.change.SuggestedReviewer) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Iterator(java.util.Iterator) ReviewerStateInternal(com.google.gerrit.server.notedb.ReviewerStateInternal) ProjectState(com.google.gerrit.server.project.ProjectState) Account(com.google.gerrit.entities.Account) Set(java.util.Set) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) ApprovalsUtil(com.google.gerrit.server.approval.ApprovalsUtil) PluginMapContext(com.google.gerrit.server.plugincontext.PluginMapContext) ChangeField(com.google.gerrit.server.index.change.ChangeField) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) ChangeData(com.google.gerrit.server.query.change.ChangeData) Provider(com.google.inject.Provider) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Stream(java.util.stream.Stream) ChangeQueryBuilder(com.google.gerrit.server.query.change.ChangeQueryBuilder) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Optional(java.util.Optional) AccountState(com.google.gerrit.server.account.AccountState) Collections(java.util.Collections) FluentLogger(com.google.common.flogger.FluentLogger) ReviewerSuggestion(com.google.gerrit.server.change.ReviewerSuggestion) Account(com.google.gerrit.entities.Account) MutableDouble(org.apache.commons.lang3.mutable.MutableDouble) ChangeData(com.google.gerrit.server.query.change.ChangeData) LinkedHashMap(java.util.LinkedHashMap) QueryParseException(com.google.gerrit.index.query.QueryParseException)

Aggregations

Account (com.google.gerrit.entities.Account)124 Test (org.junit.Test)59 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)37 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)35 AccountState (com.google.gerrit.server.account.AccountState)35 IOException (java.io.IOException)31 Repository (org.eclipse.jgit.lib.Repository)31 Change (com.google.gerrit.entities.Change)28 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 Inject (com.google.inject.Inject)25 PersonIdent (org.eclipse.jgit.lib.PersonIdent)25 List (java.util.List)24 ArrayList (java.util.ArrayList)23 HashSet (java.util.HashSet)23 Set (java.util.Set)22 RefNames (com.google.gerrit.entities.RefNames)21 AuthRequest (com.google.gerrit.server.account.AuthRequest)21 Map (java.util.Map)21 ObjectId (org.eclipse.jgit.lib.ObjectId)21 ImmutableList (com.google.common.collect.ImmutableList)20