Search in sources :

Example 71 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class MergeOp method integrateIntoHistory.

private void integrateIntoHistory(ChangeSet cs, SubmissionExecutor submissionExecutor) throws RestApiException, UpdateException {
    checkArgument(!cs.furtherHiddenChanges(), "cannot integrate hidden changes into history");
    logger.atFine().log("Beginning merge attempt on %s", cs);
    Map<BranchNameKey, BranchBatch> toSubmit = new HashMap<>();
    ListMultimap<BranchNameKey, ChangeData> cbb;
    try {
        cbb = cs.changesByBranch();
    } catch (StorageException e) {
        throw new StorageException("Error reading changes to submit", e);
    }
    Set<BranchNameKey> branches = cbb.keySet();
    for (BranchNameKey branch : branches) {
        OpenRepo or = openRepo(branch.project());
        if (or != null) {
            toSubmit.put(branch, validateChangeList(or, cbb.get(branch)));
        }
    }
    // Done checks that don't involve running submit strategies.
    commitStatus.maybeFailVerbose();
    try {
        SubscriptionGraph subscriptionGraph = subscriptionGraphFactory.compute(branches, orm);
        SubmoduleCommits submoduleCommits = submoduleCommitsFactory.create(orm);
        UpdateOrderCalculator updateOrderCalculator = new UpdateOrderCalculator(subscriptionGraph);
        List<SubmitStrategy> strategies = getSubmitStrategies(toSubmit, updateOrderCalculator, submoduleCommits, subscriptionGraph, dryrun);
        this.allProjects = updateOrderCalculator.getProjectsInOrder();
        List<BatchUpdate> batchUpdates = orm.batchUpdates(allProjects);
        // Group batch updates by project
        Map<Project.NameKey, BatchUpdate> batchUpdatesByProject = batchUpdates.stream().collect(Collectors.toMap(b -> b.getProject(), Function.identity()));
        for (Map.Entry<Change.Id, ChangeData> entry : cs.changesById().entrySet()) {
            Project.NameKey project = entry.getValue().project();
            Change.Id changeId = entry.getKey();
            ChangeData cd = entry.getValue();
            batchUpdatesByProject.get(project).addOp(changeId, storeSubmitRequirementsOpFactory.create(cd.submitRequirementsIncludingLegacy().values(), cd));
        }
        try {
            submissionExecutor.setAdditionalBatchUpdateListeners(ImmutableList.of(new SubmitStrategyListener(submitInput, strategies, commitStatus)));
            submissionExecutor.execute(batchUpdates);
        } finally {
            // If the BatchUpdate fails it can be that merging some of the changes was actually
            // successful. This is why we must to collect the updated changes also when an
            // exception was thrown.
            strategies.forEach(s -> updatedChanges.putAll(s.getUpdatedChanges()));
            // Do not leave executed BatchUpdates in the OpenRepos
            if (!dryrun) {
                orm.resetUpdates(ImmutableSet.copyOf(this.allProjects));
            }
        }
    } catch (NoSuchProjectException e) {
        throw new ResourceNotFoundException(e.getMessage());
    } catch (IOException e) {
        throw new StorageException(e);
    } catch (SubmoduleConflictException e) {
        throw new IntegrationConflictException(e.getMessage(), e);
    } catch (UpdateException e) {
        if (e.getCause() instanceof LockFailureException) {
            // as to be unnoticeable, assuming RetryHelper is retrying sufficiently.
            throw e;
        }
        // inner IntegrationConflictException to a ResourceConflictException.
        if (e.getCause() instanceof IntegrationConflictException) {
            throw (IntegrationConflictException) e.getCause();
        }
        throw new MergeUpdateException(genericMergeError(cs), e);
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) SuperprojectUpdateOnSubmission(com.google.gerrit.server.update.SuperprojectUpdateOnSubmission) ListMultimap(com.google.common.collect.ListMultimap) MultimapBuilder(com.google.common.collect.MultimapBuilder) InternalUser(com.google.gerrit.server.InternalUser) Inject(com.google.inject.Inject) SubmissionId(com.google.gerrit.entities.SubmissionId) UpdateException(com.google.gerrit.server.update.UpdateException) SubmitRequirementResult(com.google.gerrit.entities.SubmitRequirementResult) MergeUpdateException(com.google.gerrit.exceptions.MergeUpdateException) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) SubmitInput(com.google.gerrit.extensions.api.changes.SubmitInput) Map(java.util.Map) AuthException(com.google.gerrit.extensions.restapi.AuthException) StoreSubmitRequirementsOp(com.google.gerrit.server.notedb.StoreSubmitRequirementsOp) RetryHelper(com.google.gerrit.server.update.RetryHelper) MergeTip(com.google.gerrit.server.git.MergeTip) Collectors.toSet(java.util.stream.Collectors.toSet) ImmutableSetMultimap(com.google.common.collect.ImmutableSetMultimap) ImmutableSet(com.google.common.collect.ImmutableSet) Status(com.google.gerrit.entities.Change.Status) ImmutableMap(com.google.common.collect.ImmutableMap) TraceContext(com.google.gerrit.server.logging.TraceContext) SubmitType(com.google.gerrit.extensions.client.SubmitType) Collection(java.util.Collection) Set(java.util.Set) Constants(org.eclipse.jgit.lib.Constants) CodeReviewCommit(com.google.gerrit.server.git.CodeReviewCommit) Instant(java.time.Instant) RetryListener(com.github.rholder.retry.RetryListener) SubmitRecord(com.google.gerrit.entities.SubmitRecord) Collectors(java.util.stream.Collectors) BranchNameKey(com.google.gerrit.entities.BranchNameKey) NotifyHandling(com.google.gerrit.extensions.api.changes.NotifyHandling) SubmitTypeRecord(com.google.gerrit.entities.SubmitTypeRecord) ChangeData(com.google.gerrit.server.query.change.ChangeData) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Ref(org.eclipse.jgit.lib.Ref) AutoValue(com.google.auto.value.AutoValue) InternalChangeQuery(com.google.gerrit.server.query.change.InternalChangeQuery) Optional(java.util.Optional) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) Counter0(com.google.gerrit.metrics.Counter0) MetricMaker(com.google.gerrit.metrics.MetricMaker) BatchUpdateOp(com.google.gerrit.server.update.BatchUpdateOp) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) ChangeMessagesUtil(com.google.gerrit.server.ChangeMessagesUtil) Singleton(com.google.inject.Singleton) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) OpenRepo(com.google.gerrit.server.submit.MergeOpRepoManager.OpenRepo) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) HashMap(java.util.HashMap) Function(java.util.function.Function) SubmissionListener(com.google.gerrit.server.update.SubmissionListener) MergeValidators(com.google.gerrit.server.git.validators.MergeValidators) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) SubmissionExecutor(com.google.gerrit.server.update.SubmissionExecutor) Description(com.google.gerrit.metrics.Description) Objects.requireNonNull(java.util.Objects.requireNonNull) Change(com.google.gerrit.entities.Change) PatchSet(com.google.gerrit.entities.PatchSet) Comparator.comparing(java.util.Comparator.comparing) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ChangeUtil(com.google.gerrit.server.ChangeUtil) LockFailureException(com.google.gerrit.git.LockFailureException) ChangeContext(com.google.gerrit.server.update.ChangeContext) MergeValidationException(com.google.gerrit.server.git.validators.MergeValidationException) LinkedHashSet(java.util.LinkedHashSet) SubmitRequirement(com.google.gerrit.entities.SubmitRequirement) NotifyResolver(com.google.gerrit.server.change.NotifyResolver) OpenBranch(com.google.gerrit.server.submit.MergeOpRepoManager.OpenBranch) StorageException(com.google.gerrit.exceptions.StorageException) Attempt(com.github.rholder.retry.Attempt) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) SubmitRuleOptions(com.google.gerrit.server.project.SubmitRuleOptions) SetMultimap(com.google.common.collect.SetMultimap) ObjectId(org.eclipse.jgit.lib.ObjectId) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.entities.Project) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) RequestId(com.google.gerrit.server.logging.RequestId) HashMap(java.util.HashMap) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) LockFailureException(com.google.gerrit.git.LockFailureException) BranchNameKey(com.google.gerrit.entities.BranchNameKey) UpdateException(com.google.gerrit.server.update.UpdateException) MergeUpdateException(com.google.gerrit.exceptions.MergeUpdateException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Change(com.google.gerrit.entities.Change) IOException(java.io.IOException) ChangeData(com.google.gerrit.server.query.change.ChangeData) BranchNameKey(com.google.gerrit.entities.BranchNameKey) MergeUpdateException(com.google.gerrit.exceptions.MergeUpdateException) Project(com.google.gerrit.entities.Project) OpenRepo(com.google.gerrit.server.submit.MergeOpRepoManager.OpenRepo) SubmissionId(com.google.gerrit.entities.SubmissionId) ObjectId(org.eclipse.jgit.lib.ObjectId) RequestId(com.google.gerrit.server.logging.RequestId) StorageException(com.google.gerrit.exceptions.StorageException) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap)

Example 72 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class SuperprojectUpdateSubmissionListener method afterSubmission.

@Override
public void afterSubmission(MergeOpRepoManager orm) {
    collectSuccessfullUpdates();
    // Update superproject gitlinks if required.
    if (!updatedBranches.isEmpty()) {
        try {
            SubmoduleOp op = subOpFactory.create(updatedBranches, orm);
            op.updateSuperProjects(dryrun);
        } catch (RestApiException e) {
            logger.atWarning().withCause(e).log("Can't update the superprojects");
        }
    }
}
Also used : SubmoduleOp(com.google.gerrit.server.submit.SubmoduleOp) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Example 73 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class GpgApiAdapterImpl method putGpgKeys.

@Override
public Map<String, GpgKeyInfo> putGpgKeys(AccountResource account, List<String> add, List<String> delete) throws RestApiException, GpgException {
    GpgKeysInput in = new GpgKeysInput();
    in.add = add;
    in.delete = delete;
    try {
        return postGpgKeys.get().apply(account, in).value();
    } catch (PGPException | IOException | ConfigInvalidException e) {
        throw new GpgException(e);
    } catch (Exception e) {
        throw asRestApiException("Cannot put GPG keys", e);
    }
}
Also used : PGPException(org.bouncycastle.openpgp.PGPException) GpgException(com.google.gerrit.server.GpgException) GpgKeysInput(com.google.gerrit.extensions.api.accounts.GpgKeysInput) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) ApiUtil.asRestApiException(com.google.gerrit.server.api.ApiUtil.asRestApiException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) GpgException(com.google.gerrit.server.GpgException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) PGPException(org.bouncycastle.openpgp.PGPException)

Example 74 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class RestApiServlet method view.

private ViewData view(RestCollection<RestResource, RestResource> rc, String method, List<IdString> path) throws AmbiguousViewException, RestApiException {
    DynamicMap<RestView<RestResource>> views = rc.views();
    final IdString projection = path.isEmpty() ? IdString.fromUrl("/") : path.remove(0);
    if (!path.isEmpty()) {
        // If there are path components still remaining after this projection
        // is chosen, look for the projection based upon GET as the method as
        // the client thinks it is a nested collection.
        method = "GET";
    } else if ("HEAD".equals(method)) {
        method = "GET";
    }
    List<String> p = splitProjection(projection);
    if (p.size() == 2) {
        String viewname = p.get(1);
        if (Strings.isNullOrEmpty(viewname)) {
            viewname = "/";
        }
        RestView<RestResource> view = views.get(p.get(0), method + "." + viewname);
        if (view != null) {
            return new ViewData(p.get(0), view);
        }
        view = views.get(p.get(0), "GET." + viewname);
        if (view != null) {
            return new ViewData(p.get(0), view);
        }
        throw new ResourceNotFoundException(projection);
    }
    String name = method + "." + p.get(0);
    RestView<RestResource> core = views.get(PluginName.GERRIT, name);
    if (core != null) {
        return new ViewData(PluginName.GERRIT, core);
    }
    // GET.name so we have to check for this since we haven't found any other views.
    if (method.equals("GET")) {
        core = views.get(PluginName.GERRIT, "GET." + p.get(0));
        if (core != null) {
            return new ViewData(PluginName.GERRIT, core);
        }
    }
    Map<String, RestView<RestResource>> r = new TreeMap<>();
    for (String plugin : views.plugins()) {
        RestView<RestResource> action = views.get(plugin, name);
        if (action != null) {
            r.put(plugin, action);
        }
    }
    if (r.isEmpty()) {
        // GET.name so we have to check for this since we haven't found any other views.
        for (String plugin : views.plugins()) {
            RestView<RestResource> action = views.get(plugin, "GET." + p.get(0));
            if (action != null) {
                r.put(plugin, action);
            }
        }
    }
    if (r.size() == 1) {
        Map.Entry<String, RestView<RestResource>> entry = Iterables.getOnlyElement(r.entrySet());
        return new ViewData(entry.getKey(), entry.getValue());
    }
    if (r.isEmpty()) {
        throw new ResourceNotFoundException(projection);
    }
    throw new AmbiguousViewException(String.format("Projection %s is ambiguous: %s", name, r.keySet().stream().map(in -> in + "~" + projection).collect(joining(", "))));
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) PluginName(com.google.gerrit.extensions.registration.PluginName) ListMultimap(com.google.common.collect.ListMultimap) DynamicItem(com.google.gerrit.extensions.registration.DynamicItem) DeadlineChecker(com.google.gerrit.server.DeadlineChecker) OptionUtil(com.google.gerrit.server.OptionUtil) RequestStateProvider(com.google.gerrit.server.cancellation.RequestStateProvider) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ActionType(com.google.gerrit.server.update.RetryableAction.ActionType) GsonBuilder(com.google.gson.GsonBuilder) InvalidDeadlineException(com.google.gerrit.server.InvalidDeadlineException) Config(org.eclipse.jgit.lib.Config) IntMath(com.google.common.math.IntMath) OutputFormat(com.google.gerrit.json.OutputFormat) ISO_8859_1(java.nio.charset.StandardCharsets.ISO_8859_1) HttpHeaders(com.google.common.net.HttpHeaders) Map(java.util.Map) CEILING(java.math.RoundingMode.CEILING) RawInput(com.google.gerrit.extensions.restapi.RawInput) RetryHelper(com.google.gerrit.server.update.RetryHelper) AnonymousUser(com.google.gerrit.server.AnonymousUser) ExclusionStrategy(com.google.gson.ExclusionStrategy) GroupAuditService(com.google.gerrit.server.group.GroupAuditService) Metadata(com.google.gerrit.server.logging.Metadata) RestReadView(com.google.gerrit.extensions.restapi.RestReadView) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) HttpServlet(javax.servlet.http.HttpServlet) TraceContext(com.google.gerrit.server.logging.TraceContext) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) PerThreadCache(com.google.gerrit.server.cache.PerThreadCache) Set(java.util.Set) FilterOutputStream(java.io.FilterOutputStream) Collectors.joining(java.util.stream.Collectors.joining) InvocationTargetException(java.lang.reflect.InvocationTargetException) RequestListener(com.google.gerrit.server.RequestListener) SC_NOT_FOUND(javax.servlet.http.HttpServletResponse.SC_NOT_FOUND) Stream(java.util.stream.Stream) ChangesCollection(com.google.gerrit.server.restapi.change.ChangesCollection) SC_CONFLICT(javax.servlet.http.HttpServletResponse.SC_CONFLICT) ImmutableListMultimap(com.google.common.collect.ImmutableListMultimap) PluginSetContext(com.google.gerrit.server.plugincontext.PluginSetContext) GZIPOutputStream(java.util.zip.GZIPOutputStream) LazyArgs.lazy(com.google.common.flogger.LazyArgs.lazy) TypeLiteral(com.google.inject.TypeLiteral) ACCESS_CONTROL_ALLOW_HEADERS(com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS) FluentLogger(com.google.common.flogger.FluentLogger) ACCESS_CONTROL_ALLOW_CREDENTIALS(com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS) Joiner(com.google.common.base.Joiner) Iterables(com.google.common.collect.Iterables) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) CountingOutputStream(com.google.common.io.CountingOutputStream) RawInputUtil(com.google.gerrit.common.RawInputUtil) Action(com.google.gerrit.server.update.RetryableAction.Action) Response(com.google.gerrit.extensions.restapi.Response) TraceTimer(com.google.gerrit.server.logging.TraceContext.TraceTimer) CONTENT_TYPE(com.google.common.net.HttpHeaders.CONTENT_TYPE) Constructor(java.lang.reflect.Constructor) DefaultInput(com.google.gerrit.extensions.restapi.DefaultInput) CancellationMetrics(com.google.gerrit.server.CancellationMetrics) FieldAttributes(com.google.gson.FieldAttributes) JsonReader(com.google.gson.stream.JsonReader) PerformanceLogger(com.google.gerrit.server.logging.PerformanceLogger) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) HttpServletRequest(javax.servlet.http.HttpServletRequest) VARY(com.google.common.net.HttpHeaders.VARY) SC_NOT_IMPLEMENTED(javax.servlet.http.HttpServletResponse.SC_NOT_IMPLEMENTED) Lists(com.google.common.collect.Lists) RestCollectionDeleteMissingView(com.google.gerrit.extensions.restapi.RestCollectionDeleteMissingView) RestCollectionCreateView(com.google.gerrit.extensions.restapi.RestCollectionCreateView) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) CacheHeaders(com.google.gerrit.util.http.CacheHeaders) JsonWriter(com.google.gson.stream.JsonWriter) NeedsParams(com.google.gerrit.extensions.restapi.NeedsParams) RequestUtil(com.google.gerrit.util.http.RequestUtil) PreconditionFailedException(com.google.gerrit.extensions.restapi.PreconditionFailedException) BaseEncoding(com.google.common.io.BaseEncoding) QueryParams(com.google.gerrit.httpd.restapi.ParameterParser.QueryParams) ExperimentFeatures(com.google.gerrit.server.experiments.ExperimentFeatures) BufferedWriter(java.io.BufferedWriter) Throwables(com.google.common.base.Throwables) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Field(java.lang.reflect.Field) ETagView(com.google.gerrit.extensions.restapi.ETagView) MalformedJsonException(com.google.gson.stream.MalformedJsonException) JsonToken(com.google.gson.stream.JsonToken) ParameterizedType(java.lang.reflect.ParameterizedType) TreeMap(java.util.TreeMap) SC_NOT_MODIFIED(javax.servlet.http.HttpServletResponse.SC_NOT_MODIFIED) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) Project(com.google.gerrit.entities.Project) DynamicSet(com.google.gerrit.extensions.registration.DynamicSet) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) DynamicOptions(com.google.gerrit.server.DynamicOptions) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) BufferedReader(java.io.BufferedReader) RequestCancelledException(com.google.gerrit.server.cancellation.RequestCancelledException) RequestId(com.google.gerrit.server.logging.RequestId) ChangeFinder(com.google.gerrit.server.change.ChangeFinder) ACCESS_CONTROL_ALLOW_METHODS(com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS) ServletException(javax.servlet.ServletException) Inject(com.google.inject.Inject) HttpServletRequestWrapper(javax.servlet.http.HttpServletRequestWrapper) AUTHORIZATION(com.google.common.net.HttpHeaders.AUTHORIZATION) AccessPath(com.google.gerrit.server.AccessPath) CacheControl(com.google.gerrit.extensions.restapi.CacheControl) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) RestResource(com.google.gerrit.extensions.restapi.RestResource) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ACCESS_CONTROL_ALLOW_ORIGIN(com.google.common.net.HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN) Gson(com.google.gson.Gson) Locale(java.util.Locale) AuthException(com.google.gerrit.extensions.restapi.AuthException) GERRIT_BACKEND_REQUEST_FEATURE_REMOVE_REVISION_ETAG(com.google.gerrit.server.experiments.ExperimentFeaturesConstants.GERRIT_BACKEND_REQUEST_FEATURE_REMOVE_REVISION_ETAG) PerformanceLogContext(com.google.gerrit.server.logging.PerformanceLogContext) Splitter(com.google.common.base.Splitter) ORIGIN(com.google.common.net.HttpHeaders.ORIGIN) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) ImmutableSet(com.google.common.collect.ImmutableSet) RestCollectionView(com.google.gerrit.extensions.restapi.RestCollectionView) Timestamp(java.sql.Timestamp) ACCESS_CONTROL_REQUEST_HEADERS(com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_HEADERS) SC_REQUEST_TIMEOUT(javax.servlet.http.HttpServletResponse.SC_REQUEST_TIMEOUT) RequestInfo(com.google.gerrit.server.RequestInfo) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) EOFException(java.io.EOFException) Preconditions.checkState(com.google.common.base.Preconditions.checkState) TopLevelResource(com.google.gerrit.extensions.restapi.TopLevelResource) RestCollectionModifyView(com.google.gerrit.extensions.restapi.RestCollectionModifyView) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Type(java.lang.reflect.Type) ACCESS_CONTROL_MAX_AGE(com.google.common.net.HttpHeaders.ACCESS_CONTROL_MAX_AGE) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) Url(com.google.gerrit.extensions.restapi.Url) Writer(java.io.Writer) Optional(java.util.Optional) Providers(com.google.inject.util.Providers) Pattern(java.util.regex.Pattern) SC_METHOD_NOT_ALLOWED(javax.servlet.http.HttpServletResponse.SC_METHOD_NOT_ALLOWED) RestCollection(com.google.gerrit.extensions.restapi.RestCollection) RequestStateContext(com.google.gerrit.server.cancellation.RequestStateContext) JsonParseException(com.google.gson.JsonParseException) NotImplementedException(com.google.gerrit.extensions.restapi.NotImplementedException) SC_PRECONDITION_FAILED(javax.servlet.http.HttpServletResponse.SC_PRECONDITION_FAILED) ACCESS_CONTROL_REQUEST_METHOD(com.google.common.net.HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) SC_INTERNAL_SERVER_ERROR(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR) IdString(com.google.gerrit.extensions.restapi.IdString) HashMap(java.util.HashMap) AtomicReference(java.util.concurrent.atomic.AtomicReference) JsonElement(com.google.gson.JsonElement) HashSet(java.util.HashSet) GitReferenceUpdatedListener(com.google.gerrit.extensions.events.GitReferenceUpdatedListener) BinaryResult(com.google.gerrit.extensions.restapi.BinaryResult) FieldNamingPolicy(com.google.gson.FieldNamingPolicy) ImmutableList(com.google.common.collect.ImmutableList) ExceptionHook(com.google.gerrit.server.ExceptionHook) Objects.requireNonNull(java.util.Objects.requireNonNull) ExtendedHttpAuditEvent(com.google.gerrit.server.audit.ExtendedHttpAuditEvent) OutputStreamWriter(java.io.OutputStreamWriter) WebSession(com.google.gerrit.httpd.WebSession) OutputStream(java.io.OutputStream) CurrentUser(com.google.gerrit.server.CurrentUser) TemporaryBuffer(org.eclipse.jgit.util.TemporaryBuffer) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ProjectsCollection(com.google.gerrit.server.restapi.project.ProjectsCollection) RestView(com.google.gerrit.extensions.restapi.RestView) HttpServletResponse(javax.servlet.http.HttpServletResponse) RetryableAction(com.google.gerrit.server.update.RetryableAction) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) Provider(com.google.inject.Provider) ServletUtils(org.eclipse.jgit.http.server.ServletUtils) Heap(org.eclipse.jgit.util.TemporaryBuffer.Heap) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) RevisionResource(com.google.gerrit.server.change.RevisionResource) SC_FORBIDDEN(javax.servlet.http.HttpServletResponse.SC_FORBIDDEN) QuotaException(com.google.gerrit.server.quota.QuotaException) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Collections(java.util.Collections) InputStream(java.io.InputStream) RestResource(com.google.gerrit.extensions.restapi.RestResource) RestView(com.google.gerrit.extensions.restapi.RestView) IdString(com.google.gerrit.extensions.restapi.IdString) TreeMap(java.util.TreeMap) IdString(com.google.gerrit.extensions.restapi.IdString) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Map(java.util.Map) TreeMap(java.util.TreeMap) DynamicMap(com.google.gerrit.extensions.registration.DynamicMap) HashMap(java.util.HashMap)

Example 75 with RestApiException

use of com.google.gerrit.extensions.restapi.RestApiException in project gerrit by GerritCodeReview.

the class IndexServlet method doGet.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    SoySauce.Renderer renderer;
    try {
        Map<String, String[]> parameterMap = req.getParameterMap();
        // TODO(hiesel): Remove URL ordainer as parameter once Soy is consistent
        ImmutableMap<String, Object> templateData = IndexHtmlUtil.templateData(gerritApi, experimentFeatures, canonicalUrl, cdnPath, faviconPath, parameterMap, urlOrdainer, getRequestUrl(req));
        renderer = soySauce.renderTemplate("com.google.gerrit.httpd.raw.Index").setData(templateData);
    } catch (URISyntaxException | RestApiException e) {
        throw new IOException(e);
    }
    rsp.setCharacterEncoding(UTF_8.name());
    rsp.setContentType("text/html");
    rsp.setStatus(SC_OK);
    try (OutputStream w = rsp.getOutputStream()) {
        w.write(renderer.renderHtml().get().toString().getBytes(UTF_8));
    }
}
Also used : SoySauce(com.google.template.soy.jbcsrc.api.SoySauce) OutputStream(java.io.OutputStream) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Aggregations

RestApiException (com.google.gerrit.extensions.restapi.RestApiException)93 ApiUtil.asRestApiException (com.google.gerrit.server.api.ApiUtil.asRestApiException)38 IOException (java.io.IOException)31 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)24 UpdateException (com.google.gerrit.server.update.UpdateException)23 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)22 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)20 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)19 AuthException (com.google.gerrit.extensions.restapi.AuthException)18 StorageException (com.google.gerrit.exceptions.StorageException)17 List (java.util.List)17 BatchUpdateOp (com.google.gerrit.server.update.BatchUpdateOp)16 Inject (com.google.inject.Inject)15 ArrayList (java.util.ArrayList)15 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)14 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)14 ChangeContext (com.google.gerrit.server.update.ChangeContext)14 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 Provider (com.google.inject.Provider)12 Change (com.google.gerrit.entities.Change)11