Search in sources :

Example 66 with CurrentUser

use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.

the class ActionJson method toActionMap.

private Map<String, ActionInfo> toActionMap(ChangeData changeData, List<ActionVisitor> visitors, ChangeInfo changeInfo) {
    CurrentUser user = userProvider.get();
    Map<String, ActionInfo> out = new LinkedHashMap<>();
    if (!user.isIdentifiedUser()) {
        return out;
    }
    Iterable<UiAction.Description> descs = uiActions.from(changeViews, changeResourceFactory.create(changeData, user));
    // resulting action map.
    if (!changeData.change().isAbandoned()) {
        UiAction.Description descr = new UiAction.Description();
        PrivateInternals_UiActionDescription.setId(descr, "followup");
        PrivateInternals_UiActionDescription.setMethod(descr, "POST");
        descr.setTitle("Create follow-up change");
        descr.setLabel("Follow-Up");
        descs = Iterables.concat(descs, Collections.singleton(descr));
    }
    ACTION: for (UiAction.Description d : descs) {
        ActionInfo actionInfo = new ActionInfo(d);
        for (ActionVisitor visitor : visitors) {
            if (!visitor.visit(d.getId(), actionInfo, changeInfo)) {
                continue ACTION;
            }
        }
        out.put(d.getId(), actionInfo);
    }
    return out;
}
Also used : PrivateInternals_UiActionDescription(com.google.gerrit.extensions.webui.PrivateInternals_UiActionDescription) CurrentUser(com.google.gerrit.server.CurrentUser) ActionVisitor(com.google.gerrit.extensions.api.changes.ActionVisitor) ActionInfo(com.google.gerrit.extensions.common.ActionInfo) UiAction(com.google.gerrit.extensions.webui.UiAction) LinkedHashMap(java.util.LinkedHashMap)

Example 67 with CurrentUser

use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.

the class EventBroker method fireEvent.

protected void fireEvent(Change change, ChangeEvent event) throws PermissionBackendException {
    setInstanceIdWhenEmpty(event);
    for (PluginSetEntryContext<UserScopedEventListener> c : listeners) {
        CurrentUser user = c.call(UserScopedEventListener::getUser);
        if (isVisibleTo(change, user)) {
            c.run(l -> l.onEvent(event));
        }
    }
    fireEventForUnrestrictedListeners(event);
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser)

Example 68 with CurrentUser

use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.

the class SubmitWithStickyApprovalDiff method apply.

public String apply(ChangeNotes notes, CurrentUser currentUser) throws AuthException, IOException, PermissionBackendException, InvalidChangeOperationException {
    PatchSet currentPatchset = notes.getCurrentPatchSet();
    PatchSet.Id latestApprovedPatchsetId = getLatestApprovedPatchsetId(notes);
    if (latestApprovedPatchsetId.get() == currentPatchset.id().get()) {
        // If the latest approved patchset is the current patchset, no need to return anything.
        return "";
    }
    StringBuilder diff = new StringBuilder(String.format("\n\n%d is the latest approved patch-set.\n", latestApprovedPatchsetId.get()));
    Map<String, FileDiffOutput> modifiedFiles = listModifiedFiles(notes.getProjectName(), currentPatchset, notes.getPatchSets().get(latestApprovedPatchsetId));
    // To make the message a bit more concise, we skip the magic files.
    List<FileDiffOutput> modifiedFilesList = modifiedFiles.values().stream().filter(p -> !Patch.isMagic(p.newPath().orElse(""))).collect(Collectors.toList());
    if (modifiedFilesList.isEmpty()) {
        diff.append("No files were changed between the latest approved patch-set and the submitted one.\n");
        return diff.toString();
    }
    diff.append("The change was submitted with unreviewed changes in the following files:\n\n");
    TemporaryBuffer.Heap buffer = new TemporaryBuffer.Heap(Math.min(HEAP_EST_SIZE, DEFAULT_POST_SUBMIT_SIZE_LIMIT), DEFAULT_POST_SUBMIT_SIZE_LIMIT);
    try (Repository repository = repositoryManager.openRepository(notes.getProjectName());
        DiffFormatter formatter = new DiffFormatter(buffer)) {
        formatter.setRepository(repository);
        formatter.setDetectRenames(true);
        boolean isDiffTooLarge = false;
        List<String> formatterResult = null;
        try {
            formatter.format(modifiedFilesList.get(0).oldCommitId(), modifiedFilesList.get(0).newCommitId());
            // This returns the diff for all the files.
            formatterResult = Arrays.stream(RawParseUtils.decode(buffer.toByteArray()).split("\n")).collect(Collectors.toList());
        } catch (IOException e) {
            if (JGitText.get().inMemoryBufferLimitExceeded.equals(e.getMessage())) {
                isDiffTooLarge = true;
            } else {
                throw e;
            }
        }
        if (formatterResult != null) {
            int addedBytes = formatterResult.stream().mapToInt(String::length).sum();
            if (!CommentCumulativeSizeValidator.isEnoughSpace(notes, addedBytes, maxCumulativeSize)) {
                isDiffTooLarge = true;
            }
        }
        for (FileDiffOutput fileDiff : modifiedFilesList) {
            diff.append(getDiffForFile(notes, currentPatchset.id(), latestApprovedPatchsetId, fileDiff, currentUser, formatterResult, isDiffTooLarge));
        }
    }
    return diff.toString();
}
Also used : Patch(com.google.gerrit.entities.Patch) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Arrays(java.util.Arrays) LabelId(com.google.gerrit.entities.LabelId) Whitespace(com.google.gerrit.extensions.client.DiffPreferencesInfo.Whitespace) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) JGitText(org.eclipse.jgit.internal.JGitText) ArrayList(java.util.ArrayList) PatchSetApproval(com.google.gerrit.entities.PatchSetApproval) Config(org.eclipse.jgit.lib.Config) PatchScript(com.google.gerrit.common.data.PatchScript) ChangeType(com.google.gerrit.entities.Patch.ChangeType) CommentCumulativeSizeValidator(com.google.gerrit.server.git.validators.CommentCumulativeSizeValidator) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) LabelType(com.google.gerrit.entities.LabelType) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) PatchSet(com.google.gerrit.entities.PatchSet) ProjectCache.illegalState(com.google.gerrit.server.project.ProjectCache.illegalState) DiffPreferencesInfo(com.google.gerrit.extensions.client.DiffPreferencesInfo) CurrentUser(com.google.gerrit.server.CurrentUser) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) LargeObjectException(com.google.gerrit.server.git.LargeObjectException) StorageException(com.google.gerrit.exceptions.StorageException) ProjectState(com.google.gerrit.server.project.ProjectState) RawParseUtils(org.eclipse.jgit.util.RawParseUtils) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) DiffInfoCreator(com.google.gerrit.server.diff.DiffInfoCreator) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) Repository(org.eclipse.jgit.lib.Repository) PatchSet(com.google.gerrit.entities.PatchSet) IOException(java.io.IOException) FileDiffOutput(com.google.gerrit.server.patch.filediff.FileDiffOutput) Repository(org.eclipse.jgit.lib.Repository) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) DiffFormatter(org.eclipse.jgit.diff.DiffFormatter)

Example 69 with CurrentUser

use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.

the class PostReview method batchReviewerEvents.

private void batchReviewerEvents(CurrentUser user, ChangeData cd, PatchSet patchSet, List<ReviewerModification> reviewerModifications, Instant when) {
    List<AccountState> newlyAddedReviewers = new ArrayList<>();
    // There are no events for CCs and reviewers added/deleted by email.
    for (ReviewerModification modification : reviewerModifications) {
        Result reviewerAdditionResult = modification.op.getResult();
        if (modification.state() == ReviewerState.REVIEWER) {
            newlyAddedReviewers.addAll(reviewerAdditionResult.addedReviewers().stream().map(psa -> psa.accountId()).map(accountId -> accountCache.get(accountId)).flatMap(Streams::stream).collect(toList()));
        } else if (modification.state() == ReviewerState.REMOVED) {
            // There is no batch event for reviewer removals, hence fire the event for each
            // modification that deleted a reviewer immediately.
            modification.op.sendEvent();
        }
    }
    // Fire a batch event for all newly added reviewers.
    reviewerAdded.fire(cd, patchSet, newlyAddedReviewers, user.asIdentifiedUser().state(), when);
}
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) ArrayList(java.util.ArrayList) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) AccountState(com.google.gerrit.server.account.AccountState) Streams(com.google.common.collect.Streams) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) Result(com.google.gerrit.server.change.ReviewerOp.Result)

Example 70 with CurrentUser

use of com.google.gerrit.server.CurrentUser in project gerrit by GerritCodeReview.

the class QueryChanges method skipVisibility.

@Option(name = "--skip-visibility", usage = "Skip visibility check, only for administrators")
public void skipVisibility(boolean on) throws AuthException, PermissionBackendException {
    if (on) {
        CurrentUser user = userProvider.get();
        permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
    }
    skipVisibility = on;
}
Also used : CurrentUser(com.google.gerrit.server.CurrentUser) ListChangesOption(com.google.gerrit.extensions.client.ListChangesOption) ListOption(com.google.gerrit.extensions.client.ListOption) Option(org.kohsuke.args4j.Option)

Aggregations

CurrentUser (com.google.gerrit.server.CurrentUser)73 AuthException (com.google.gerrit.extensions.restapi.AuthException)21 Account (com.google.gerrit.reviewdb.client.Account)11 Account (com.google.gerrit.entities.Account)10 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)10 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)10 ChangeData (com.google.gerrit.server.query.change.ChangeData)10 Change (com.google.gerrit.entities.Change)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)9 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)9 IOException (java.io.IOException)9 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)8 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)8 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)8 Provider (com.google.inject.Provider)8 HashMap (java.util.HashMap)8 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 Test (org.junit.Test)6 PatchSet (com.google.gerrit.entities.PatchSet)5