001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server;
018
019import static jakarta.servlet.http.HttpServletResponse.*;
020import static java.util.Collections.*;
021import static org.apache.juneau.commons.function.Suppliers.*;
022import static org.apache.juneau.commons.reflect.AnnotationTraversal.*;
023import static org.apache.juneau.commons.reflect.ReflectionUtils.*;
024import static org.apache.juneau.commons.utils.CollectionUtils.*;
025import static org.apache.juneau.commons.utils.IoUtils.*;
026import static org.apache.juneau.commons.utils.ObjectUtils.*;
027import static org.apache.juneau.commons.utils.PredicateUtils.*;
028import static org.apache.juneau.commons.utils.Shorts.*;
029import static org.apache.juneau.commons.utils.Shorts.eq;
030import static org.apache.juneau.commons.utils.StringUtils.*;
031import static org.apache.juneau.commons.utils.StringUtils.isEmpty;
032import static org.apache.juneau.commons.utils.ThrowableUtils.*;
033import static org.apache.juneau.rest.server.RestOpAnnotation.*;
034import static org.apache.juneau.rest.server.processor.ResponseProcessor.*;
035import static org.apache.juneau.rest.server.util.RestUtils.*;
036
037import java.io.*;
038import java.lang.annotation.*;
039import java.lang.reflect.*;
040import java.lang.reflect.Method;
041import java.time.*;
042import java.util.*;
043import java.util.concurrent.*;
044import java.util.concurrent.atomic.*;
045import java.util.function.*;
046import java.util.logging.*;
047import java.util.stream.*;
048
049import org.apache.juneau.bean.openapi3.OpenApi;
050import org.apache.juneau.bean.rfc7807.*;
051import org.apache.juneau.bean.rfc7807.adapter.*;
052import org.apache.juneau.bean.swagger.Swagger;
053import org.apache.juneau.commons.beanquery.BeanQueryExecutionException;
054import org.apache.juneau.commons.beanquery.BeanQuerySyntaxException;
055import org.apache.juneau.commons.collections.*;
056import org.apache.juneau.commons.function.*;
057import org.apache.juneau.commons.http.MediaType;
058import org.apache.juneau.commons.inject.*;
059import org.apache.juneau.commons.lang.*;
060import org.apache.juneau.commons.logging.RichLogger;
061import org.apache.juneau.commons.reflect.*;
062import org.apache.juneau.commons.reflect.ParameterInfo;
063import org.apache.juneau.commons.settings.*;
064import org.apache.juneau.commons.svl.*;
065import org.apache.juneau.commons.utils.*;
066import org.apache.juneau.config.*;
067import org.apache.juneau.config.vars.*;
068import org.apache.juneau.http.*;
069import org.apache.juneau.http.Response;
070import org.apache.juneau.http.header.*;
071import org.apache.juneau.http.response.*;
072import org.apache.juneau.marshall.*;
073import org.apache.juneau.marshall.cp.*;
074import org.apache.juneau.marshall.encoders.*;
075import org.apache.juneau.marshall.html.*;
076import org.apache.juneau.marshall.httppart.*;
077import org.apache.juneau.marshall.marshaller.*;
078import org.apache.juneau.marshall.jsonschema.*;
079import org.apache.juneau.marshall.oapi.*;
080import org.apache.juneau.marshall.parser.*;
081import org.apache.juneau.marshall.serializer.*;
082import org.apache.juneau.rest.server.arg.*;
083import org.apache.juneau.rest.server.auth.*;
084import org.apache.juneau.rest.server.config.*;
085import org.apache.juneau.rest.server.filter.*;
086import org.apache.juneau.rest.server.httppart.*;
087import org.apache.juneau.rest.server.logging.*;
088import org.apache.juneau.rest.server.metrics.*;
089import org.apache.juneau.rest.server.openapi.*;
090import org.apache.juneau.rest.server.processor.*;
091import org.apache.juneau.rest.server.rrpc.*;
092import org.apache.juneau.rest.server.servlet.*;
093import org.apache.juneau.rest.server.staticfile.*;
094import org.apache.juneau.rest.server.stats.*;
095import org.apache.juneau.rest.server.swagger.*;
096import org.apache.juneau.rest.server.tracing.*;
097import org.apache.juneau.rest.server.util.*;
098import org.apache.juneau.rest.server.validation.*;
099import org.apache.juneau.rest.server.vars.*;
100
101import jakarta.servlet.*;
102import jakarta.servlet.http.*;
103
104/**
105 * Defines the initial configuration of a <c>RestServlet</c> or <c>@Rest</c> annotated object.
106 *
107 * <p>
108 * An extension of the {@link ServletConfig} object used during servlet initialization.
109 *
110 * <p>
111 * Configuration is supplied declaratively through the {@link Rest @Rest} annotation on the resource class
112 * (and inherited from any parent classes), and programmatically through {@link Bean @Bean}-annotated
113 * methods/fields that contribute named beans (e.g. <c>encoders</c>, <c>parsers</c>, <c>restDebugFormatter</c>) to
114 * the REST resource's bean store. Where direct construction is needed (test rigs, mock clients, embedded usage),
115 * the public constructor takes a {@link RestContext.Args} record carrying the bootstrap state.
116 *
117 * <h2 class='section'>Example:</h2>
118 * <p class='bjava'>
119 *    <ja>@Rest</ja>(path=<js>"/myresource"</js>, serializers=JsonSerializer.<jk>class</jk>, parsers=JsonParser.<jk>class</jk>)
120 *    <jk>public class</jk> MyResource {
121 *
122 *       <jc>// Programmatically contribute a bean to the resource's bean store.</jc>
123 *       <ja>@Bean</ja>
124 *       <jk>public</jk> RestDebugFormatter restDebugFormatter() {
125 *          <jk>return new</jk> MyCustomRestDebugFormatter();
126 *       }
127 *    }
128 * </p>
129 *
130 * <p>
131 * The historical <c>public MyResource(RestContext.Builder builder)</c> constructor-injection pattern and the
132 * <c>{@link RestInit @RestInit} public void init(RestContext.Builder builder)</c> method-injection pattern were both
133 * removed in 10.0. {@code RestContext.Builder} itself is on the deletion path; new code should not depend on it.
134 * See <a class="doclink" href="https://juneau.apache.org/docs/topics/V10MigrationGuide">v10.0 Migration Guide</a>
135 * for replacement recipes.
136 *
137 * <h2 class='section'>Notes:</h2><ul>
138 *    <li class='note'>This class is thread safe and reusable.
139 *    <li class='note'>
140 *       No authentication, authorization or CSRF filter is registered by default; those are opt-in
141 *       (see {@link CsrfBoundary} and the auth modules).
142 *       The one default request check is the cross-site refusal for unsafe methods:  a request using a method other
143 *       than <c>GET</c>, <c>HEAD</c>, <c>OPTIONS</c> or <c>TRACE</c> is answered with a <c>403</c> when the browser marks it
144 *       <c>Sec-Fetch-Site: cross-site</c>, or when its <c>Origin</c> does not match the <c>Host</c>.
145 *       It is on unless {@link Rest#allowCrossSite()} is set, and {@link Rest#allowedOrigins()} lists trusted origins.
146 * </ul>
147 *
148 * <h2 class='section'>See Also:</h2><ul>
149 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestContext">RestContext</a>
150 * </ul>
151 */
152@SuppressWarnings({
153   "java:S112", // RuntimeException used in memoizer lambdas to re-wrap checked exceptions (ServletException/Exception) that Supplier<T> cannot declare
154   "java:S125", // Explanatory comments reference SVL (${C:...}/${E:...}) and annotation (@Bean/@Rest) tokens that Sonar misreads as commented-out code
155   "java:S1141", // Nested try/catch blocks required for granular error reporting during initialization.
156   "java:S1192", // Duplicate string literals are property key names and REST annotation attribute values; intentional
157   "java:S1200", // Class has many dependencies; acceptable for this core context class
158   "java:S2259", // Values are non-null by construction or guarded by earlier checks that static flow analysis does not track.
159   "java:S3776", // Cognitive complexity in field-initializer lambdas (memoizer wiring); cannot annotate at lambda scope
160   "java:S6539", // Monster class; RestContext is intentionally a central hub for REST framework configuration
161   "resource" // Streams and session objects returned to callers; lifecycle managed by the servlet container or RestCall
162})
163public class RestContext extends Context {
164
165   private static final RichLogger LOG = RichLogger.getLogger(RestContext.class);
166
167   /**
168    * Bootstrap arguments for {@link RestContext}.
169    *
170    * <p>
171    * Bundles the small, fixed set of inputs needed to construct a {@link RestContext} into a single immutable record.
172    *
173    * <p>
174    * All non-required values default sensibly:
175    * <ul>
176    *    <li>{@code parentContext}, {@code servletConfig} — {@code null} (top-level resource, no servlet container)
177    *    <li>{@code path} — {@code ""} (no path prefix)
178    *    <li>{@code beanStoreConfigurer} — no-op (no pre-build bean-store mutation)
179    *    <li>{@code overridingParent} — {@code null} (no test-time override layer)
180    * </ul>
181    *
182    * <p>
183    * The {@code beanStoreConfigurer} hook gives test fixtures and integration code a chance to register beans on
184    * the {@link WritableBeanStore} after the resource has been wired in but before the
185    * {@code findXxx()} memoizers fire.
186    *
187    * <p>
188    * The {@code overridingParent} hook installs a {@link BeanStore} into the {@code overridingParent} slot of the
189    * freshly-constructed {@link BasicBeanStore} so that test-time overrides resolve at tier 1 of the lookup chain
190    * (above the resource's local {@code @Bean} factory entries and the Spring bridge).  This is the
191    * canonical Mode INJECT wiring point for {@code juneau-junit5}'s {@code TestBeanStore}.
192    *
193    * <h2 class='section'>Example:</h2>
194    * <p class='bjava'>
195    *    <jk>var</jk> <jv>ctx</jv> = <jk>new</jk> RestContext(<jk>new</jk> RestContext.Args(MyResource.<jk>class</jk>, () -&gt; <jk>new</jk> MyResource()));
196    * </p>
197    *
198    * @param resourceClass The {@link Rest @Rest}-annotated REST resource class. Must not be {@code null}.
199    * @param parentContext The parent {@link RestContext}, or {@code null} if this is a top-level resource.
200    * @param servletConfig The {@link ServletConfig} from the servlet container, or {@code null} when none is available.
201    * @param resource The supplier that provides the resource instance during initialization. Must not be {@code null}.
202    * @param path The path prefix relative to the parent. Defaults to {@code ""}.
203    * @param beanStoreConfigurer A pre-build hook that runs against the resolved {@link WritableBeanStore}
204    *    after the resource has been wired in but before any {@code findXxx()} memoizer fires. Defaults to a no-op.
205    * @param overridingParent An optional test-time override layer installed into the {@code overridingParent}
206    *    slot of the freshly-constructed {@link BasicBeanStore}.  May be {@code null}.  Honored only when the
207    *    resource does <i>not</i> declare an {@code @Bean WritableBeanStore} factory method; user-supplied bean
208    *    stores are passed through unchanged.
209    * @param paths An optional programmatic override for the top-level mount-paths array (the highest-priority
210    *    rung in the runtime-override chain documented on {@link RestContext#getPaths()}).  {@code null} (the
211    *    default) means &quot;no programmatic override&quot; &mdash; resolution falls through to the resource's
212    *    {@code getPaths()} getter, then {@link Rest#paths()} (SVL-resolved per element and comma-split).
213    *    An empty array explicitly clears the mount list (no top-level mounts).
214    * @param kind The build-time {@link ContextKind kind} of this context — {@link ContextKind#ROOT ROOT} for a
215    *    top-level/host/mock resource, a {@link ContextKind.Child CHILD} carrying the {@link ResolvedChild} for a
216    *    {@link Rest#children() @Rest(children)}/{@link Rest#childrenDefs() childrenDefs} sub-resource (isolated
217    *    resolution, with an optional host-seeded payload), or a {@link ContextKind.Mixin MIXIN} carrying the
218    *    {@link ResolvedMixin} that produced a per-mixin sub-context (parent-linked to the host so that
219    *    {@link RestContext#getRestAnnotationsForProperty(String) annotation-property walks} prepend the host's
220    *    {@code @Rest} chain before the mixin's own).
221    *
222    * @since 10.0.0
223    */
224   @SuppressWarnings({
225      "java:S6218" // Args is a transient constructor-parameter holder; it is never compared for equality or used as a map key, so array-identity semantics on the paths[] component are irrelevant.
226   })
227   public static record Args(
228      Class<?> resourceClass,
229      RestContext parentContext,
230      ServletConfig servletConfig,
231      Supplier<?> resource,
232      String path,
233      Consumer<WritableBeanStore> beanStoreConfigurer,
234      BeanStore overridingParent,
235      String[] paths,
236      ContextKind kind,
237      RestBuilder<?> restBuilder
238   ) {
239
240      /**
241       * Compact canonical constructor — null-coalesces optional fields and validates required ones.
242       */
243      public Args {
244         reqnn("resourceClass", resourceClass);
245         reqnn("resource", resource);
246         if (path == null)
247            path = "";
248         if (beanStoreConfigurer == null)
249            beanStoreConfigurer = bs -> {};
250         if (kind == null)
251            kind = ContextKind.ROOT;
252      }
253
254      /**
255       * Back-compatible constructor without the {@code restBuilder} component (defaults it to <jk>null</jk>).
256       *
257       * <p>
258       * The {@code restBuilder} is then resolved during {@link RestContext} construction from the
259       * resource instance's stashed builder, so call sites that don't carry one keep working unchanged.
260       *
261       * @param resourceClass The resource class.
262       * @param parentContext The parent context, or <jk>null</jk>.
263       * @param servletConfig The servlet config, or <jk>null</jk>.
264       * @param resource The resource supplier.
265       * @param path The mount path override, or <jk>null</jk>.
266       * @param beanStoreConfigurer The bean-store configurer, or <jk>null</jk>.
267       * @param overridingParent The overriding parent bean store, or <jk>null</jk>.
268       * @param paths The programmatic mount-paths override, or <jk>null</jk>.
269       * @param kind The build-time {@link ContextKind kind} of this context, or <jk>null</jk> for {@link ContextKind#ROOT}.
270       */
271      public Args(Class<?> resourceClass, RestContext parentContext, ServletConfig servletConfig, Supplier<?> resource, String path, Consumer<WritableBeanStore> beanStoreConfigurer, BeanStore overridingParent, String[] paths, ContextKind kind) {
272         this(resourceClass, parentContext, servletConfig, resource, path, beanStoreConfigurer, overridingParent, paths, kind, null);
273      }
274
275      /**
276       * Returns {@code true} when this context is a per-mixin sub-context (its {@link #kind()} is a
277       * {@link ContextKind.Mixin}).
278       *
279       * @return {@code true} for a mixin sub-context.
280       */
281      public boolean isMixinContext() {
282         return kind instanceof ContextKind.Mixin;
283      }
284   }
285
286   /**
287    * The discovery-time normalized declaration of a single mixin.
288    *
289    * <p>
290    * Every mixin entry &mdash; whether a bare {@link Rest#mixins() Class&lt;?&gt;} or a rich
291    * {@link Rest#mixinDefs() &#64;Mixin} &mdash; is normalized to one of these immutable carriers at discovery
292    * time, so all downstream code consumes a single shape with no bare-vs-def branching.  A bare class is
293    * normalized to {@code new ResolvedMixin(type, MixinAnnotation.DEFAULT)} (i.e. {@code @Mixin(type=X)} with
294    * empty overrides), so a bare class and an empty-override {@code @Mixin} are structurally identical.
295    *
296    * <p>
297    * The {@code overrides} annotation is the single home for the host-declared override payload (guards,
298    * serializers, default headers, {@code path}/{@code paths}, {@code noInherit}, &hellip;).  For bare classes
299    * it is {@link MixinAnnotation#DEFAULT} (all slots empty), which contributes nothing &mdash; so bare-class
300    * mixins behave exactly as they did before the {@code @Mixin} feature.
301    *
302    * @param type The mixin class.
303    * @param overrides The host-declared override annotation, or {@link MixinAnnotation#DEFAULT} for a bare class.
304    *
305    * @since 10.0.0
306    */
307   public static record ResolvedMixin(Class<?> type, Mixin overrides) {
308
309      /**
310       * Compact canonical constructor — validates required components and null-coalesces {@code overrides}.
311       */
312      public ResolvedMixin {
313         reqnn("type", type);
314         if (overrides == null)
315            overrides = MixinAnnotation.DEFAULT;
316      }
317
318      /**
319       * Normalizes a bare mixin class to a {@link ResolvedMixin} with no overrides.
320       *
321       * @param type The mixin class.
322       * @return A {@link ResolvedMixin} carrying {@link MixinAnnotation#DEFAULT} overrides.
323       */
324      static ResolvedMixin ofBare(Class<?> type) {
325         return new ResolvedMixin(type, MixinAnnotation.DEFAULT);
326      }
327
328      /**
329       * Normalizes a rich {@code @Mixin} declaration to a {@link ResolvedMixin}.
330       *
331       * @param m The {@code @Mixin} annotation.
332       * @return A {@link ResolvedMixin} carrying {@code m} as its override payload.
333       */
334      static ResolvedMixin ofDef(Mixin m) {
335         return new ResolvedMixin(m.type(), m);
336      }
337
338      /**
339       * Returns {@code true} when this mixin carries no host-declared overrides (i.e. is equivalent to a bare class).
340       *
341       * @return {@code true} if the override payload is {@link MixinAnnotation#DEFAULT}.
342       */
343      boolean hasNoOverrides() {
344         return overrides == MixinAnnotation.DEFAULT;
345      }
346   }
347
348   /**
349    * Normalized carrier for a routed child, produced by discovery from either a bare {@link Rest#children()}
350    * class or a rich {@link Rest#childrenDefs() @Child} declaration — the exact structural analog of
351    * {@link ResolvedMixin}.
352    *
353    * <p>
354    * A bare class is normalized to {@code new ResolvedChild(type, ChildAnnotation.DEFAULT)} (i.e.
355    * {@code @Child(type=X)} with an empty seed), so a bare class and an empty-seed {@code @Child} are
356    * structurally identical — the same equivalence {@link ResolvedMixin} establishes for mixins.
357    *
358    * @param type The child class.
359    * @param seed The host-declared seed annotation, or {@link ChildAnnotation#DEFAULT} for a bare class.
360    *
361    * @since 10.0.0
362    */
363   public static record ResolvedChild(Class<?> type, Child seed) {
364
365      /**
366       * Compact canonical constructor — validates required components and null-coalesces {@code seed}.
367       */
368      public ResolvedChild {
369         reqnn("type", type);
370         if (seed == null)
371            seed = ChildAnnotation.DEFAULT;
372      }
373
374      /**
375       * Normalizes a bare child class to a {@link ResolvedChild} with no seed.
376       *
377       * @param type The child class.
378       * @return A {@link ResolvedChild} carrying {@link ChildAnnotation#DEFAULT} as its seed.
379       */
380      static ResolvedChild ofBare(Class<?> type) {
381         return new ResolvedChild(type, ChildAnnotation.DEFAULT);
382      }
383
384      /**
385       * Normalizes a rich {@code @Child} declaration to a {@link ResolvedChild}.
386       *
387       * @param c The {@code @Child} annotation.
388       * @return A {@link ResolvedChild} carrying {@code c} as its seed.
389       */
390      static ResolvedChild ofDef(Child c) {
391         return new ResolvedChild(c.type(), c);
392      }
393
394      /**
395       * Returns {@code true} when this child carries no host-declared seed (i.e. is equivalent to a bare class).
396       *
397       * @return {@code true} if the seed payload is {@link ChildAnnotation#DEFAULT}.
398       */
399      boolean hasNoSeed() {
400         return seed == ChildAnnotation.DEFAULT;
401      }
402   }
403
404   /**
405    * The build-time <i>kind</i> of a {@link RestContext} — which of the three construction flavors produced it.
406    *
407    * <p>
408    * Replaces the former boolean {@code mixinContext} flag on {@link Args} with a typed discriminator so the
409    * three flavors are explicit and self-documenting at every call site, and so the {@code MIXIN} flavor can
410    * carry the {@link ResolvedMixin} that produced it (the single home for the host-declared override payload,
411    * consumed at build time when the mixin sub-context resolves its settings).
412    *
413    * <p>
414    * <b>Mixin vs. child asymmetry (important — do not assume symmetry):</b> a {@link Mixin} sub-context is
415    * parent-linked to the host and <i>inherits</i> the host's {@code @Rest} annotation chain
416    * ({@link #getRestAnnotationsForProperty(String)} walks host&rarr;mixin), so {@code @Mixin} overrides
417    * <i>layer on top of</i> an inherited chain.  A {@link Child} is <i>isolated</i> ({@link #HOST_ONLY_PROPERTIES}
418    * includes {@code "children"}; children retain pre-10.0.0 isolated resolution with
419    * no parent walk).  A {@code @Child} seed therefore does not <i>override</i> an inherited chain the way a
420    * {@code @Mixin} override does — instead, {@link #computeRawRestAnnotations()} injects the seed's synthetic
421    * {@code @Rest} at the <b>least-derived</b> slot of the child's own (still fully isolated) annotation chain,
422    * between the child's real {@code @Rest} declarations and the synthesized {@link
423    * org.apache.juneau.rest.server.config.DefaultConfig DefaultConfig} fallback.  This ranks the seed below
424    * everything the child itself declares (so the child's own explicit value wins for child-wins scalars, and
425    * the child's own {@code noInherit} cutoff naturally cuts the seed too) but above the framework defaults.
426    *
427    * @since 10.0.0
428    */
429   public sealed interface ContextKind permits ContextKind.Root, ContextKind.Child, ContextKind.Mixin {
430
431      /** A top-level (host) resource, mock context, or servlet-mounted resource. */
432      record Root() implements ContextKind {}
433
434      /**
435       * A routed child resource (mounted via {@link Rest#children()}/{@link Rest#childrenDefs()}); isolated
436       * resolution, with an optional host-seeded {@code @Child} payload injected at the least-derived slot of
437       * its own annotation chain (see the class javadoc above).
438       *
439       * @param def The normalized declaration that produced this sub-context — carries the host-declared seed payload.
440       */
441      record Child(ResolvedChild def) implements ContextKind {}
442
443      /**
444       * A per-mixin sub-context (composed via {@link Rest#mixins()}/{@link Rest#mixinDefs()}); inherits the host chain.
445       *
446       * @param def The normalized declaration that produced this sub-context — carries the host-declared override payload.
447       */
448      record Mixin(ResolvedMixin def) implements ContextKind {}
449
450      /** Shared {@link Root} singleton (the common case). */
451      ContextKind ROOT = new Root();
452   }
453
454   /**
455    * Builder class.
456    *
457    * <p>
458    * Demoted to package-private in the April 2026 refactor (2026-04-19). User code should construct a
459    * {@link RestContext} via the public {@link #RestContext(Args)} constructor; this Builder
460    * exists only as internal bootstrap state for the framework and is slated for inlining in a later phase.
461    */
462   @SuppressWarnings({
463      "rawtypes" // Raw types required: annotation type parameter is unknown at static analysis time.
464   })
465   static class Builder extends Context.Builder implements ServletConfig {
466
467      private final Class<?> resourceClass;
468      private final RestContext parentContext;
469      private final ServletConfig inner;
470      final Args args;
471
472      /**
473       * Programmatic top-level mount-paths override.
474       *
475       * <p>
476       * Highest-priority rung in the runtime-override chain documented on {@link RestContext#getPaths()}.
477       * Set via {@link #paths(String...)}.
478       *
479       * <ul>
480       *    <li>{@code null} (default) &mdash; no programmatic override; falls through to the resource's
481       *       {@code getPaths()} getter, then the {@code @Rest(paths=...)} annotation default (SVL-resolved
482       *       per element and comma-split).
483       *    <li>Empty array &mdash; explicit clear; resource is resolved with no top-level mounts.
484       *    <li>Non-empty array &mdash; replaces all lower rungs.
485       * </ul>
486       */
487      String[] paths;
488
489      /**
490       * Programmatic override for the MDC async propagation flag.
491       *
492       * <p>
493       * {@code null} (default) &mdash; defers to the {@code RestContext.mdcAsyncPropagation} env-driven
494       * default (itself defaulting to {@code true} when SLF4J is detected). Set via
495       * {@link #mdcAsyncPropagation(boolean)}.
496       */
497      Boolean mdcAsyncPropagation;
498
499      /**
500       * Programmatic override for the async-completion executor bean name.
501       *
502       * <p>
503       * {@code null} (default) &mdash; resolved from the {@code @Rest(asyncCompletionExecutor)} annotation chain.
504       * Set via {@link #asyncCompletionExecutor(String)} to supply the bean-name programmatically (useful in
505       * test rigs that construct a {@link RestContext} directly without annotations).
506       */
507      String asyncCompletionExecutorName;
508
509      /**
510       * Programmatic override for the lazy-children flag.
511       *
512       * <p>
513       * {@code null} (default) &mdash; defers to the {@link Rest#lazyChildren() @Rest(lazyChildren)} annotation
514       * chain, then to the {@code RestContext.lazyChildren} env-driven default (itself defaulting to
515       * {@code false}). Set via {@link #lazyChildInit(boolean)}.
516       *
517       * <p>
518       * When {@code true}, all children registered via {@link Rest#children() @Rest(children)} on this resource
519       * are built lazily on first invocation rather than eagerly at parent startup.
520       */
521      Boolean lazyChildInit;
522
523      /**
524       * Package-private constructor.
525       *
526       * <p>
527       * Minimized in the May 2026 refactor — the beanStore setup, {@code @Bean} processing,
528       * {@code @RestInit} hooks, and {@code beanStoreConfigurer} call were all moved into
529       * {@link RestContext#RestContext(Builder)}. The Builder now only stores the three fields
530       * that are final and needed by the {@link ServletConfig} overrides and factory methods.
531       *
532       * @param rci The bootstrap arguments. Must not be {@code null}.
533       */
534      Builder(Args rci) {
535         this.resourceClass = rci.resourceClass();
536         this.inner = rci.servletConfig();
537         this.parentContext = rci.parentContext();
538         this.args = rci;
539         this.paths = rci.paths();
540      }
541
542      /**
543       * Programmatic override for the top-level mount-paths array.
544       *
545       * <p>
546       * This is the highest-priority rung in the runtime-override chain &mdash; see
547       * {@link RestContext#getPaths()} for the full precedence order.
548       *
549       * <h5 class='section'>Notes:</h5><ul>
550       *    <li class='note'>
551       *       Passing {@code null} resets the override and lets the lower rungs ({@code getPaths()} getter,
552       *       {@code @Rest(paths)} annotation) resolve.
553       *    <li class='note'>
554       *       Passing {@code new String[0]} explicitly clears the mount list &mdash; the resource ends up with
555       *       no top-level mounts, which surfaces a clear &quot;no mounts&quot; error from the hosting runtime.
556       * </ul>
557       *
558       * @param value The new mount paths, or {@code null} to inherit. Empty array clears.
559       * @return This object.
560       * @since 10.0.0
561       */
562      public Builder paths(String...value) {
563         paths = value;
564         return this;
565      }
566
567      /**
568       * Enables or disables SLF4J MDC propagation from the request thread to
569       * {@link CompletableFuture} completion threads.
570       *
571       * <p>
572       * Default is {@code true} (enabled) when SLF4J is on the runtime classpath.
573       * When enabled, the {@link MdcAsyncListener} snapshots the
574       * request thread's MDC map before the async dispatch and restores it inside the
575       * {@link CompletionStage#whenComplete(BiConsumer) whenComplete}
576       * callback so that log statements emitted during async completion see the original request context.
577       *
578       * <p>
579       * Call {@code mdcAsyncPropagation(false)} to opt a resource out of MDC propagation. The global default
580       * can also be overridden via the {@code RestContext.mdcAsyncPropagation} env-driven default.
581       *
582       * @param value {@code false} to disable MDC propagation on this resource.
583       * @return This object.
584       * @since 10.0.0
585       */
586      public Builder mdcAsyncPropagation(boolean value) {
587         mdcAsyncPropagation = value;
588         return this;
589      }
590
591      /**
592       * Programmatically sets the {@link Executor} bean name used to route
593       * {@link CompletableFuture} completion callbacks through a dedicated thread pool
594       * Equivalent to {@link Rest#asyncCompletionExecutor()} on the resource class.
595       *
596       * <p>
597       * The value is looked up by name in the resource's bean store at context-build time. If the name does
598       * not resolve to an {@link Executor} bean, the context constructor throws. Pass
599       * {@code null} (or omit this call) to clear the override and fall back to the annotation chain.
600       *
601       * @param beanName The bean-store name of the {@link Executor} to use, or {@code null} to clear.
602       * @return This object.
603       * @since 10.0.0
604       */
605      public Builder asyncCompletionExecutor(String beanName) {
606         asyncCompletionExecutorName = beanName;
607         return this;
608      }
609
610      /**
611       * Programmatically opt this resource into (or out of) deferred child construction.
612       *
613       * <p>
614       * When {@code true}, all children registered via {@link Rest#children() @Rest(children)} are built
615       * lazily on first invocation instead of eagerly at parent startup.  The routing entry for each child
616       * is always populated at startup so URL matching works immediately.
617       *
618       * <p>
619       * This is the highest-priority knob — it overrides both the
620       * {@link Rest#lazyChildren() @Rest(lazyChildren)} annotation and the
621       * {@code RestContext.lazyChildren} env-driven default.
622       *
623       * @param value {@code true} to defer child construction to first invocation.
624       * @return This object.
625       * @since 10.0.0
626       */
627      public Builder lazyChildInit(boolean value) {
628         lazyChildInit = value;
629         return this;
630      }
631
632      @Override /* Context.Builder<?> is abstract - copy() is not meaningful for the transient RestContext bootstrap state. */
633      public Builder copy() {
634         throw new NoSuchMethodError("Not implemented.");
635      }
636
637      @Override /* Overridden from ServletConfig */
638      public String getInitParameter(String name) {
639         return inner == null ? null : inner.getInitParameter(name);
640      }
641
642      @Override /* Overridden from ServletConfig */
643      public Enumeration<String> getInitParameterNames() { return o(inner).map(ServletConfig::getInitParameterNames).orElseGet(() -> new Vector<String>().elements()); }
644
645      @Override /* Overridden from ServletConfig */
646      public ServletContext getServletContext() {
647         if (nn(inner)) {
648            return inner.getServletContext();
649         } else if (nn(parentContext)) {
650            return parentContext.getBuilder().getServletContext();
651         } else {
652            return null;
653         }
654      }
655
656      @Override /* Overridden from ServletConfig */
657      public String getServletName() { return o(inner).map(ServletConfig::getServletName).orElse(null); }
658
659   }
660
661   private static final Map<Class<?>,RestContext> REGISTRY = new ConcurrentHashMap<>();
662
663   /**
664    * Returns a registry of all created {@link RestContext} objects.
665    *
666    * @return An unmodifiable map of resource classes to {@link RestContext} objects.
667    */
668   public static final Map<Class<?>,RestContext> getGlobalRegistry() { return u(REGISTRY); }
669
670   static ServletException servletException(String msg, Object...args) {
671      return new ServletException(f(msg, args));
672   }
673
674   static ServletException servletException(Throwable t, String msg, Object...args) {
675      return new ServletException(f(msg, args), t);
676   }
677
678   private static <T extends Annotation> Stream<Method> getAnnotatedMethods(Supplier<?> resource, Class<T> annotation) {
679      return ClassInfo.ofProxy(resource.get()).getAllMethodsTopDown().stream()
680         .filter(y -> y.hasAnnotation(annotation))
681         .filter(distinctByKey(MethodInfo::getSignature))
682         .map(y -> y.accessible().inner());
683   }
684
685   /**
686    * Resolves the top-level mount paths for a resource using the runtime-override chain.
687    *
688    * <p>
689    * Walks the three rungs in precedence order (highest first):
690    * <ol>
691    *    <li>Programmatic override on {@link Builder#paths} (set by {@link Builder#paths(String...)} or seeded from
692    *       {@link Args#paths()}).
693    *    <li>The resource's {@code getPaths()} getter (when non-{@code null}).
694    *    <li>{@link Rest#paths() @Rest(paths)} annotation default, walked top-down with the most-derived non-empty
695    *       array winning.  Each element is SVL-resolved against a session of {@code vr} backed by
696    *       {@code beanStore} (so {@code ${C:key}} consults whatever {@link Config} is registered), then
697    *       comma-split.
698    * </ol>
699    *
700    * @return The resolved paths array (never {@code null}; possibly empty).
701    */
702   private static String[] resolveMountPaths(Builder builder, Object resource, VarResolver vr, WritableBeanStore beanStore, List<AnnotationInfo<Rest>> annotations) {
703      // Rung 1: programmatic override (Builder.paths / Args.paths).
704      var programmatic = builder.paths;
705      if (programmatic != null)
706         return cp(programmatic);
707      return resolvePathsCore(annotations, resource, vr, beanStore);
708   }
709
710   /**
711    * Public mount-time path resolver for use by hosting runtimes that mount {@code @Rest}-annotated resources
712    * before the {@link RestContext} has been constructed (e.g. {@code JettyServerComponent}'s auto-discovery
713    * loop, or Spring Boot's {@code ServletRegistrationBean} wiring).
714    *
715    * <p>
716    * Operates on the same chain as {@link RestContext#getPaths()} but skips the programmatic Builder rung
717    * (which is only meaningful inside the {@link RestContext} constructor):
718    * <ol>
719    *    <li>The resource's {@code getPaths()} virtual getter (defined on {@code RestServlet} /
720    *       {@code RestResource}). {@code null} return falls through; non-{@code null} (including empty array) wins.
721    *    <li>{@link Rest#paths() @Rest(paths)} annotation default on the most-derived class, SVL-resolved per
722    *       element and comma-split.  A {@code VarResolver} is looked up on {@code store} (when present); SVL
723    *       variables like {@code ${C:key}} resolve against beans visible to the bean store.
724    * </ol>
725    *
726    * @param resourceClass The {@code @Rest}-annotated resource class. Must not be {@code null}.
727    * @param resource The resource instance. May be {@code null} (in which case the getter rung is skipped).
728    * @param store The bean store used to look up the {@link VarResolver} for SVL substitution on annotation
729    *    elements, and to back the resolver session for bean-driven SVL vars like {@code ${C:key}}. May be
730    *    {@code null} (SVL is then skipped; literals pass through unchanged).
731    * @return The resolved paths array (never {@code null}; possibly empty).
732    * @since 10.0.0
733    */
734   public static String[] resolveTopLevelPaths(Class<?> resourceClass, Object resource, BeanStore store) {
735      var ap = AnnotationProvider.INSTANCE;
736      var ci = ClassInfo.of(resourceClass);
737      var annotations = rstream(ap.find(Rest.class, ci)).toList();
738      var vr = (store == null) ? null : store.getBean(VarResolver.class).orElse(null);
739      // Cast for the bean-store-backed resolver session only — when store is a plain BeanStore (not
740      // WritableBeanStore) we skip the session form and call vr.resolve(...) directly.
741      var ws = (store instanceof WritableBeanStore store2) ? store2 : null;
742      return resolvePathsCore(annotations, resource, vr, ws);
743   }
744
745   private static String[] resolvePathsCore(List<AnnotationInfo<Rest>> annotations, Object resource, VarResolver vr, WritableBeanStore beanStore) {
746      // Rung 2: getPaths() virtual getter on the resource (RestServlet / RestResource / any matching class).
747      // The getter return is normalized to a flat List<String> of raw leaves (any String / String[] /
748      // Collection / Iterable / Stream / nested mix of those), then each leaf flows through the same
749      // SVL-resolve + comma-split pipeline used for @Rest(paths=...) annotation elements.
750      var raw = invokeGetPaths(resource);
751      if (raw != null) {
752         var leaves = normalizePaths(raw);
753         return expandPathsElements(leaves.toArray(new String[0]), vr, beanStore);
754      }
755
756      // Rung 3: @Rest(paths) annotation default — most-derived non-empty array wins, with each element
757      // SVL-resolved then comma-split (trim each piece, drop empties).  A single template element can
758      // therefore expand to zero, one, or many mount paths.  Annotation arrays from javac are never
759      // null, so the only filter needed is the empty-array case.
760      return annotations.stream()
761         .map(ai -> ai.inner().paths())
762         .filter(arr -> arr.length > 0)
763         .findFirst()
764         .map(arr -> expandPathsElements(arr, vr, beanStore))
765         .orElseGet(() -> new String[0]);
766   }
767
768   /**
769    * Applies the per-element SVL + comma-split pipeline to a {@code @Rest(paths=...)} array.
770    *
771    * <p>
772    * Each input element is SVL-resolved (via a session of the bootstrap {@link VarResolver} that's backed
773    * by {@code beanStore} when one is available, so bean-driven vars like {@code ${C:key}} can find the
774    * registered {@link Config}), then split on {@code ,}; each piece is trimmed and empty pieces are
775    * dropped.  This lets a single element like {@code "${C:health.paths}"} or
776    * {@code "${E:HEALTH_PATHS:/healthz,/readyz}"} expand to multiple mount paths.
777    */
778   private static String[] expandPathsElements(String[] elements, VarResolver vr, WritableBeanStore beanStore) {
779      // Open a single session for the whole array — reusing it across elements avoids re-walking the
780      // Var catalog and lets ConfigVar / FileVar / etc. all share one bean-lookup context.
781      var session = (vr == null) ? null : vr.createSession(beanStore);
782      var out = new ArrayList<String>(elements.length);
783      for (var e : elements) {
784         var resolved = applySvl(e, session);
785         splitPathsValue(resolved, out);
786      }
787      return out.toArray(new String[0]);
788   }
789
790   private static String applySvl(String value, VarResolverSession session) {
791      // Callers only pass annotation-array elements, which javac guarantees non-null.  An empty string
792      // has no SVL markers to resolve, so we short-circuit it (avoids a pointless session.resolve call).
793      if (session == null || value.isEmpty())
794         return value;
795      try {
796         return session.resolve(value);
797      } catch (@SuppressWarnings("unused") Exception e) {
798         return value; // SVL failure: prefer the literal over throwing during construction.
799      }
800   }
801
802   private static void splitPathsValue(String value, List<String> out) {
803      // Callers pass the return of applySvl, which never returns null (we control both branches above).
804      if (value.isBlank())
805         return;
806      var parts = value.split(",");
807      for (var p : parts) {
808         var t = p.trim();
809         if (! t.isEmpty())
810            out.add(t);
811      }
812   }
813
814   /**
815    * Flattens any {@link Object} returned from {@code getPaths()} (String, {@code String[]},
816    * {@link Collection}, {@link Iterable}, {@link Stream}, primitive array, or nested mixes of these)
817    * into a flat {@link List} of raw leaf strings.
818    *
819    * <p>
820    * Non-{@link String} leaves are coerced via {@link String#valueOf(Object)}.  The returned list
821    * preserves traversal order; {@code null} leaves are dropped.  Comma-split + SVL resolution are
822    * intentionally <i>not</i> applied here &mdash; they happen downstream in
823    * {@link #expandPathsElements(String[], VarResolver, WritableBeanStore)} so SVL substitution sees the
824    * raw element (preserving {@code ${E:NAME:defaultWithCommas}}-style defaults) before the post-SVL
825    * comma-split fires.
826    */
827   private static List<String> normalizePaths(Object o) {
828      if (o == null)
829         return List.of();
830      var out = new ArrayList<String>();
831      CollectionUtils.<Object>accumulate(o).forEach(x -> {
832         if (x != null)
833            out.add(String.valueOf(x));
834      });
835      return out;
836   }
837
838   /**
839    * Reflectively invokes a no-arg {@code getPaths()} method on the resource (defined on
840    * {@link RestServlet RestServlet} and
841    * {@link RestResource RestResource}). Reflection is used to avoid coupling this
842    * static utility to either base class &mdash; if a custom {@code @Rest}-annotated POJO declares
843    * {@code public Object getPaths()} (or any covariant return type such as {@code String[]},
844    * {@code List<String>}, etc.), it participates uniformly.
845    *
846    * @return The raw getter return value, or {@code null} when no method exists, the method returns
847    *    {@code void}, the method returned {@code null}, or reflective invocation failed.
848    */
849   private static Object invokeGetPaths(Object resource) {
850      if (resource == null)
851         return null;
852      Method m;
853      try {
854         m = resource.getClass().getMethod("getPaths");
855      } catch (@SuppressWarnings("unused") NoSuchMethodException e) {
856         return null;
857      }
858      if (m.getReturnType() == void.class)
859         return null;
860      try {
861         return m.invoke(resource);
862      } catch (@SuppressWarnings("unused") IllegalAccessException | InvocationTargetException e) {
863         return null;
864      }
865   }
866
867   private static boolean isBeanMethod(MethodInfo mi) {
868      return isBeanMethod(mi, null);
869   }
870
871   // Judges the effective (first) @Bean annotation, consistent with the registration walk; the name is
872   // compared through BeanAnnotation.name() so that the @Bean("x") value alias matches a named lookup.
873   private static boolean isBeanMethod(MethodInfo mi, String name) {
874      return mi.getAnnotations(Bean.class)
875         .map(AnnotationInfo::inner)
876         .findFirst()
877         .filter(x -> x.methodScope().length == 0 && (n(name) || eq(BeanAnnotation.name(x), name)))
878         .isPresent();
879   }
880
881   protected final AtomicBoolean initialized = new AtomicBoolean(false);
882   protected final BasicHttpException initException;
883   protected final WritableBeanStore beanStore;
884   protected final WritableBeanStore bootstrapBeanStore;  // Writable during bootstrap; exposed for child-context composition.
885   protected final WritableBeanStore inheritableBeanStore;  // This resource's @Bean results, layered over bootstrapBeanStore; the parent of @Rest(children) stores.
886   protected final Builder builder;
887   protected final Class<?> resourceClass;
888   protected final ConcurrentHashMap<Locale,Swagger> swaggerCache = new ConcurrentHashMap<>();
889   protected final ConcurrentHashMap<Locale,OpenApi> openApiCache = new ConcurrentHashMap<>();
890   protected final Instant startTime;
891   protected final RestContext parentContext;
892   protected final boolean isMixinContext;
893   /** The build-time kind of this context (never {@code null}). */
894   protected final ContextKind contextKind;
895   /** The normalized mixin declaration that produced this sub-context, or {@code null} when not a mixin context. */
896   protected final ResolvedMixin resolvedMixin;
897   /** The normalized child declaration that produced this sub-context, or {@code null} when not a child context. */
898   protected final ResolvedChild resolvedChild;
899   protected final String fullPath;
900   protected final String path;
901   protected final String[] paths;
902   protected final ThreadLocal<RestSession> localSession = new ThreadLocal<>();
903   protected final UrlPathMatcher pathMatcher;
904   private final Supplier<?> resource;
905   private AnnotationWorkList annotationWork;
906
907   /**
908    * The programmatic configuration builder for this resource, or <jk>null</jk> when configured purely
909    * by annotation.  Resolved during construction from {@link Args#restBuilder()} or, failing that, from the
910    * resource instance's stashed builder.  When non-<jk>null</jk>, a synthetic highest-priority {@code @Rest}
911    * annotation built from its set members is prepended to {@link #getRestAnnotations()} so builder-supplied
912    * values take precedence over the resource class's own {@code @Rest} annotation values.
913    */
914   private final RestBuilder<?> restBuilder;
915
916   /**
917    * The synthetic {@code @Rest} annotation built from {@link #restBuilder}'s set members, or <jk>null</jk> when
918    * there is no programmatic builder.  Prepended at the most-derived (child) position of
919    * {@link #getRestAnnotations()} so builder-supplied values win over the resource class's own annotation.
920    */
921   private final Rest builderRestAnnotation;
922
923   // Private accessors used by memoizer lambdas to satisfy Java's definite-assignment rules for blank final fields.
924   private WritableBeanStore beanStore() { return beanStore; }
925   private Supplier<?> resource() { return resource; }
926   private Class<?> resourceClass() { return resourceClass; }
927   private boolean isMixinContextField() { return isMixinContext; }
928
929   /**
930    * Field accessor for {@link #resolvedMixin}, callable from memoizer field-initializer lambdas (which run
931    * before the blank-final field is read directly).  Returns the normalized mixin declaration that produced
932    * this sub-context, or {@code null} when this is not a mixin context.
933    *
934    * @return The resolved mixin, or {@code null}.
935    */
936   private ResolvedMixin resolvedMixinField() { return resolvedMixin; }
937
938   /**
939    * Field accessor for {@link #resolvedChild}, callable from memoizer field-initializer lambdas (which run
940    * before the blank-final field is read directly).  Returns the normalized child declaration that produced
941    * this sub-context, or {@code null} when this is not a child context.
942    *
943    * @return The resolved child, or {@code null}.
944    */
945   private ResolvedChild resolvedChildField() { return resolvedChild; }
946
947   /**
948    * Creates the bean store for this context.
949    *
950    * <p>
951    * The 10.0 precedence model places the parent (Spring or parent-resource bootstrap) as the
952    * overriding parent so it wins over local entries.  Memoizer-backed framework defaults are
953    * registered later in the constructor via {@code addDefaultSupplier}, putting them at the
954    * bottom of the resolution order.
955    *
956    * <p>
957    * Resolution:
958    * <ol>
959    *    <li>If the resource declares an {@code @Bean} factory method returning a
960    *       {@link WritableBeanStore} (e.g. {@code SpringRestServlet.createBeanStore(Optional<BeanStore>)}),
961    *       that store is used directly.  Spring integration relies on this hook.
962    *    <li>Otherwise a fresh {@link BasicBeanStore} is created with {@code parentBs} as its
963    *       regular parent and {@code overridingParent} (if non-{@code null}) installed in the
964    *       overriding-parent slot so test-time overrides win over local entries.
965    * </ol>
966    *
967    * @param parentBs
968    *    The parent (bootstrap) bean store to layer onto, or {@code null} for root resources.
969    * @param resource
970    *    The REST servlet/bean instance that this context is defined against.
971    * @param overridingParent
972    *    Optional test-time override layer for the {@code overridingParent} slot of the freshly-constructed
973    *    {@link BasicBeanStore}.  May be {@code null}.  Ignored when the resource supplies its own
974    *    {@link WritableBeanStore} via an {@code @Bean} factory method &mdash; user-supplied stores are
975    *    passed through unchanged.
976    * @return The bean store for this context.
977    */
978   private WritableBeanStore createBeanStore(BeanStore parentBs, Supplier<?> resource, BeanStore overridingParent) {
979      var defaultBs = new BasicBeanStore(parentBs, overridingParent);
980      return defaultBs.createBeanFromMethod(WritableBeanStore.class, resource.get(), RestContext::isBeanMethod)
981         .orElse(defaultBs);
982   }
983
984   /**
985    * Returns {@code true} if a {@link Bean @Bean} field value of the specified type and name should be exported
986    * to the {@link #getInheritableBeanStore() inheritable bean store}.
987    *
988    * <p>
989    * Bean-store types and framework-managed types (see {@link #isFrameworkBeanType(Class, String)}, such as
990    * {@link SerializerSet} or {@link MethodExecStore}) are excluded so that each child keeps its own instances.
991    * This holds for named beans too: a {@code @Bean(name="encoders") EncoderSet} is not exported.
992    *
993    * @param type The bean type.
994    * @param name The bean name, or {@code null} for an unnamed bean.
995    * @return {@code true} if the value should be visible to {@code @Rest(children)} sub-resources.
996    */
997   private boolean isInheritableBeanType(Class<?> type, String name) {
998      if (WritableBeanStore.class.equals(type) || BeanStore.class.equals(type))
999         return false;
1000      return ! isFrameworkBeanType(type, name);
1001   }
1002
1003   /**
1004    * Returns {@code true} if the specified type and name denote a framework-managed bean, i.e. one backed by a
1005    * per-context default supplier registered under either the exact name or the unnamed slot.
1006    *
1007    * <p>
1008    * A framework type has one per-context instance, so {@code @Bean} methods of such a type are never invoked by the
1009    * registration walk (the framework memoizer invokes them) and are never exported to children.
1010    *
1011    * @param type The bean type.
1012    * @param name The bean name, or {@code null} for an unnamed bean.
1013    * @return {@code true} if the type is framework-managed.
1014    */
1015   private boolean isFrameworkBeanType(Class<?> type, String name) {
1016      return beanStore.hasDefaultSupplier(type, name) || beanStore.hasDefaultSupplier(type, "");
1017   }
1018
1019   private RestContext parentContext() { return parentContext; }
1020   private RestOperations restOperations() { return restOperations.get(); }
1021
1022   /**
1023    * Returns {@code true} when this context is a per-mixin sub-context constructed by the host's
1024    * {@code restOperations} memoizer.
1025    *
1026    * <p>
1027    * A mixin sub-context is parent-linked to the host's {@link RestContext} so that
1028    * {@link #getRestAnnotationsForProperty(String) annotation-property walks} prepend the host's {@code @Rest}
1029    * chain before the mixin's own &mdash; serializers, parsers, encoders, converters, response processors,
1030    * REST op args, guards, restDebugFormatter, messages, and varResolver tokens all inherit from the
1031    * host first, with the mixin's contributions appended.  Use {@link Rest#noInherit() @Rest(noInherit)} on the
1032    * mixin class to cut off inheritance for any specific property.
1033    *
1034    * <p>
1035    * {@link Rest#children() @Rest(children)} sub-resources are <i>not</i> mixin contexts &mdash; they retain
1036    * pre-10.0.0 isolated resolution (no parent-context walk), and inherit only the parent's
1037    * {@link #getInheritableBeanStore() non-framework beans}.  The mixin-vs-child divergence is intentional:
1038    * mixins are inline composers that share the host's URL namespace; children are heavyweight independent
1039    * resources mounted at their own URL prefix.
1040    *
1041    * @return {@code true} if this is a mixin sub-context, {@code false} for top-level resources and child
1042    *    resources.
1043    * @since 10.0.0
1044    */
1045   public boolean isMixinContext() { return isMixinContext; }
1046
1047   /**
1048    * Returns the parent {@link RestContext}, or {@code null} for top-level resources.
1049    *
1050    * <p>
1051    * The parent linkage drives the inheritance walk in {@link #getRestAnnotationsForProperty(String)} for
1052    * {@linkplain #isMixinContext() mixin sub-contexts}, and the {@code parentContext} walks performed by
1053    * {@link #getMessages()}, {@link #getVarResolver()}, {@code getFullPath()}, and the bean-store layering.
1054    *
1055    * @return The parent context, or {@code null} for top-level (host) resources.
1056    * @since 10.0.0
1057    */
1058   public RestContext getParentContext() { return parentContext; }
1059
1060   /**
1061    * Registers memoizer-backed default suppliers for every framework-managed bean type on the supplied
1062    * bean store.
1063    *
1064    * <p>
1065    * Default suppliers sit at the bottom of the bean-store resolution order: they fire only when no
1066    * {@link Bean @Bean} method, no programmatic {@code addBean(...)} call, and no Spring/overriding-parent
1067    * binding has been registered for the type.  This is the mechanism that replaces the old
1068    * {@code DELAYED_INJECTION} list — by registering the framework's own factories as defaults
1069    * <i>before</i> the {@link Bean @Bean} method walk runs, any {@link Bean @Bean} method whose parameters
1070    * include framework types can now resolve those parameters lazily through the bean store without
1071    * requiring a hand-maintained skip list.
1072    */
1073   private void registerFrameworkDefaults(WritableBeanStore bs) {
1074      // @formatter:off
1075      // Unnamed framework types backed by per-resource memoizers.
1076      bs.addDefaultSupplier(MarshallingContext.class, marshallingContext::get);
1077      bs.addDefaultSupplier(EncoderSet.class, encoders::get);
1078      bs.addDefaultSupplier(SerializerSet.class, serializers::get);
1079      bs.addDefaultSupplier(ParserSet.class, parsers::get);
1080      bs.addDefaultSupplier(RichLogger.class, logger::get);
1081      bs.addDefaultSupplier(java.util.logging.Logger.class, logger::get);
1082      bs.addDefaultSupplier(ThrownStore.class, thrownStore::get);
1083      bs.addDefaultSupplier(MethodExecStore.class, methodExecStore::get);
1084      bs.addDefaultSupplier(Messages.class, messages::get);
1085      bs.addDefaultSupplier(VarResolver.class, varResolver::get);
1086      bs.addDefaultSupplier(Config.class, config::get);
1087      bs.addDefaultSupplier(ResponseProcessor[].class, responseProcessors::get);
1088      bs.addDefaultSupplier(RestDebugFormatter.class, restDebugFormatter::get);
1089      bs.addDefaultSupplier(HttpPartSerializer.class, partSerializer::get);
1090      bs.addDefaultSupplier(HttpPartParser.class, partParser::get);
1091      bs.addDefaultSupplier(JsonSchemaGenerator.class, jsonSchemaGenerator::get);
1092      bs.addDefaultSupplier(StaticFiles.class, staticFiles::get);
1093      bs.addDefaultSupplier(FileFinder.class, staticFiles::get);
1094      bs.addDefaultSupplier(SwaggerProvider.class, swaggerProvider::get);
1095      bs.addDefaultSupplier(OpenApiProvider.class, openApiProvider::get);
1096      bs.addDefaultSupplier(RestOperations.class, restOperations::get);
1097      bs.addDefaultSupplier(RestChildren.class, restChildren::get);
1098      // Named framework beans (replaces DELAYED_INJECTION_NAMES).
1099      bs.addDefaultSupplier(VarResolver.class, this::getBootstrapVarResolver, "bootstrapVarResolver");
1100      bs.addDefaultSupplier(HttpHeaderList.class, defaultRequestHeaders::get, "defaultRequestHeaders");
1101      bs.addDefaultSupplier(HttpHeaderList.class, defaultResponseHeaders::get, "defaultResponseHeaders");
1102      bs.addDefaultSupplier(NamedAttributeMap.class, defaultRequestAttributes::get, "defaultRequestAttributes");
1103      bs.addDefaultSupplier(MethodList.class, () -> destroyInvokerPair.get().methods, "destroyMethods");
1104      bs.addDefaultSupplier(MethodList.class, () -> endCallInvokerPair.get().methods, "endCallMethods");
1105      bs.addDefaultSupplier(MethodList.class, postCallMethods::get, "postCallMethods");
1106      bs.addDefaultSupplier(MethodList.class, () -> postInitChildFirstInvokerPair.get().methods, "postInitChildFirstMethods");
1107      bs.addDefaultSupplier(MethodList.class, () -> postInitInvokerPair.get().methods, "postInitMethods");
1108      bs.addDefaultSupplier(MethodList.class, preCallMethods::get, "preCallMethods");
1109      bs.addDefaultSupplier(MethodList.class, () -> startCallInvokerPair.get().methods, "startCallMethods");
1110      // @formatter:on
1111   }
1112
1113   /**
1114    * Registers a {@link PropertySource} bean named {@code "rest.config"} in this resource's
1115    * {@code BeanStore} so that {@code @Value("${cfg-key}")} fields on the resource bean (and on
1116    * request-scoped beans whose {@code BeanStore} parent-walks to this one) resolve against the
1117    * resource's {@code @Rest(config=...)} {@link Config}(s).
1118    *
1119    * <p>
1120    * Lookup order honored by the registered source:
1121    * <ol>
1122    *    <li>The child class's resolved {@link Config} &mdash; sourced from {@link #rawConfig} so that
1123    *       any {@link Bean @Bean Config} factory-method override on the resource bean is preserved.
1124    *    <li>Any additional, distinct {@code @Rest(config=...)} {@code Config}s declared on parent
1125    *       classes (child-to-parent order, dedup'd by resolved file name). Child keys win on
1126    *       collision; parent keys fill the gaps.
1127    * </ol>
1128    *
1129    * <p>
1130    * Critically, this registration lives on the per-resource {@code BeanStore} &mdash; <i>not</i> on
1131    * the process-wide {@code Settings.get()} singleton. The static {@code RestContext} cache in
1132    * {@code MockRestClient} (and any other long-lived cache) is therefore benign: leaked
1133    * {@code RestContext}s carry their {@code PropertySource}s in their own {@code BeanStore}s.
1134    * The global {@code Settings} source list does not grow, and {@code Settings.get(name)}'s
1135    * reverse-order walk stays O(constant).
1136    */
1137   private void registerRestConfigPropertySources() {
1138      var sources = collectRestConfigPropertySources();
1139      if (sources.isEmpty())
1140         return;
1141      final List<PropertySource> chain = List.copyOf(sources);
1142      PropertySource src;
1143      if (chain.size() == 1) {
1144         src = chain.get(0);
1145      } else {
1146         src = name -> {
1147            for (var s : chain) {
1148               var r = s.get(name);
1149               if (r.isPresent())
1150                  return r;
1151            }
1152            return PropertyLookupResult.missing();
1153         };
1154      }
1155      beanStore.addBean(PropertySource.class, src, "rest.config");
1156   }
1157
1158   /**
1159    * Walks the {@code @Rest(config=...)} annotation chain (child-first) and builds a
1160    * {@link ConfigPropertySource} for each distinct, non-empty config attribute.
1161    *
1162    * <p>
1163    * The first (most-derived) slot reuses {@code rawConfig.get()} so that any {@link Bean @Bean}
1164    * {@code Config} factory-method override on the resource bean is preserved &mdash; the rest of
1165    * the framework already sees that exact instance via {@link #getConfig()} and {@code @RestInit}
1166    * parameter resolution. Parent slots load via {@code Config.create().name(...)} since {@code @Bean}
1167    * overrides apply to the most-derived class only.
1168    *
1169    * <p>
1170    * Edge case: a resource with no {@code @Rest(config=...)} annotation but with a {@link Bean @Bean}
1171    * {@code Config} factory method has a non-null {@code rawConfig.get()} and no annotation-driven
1172    * slot. That single {@code rawConfig} is still registered so user-supplied {@code Config}s flow
1173    * through to {@code @Value} resolution.
1174    */
1175   @SuppressWarnings({
1176      "java:S135" // Per-annotation continue guards are clearer than restructuring the config-source filter chain.
1177   })
1178   private List<PropertySource> collectRestConfigPropertySources() {
1179      var bs = beanStore();
1180      var vr = bs.getBean(VarResolver.class, "bootstrapVarResolver").orElseGet(this::getBootstrapVarResolver);
1181      var result = new ArrayList<PropertySource>();
1182      var seen = new LinkedHashSet<String>();
1183      // AnnotationProvider returns child-first; iterate in the same order so child wins on collision.
1184      var anns = AnnotationProvider.INSTANCE.find(Rest.class, info(resourceClass));
1185      for (var i = 0; i < anns.size(); i++) {
1186         var raw = anns.get(i).inner().config();
1187         if (isEmpty(raw))
1188            continue;
1189         var resolvedName = vr.resolve(raw);
1190         if (isEmpty(resolvedName))
1191            continue;
1192         if (! seen.add(resolvedName))
1193            continue;
1194         Config cfg;
1195         if (result.isEmpty()) {
1196            // Most-derived child slot. rawConfig.get() captures @Bean Config override; reuse it.
1197            cfg = rawConfig.get();
1198         } else if (eq(resolvedName, "SYSTEM_DEFAULT")) {
1199            cfg = Config.getSystemDefault();
1200         } else {
1201            cfg = Config.create().varResolver(vr).name(resolvedName).build();
1202         }
1203         if (cfg != null)
1204            result.add(new ConfigPropertySource(cfg));
1205      }
1206      // Edge case: no @Rest(config=...) annotation produced a slot, but rawConfig.get() is non-null
1207      // (e.g. a @Bean Config factory method without a matching @Rest(config=...) attribute, or the
1208      // SYSTEM_DEFAULT branch fired without an annotation). Still register rawConfig as the sole source.
1209      if (result.isEmpty()) {
1210         var rc = rawConfig.get();
1211         if (rc != null)
1212            result.add(new ConfigPropertySource(rc));
1213      }
1214      return result;
1215   }
1216
1217   private static final class LifecycleInvokerPair {
1218      final MethodList methods;
1219      final MethodInvoker[] invokers;
1220
1221      LifecycleInvokerPair(MethodList methods, MethodInvoker[] invokers) {
1222         this.methods = methods;
1223         this.invokers = invokers;
1224      }
1225   }
1226
1227   /**
1228    * The {@link MarshallingContext} for this resource.
1229    *
1230    * <p>
1231    * Triggered eagerly in the constructor after {@code annotationWork} is set, so that annotation
1232    * work is applied before the builder is used by any other memoizer.
1233    */
1234   private final Memoizer<MarshallingContext.Builder> beanContextBuilder = memoizer(() -> {
1235      var v = Holder.of(MarshallingContext.create());
1236      v.get().apply(annotationWork);
1237      return v.get();
1238   });
1239
1240   /**
1241    * The {@link MarshallingContext} for this resource.
1242    */
1243   private final Memoizer<MarshallingContext> marshallingContext = memoizer(() -> beanContextBuilder.get().build());
1244
1245   /**
1246    * The unresolved (bootstrap-time) {@link Config} for this resource.
1247    *
1248    * <p>
1249    * Resolved by reading {@code @Rest(config)} from the annotation chain against the bootstrap
1250    * {@link VarResolver} (which must already be in the bean store). Triggered eagerly in the constructor
1251    * so the raw config is registered before {@code @RestInit} hooks run.
1252    */
1253   private final Memoizer<Config> rawConfig = memoizer(() -> {
1254      var bs = beanStore();
1255      var v = Holder.<Config>empty();
1256      // Bootstrap VarResolver is registered under "bootstrapVarResolver" during construction; the
1257      // unnamed VarResolver slot is reserved for the full runtime resolver default supplier.
1258      var vr = bs.getBean(VarResolver.class, "bootstrapVarResolver").orElseGet(this::getBootstrapVarResolver);
1259      var cfv = Holder.<String>empty();
1260      rstream(AnnotationProvider.INSTANCE.find(Rest.class, info(resourceClass()))).map(x -> x.inner().config()).filter(Shorts::ine).forEach(x -> cfv.set(vr.resolve(x)));
1261      var cf = cfv.orElse("");
1262      if (v.isEmpty() && eq(cf, "SYSTEM_DEFAULT"))
1263         v.set(Config.getSystemDefault());
1264      if (v.isEmpty() && cf.isEmpty() && isMixinContextField() && getParentContext() != null)
1265         // Mixin sub-contexts with no own @Rest(config) inherit the host's raw Config, so that ${C:...}
1266         // SVL variables embedded in inherited class-level config (e.g. the @HtmlDocConfig theme/header/
1267         // footer declared via ${C:REST/...} on BasicRestConfig) resolve against the host's loaded config
1268         // rather than an empty one.  This mirrors the way messages and varResolver tokens already inherit
1269         // from the host for mixin sub-contexts.
1270         v.set(getParentContext().rawConfig.get());
1271      if (v.isEmpty()) {
1272         Config.Builder cb = Config.create().varResolver(vr);
1273         if (!cf.isEmpty())
1274            cb.name(cf);
1275         v.set(cb.build());
1276      }
1277      bs.createBeanFromMethod(Config.class, resource().get(), RestContext::isBeanMethod, v.get()).ifPresent(v::set);
1278      return v.get();
1279   });
1280
1281   /**
1282    * The bootstrap-time {@link VarResolver} — no {@link Messages} or {@link Config} bean available yet.
1283    *
1284    * <p>
1285    * Builds the same {@link Var} catalog as the runtime resolver but without {@link Messages} or {@link Config}
1286    * beans wired in — those depend on settings that are themselves resolved against this resolver.
1287    * Triggered eagerly in the constructor so the result is available in the bean store before
1288    * {@link Config} and annotation work are initialized.
1289    */
1290   // @formatter:off
1291   private final Memoizer<VarResolver> bootstrapVarResolver = memoizer(() -> {
1292      var bs = beanStore();
1293      Holder<VarResolver> v = Holder.of(
1294         VarResolver.create()
1295            .defaultVars()
1296            .defaultFunctions()
1297            .vars(VarList.of(
1298               ConfigVar.class, FileVar.class, LocalizationVar.class,
1299               RequestAttributeVar.class, RequestFormDataVar.class, RequestHeaderVar.class,
1300               RequestPathVar.class, RequestQueryVar.class, RequestVar.class,
1301               RequestSwaggerVar.class, SerializedRequestAttrVar.class, ServletInitParamVar.class,
1302               SwaggerVar.class, OpenApiVar.class, UrlVar.class, UrlEncodeVar.class, HtmlWidgetVar.class
1303            ).addDefault())
1304            .bean(FileFinder.class, FileFinder.create(bs).cp(resourceClass(), null, true).build())
1305            .build()
1306      );
1307      bs.createBeanFromMethod(VarResolver.class, resource().get(), x -> isBeanMethod(x, "bootstrapVarResolver")).ifPresent(v::set);
1308      return v.get();
1309   });
1310   // @formatter:on
1311
1312   /**
1313    * The default {@link RestDebugFormatter} for this resource.
1314    *
1315    * <p>
1316    * Defaults to {@link BasicRestDebugFormatter}. A bean-store override or {@code @Bean} factory method REPLACES the
1317    * result. (Resource-class-implements-the-SPI precedence is applied by {@link #getRestDebugFormatter()}, ahead of this
1318    * default supplier.)
1319    */
1320   private final Memoizer<RestDebugFormatter> restDebugFormatter = memoizer(() -> {
1321      var bs = beanStore();
1322      var creator = BeanInstantiator.of(RestDebugFormatter.class, bs).type(BasicRestDebugFormatter.class).noBuilder();
1323      bs.getBeanType(RestDebugFormatter.class).ifPresent(creator::type);
1324      bs.createBeanFromMethod(RestDebugFormatter.class, resource().get(), RestContext::isBeanMethod).ifPresent(creator::impl);
1325      return creator.asOptional().orElse(null);
1326   });
1327
1328   /**
1329    * The effective {@link RequestIdSettings} for this resource's always-on request-id resolver.
1330    *
1331    * <p>
1332    * Explicit three-rung resolution (highest precedence first):
1333    * <ol>
1334    *    <li>Registered bean &mdash; {@code beanStore().getBean(RequestIdSettings.class)}.
1335    *    <li>{@code @Bean} factory method on the resource.
1336    *    <li>The built-in defaults ({@link RequestIdSettings.Builder}: sanitize-and-accept validator, {@code "requestId"}
1337    *       attribute key, version-7 UUID supplier).
1338    * </ol>
1339    */
1340   private final Memoizer<RequestIdSettings> requestIdSettings = memoizer(() -> {
1341      var bs = beanStore();
1342      var bean = bs.getBean(RequestIdSettings.class).orElse(null);
1343      if (bean != null)
1344         return bean;
1345      var fromMethod = bs.createBeanFromMethod(RequestIdSettings.class, resource().get(), RestContext::isBeanMethod).orElse(null);
1346      if (fromMethod != null)
1347         return fromMethod;
1348      return RequestIdSettings.create().build();
1349   });
1350
1351   /**
1352    * The locally-resolved {@link RestAuthenticator} for this resource, if any.
1353    *
1354    * <p>
1355    * Resolution precedence (highest first):
1356    * <ol>
1357    *    <li>Registered bean &mdash; {@code beanStore().getBean(RestAuthenticator.class)}.
1358    *    <li>{@code @Rest(authenticator=X)} &mdash; instantiated via the bean store (constructor injection).
1359    *    <li>{@code @Bean} factory method on the resource.
1360    *    <li>{@link RestServlet#createAuthenticator(BeanStore)} override.
1361    * </ol>
1362    * The {@link RestAuthenticator.Null} sentinel is treated as &quot;unset.&quot;
1363    */
1364   private final Memoizer<Optional<RestAuthenticator>> localAuthenticator = memoizer(() -> {
1365      var bs = beanStore();
1366      var bean = bs.getBean(RestAuthenticator.class).orElse(null);
1367      if (bean != null)
1368         return o(bean);
1369      var annoClass = getRestAnnotationsForProperty("authenticator")
1370         .map(ai -> ai.inner().authenticator())
1371         .filter(x -> x != RestAuthenticator.Null.class)
1372         .reduce((first, second) -> second)
1373         .orElse(null);
1374      if (annoClass != null)
1375         return o(BeanInstantiator.of(RestAuthenticator.class, bs).type(annoClass).noBuilder().run());
1376      var fromMethod = bs.createBeanFromMethod(RestAuthenticator.class, resource().get(), RestContext::isBeanMethod).orElse(null);
1377      if (fromMethod != null)
1378         return o(fromMethod);
1379      if (resource().get() instanceof RestServlet rs) {
1380         var fromOverride = rs.createAuthenticator(bs);
1381         if (fromOverride != null)
1382            return o(fromOverride);
1383      }
1384      return Optional.<RestAuthenticator>empty();
1385   });
1386
1387   /**
1388    * The effective root-to-this {@link RestAuthenticator} list, honoring {@code noInherit={"authenticator"}}.
1389    *
1390    * <p>
1391    * Unlike guards (which are child-isolated), authenticators inherit down the child-resource tree: the parent
1392    * context's effective list is prepended (root first), then this resource's local authenticator is appended.
1393    * A {@code @Rest(noInherit={"authenticator"})} on this resource cuts off the parent walk (subtree opt-out).
1394    */
1395   private final Memoizer<List<RestAuthenticator>> effectiveAuthenticators = memoizer(() -> {
1396      var l = new ArrayList<RestAuthenticator>();
1397      var pc = parentContext();
1398      if (isInherited("authenticator") && pc != null)
1399         l.addAll(pc.getEffectiveAuthenticators());
1400      localAuthenticator.get().ifPresent(l::add);
1401      return u(l);
1402   });
1403
1404   /**
1405    * Returns the effective (root-to-this) authenticator chain for this resource.
1406    *
1407    * @return The effective authenticator chain, never <jk>null</jk>; may be empty.
1408    * @since 10.0.0
1409    */
1410   public List<RestAuthenticator> getEffectiveAuthenticators() {
1411      return effectiveAuthenticators.get();
1412   }
1413
1414   /**
1415    * Runs the effective authenticator chain for this request, folding results and applying the resolved
1416    * principal/roles to the {@link RestRequest}.
1417    *
1418    * <p>
1419    * Invoked by {@link RestSession} before {@code preCall}.  When no authenticators are configured this is a
1420    * no-op (anonymous passthrough).  Each authenticator's {@link AuthenticationException} propagates to abort
1421    * the request with a {@code 401}.
1422    *
1423    * @param session The op session for this request.
1424    * @throws AuthenticationException If credentials are present but invalid.
1425    * @since 10.0.0
1426    */
1427   protected void authenticate(RestOpSession session) throws AuthenticationException {
1428      var auths = getEffectiveAuthenticators();
1429      if (auths.isEmpty())
1430         return;
1431      var req = session.getRequest();
1432      var acc = new AuthResultAccumulator();
1433      // Seed the fold with any pre-existing identity (container security or a servlet-layer AuthFilterChain) so
1434      // roles-only ADD results from resource authenticators augment it instead of being dropped.
1435      // A later REPLACE result still overrides this seed (the accumulator resets principal+roles on REPLACE).
1436      var existing = req.getUserPrincipal();
1437      if (existing != null)
1438         acc.add(AuthResult.of(existing));
1439      for (var a : auths)
1440         a.authenticate(req).ifPresent(acc::add);  // RestRequest is-a HttpServletRequest; AuthenticationException propagates -> 401
1441      acc.result().ifPresent(req::setAuthResult);
1442   }
1443
1444   /**
1445    * The resolving {@link Config} for this resource.
1446    *
1447    * <p>
1448    * Wraps the builder's unresolved config with a {@link VarResolver} session so that SVL variables
1449    * in config values are expanded on access.
1450    */
1451   private final Memoizer<Config> config = memoizer(() -> rawConfig.get().resolving(getVarResolver().createSession()));
1452
1453   /**
1454    * The supported request content types ({@code Content-Type} media types) for this resource.
1455    *
1456    * <p>
1457    * Walks {@code @Rest(consumes)} annotations parent-to-child and returns the union. When no annotation
1458    * declares types, falls back to the intersection of all op-level parser supported media types.
1459    */
1460   private final Memoizer<List<MediaType>> consumes = memoizer(() -> {
1461      // Walk @Rest(consumes=...) chain (parent-to-child); concat all entries in chain order.
1462      var fromAnnotations = new ArrayList<MediaType>();
1463      getRestAnnotationsForProperty("consumes")
1464         .forEach(ai -> stream(ai.inner().consumes()).map(MediaType::of).forEach(fromAnnotations::add));
1465      if (! fromAnnotations.isEmpty())
1466         return u(fromAnnotations);
1467      // Fall back to the intersection of opContexts' parser-supported media types — matches legacy behavior.
1468      var opContexts = restOperations().getOpContexts();
1469      Set<MediaType> s = opContexts.isEmpty() ? emptySet() : toSet(opContexts.get(0).getParsers().getSupportedMediaTypes());
1470      opContexts.forEach(x -> s.retainAll(x.getParsers().getSupportedMediaTypes()));
1471      return u(toList(s));
1472   });
1473
1474   //---------------------------------------------------------------------------------------------
1475   // Env-driven defaults
1476   //
1477   // The three @Value fields (debug level, uriAuthority, uriContext) are populated by
1478   // ClassInfo.of(this).inject(this, beanStore) during construction; the remaining RestContext.* defaults are
1479   // carried by the RestContextProperties bean (materialized once during construction — see the constructor).
1480   // Together they supply the env-driven default that flows into mergeReplacedStringAttribute /
1481   // mergeReplacedBooleanAttribute as the initial value before the @Rest annotation chain is walked.
1482   //---------------------------------------------------------------------------------------------
1483
1484   /** Env-driven default for {@code @Rest(uriAuthority)}; {@link Optional#empty()} when unset (preserves null-vs-empty distinction). */
1485   @Value("${RestContext.uriAuthority}")
1486   private Optional<String> defaultUriAuthority;
1487
1488   /** Env-driven default for {@code @Rest(uriContext)}; {@link Optional#empty()} when unset (preserves null-vs-empty distinction). */
1489   @Value("${RestContext.uriContext}")
1490   private Optional<String> defaultUriContext;
1491
1492   /**
1493    * The env-driven {@code RestContext.*} default properties for this resource.
1494    *
1495    * <p>
1496    * Materialized through {@link BeanInstantiator}, which runs the {@code @ConfigProperties} resolution hook and
1497    * auto-registers the bound instance into {@link #beanStore()}. The bind resolves each {@code RestContext.*} key
1498    * against the resource's per-resource {@link PropertySource PropertySource}s
1499    * (including a {@code @Rest(config=...)} file) ahead of the global settings chain, so a config-file key takes
1500    * effect in the resolved defaults. This memoizer is forced exactly once during construction (after the
1501    * PropertySources are registered) so the single bound instance is the same one held in the bean store; see the
1502    * constructor for the ordering rationale.
1503    */
1504   private final Memoizer<RestContextProperties> restContextProperties = memoizer(() ->
1505      BeanInstantiator.of(RestContextProperties.class, beanStore()).run());
1506
1507   /**
1508    * The default request attributes contributed by {@code @Rest(defaultRequestAttributes)} for this resource.
1509    *
1510    * <p>
1511    * Walks {@code @Rest} annotations parent-to-child, resolving each attribute string and parsing it as a
1512    * key=value or key:value pair. A named bean-store override or {@code @Bean} factory method REPLACES
1513    * the accumulated result.
1514    */
1515   private final Memoizer<NamedAttributeMap> defaultRequestAttributes = memoizer(() -> {
1516      var v = Holder.of(NamedAttributeMap.create());
1517      // Resolution goes through the unified noInherit-aware walk: getRestAnnotationsForProperty yields
1518      // the same parent-to-child order getRestAnnotationsTopDown did for non-mixin contexts, plus host→mixin
1519      // inheritance, noInherit cutoff, and @Mixin override injection for mixin sub-contexts.
1520      getRestAnnotationsForProperty("defaultRequestAttributes").forEach(ai -> Arrays.stream(ai.inner().defaultRequestAttributes())
1521         .filter(StringUtils::isNotBlank)
1522         .map(this::resolve)
1523         .filter(StringUtils::isNotBlank)
1524         .map(BasicNamedAttribute::ofPair)
1525         .forEach(v.get()::add));
1526      beanStore().createBeanFromMethod(NamedAttributeMap.class, resource().get(), x -> isBeanMethod(x, "defaultRequestAttributes"), v.get()).ifPresent(v::set);
1527      return v.get();
1528   });
1529
1530   /**
1531    * The default request headers contributed by {@code @Rest(defaultRequestHeaders)},
1532    * {@code @Rest(defaultAccept)}, and {@code @Rest(defaultContentType)} for this resource.
1533    *
1534    * <p>
1535    * Walks {@code @Rest} annotations parent-to-child, resolving each header string. A named bean-store
1536    * override or {@code @Bean} factory method REPLACES the accumulated result.
1537    */
1538   private final Memoizer<HttpHeaderList> defaultRequestHeaders = memoizer(() -> {
1539      var v = Holder.of(HttpHeaderList.create());
1540      // Resolution goes through the unified noInherit-aware walk — see defaultRequestAttributes.
1541      // defaultAccept/defaultContentType are folded into this same walk (as they always were); they key off
1542      // the defaultRequestHeaders property for noInherit/override purposes.
1543      getRestAnnotationsForProperty("defaultRequestHeaders").forEach(ai -> {
1544         Rest a = ai.inner();
1545         Arrays.stream(a.defaultRequestHeaders()).filter(StringUtils::isNotBlank).map(this::resolve).filter(StringUtils::isNotBlank).map(HttpStringHeader::ofPair).forEach(v.get()::setDefault);
1546         var defaultAccept = resolve(a.defaultAccept());
1547         if (isNotBlank(defaultAccept))
1548            v.get().setDefault(Accept.of(defaultAccept));
1549         var defaultContentType = resolve(a.defaultContentType());
1550         if (isNotBlank(defaultContentType))
1551            v.get().setDefault(ContentType.of(defaultContentType));
1552      });
1553      beanStore().createBeanFromMethod(HttpHeaderList.class, resource().get(), x -> isBeanMethod(x, "defaultRequestHeaders"), v.get()).ifPresent(v::set);
1554      return v.get();
1555   });
1556
1557   /**
1558    * The default response headers contributed by {@code @Rest(defaultResponseHeaders)} for this resource.
1559    *
1560    * <p>
1561    * Walks {@code @Rest} annotations parent-to-child, resolving each header string. A named bean-store
1562    * override or {@code @Bean} factory method REPLACES the accumulated result.
1563    */
1564   private final Memoizer<HttpHeaderList> defaultResponseHeaders = memoizer(() -> {
1565      var v = Holder.of(HttpHeaderList.create());
1566      // Resolution goes through the unified noInherit-aware walk — see defaultRequestAttributes.
1567      getRestAnnotationsForProperty("defaultResponseHeaders").forEach(ai -> Arrays.stream(ai.inner().defaultResponseHeaders()).filter(StringUtils::isNotBlank).map(this::resolve).filter(StringUtils::isNotBlank).map(HttpStringHeader::ofPair).forEach(v.get()::setDefault));
1568      beanStore().createBeanFromMethod(HttpHeaderList.class, resource().get(), x -> isBeanMethod(x, "defaultResponseHeaders"), v.get()).ifPresent(v::set);
1569      return v.get();
1570   });
1571
1572   /**
1573    * Methods annotated with {@link RestDestroy @RestDestroy} and their invokers.
1574    */
1575   private final Memoizer<LifecycleInvokerPair> destroyInvokerPair = memoizer(() -> buildLifecycleInvokerPair(() -> {
1576      var bs = beanStore();
1577      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestDestroy.class).toList()));
1578      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "destroyMethods"), v.get()).ifPresent(v::set);
1579      return v.get();
1580   }));
1581
1582   /**
1583    * Fully-configured {@link EncoderSet.Builder} for this resource, populated from the
1584    * {@code @Rest(encoders)} annotation chain and any {@code @Bean} override.
1585    *
1586    * <p>
1587    * Starts with {@link IdentityEncoder} as the implicit default. A bean-store type override
1588    * or bean-store instance override REPLACES the builder or its impl. Annotation entries
1589    * (parent-to-child) are appended after the default. A {@code @Bean} factory method
1590    * REPLACES the impl with the returned value.
1591    */
1592   private final Memoizer<EncoderSet.Builder> encodersBuilder = memoizer(() -> {
1593      var bs = beanStore();
1594      var v = Holder.of(EncoderSet.create(bs));
1595      getRestAnnotationsForProperty("encoders").forEach(ai -> v.get().add(ai.inner().encoders()));
1596      bs.createBeanFromMethod(EncoderSet.class, resource().get(), RestContext::isBeanMethod, v.get()).ifPresent(x -> v.get().impl(x));
1597      return v.get();
1598   });
1599
1600   /**
1601    * The {@link EncoderSet} for this resource, built from the self-contained encoder builder memoizer.
1602    */
1603   private final Memoizer<EncoderSet> encoders = memoizer(() -> encodersBuilder.get().build());
1604
1605   /**
1606    * Methods annotated with {@link RestEndCall @RestEndCall} and their invokers.
1607    */
1608   private final Memoizer<LifecycleInvokerPair> endCallInvokerPair = memoizer(() -> buildLifecycleInvokerPair(() -> {
1609      var bs = beanStore();
1610      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestEndCall.class).toList()));
1611      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "endCallMethods"), v.get()).ifPresent(v::set);
1612      return v.get();
1613   }));
1614
1615   /**
1616    * The {@link JsonSchemaGenerator.Builder} for this resource, with annotation work applied.
1617    */
1618   private final Memoizer<JsonSchemaGenerator.Builder> jsonSchemaGeneratorBuilder = memoizer(() -> {
1619      var bs = beanStore();
1620      var v = Holder.of(JsonSchemaGenerator.create());
1621      bs.createBeanFromMethod(JsonSchemaGenerator.class, resource().get(), RestContext::isBeanMethod).ifPresent(x -> v.get().impl(x));
1622      v.get().apply(annotationWork);
1623      return v.get();
1624   });
1625
1626   /**
1627    * The {@link JsonSchemaGenerator} for this resource.
1628    */
1629   private final Memoizer<JsonSchemaGenerator> jsonSchemaGenerator = memoizer(() -> jsonSchemaGeneratorBuilder.get().build());
1630
1631   /**
1632    * The {@link RichLogger} for this resource.
1633    *
1634    * <p>
1635    * Defaults to {@code RichLogger.getLogger(LoggerNaming.userClassName(resourceClass))}. A bean-store override or
1636    * {@code @Bean} factory method REPLACES the default.
1637    */
1638   private final Memoizer<RichLogger> logger = memoizer(() -> {
1639      var v = Holder.of(RichLogger.getLogger(LoggerNaming.userClassName(resourceClass())));
1640      beanStore().createBeanFromMethod(RichLogger.class, resource().get(), RestContext::isBeanMethod, v.get()).ifPresent(v::set);
1641      return v.get();
1642   });
1643
1644   /**
1645    * The {@link Messages} bundle for this resource.
1646    *
1647    * <p>
1648    * Walks {@code @Rest} annotations parent-to-child, resolving each {@code messages} location string
1649    * against the bootstrap resolver (full resolver not yet available — it depends on {@code getMessages()}).
1650    * A bean-store override or {@code @Bean} factory method REPLACES the result.
1651    */
1652   private final Memoizer<Messages> messages = memoizer(() -> {
1653      var b = Messages.create(resourceClass());
1654      // Walk @Rest annotations parent-to-child; child wins because location() prepends.
1655      // Resolve location strings against the simple resolver — full resolver isn't available yet
1656      // (it depends on getMessages()).
1657      // NOTE: messages is structurally bundle-CHAINED (not list/replace-merged), so it keeps its
1658      // own local location walk + Messages.chain rather than routing through getRestAnnotationsForProperty
1659      // (which would double-count host locations for a mixin context).  The two @Mixin hooks are layered on
1660      // explicitly instead: (1) a host @Mixin(messages=...) location is applied last (highest priority), and
1661      // (2) the host→mixin chain cutoff consults the unified noInherit set, so @Mixin(noInherit="messages")
1662      // cuts the host bundle exactly like the mixin class's own @Rest(noInherit="messages").
1663      var vrs = getBootstrapVarResolver().createSession();
1664      getRestAnnotationsTopDown().forEach(ai -> ai.getString("messages").filter(StringUtils::isNotBlank).ifPresent(s -> b.location(vrs.resolve(s))));
1665      var rmMessages = resolvedMixinField();
1666      if (rmMessages != null) {
1667         var mm = rmMessages.overrides().messages();
1668         if (StringUtils.isNotBlank(mm))
1669            b.location(vrs.resolve(mm));
1670      }
1671      var override = beanStore().createBeanFromMethod(Messages.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
1672      var local = nn(override) ? override : b.build();
1673      var parent = parentContext();
1674      // Use the SVL-free isNoInheritLiteral (NOT the noInherit memoizer) to avoid a resolver cycle:
1675      // noInherit -> resolveCdl -> getVarResolver -> getMessages -> messages.  It now also consults the
1676      // host @Mixin(noInherit=...) tokens so a @Mixin can cut the host bundle just like the mixin class's own.
1677      if (isMixinContextField() && nn(parent) && !isNoInheritLiteral("messages"))
1678         return Messages.chain(local, parent.getMessages());
1679      return local;
1680   });
1681
1682   /**
1683    * The {@link MethodExecStore} for this resource, wired to the {@link ThrownStore}.
1684    *
1685    * <p>
1686    * A bean-store override or {@code @Bean} factory method REPLACES the result.
1687    */
1688   private final Memoizer<MethodExecStore> methodExecStore = memoizer(() -> {
1689      var bs = beanStore();
1690      var b = MethodExecStore.create(bs).thrownStoreOnce(getThrownStore());
1691      bs.createBeanFromMethod(MethodExecStore.class, resource().get(), RestContext::isBeanMethod, b).ifPresent(b::impl);
1692      return b.build();
1693   });
1694
1695   /**
1696    * Fully-configured {@link ParserSet.Builder} for this resource, populated from the
1697    * {@code @Rest(parsers)} annotation chain and any {@code @Bean} override.
1698    *
1699    * <p>
1700    * Starts with an empty set. A bean-store type or instance override REPLACES the builder or its impl.
1701    * Annotation entries (parent-to-child) are appended. A {@code @Bean} factory method REPLACES the impl.
1702    */
1703   private final Memoizer<ParserSet.Builder> parsersBuilder = memoizer(() -> {
1704      var bs = beanStore();
1705      var v = Holder.of(ParserSet.create(bs));
1706      getRestAnnotationsForProperty("parsers").forEach(ai -> v.get().add(ai.inner().parsers()));
1707      bs.createBeanFromMethod(ParserSet.class, resource().get(), RestContext::isBeanMethod, v.get()).ifPresent(x -> v.get().impl(x));
1708      return v.get();
1709   });
1710
1711   /**
1712    * The {@link ParserSet} for this resource, built from the self-contained parser builder memoizer.
1713    */
1714   private final Memoizer<ParserSet> parsers = memoizer(() -> parsersBuilder.get().build());
1715
1716   /**
1717    * The {@link HttpPartParser.Creator} for this resource, with annotation work applied.
1718    */
1719   private final Memoizer<HttpPartParser.Creator> partParserCreator = memoizer(() -> {
1720      var bs = beanStore();
1721      Holder<HttpPartParser.Creator> v = Holder.of(HttpPartParser.creator().type(OpenApiParser.class));
1722      o(resource().get() instanceof HttpPartParser x ? x : null).ifPresent(x -> v.get().impl(x));
1723      bs.createBeanFromMethod(HttpPartParser.class, resource().get(), RestContext::isBeanMethod).ifPresent(x -> v.get().impl(x));
1724      v.get().apply(annotationWork);
1725      return v.get();
1726   });
1727
1728   /**
1729    * The {@link HttpPartParser} for this resource.
1730    *
1731    * <p>
1732    * Starts from the creator (general config annotations already applied) and adds the
1733    * {@code @Rest(partParser)} type override from the most specific annotation in the hierarchy.
1734    */
1735   private final Memoizer<HttpPartParser> partParser = memoizer(() -> {
1736      var creator = partParserCreator.get();
1737      getRestAnnotationsForProperty("partParser")
1738         .map(ai -> ai.inner().partParser())
1739         .filter(ClassUtils::isNotVoid)
1740         .reduce((a, b) -> b)
1741         .ifPresent(creator::type);
1742      return creator.create();
1743   });
1744
1745   /**
1746    * The {@link HttpPartSerializer.Creator} for this resource, with annotation work applied.
1747    */
1748   private final Memoizer<HttpPartSerializer.Creator> partSerializerCreator = memoizer(() -> {
1749      var bs = beanStore();
1750      Holder<HttpPartSerializer.Creator> v = Holder.of(HttpPartSerializer.creator().type(OpenApiSerializer.class));
1751      o(resource().get() instanceof HttpPartSerializer x ? x : null).ifPresent(x -> v.get().impl(x));
1752      bs.createBeanFromMethod(HttpPartSerializer.class, resource().get(), RestContext::isBeanMethod).ifPresent(x -> v.get().impl(x));
1753      v.get().apply(annotationWork);
1754      return v.get();
1755   });
1756
1757   /**
1758    * The {@link HttpPartSerializer} for this resource.
1759    *
1760    * <p>
1761    * Starts from the creator (general config annotations already applied) and adds the
1762    * {@code @Rest(partSerializer)} type override from the most specific annotation in the hierarchy.
1763    */
1764   private final Memoizer<HttpPartSerializer> partSerializer = memoizer(() -> {
1765      var creator = partSerializerCreator.get();
1766      getRestAnnotationsForProperty("partSerializer")
1767         .map(ai -> ai.inner().partSerializer())
1768         .filter(ClassUtils::isNotVoid)
1769         .reduce((a, b) -> b)
1770         .ifPresent(creator::type);
1771      return creator.create();
1772   });
1773
1774   /**
1775    * Methods annotated with {@link RestPostCall @RestPostCall}.
1776    */
1777   private final Memoizer<MethodList> postCallMethods = memoizer(() -> {
1778      var bs = beanStore();
1779      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestPostCall.class).toList()));
1780      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "postCallMethods"), v.get()).ifPresent(v::set);
1781      return v.get();
1782   });
1783
1784   /**
1785    * Pre-resolved invokers for this context's local {@code @RestPostCall} methods, bound to this
1786    * context's resource instance and bean-store-resolved arg resolvers. Used by the {@link #postCall(RestOpSession)}
1787    * parent-chain walk so that host hooks fire before mixin hooks on mixin-endpoint requests.
1788    *
1789    * <p>
1790    * Hook methods aren't op-specific, so the wrapping bean store stubs in the op-only {@link UrlPathMatcher}
1791    * binding with {@code null} so that {@link PathArg#create PathArg.create()} (and
1792    * other op-aware resolvers) can be called by {@link #findRestOperationArgs(java.lang.reflect.Method, BeanStore)}
1793    * and abstain (return {@code null}) for parameters that aren't {@code @Path}-annotated. Using
1794    * {@code @Path} on a {@code @RestPostCall} method is not supported.
1795    */
1796   private final Memoizer<RestOpInvoker[]> localPostCallInvokers = memoizer(() -> {
1797      var bs = new BasicBeanStore(beanStore());
1798      var pm = getPathMatcher() != null ? getPathMatcher() : UrlPathMatcher.of("");
1799      bs.addBean(UrlPathMatcher.class, pm);
1800      bs.addBean(UrlPathMatcher[].class, new UrlPathMatcher[]{pm});
1801      return postCallMethods.get().stream()
1802         .map(x -> new RestOpInvoker(x, findRestOperationArgs(x, bs), getMethodExecStats(x), this::getResource))
1803         .toArray(RestOpInvoker[]::new);
1804   });
1805
1806   /**
1807    * Methods annotated with {@link RestPostInit @RestPostInit}{@code (childFirst=true)} and their invokers.
1808    */
1809   private final Memoizer<LifecycleInvokerPair> postInitChildFirstInvokerPair = memoizer(() -> buildLifecycleInvokerPair(() -> {
1810      var bs = beanStore();
1811      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestPostInit.class)
1812         .filter(m -> rstream(AnnotationProvider.INSTANCE.find(RestPostInit.class, MethodInfo.of(m))).map(AnnotationInfo::inner).anyMatch(RestPostInit::childFirst))
1813         .toList()));
1814      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "postInitChildFirstMethods"), v.get()).ifPresent(v::set);
1815      return v.get();
1816   }));
1817
1818   /**
1819    * Methods annotated with {@link RestPostInit @RestPostInit} and their invokers.
1820    */
1821   private final Memoizer<LifecycleInvokerPair> postInitInvokerPair = memoizer(() -> buildLifecycleInvokerPair(() -> {
1822      var bs = beanStore();
1823      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestPostInit.class)
1824         .filter(m -> rstream(AnnotationProvider.INSTANCE.find(RestPostInit.class, MethodInfo.of(m))).map(AnnotationInfo::inner).anyMatch(x -> !x.childFirst()))
1825         .toList()));
1826      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "postInitMethods"), v.get()).ifPresent(v::set);
1827      return v.get();
1828   }));
1829
1830   /**
1831    * Methods annotated with {@link RestPreCall @RestPreCall}.
1832    */
1833   private final Memoizer<MethodList> preCallMethods = memoizer(() -> {
1834      var bs = beanStore();
1835      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestPreCall.class).toList()));
1836      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "preCallMethods"), v.get()).ifPresent(v::set);
1837      return v.get();
1838   });
1839
1840   /**
1841    * Pre-resolved invokers for this context's local {@code @RestPreCall} methods, bound to this
1842    * context's resource instance and bean-store-resolved arg resolvers. Used by the {@link #preCall(RestOpSession)}
1843    * parent-chain walk so that host hooks fire before mixin hooks on mixin-endpoint requests.
1844    *
1845    * <p>
1846    * Hook methods aren't op-specific, so the wrapping bean store stubs in the op-only {@link UrlPathMatcher}
1847    * binding with {@code null} so that {@link PathArg#create PathArg.create()} (and
1848    * other op-aware resolvers) can be called by {@link #findRestOperationArgs(java.lang.reflect.Method, BeanStore)}
1849    * and abstain (return {@code null}) for parameters that aren't {@code @Path}-annotated. Using
1850    * {@code @Path} on a {@code @RestPreCall} method is not supported.
1851    */
1852   private final Memoizer<RestOpInvoker[]> localPreCallInvokers = memoizer(() -> {
1853      var bs = new BasicBeanStore(beanStore());
1854      var pm = getPathMatcher() != null ? getPathMatcher() : UrlPathMatcher.of("");
1855      bs.addBean(UrlPathMatcher.class, pm);
1856      bs.addBean(UrlPathMatcher[].class, new UrlPathMatcher[]{pm});
1857      return preCallMethods.get().stream()
1858         .map(x -> new RestOpInvoker(x, findRestOperationArgs(x, bs), getMethodExecStats(x), this::getResource))
1859         .toArray(RestOpInvoker[]::new);
1860   });
1861
1862   /**
1863    * The supported response content types ({@code Accept} media types) for this resource.
1864    *
1865    * <p>
1866    * Walks {@code @Rest(produces)} annotations parent-to-child and returns the union. When no annotation
1867    * declares types, falls back to the intersection of all op-level serializer supported media types.
1868    */
1869   private final Memoizer<List<MediaType>> produces = memoizer(() -> {
1870      // Walk @Rest(produces=...) chain (parent-to-child); concat all entries in chain order.
1871      var fromAnnotations = new ArrayList<MediaType>();
1872      getRestAnnotationsForProperty("produces")
1873         .forEach(ai -> stream(ai.inner().produces()).map(MediaType::of).forEach(fromAnnotations::add));
1874      if (! fromAnnotations.isEmpty())
1875         return u(fromAnnotations);
1876      // Fall back to the intersection of opContexts' serializer-supported media types — matches legacy behavior.
1877      var opContexts = restOperations().getOpContexts();
1878      Set<MediaType> s = opContexts.isEmpty() ? emptySet() : toSet(opContexts.get(0).getSerializers().getSupportedMediaTypes());
1879      opContexts.forEach(x -> s.retainAll(x.getSerializers().getSupportedMediaTypes()));
1880      return u(toList(s));
1881   });
1882
1883   /**
1884    * JVM-wide cache of {@link ResponseProcessor} provider classes discovered via {@link ServiceLoader}.
1885    *
1886    * <p>
1887    * Populated lazily on first use and shared across all {@link RestContext} instances. Empty on a bare
1888    * {@code juneau-rest-server} classpath; non-empty only when an opt-in module (e.g.
1889    * {@code juneau-rest-server-reactive}) ships a
1890    * {@code META-INF/services/ResponseProcessor} provider file.
1891    */
1892   @SuppressWarnings({
1893      "java:S3077" // volatile is required for correct double-checked-locking safe-publication of this JVM-wide cache; the reference is publish-once and never compound-mutated.
1894   })
1895   private static volatile List<Class<? extends ResponseProcessor>> serviceLoaderResponseProcessors;
1896
1897   /**
1898    * Returns the module-contributed {@link ResponseProcessor} classes discovered via {@link ServiceLoader},
1899    * caching the result for the lifetime of the JVM.
1900    *
1901    * <p>
1902    * Provider <em>types</em> are resolved (not instantiated) so each {@link RestContext} can instantiate its
1903    * own bean-store-injected copy. Discovery failures are swallowed at {@code FINE} so a malformed provider
1904    * never fails resource startup; on a bare classpath the returned list is empty and the default processor
1905    * chain is unchanged.
1906    *
1907    * @return The discovered processor classes (possibly empty, never {@code null}).
1908    */
1909   private static List<Class<? extends ResponseProcessor>> discoverServiceLoaderResponseProcessors() {
1910      var p = serviceLoaderResponseProcessors;
1911      if (p == null) {
1912         synchronized (RestContext.class) {
1913            p = serviceLoaderResponseProcessors;
1914            if (p == null) {
1915               p = loadServiceLoaderResponseProcessors();
1916               serviceLoaderResponseProcessors = p;
1917            }
1918         }
1919      }
1920      return p;
1921   }
1922
1923   private static List<Class<? extends ResponseProcessor>> loadServiceLoaderResponseProcessors() {
1924      var out = new ArrayList<Class<? extends ResponseProcessor>>();
1925      try {
1926         for (var it = ServiceLoader.load(ResponseProcessor.class).stream().iterator(); it.hasNext();)
1927            addNextServiceLoaderResponseProcessor(out, it);
1928      } catch (ServiceConfigurationError | RuntimeException e) {
1929         LOG.log(Level.FINE, e, () -> "ServiceLoader for ResponseProcessor failed: " + e.getMessage());
1930      }
1931      return List.copyOf(out);
1932   }
1933
1934   private static void addNextServiceLoaderResponseProcessor(List<Class<? extends ResponseProcessor>> out, Iterator<ServiceLoader.Provider<ResponseProcessor>> it) {
1935      try {
1936         out.add(it.next().type());
1937      } catch (ServiceConfigurationError | RuntimeException e) {
1938         LOG.log(Level.FINE, e, () -> "Skipping ServiceLoader-discovered ResponseProcessor: " + e.getMessage());
1939      }
1940   }
1941
1942   /**
1943    * The ordered array of {@link ResponseProcessor} instances for this resource.
1944    *
1945    * <p>
1946    * Walks {@code @Rest(responseProcessors)} annotations parent-to-child (append order). A bean-store
1947    * override or {@code @Bean} factory method REPLACES the entire list.
1948    */
1949   private final Memoizer<ResponseProcessor[]> responseProcessors = memoizer(() -> {
1950      // Walk @Rest(responseProcessors=...) chain (parent-to-child via getRestAnnotationsForProperty).
1951      // DefaultConfig contributes the framework defaults at the top of the chain; resource-class entries append.
1952      // ResponseProcessorList.Builder.add(...) uses addAll (append) — final order: [DefaultConfig, parent, child].
1953      var bs = beanStore();
1954      var b = ResponseProcessorList.create(bs);
1955      // When enabled (default on-when-tracer), front-load the W3C trace-context processor so it
1956      // writes traceparent/tracestate headers before the body-rendering processors run. It short-circuits
1957      // at request time when no TracerHook stashed a trace context, so it's zero-cost on the no-tracer path.
1958      if (isResponseTraceparent())
1959         b.add(TraceContextResponseProcessor.class);
1960      // Front-load any module-contributed ResponseProcessors discovered via
1961      // ServiceLoader (e.g. the opt-in juneau-rest-server-reactive module's ReactiveResponseProcessor,
1962      // which must run ahead of AsyncResponseProcessor). Inert on a bare juneau-rest-server classpath —
1963      // when no module ships a META-INF/services/...ResponseProcessor provider file the list is empty and
1964      // the chain is identical to the pre-feature default.
1965      discoverServiceLoaderResponseProcessors().forEach(b::add);
1966      getRestAnnotationsForProperty("responseProcessors")
1967         .forEach(ai -> b.add(ai.inner().responseProcessors()));
1968      // @Bean method override REPLACES the entire annotation-derived list.
1969      var override = bs.createBeanFromMethod(ResponseProcessorList.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
1970      return (nn(override) ? override : b.build()).toArray();
1971   });
1972
1973   /**
1974    * The ordered array of {@link RestOpArg} argument-resolver types for this resource.
1975    *
1976    * <p>
1977    * Walks {@code @Rest(restOpArgs)} annotations parent-to-child (prepend order, so child entries
1978    * take priority). A bean-store override or {@code @Bean} factory method REPLACES the entire list.
1979    */
1980   private final Memoizer<Class<? extends RestOpArg>[]> restOpArgs = memoizer(() -> {
1981      // Walk @Rest(restOpArgs=...) chain (parent-to-child via getRestAnnotationsForProperty).
1982      // DefaultConfig contributes the framework arg-resolver list; resource-class entries override.
1983      // RestOpArgList.Builder.add(...) uses prependAll — applying per-annotation in chain order yields
1984      // final order: [child, parent, DefaultConfig], matching the legacy apply-pass behavior.
1985      var bs = beanStore();
1986      var b = RestOpArgList.create(bs);
1987      getRestAnnotationsForProperty("restOpArgs")
1988         .forEach(ai -> b.add(ai.inner().restOpArgs()));
1989      // @Bean method override REPLACES the entire annotation-derived list.
1990      var override = bs.createBeanFromMethod(RestOpArgList.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
1991      return (nn(override) ? override : b.build()).asArray();
1992   });
1993
1994   /**
1995    * Fully-configured {@link SerializerSet.Builder} for this resource, populated from the
1996    * {@code @Rest(serializers)} annotation chain and any {@code @Bean} override.
1997    *
1998    * <p>
1999    * Starts with an empty set. A bean-store type or instance override REPLACES the builder or its impl.
2000    * Annotation entries (parent-to-child) are appended. A {@code @Bean} factory method REPLACES the impl.
2001    */
2002   private final Memoizer<SerializerSet.Builder> serializersBuilder = memoizer(() -> {
2003      var bs = beanStore();
2004      var v = Holder.of(SerializerSet.create(bs));
2005      getRestAnnotationsForProperty("serializers").forEach(ai -> v.get().add(ai.inner().serializers()));
2006      bs.createBeanFromMethod(SerializerSet.class, resource().get(), RestContext::isBeanMethod, v.get()).ifPresent(x -> v.get().impl(x));
2007      return v.get();
2008   });
2009
2010   /**
2011    * The {@link SerializerSet} for this resource, built from the self-contained serializer builder memoizer.
2012    */
2013   private final Memoizer<SerializerSet> serializers = memoizer(() -> serializersBuilder.get().build());
2014
2015   /**
2016    * Methods annotated with {@link RestStartCall @RestStartCall} and their invokers.
2017    */
2018   private final Memoizer<LifecycleInvokerPair> startCallInvokerPair = memoizer(() -> buildLifecycleInvokerPair(() -> {
2019      var bs = beanStore();
2020      var v = Holder.of(MethodList.of(getAnnotatedMethods(resource(), RestStartCall.class).toList()));
2021      bs.createBeanFromMethod(MethodList.class, resource().get(), x -> isBeanMethod(x, "startCallMethods"), v.get()).ifPresent(v::set);
2022      return v.get();
2023   }));
2024
2025   /**
2026    * The {@link StaticFiles} provider for this resource.
2027    *
2028    * <p>
2029    * Defaults to {@link BasicStaticFiles}. {@code @Rest(staticFiles=X)} most-derived non-{@code Void} class wins.
2030    * A bean-store override or {@code @Bean} factory method REPLACES the result.
2031    */
2032   private final Memoizer<StaticFiles> staticFiles = memoizer(() -> {
2033      var bs = beanStore();
2034      var creator = BeanInstantiator.of(StaticFiles.class, bs).type(BasicStaticFiles.class).noBuilder();
2035      bs.getBeanType(StaticFiles.class).ifPresent(creator::type);
2036      // @Rest(staticFiles=X) — most-derived non-Void wins (parent-to-child chain; reduce-last keeps the closest-to-child override).
2037      getRestAnnotationsForProperty("staticFiles")
2038         .map(ai -> ai.inner().staticFiles())
2039         .filter(c -> c != StaticFiles.Void.class)
2040         .reduce((first, second) -> second)
2041         .ifPresent(creator::type);
2042      bs.createBeanFromMethod(StaticFiles.class, resource().get(), RestContext::isBeanMethod).ifPresent(creator::impl);
2043      return creator.asOptional().orElse(null);
2044   });
2045
2046   /**
2047    * The {@link SwaggerProvider} for this resource.
2048    *
2049    * <p>
2050    * Defaults to {@link BasicSwaggerProvider}. {@code @Rest(swaggerProvider=X)} most-derived
2051    * non-{@code Void} class wins. A bean-store override or {@code @Bean} factory method REPLACES the result.
2052    */
2053   private final Memoizer<SwaggerProvider> swaggerProvider = memoizer(() -> {
2054      var bs = beanStore();
2055      // Register the resource class as a SwaggerResource bean so SwaggerProvider implementations
2056      // can resolve it via constructor injection (rather than reading it off a Builder).
2057      bs.addBean(SwaggerResource.class, SwaggerResource.of(resourceClass()));
2058      var creator = BeanInstantiator.of(SwaggerProvider.class, bs).type(BasicSwaggerProvider.class).noBuilder();
2059      bs.getBeanType(SwaggerProvider.class).ifPresent(creator::type);
2060      // @Rest(swaggerProvider=X) — most-derived non-Void wins (parent-to-child chain; reduce-last keeps the closest-to-child override).
2061      getRestAnnotationsForProperty("swaggerProvider")
2062         .map(ai -> ai.inner().swaggerProvider())
2063         .filter(c -> c != SwaggerProvider.Void.class)
2064         .reduce((first, second) -> second)
2065         .ifPresent(creator::type);
2066      bs.createBeanFromMethod(SwaggerProvider.class, resource().get(), RestContext::isBeanMethod).ifPresent(creator::impl);
2067      return creator.asOptional().orElse(null);
2068   });
2069
2070   /**
2071    * The {@link OpenApiProvider} for this resource.
2072    *
2073    * <p>
2074    * Defaults to {@link BasicOpenApiProvider}. {@code @Rest(openApiProvider=X)} most-derived
2075    * non-{@code Void} class wins. A bean-store override or {@code @Bean} factory method REPLACES the result.
2076    */
2077   private final Memoizer<OpenApiProvider> openApiProvider = memoizer(() -> {
2078      var bs = beanStore();
2079      bs.addBean(OpenApiResource.class, OpenApiResource.of(resourceClass()));
2080      var creator = BeanInstantiator.of(OpenApiProvider.class, bs).type(BasicOpenApiProvider.class).noBuilder();
2081      bs.getBeanType(OpenApiProvider.class).ifPresent(creator::type);
2082      // @Rest(openApiProvider=X) — most-derived non-Void wins.
2083      getRestAnnotationsForProperty("openApiProvider")
2084         .map(ai -> ai.inner().openApiProvider())
2085         .filter(c -> c != OpenApiProvider.Void.class)
2086         .reduce((first, second) -> second)
2087         .ifPresent(creator::type);
2088      bs.createBeanFromMethod(OpenApiProvider.class, resource().get(), RestContext::isBeanMethod).ifPresent(creator::impl);
2089      return creator.asOptional().orElse(null);
2090   });
2091
2092   /**
2093    * The {@link ThrownStore} for this resource, used to track exception statistics.
2094    *
2095    * <p>
2096    * Inherits from the parent context's store when one is present. A bean-store override or
2097    * {@code @Bean} factory method REPLACES the result.
2098    */
2099   private final Memoizer<ThrownStore> thrownStore = memoizer(() -> {
2100      var bs = beanStore();
2101      var b = ThrownStore.create(bs).impl(parentContext() == null ? null : parentContext().getThrownStore());
2102      bs.createBeanFromMethod(ThrownStore.class, resource().get(), RestContext::isBeanMethod, b).ifPresent(b::impl);
2103      return b.build();
2104   });
2105
2106   /**
2107    * The runtime {@link VarResolver} — wraps the bootstrap resolver and adds {@link Messages} and {@link Config} beans.
2108    *
2109    * <p>
2110    * The bootstrap {@link Config} is pulled from the {@code rawConfig} memoizer to avoid a circular
2111    * dependency: the runtime {@link Config} wraps the bootstrap config in a session backed by this resolver.
2112    * A bean-store override or {@code @Bean} factory method REPLACES the result.
2113    */
2114   private final Memoizer<VarResolver> varResolver = memoizer(() -> {
2115      var bs = beanStore();
2116      var b = getBootstrapVarResolver().copy()
2117         .bean(Messages.class, getMessages())
2118         .bean(Config.class, rawConfig.get());
2119      var override = bs.createBeanFromMethod(VarResolver.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
2120      return nn(override) ? override : b.build();
2121   });
2122
2123   /**
2124    * Per-mixin {@link RestContext} sub-contexts, keyed by the mixin class.
2125    *
2126    * <p>
2127    * Built lazily (alongside {@link #restOperations}) and only on the host's {@link RestContext} &mdash; mixin
2128    * sub-contexts themselves never spawn further sub-contexts (the flat-inheritance rule: a mixin's
2129    * {@code @Rest(mixins=B)} discovers B as a mixin of the host, not as a nested mixin of A).
2130    *
2131    * <p>
2132    * Each sub-context is constructed with a {@link ContextKind.Mixin} {@link Args#kind() kind}, with its
2133    * {@code parentContext} pointing at this host context.  That parent-linkage drives the inheritance walk in
2134    * {@link #getRestAnnotationsForProperty(String)} for serializers, parsers, encoders, converters, response
2135    * processors, REST op args, guards, restDebugFormatter, messages, varResolver tokens, etc.
2136    *
2137    * @since 10.0.0
2138    */
2139   private final Memoizer<Map<Class<?>,RestContext>> mixinContexts = memoizer(() -> {
2140      if (isMixinContextField())
2141         return Map.of();
2142      var out = new LinkedHashMap<Class<?>,RestContext>();
2143      for (var rm : getResolvedMixins()) {
2144         if (rm.type() == resourceClass())
2145            continue;
2146         RestContext mixinCtx;
2147         try {
2148            mixinCtx = buildMixinContext(rm);
2149         } catch (RuntimeException e) {
2150            throw e;
2151         } catch (Exception e) {
2152            throw rex(e, "Failed to construct mixin sub-context for %s: %s", rm.type().getName(), e.getMessage());
2153         }
2154         out.put(rm.type(), mixinCtx);
2155      }
2156      return u(out);
2157   });
2158
2159   /**
2160    * Builds a per-mixin sub-{@link RestContext} for the given mixin class.
2161    *
2162    * <p>
2163    * Instantiates the mixin resource via this host's bean store, constructs a new {@link RestContext} with
2164    * {@code parentContext=this} and a {@link ContextKind.Mixin} {@link Args#kind() kind}, and reflectively invokes
2165    * any {@code setContext(RestContext)} method on the mixin instance (mirroring the existing
2166    * {@code RestChildren.buildChildContext(...)} contract).  The host's {@link ServletConfig} is propagated
2167    * so the mixin sees the same servlet container settings.
2168    *
2169    * <p>
2170    * Mixin instance resolution: an importer-supplied {@code @Bean <MixinClass>} factory in the host's
2171    * bean store wins over reflective instantiation. When the host registers
2172    * {@code @Bean public MyMixin myMixin() { ... }} (or a Spring {@code @Bean} of the same type), that
2173    * pre-built instance is used as the mixin resource; otherwise the mixin is instantiated via
2174    * {@code beanStore.instantiate(mixinClass)} (no-arg / builder / injected-constructor path). This lets
2175    * convention-endpoint mixins (favicon, SEO, version, well-known) be configured by the importer using
2176    * their own builder before the mixin walk wires them in.
2177    */
2178   private RestContext buildMixinContext(ResolvedMixin rm) throws Exception {
2179      var mixinClass = rm.type();
2180      Object preBuilt = beanStore.getBean(mixinClass).orElse(null);
2181      final var mixinResource = preBuilt != null ? preBuilt : beanStore.instantiate(mixinClass);
2182      var args = new Args(mixinClass, this, builder.inner, () -> mixinResource, "", null, null, null, new ContextKind.Mixin(rm));
2183      var mixinCtx = new RestContext(args);
2184      var setCtx = ClassInfo.of(mixinResource).getMethod(x -> x.hasName("setContext") && x.hasParameterTypes(RestContext.class)).orElse(null);
2185      if (setCtx != null)
2186         setCtx.accessible().invoke(mixinResource, mixinCtx);
2187      return mixinCtx;
2188   }
2189
2190   /**
2191    * Returns the per-mixin {@link RestContext} sub-contexts indexed by mixin class.
2192    *
2193    * <p>
2194    * Returns an empty map when this context is itself a mixin sub-context, or when no mixins are declared.
2195    *
2196    * @return An unmodifiable map of mixin class to its sub-{@link RestContext}; never {@code null}.
2197    * @since 10.0.0
2198    */
2199   public Map<Class<?>,RestContext> getMixinContexts() { return mixinContexts.get(); }
2200
2201   /**
2202    * Returns the host-chosen mount prefix(es) declared on the {@code @Mixin} that produced this mixin
2203    * sub-context, for re-mounting the mixin's endpoints under host-chosen path(s).
2204    *
2205    * <p>
2206    * Resolved from {@link Mixin#path()} and {@link Mixin#paths()} (SVL-resolved, then normalized via the same
2207    * {@code pathToken} cleanup the bundled SVL-configurable mixins use — leading/trailing slashes and a trailing
2208    * {@code /*} wildcard stripped to a bare token).  {@link Mixin#path()} (single) and {@link Mixin#paths()}
2209    * (multi) are unioned; an empty result means "no host re-mount" (the mixin's own op paths apply unchanged).
2210    *
2211    * @return The normalized, de-duplicated mount-prefix tokens (no slashes), or an empty list when none; never {@code null}.
2212    * @since 10.0.0
2213    */
2214   public List<String> getMixinMountPrefixes() { return mixinMountPrefixes.get(); }
2215
2216   /**
2217    * Memoized normalized {@code @Mixin(path/paths)} mount prefixes (built once; zero per-request cost).
2218    */
2219   private final Memoizer<List<String>> mixinMountPrefixes = memoizer(() -> {
2220      var rm = resolvedMixinField();
2221      if (rm == null || rm.hasNoOverrides())
2222         return List.of();
2223      var m = rm.overrides();
2224      var out = new LinkedHashSet<String>();
2225      var vrs = getBootstrapVarResolver().createSession();
2226      if (StringUtils.isNotBlank(m.path()))
2227         addMountPrefix(out, vrs.resolve(m.path()));
2228      for (var p : m.paths())
2229         if (StringUtils.isNotBlank(p))
2230            addMountPrefix(out, vrs.resolve(p));
2231      return List.copyOf(out);
2232   });
2233
2234   /** Normalizes one path override to a bare token (strip leading/trailing slashes and a trailing {@code /*}). */
2235   private static void addMountPrefix(Set<String> out, String raw) {
2236      var s = trim(raw);
2237      if (s.endsWith("/*"))
2238         s = s.substring(0, s.length() - 2);
2239      // Strip leading and trailing slashes.
2240      while (s.startsWith("/"))
2241         s = s.substring(1);
2242      while (s.endsWith("/"))
2243         s = s.substring(0, s.length() - 1);
2244      if (! s.isEmpty())
2245         out.add(s);
2246   }
2247
2248   /**
2249    * The {@link RestOperations} for this resource — all {@link RestOpContext} instances built from
2250    * methods annotated with {@link RestOp @RestOp} (and related).
2251    *
2252    * <p>
2253    * Eagerly initialized in the constructor (via an explicit {@code .get()} call inside the try-catch block)
2254    * so that any {@link ServletException} surfaces at construction time rather than lazily on first request.
2255    * Subsequent calls return the cached instance.
2256    *
2257    * <p>
2258    * For mixin classes declared via {@link Rest#mixins() @Rest(mixins)}, each mixin's {@code @RestOp} methods
2259    * are bound to a per-mixin {@link RestContext} sub-context (see {@link #mixinContexts}) so that the
2260    * mixin's annotation chain inherits from the host's via {@link #getRestAnnotationsForProperty(String)}.
2261    * Mixin sub-contexts themselves never participate in mixin discovery &mdash; the {@code if (!isMixinContext)}
2262    * guard below short-circuits the flat-inheritance rule (a mixin's {@code @Rest(mixins=B)} is collected at
2263    * the host level, not nested under A).
2264    */
2265   private final Memoizer<RestOperations> restOperations = memoizer(() -> safe(() -> {
2266      initializeFrameworkBeansForRestOps();
2267      var bs = beanStore();
2268      var b = RestOperations.create(bs);
2269      var ap = getMarshallingContext().getAnnotationProvider();
2270      var rci = ClassInfo.of(resource().get());
2271      if (!isMixinContextField()) {
2272         var contexts = mixinContexts.get();
2273         for (var e : contexts.entrySet()) {
2274            var mixinClass = e.getKey();
2275            var mixinCtx = e.getValue();
2276            addRestOperationsForClass(b, ap, ClassInfo.of(mixinClass), mixinCtx, mixinCtx::getResource);
2277         }
2278      }
2279      addRestOperationsForClass(b, ap, rci, this, this::getResource);
2280      var override = bs.createBeanFromMethod(RestOperations.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
2281      return nn(override) ? override : b.build();
2282   }));
2283
2284   private void addRestOperationsForClass(RestOperations.Builder b, AnnotationProvider ap, ClassInfo classInfo, RestContext opContext, Supplier<Object> targetSupplier) throws ServletException {
2285      for (var mi : classInfo.getPublicMethods()) {
2286         var al = rstream(ap.find(mi)).filter(REST_OP_GROUP).collect(Collectors.toList());
2287         if (al.isEmpty()) {
2288            Predicate<MethodInfo> isRestAnnotatedInterface = x -> x.getDeclaringClass().isInterface()
2289               && nn(x.getDeclaringClass().getAnnotations(Rest.class).findFirst().map(AnnotationInfo::inner).orElse(null));
2290            mi.getMatchingMethods().stream().filter(isRestAnnotatedInterface).forEach(x -> al.add(AnnotationInfo.of(x, RestOpAnnotation.DEFAULT)));
2291         }
2292         if (!al.isEmpty()) {
2293            try {
2294               if (mi.isNotPublic())
2295                  throw servletException("@RestOp method %s.%s must be defined as public.", classInfo.inner().getName(), mi.getNameSimple());
2296               var roc = new RestOpContext(mi.inner(), opContext, targetSupplier);
2297               if (eq(roc.getHttpMethod(), "RRPC")) {
2298                  RestOpContext roc2 = new RrpcRestOpContext(mi.inner(), opContext, targetSupplier);
2299                  b.add("GET", roc2).add("POST", roc2);
2300               } else {
2301                  b.add(roc);
2302               }
2303            } catch (Exception e) {
2304               throw servletException(e, "Problem occurred trying to initialize methods on class %s", classInfo.inner().getName());
2305            }
2306         }
2307      }
2308   }
2309
2310   /**
2311    * Discovers all mixins declared on this resource's {@code @Rest} chain, normalized to {@link ResolvedMixin}.
2312    *
2313    * <p>
2314    * Reads both {@link Rest#mixins() bare-class} and {@link Rest#mixinDefs() rich &#64;Mixin} entries (bare first,
2315    * then {@code mixinDefs}), recursing into each mixin class's own {@code @Rest(mixins=)}/{@code @Rest(mixinDefs=)}
2316    * (the flat-inheritance rule still applies — nested mixins are collected at the host level).  First occurrence
2317    * of a class wins for ordering; a rich {@code @Mixin} <b>upgrades</b> an earlier bare entry for the same class
2318    * (a bare class is just {@code @Mixin(type=X)} with empty overrides, so upgrading only adds the host overrides).
2319    *
2320    * @return The ordered, de-duplicated normalized mixins, never {@code null}.
2321    */
2322   private Collection<ResolvedMixin> getResolvedMixins() {
2323      var out = new LinkedHashMap<Class<?>,ResolvedMixin>();
2324      getRestAnnotationsForProperty("mixins").forEach(ai -> {
2325         for (var mixin : ai.inner().mixins())
2326            collectResolvedMixin(ResolvedMixin.ofBare(mixin), out);
2327         for (var def : ai.inner().mixinDefs())
2328            collectResolvedMixin(ResolvedMixin.ofDef(def), out);
2329      });
2330      return out.values();
2331   }
2332
2333   private void collectResolvedMixin(ResolvedMixin rm, LinkedHashMap<Class<?>,ResolvedMixin> out) {
2334      var type = rm.type();
2335      // type==null is defensive only — @Mixin.type() defaults to Object.class and a declarative @Mixin requires
2336      // a class literal, so it is never null in practice.  type==resourceClass() guards a host/mixin listing
2337      // itself (skip to avoid self-recursion).
2338      if (type == null || type == resourceClass())  // HTT: the null arm is not reachable via the annotation API.
2339         return;
2340      var existing = out.get(type);
2341      if (existing != null) {
2342         // Already discovered.  A rich @Mixin upgrades a bare entry (in place, preserving position); otherwise
2343         // the first occurrence wins and we do not recurse again.
2344         if (existing.hasNoOverrides() && ! rm.hasNoOverrides())
2345            out.put(type, rm);
2346         return;
2347      }
2348      out.put(type, rm);
2349      var r = type.getAnnotation(Rest.class);
2350      if (r != null) {
2351         for (var nested : r.mixins())
2352            collectResolvedMixin(ResolvedMixin.ofBare(nested), out);
2353         for (var nestedDef : r.mixinDefs())
2354            collectResolvedMixin(ResolvedMixin.ofDef(nestedDef), out);
2355      }
2356   }
2357
2358   /**
2359    * Discovers all children declared on this resource's {@code @Rest} chain, normalized to {@link ResolvedChild}.
2360    *
2361    * <p>
2362    * Reads both {@link Rest#children() bare-class} and {@link Rest#childrenDefs() rich &#64;Child} entries (bare
2363    * first, then {@code childrenDefs}). First occurrence of a class wins for ordering; a rich {@code @Child}
2364    * <b>upgrades</b> an earlier bare entry for the same class (a bare class is just {@code @Child(type=X)} with
2365    * an empty seed, so upgrading only adds the host-declared seed).
2366    *
2367    * <p>
2368    * Deliberately <b>non-recursive</b>, unlike {@link #getResolvedMixins()}: children do not flatten transitively
2369    * to the host — each child resolves its own nested {@code @Rest(children=...)}/{@code childrenDefs} independently
2370    * when its own {@link RestContext} is constructed.
2371    *
2372    * @return The ordered, de-duplicated normalized children, never {@code null}.
2373    */
2374   private Collection<ResolvedChild> getResolvedChildren() {
2375      var out = new LinkedHashMap<Class<?>,ResolvedChild>();
2376      getRestAnnotations().forEach(ai -> {
2377         for (var c : ai.inner().children())
2378            collectResolvedChild(ResolvedChild.ofBare(c), out);
2379         for (var def : ai.inner().childrenDefs())
2380            collectResolvedChild(ResolvedChild.ofDef(def), out);
2381      });
2382      return out.values();
2383   }
2384
2385   private void collectResolvedChild(ResolvedChild rc, LinkedHashMap<Class<?>,ResolvedChild> out) {
2386      var type = rc.type();
2387      // type==null is defensive only — @Child.type() is required and a declarative @Child requires a class
2388      // literal, so it is never null in practice.  type==resourceClass() guards a self-reference (skip to
2389      // avoid an infinite loop).
2390      if (type == null || type == resourceClass())  // HTT: the null arm is not reachable via the annotation API.
2391         return;
2392      var existing = out.get(type);
2393      if (existing != null) {
2394         // Already discovered.  A rich @Child upgrades a bare entry (in place, preserving position); otherwise
2395         // the first occurrence wins.  No recursion into the child's own nested children (see javadoc above).
2396         if (existing.hasNoSeed() && ! rc.hasNoSeed())
2397            out.put(type, rc);
2398         return;
2399      }
2400      out.put(type, rc);  // No recursion into type's own children — each child owns its own subtree.
2401   }
2402
2403   /**
2404    * The {@link RestChildren} for this resource — child {@link RestContext} instances registered via
2405    * {@link Rest#children() @Rest(children)}/{@link Rest#childrenDefs() childrenDefs}.
2406    *
2407    * <p>
2408    * Reads children (bare and rich) directly from the {@code @Rest} annotation chain via
2409    * {@link #getResolvedChildren()}, instantiates each child via the bean store, and builds a {@link RestContext}
2410    * for each, threading through any host-declared {@code @Child} seed. Eagerly initialized in the constructor
2411    * (via an explicit {@code .get()} call inside the try-catch block) so that any construction failure surfaces
2412    * at initialization time rather than lazily.
2413    */
2414   private final Memoizer<RestChildren> restChildren = memoizer(() -> safe(() -> {
2415      var bs = beanStore();
2416      var servletConfig = bs.getBean(ServletConfig.class).orElse(null);
2417      var b = RestChildren.create(this, bs, servletConfig);
2418
2419      var lazy = isLazyChildren();
2420
2421      for (var rc2 : getResolvedChildren()) {
2422         if (lazy) {
2423            // Lazy: register a routing stub now; defer full RestContext construction to first request.
2424            // The stub carries the full ResolvedChild (including any host-declared @Child seed), so a
2425            // lazily-materialized child receives its seed on first invocation identically to an eager one.
2426            b.addLazy(rc2, "");
2427         } else {
2428            // Eager (default): build the full child RestContext immediately, seed included.
2429            b.add(RestChildren.buildChildContext(this, bs, servletConfig, rc2, null, ""));
2430         }
2431      }
2432
2433      // @Bean override — allows replacing the entire RestChildren instance.
2434      var override = bs.createBeanFromMethod(RestChildren.class, resource().get(), RestContext::isBeanMethod, b).orElse(null);
2435      return nn(override) ? override : b.build();
2436   }));
2437
2438   /**
2439    * Constructor.
2440    *
2441    * @param args The bootstrap arguments. Must not be <jk>null</jk>.
2442    * @throws Exception If any initialization problems were encountered.
2443    * @since 10.0.0
2444    */
2445   public RestContext(Args args) throws Exception {
2446      this(new Builder(args));
2447   }
2448
2449   /**
2450    * Internal constructor.
2451    *
2452    * <p>
2453    * Privatized in the April 2026 refactor (2026-04-19). External callers must use
2454    * {@link #RestContext(Args)} instead.
2455    *
2456    * @param builder The builder containing the settings for this bean.
2457    * @throws Exception If any initialization problems were encountered.
2458    */
2459   private RestContext(Builder builder) throws Exception {
2460      super(builder);
2461
2462      startTime = Instant.now();
2463
2464      REGISTRY.put(builder.resourceClass, this);
2465
2466      BasicHttpException initExceptionTemp = null;
2467
2468      try {
2469         this.builder = builder;
2470
2471         parentContext = builder.parentContext;
2472         contextKind = builder.args.kind();
2473         isMixinContext = contextKind instanceof ContextKind.Mixin;
2474         resolvedMixin = (contextKind instanceof ContextKind.Mixin contextKind2) ? contextKind2.def() : null;
2475         resolvedChild = (contextKind instanceof ContextKind.Child contextKind3) ? contextKind3.def() : null;
2476         resourceClass = builder.resourceClass;
2477         var rs = new ResourceSupplier(resourceClass, reqnn("resource", builder.args.resource()));
2478         resource = rs;
2479
2480         // Resolve the programmatic configuration builder.  Prefer the one carried on Args (set by
2481         // RestServlet.init()); otherwise read the builder stashed on the resource instance (non-reflective) so
2482         // programmatic construction via MockRestClient, child mounting, and mixin composition all honor it.
2483         var rb = builder.args.restBuilder();
2484         if (rb == null)
2485            rb = stashedRestBuilder(rs.get());
2486         restBuilder = rb;
2487         if (restBuilder instanceof AbstractRestBuilder<?,?> restBuilder2) {
2488            // Synthetic, highest-priority @Rest carrying the builder-set members; prepended (most-derived
2489            // child position) to the @Rest chain by the restAnnotations memoizer so builder values win.
2490            builderRestAnnotation = restBuilder2.toRestAnnotation();
2491            // Programmatic mdcAsyncPropagation knob (no @Rest member) wins over the env-driven default.
2492            if (restBuilder2.getMdcAsyncPropagation() != null && builder.mdcAsyncPropagation == null)
2493               builder.mdcAsyncPropagation = restBuilder2.getMdcAsyncPropagation();
2494         } else {
2495            builderRestAnnotation = null;
2496         }
2497
2498         // --- beanStore setup (May 2026 refactor; precedence-flipped 10.0) ---
2499
2500         // Determine the parent (bootstrap) store: inherited from parent resource if present.
2501         //
2502         // For mixin sub-contexts, the parent is the host's FULL beanStore (not just the bootstrap layer)
2503         // so that resource-class-level @Bean factory methods declared on the host class are visible to
2504         // the mixin's resolution chain.  Mixin endpoints resolved through the host's beanStore directly;
2505         // with per-mixin sub-contexts, the same effect is
2506         // achieved by parent-linking the mixin's beanStore to the host's full beanStore.
2507         //
2508         // For @Rest(children) sub-resources, the parent is the host's inheritable layer: the host's bootstrap
2509         // store plus the host's own non-framework @Bean method results and @Bean field values.  Children see
2510         // the group's beans (transitively, since each child's inheritable layer sits on top of its parent's),
2511         // but not the host's framework-managed beans (serializers, call logger, children, ...), which stay
2512         // per-context.
2513         WritableBeanStore parentBs;
2514         if (parentContext != null && isMixinContext)
2515            parentBs = parentContext.beanStore;
2516         else if (parentContext != null)
2517            parentBs = parentContext.inheritableBeanStore;
2518         else
2519            parentBs = null;
2520
2521         // Build the initial beanStore; honor an optional @Bean WritableBeanStore override.
2522         // In the new 10.0 precedence model, the parent (Spring or parent-resource bootstrap) is
2523         // installed as the overriding parent so it wins over local entries.
2524         // Args.overridingParent threads into the per-resource (final beanStore) overridingParent
2525         // slot so test-time overlays (TestBeanStore) resolve at tier 1 of the chain ahead of
2526         // any @Bean factory result registered as a local entry below.
2527         // @formatter:off
2528         var argsOverlay = builder.args.overridingParent();
2529         WritableBeanStore bs = createBeanStore(parentBs, rs, parentBs == null ? null : argsOverlay)
2530            .addBean(ResourceSupplier.class, rs)
2531            .addBean(ServletConfig.class, nn(builder.inner) ? builder.inner : builder)
2532            .addBean(ServletContext.class, (nn(builder.inner) ? builder.inner : builder).getServletContext());
2533         // @formatter:on
2534
2535         // If no parent store, promote bs to bootstrap and layer a fresh per-resource v2 store on top.
2536         // The overlay belongs on the per-resource store so it wins over @Bean factories registered
2537         // as local entries below; the bootstrap deliberately does NOT get the overlay (it sits above
2538         // the per-resource entries via the parent chain, which is too low for an overlay).
2539         if (parentBs == null) {
2540            bootstrapBeanStore = bs;
2541            bs = new BasicBeanStore(bootstrapBeanStore, argsOverlay);
2542         } else {
2543            bootstrapBeanStore = parentBs;
2544         }
2545         beanStore = bs;
2546         inheritableBeanStore = new BasicBeanStore(bootstrapBeanStore);
2547
2548         beanStore.addBean(WritableBeanStore.class, beanStore);
2549         // Register the bootstrap VarResolver as a NAMED entry only.  The unnamed VarResolver
2550         // slot is intentionally left to the registerFrameworkDefaults() default supplier (which
2551         // resolves to the full runtime VarResolver) so that internal accessors such as
2552         // getVarResolver() return the right thing when routed through beanStore.getBean(...).
2553         beanStore.add(VarResolver.class, getBootstrapVarResolver(), "bootstrapVarResolver");
2554         // Force-build raw Config now (fail fast if @Rest(config) is misconfigured).  The unnamed
2555         // Config slot in the bean store is intentionally left to the default supplier (the full
2556         // runtime Config) — @RestInit hooks that take Config as a parameter will see the fully
2557         // resolved instance instead of the raw bootstrap Config (10.0 behavior change).
2558         rawConfig.get();
2559         // Per-RestContext @Value resolution bridge: register the @Rest(config=...) Configs as
2560         // PropertySource beans inside THIS resource's BeanStore (NOT on the process-wide
2561         // Settings.get() singleton — that path was a 6.7x perf regression because
2562         // MockRestClient's static RestContext cache leaks instances and Settings.get()'s source
2563         // list grew unbounded). Per-resource isolation comes for free from the BeanStore scope.
2564         registerRestConfigPropertySources();
2565
2566         // Materialize the RestContextProperties bean exactly once, now that the per-resource PropertySources are
2567         // registered.  Forcing it here (rather than on first lazy .get()) is required for correctness:
2568         //   1. Single instance / store identity — the materialization side effect (BeanInstantiator auto-registers
2569         //      the bound bean into beanStore() via addDefaultSupplier) must run exactly once.  A lazy first-.get()
2570         //      under concurrent access could run the memoizer supplier more than once (the memoizer is CAS-based and
2571         //      does not cache the winner before running the supplier), registering two instances last-writer-wins and
2572         //      breaking getRestContextProperties() == beanStore().getBean(RestContextProperties.class).
2573         //   2. Mixin sub-context isolation — the auto-registration lands as a tier-4 default supplier on THIS store.
2574         //      Forcing it before promoteDefaultsToLocalSuppliers() (below) lets a mixin sub-context promote its own
2575         //      registration to a local (tier-2) entry, so the mixin's beanStore().getBean(RestContextProperties.class)
2576         //      resolves ITS OWN bean instead of walking up to the parent-linked host's tier-4 default.
2577         // Materialization must complete here so the bound bean is present and promotable before the @Bean /
2578         // @RestInit walk (and the promoteDefaultsToLocalSuppliers() step below) run against this store.
2579         getRestContextProperties();
2580
2581         // Register memoizer-backed defaults for every framework-managed type.  These sit at the
2582         // bottom of the precedence order and only fire when no @Bean method, no programmatic
2583         // add, and no Spring/overriding-parent bean has been registered for the type.  This is
2584         // what removes the need for the old DELAYED_INJECTION gate-keeping list — the @Bean
2585         // walk below can now invoke any framework type's factory and still resolve framework
2586         // dependencies through the bean store.
2587         registerFrameworkDefaults(beanStore);
2588
2589         var rci2 = ClassInfo.of(resourceClass);
2590
2591         // Build the annotation work list as early as possible in construction — immediately after
2592         // registerFrameworkDefaults() registers the framework-bean default suppliers above, and
2593         // before any step below (the @Bean field/method scan, @RestInit hooks, or the @Bean field
2594         // back-fill) that can trigger a beanStore lookup and force-evaluate a creator/builder memoizer
2595         // that reads annotationWork directly (partSerializerCreator, partParserCreator,
2596         // jsonSchemaGeneratorBuilder, beanContextBuilder). Building it this late used to leave those
2597         // memoizers exposed to an NPE whenever something forced them early — e.g. a @Bean static
2598         // witness field of type HttpPartSerializer, or an @RestInit method parameter of one of the
2599         // affected framework types — since annotationWork was still null at that point.
2600         var vrs = getBootstrapVarResolver().createSession();
2601         annotationWork = AnnotationWorkList.of(vrs, rstream(AnnotationProvider.INSTANCE.find(rci2)).filter(CONTEXT_APPLY_FILTER));
2602
2603         // For mixin sub-contexts, the bean store is parent-linked to the host's full beanStore so that
2604         // host-declared @Bean factory results (e.g. @Bean(name="db") HealthIndicator dbIndicator()) are
2605         // visible through the mixin's lookup chain.  But the parent walk also picks up the host's
2606         // framework defaults (SerializerSet, ParserSet, RichLogger, ...) at the parent's tier-4 slot
2607         // before this store's tier-4 defaults can fire — which would shadow this mixin's per-context
2608         // framework objects.  Promoting our defaults into local entries (tier 2) makes them resolve
2609         // ahead of the parent walk while still letting an overriding parent (e.g. Spring) and explicit
2610         // local @Bean registrations win.  Top-level resources and @Rest(children=...) sub-resources keep
2611         // the original tier-4 default semantics so a parent-supplied framework bean (e.g. Spring's
2612         // SerializerSet) still wins as it did before.
2613         if (isMixinContext && beanStore instanceof BasicBeanStore beanStore2)
2614            beanStore2.promoteDefaultsToLocalSuppliers();
2615         else if (parentContext != null && parentContext.isMixinContext)
2616            // A child-of-mixin sub-context's bean store is parent-linked to its parent (the mixin), but the
2617            // mixin's OWN bootstrap layer is the host's full beanStore (see parentBs selection above), so the
2618            // chain reaches the host's full store, whose tier-4 RestContextProperties default would otherwise
2619            // resolve ahead of this child's own tier-4 default (children run no promotion). Pin this child's
2620            // own bound instance as a local (tier-2) entry so that beanStore().getBean(RestContextProperties.class)
2621            // matches getRestContextProperties(). This narrows the promotion to this single type and to the
2622            // child-of-mixin case specifically, leaving ordinary (non-mixin-parented) children at normal
2623            // tier-4 default / parent-wins semantics, so a Spring/parent-supplied bean still wins for them.
2624            beanStore.addBean(RestContextProperties.class, getRestContextProperties());
2625
2626         // Register @Bean fields that already have a value.  Non-framework values are also exported to the
2627         // inheritable layer so that @Rest(children) sub-resources see them.  Each registered (type, name) key is
2628         // recorded so that a @Bean method with the same key does not overwrite the field (first wins).
2629         // Framework-typed fields (including named ones such as @Bean(name="encoders") EncoderSet) keep their
2630         // raw value locally and are not exported; unlike framework-typed methods they are not aliased.
2631         var registeredKeys = new HashSet<List<Object>>();
2632         // @formatter:off
2633         rci2.getAllFields().stream()
2634            .filter(x -> x.hasAnnotation(Bean.class))
2635            .forEach(x -> o(x.get(resource.get())).ifPresent(y -> {
2636               var ft = x.getFieldType().<Object>inner();
2637               var name = BeanAnnotation.name(x.getAnnotations(Bean.class).findFirst().map(AnnotationInfo::inner).orElse(null));
2638               beanStore.add(ft, y, name);
2639               registeredKeys.add(List.of(ft, name));
2640               if (isInheritableBeanType(ft, name))
2641                  inheritableBeanStore.add(ft, y, name);
2642            }));
2643         // @formatter:on
2644
2645         // Run @Bean methods and register their results as LOCAL entries (level 2 of resolve()).
2646         //
2647         // Each @Bean method is invoked directly (BeanStore.invokeBeanMethod) and its own result is registered under
2648         // its own (return type, name) key, so several same-typed methods with different names yield distinct beans.
2649         // Methods of any visibility (public, protected, package-private, private) and static methods are honored.
2650         // NOTE: for a proxied (e.g. CGLIB) resource, non-public methods run against the resource object as-is.
2651         //
2652         // Walk order is child class first, then superclasses, with interface default methods after all superclasses.
2653         // The first method to claim a (type, name) key wins; an unresolvable method (missing parameters)
2654         // claims nothing, so a later candidate can still fill the key.  An overridden method runs once (the
2655         // override); if the parent declares a covariant (wider) return type, the override's instance is also
2656         // registered under the parent's type.  Methods with a non-empty methodScope() are op-scoped and skipped
2657         // here (RestOpContext handles them); interface static methods are ignored.
2658         //
2659         // For framework types (those with a default supplier registered above, under the exact name or unnamed):
2660         // the @Bean scan already ran inside the corresponding memoizer body (see e.g. the `logger` memoizer above),
2661         // so invoking the method here would create a SECOND instance and produce inconsistent state between the
2662         // framework's memoizer-backed bean and the bean store's local entry.  Instead, the existing default
2663         // supplier (memoizer-backed, resolving to the @Bean value when one was supplied) is PROMOTED into a
2664         // local-entry supplier.  A framework type has one per-context instance, so when the method is named but only
2665         // an unnamed default exists (e.g. @Bean(name="encoders") EncoderSet), the name becomes an alias of that
2666         // single instance.  Framework types are never exported to children (framework-type isolation).
2667         // Promoting at level 2 means @Bean results win over a parent (Spring) at level 3.
2668         //
2669         // Net effect: @Bean method results uniformly take precedence over Spring/parent
2670         // bindings for both framework and user-defined types.  This auto-derives the legacy
2671         // DELAYED_INJECTION list from the default-supplier registrations.
2672         var walkedMethods = new HashMap<String,Object[]>();              // Signature -> {returnType, instance|null} for overridable methods.
2673         var frameworkMethods = new LinkedHashMap<Class<?>,List<String>>();  // Framework type -> method names (for the duplicate warning).
2674         rci2.getAllMethods().forEach(x -> {
2675            if (x.isStatic() && x.inner().getDeclaringClass().isInterface())
2676               return;
2677            var found = BeanAnnotation.find(x).orElse(null);
2678            if (found == null || found.methodScope().length > 0)
2679               return;
2680            var rt = x.getReturnType().<Object>inner();
2681            var name = BeanAnnotation.name(found);
2682            // Skip the WritableBeanStore factory (already consumed by createBeanStore()) and void methods.
2683            if (WritableBeanStore.class.equals(rt) || BeanStore.class.equals(rt) || void.class.equals(rt))
2684               return;
2685            var overridable = ! x.isPrivate() && ! x.isStatic();
2686            var sig = x.getSignature();
2687            if (overridable) {
2688               var previous = walkedMethods.get(sig);
2689               if (previous != null || walkedMethods.containsKey(sig)) {
2690                  // Overridden parent copy: never invoked.  Covariant override: share the child's instance under the parent's type.
2691                  // The parent's (type, name) key obeys first-wins too, so an earlier @Bean field or method keeps it.
2692                  if (previous != null && previous[0] != rt && previous[1] != null && registeredKeys.add(List.of(rt, name))) {
2693                     beanStore.addBean(rt, previous[1], name);
2694                     if (isInheritableBeanType(rt, name))
2695                        inheritableBeanStore.addBean(rt, previous[1], name);
2696                  }
2697                  return;
2698               }
2699               walkedMethods.put(sig, null);
2700            }
2701            if (isFrameworkBeanType(rt, name)) {
2702               frameworkMethods.computeIfAbsent(rt, k -> new ArrayList<>()).add(x.getName());
2703               if (beanStore instanceof BasicBeanStore beanStore2) {
2704                  if (beanStore2.hasDefaultSupplier(rt, name))
2705                     beanStore2.getDefaultSupplier(rt, name).ifPresent(sup -> beanStore.addSupplier(rt, sup, name));
2706                  else
2707                     beanStore2.getDefaultSupplier(rt, "").ifPresent(sup -> beanStore.addSupplier(rt, sup, name));
2708               }
2709               return;
2710            }
2711            if (registeredKeys.contains(List.of(rt, name)))
2712               return;
2713            beanStore.invokeBeanMethod(rt, x, resource.get()).ifPresent(y -> {
2714               registeredKeys.add(List.of(rt, name));
2715               if (overridable)
2716                  walkedMethods.put(sig, new Object[]{rt, y});
2717               beanStore.addBean(rt, y, name);
2718               // Same instance, exported so @Rest(children) sub-resources see it.
2719               inheritableBeanStore.addBean(rt, y, name);
2720            });
2721         });
2722         frameworkMethods.forEach((type, methods) -> {
2723            if (methods.size() > 1)
2724               LOG.warning("Resource class %s declares multiple @Bean methods %s of framework type %s.  A framework type has one per-context instance, so all of these names alias it.", resourceClass().getName(), methods, type.getName());
2725         });
2726
2727         // Run @RestInit-annotated methods on the resource object (deduplicated by signature, top-down order).
2728         // Note: pre-10.0 this filter also excluded `y.hasParameter(RestOpContext.Builder.class)` because the
2729         // per-op `@RestInit(RestOpContext.Builder)` flow handled those separately. That flow was deleted in
2730         // April 2026 refactor Route B (zero real-world callers), so the exclusion is gone too. Likewise, the
2731         // class-level `@RestInit(RestContext.Builder)` injection protocol was deleted in the same refactor
2732         // (zero non-test callers anywhere) — `RestContext.Builder` is no longer added to the bean store, so
2733         // any straggling `@RestInit` method that still declares either Builder type as a parameter will now
2734         // surface a "missing prerequisites" error here, which is the desired loud-failure signal.
2735         var r = resource.get();
2736         var initMap = CollectionUtils.<String,MethodInfo>map();
2737         ClassInfo.ofProxy(r).getAllMethodsTopDown().stream()
2738            .filter(y -> y.hasAnnotation(RestInit.class))
2739            .forEach(y -> { var sig = y.getSignature(); if (!initMap.containsKey(sig)) initMap.put(sig, y.accessible()); });
2740         for (var m : initMap.values()) {
2741            if (!m.canResolveAllParameters(beanStore, r))
2742               throw servletException("Could not call @RestInit method %s.%s.  Could not find prerequisites: %s.", cns(m.getDeclaringClass()), m.getSignature(), m.getMissingParameterTypes(beanStore, r));
2743            try {
2744               m.inject(beanStore, r);
2745            } catch (Exception e) {
2746               throw servletException(e, "Exception thrown from @RestInit method %s.%s.", cns(m.getDeclaringClass()), m.getSignature());
2747            }
2748         }
2749
2750         // Back-fill @Bean fields that were null before init hooks ran.
2751         // @formatter:off
2752         rci2.getAllFields().stream()
2753            .filter(x -> x.hasAnnotation(Bean.class))
2754            .forEach(x -> x.setIfNull(
2755               resource.get(),
2756               beanStore.getBean(
2757                  x.getFieldType().inner(),
2758                  BeanAnnotation.name(x.getAnnotations(Bean.class).findFirst().map(AnnotationInfo::inner).orElse(null))
2759               ).orElse(null)
2760            ));
2761         // @formatter:on
2762
2763         // Populate @Inject-annotated fields and methods on the resource, then fire @PostConstruct
2764         // callbacks.  This covers the JSR-330 / Spring @Autowired / jakarta.inject.Inject FQNs as
2765         // well as the Juneau-owned @Inject in commons.inject — recognition is FQN-based, see JsrSupport.
2766         rci2.inject(resource.get(), beanStore);
2767
2768         builder.args.beanStoreConfigurer().accept(beanStore);
2769
2770         // --- end beanStore setup ---
2771
2772         // Path resolution: explicit Args.path (non-empty) wins so callers like
2773         // RestChildren.addChild(String,Object) can mount the same class at a custom path; otherwise read
2774         // from the @Rest(path) annotation chain (most-derived class wins). This restores override behavior
2775         // removed in the May 2026 Builder.path elimination, without resurrecting the staging field.
2776         var argsPath = builder.args.path();
2777         if (argsPath != null && ! argsPath.isEmpty()) {
2778            path = trimLeadingSlashes(argsPath);
2779         } else {
2780            path = getRestAnnotations().stream()
2781               .map(ai -> ai.inner().path())
2782               .filter(StringUtils::isNotEmpty)
2783               .findFirst()
2784               .map(s -> trimLeadingSlashes(s))
2785               .orElse("");
2786         }
2787         fullPath = (parentContext == null ? "" : (parentContext.fullPath + '/')) + path;
2788         var p = path;
2789         if (! p.endsWith("/*"))
2790            p += "/*";
2791         pathMatcher = UrlPathMatcher.of(p);
2792
2793         // Top-level mount-paths resolution chain (programmatic > getter > annotation default).
2794         // See javadoc on getPaths() for the full precedence order. Resolution happens once at construction;
2795         // the resolved array is what hosting runtimes (Jetty auto-discovery, Spring Boot ServletRegistrationBean)
2796         // should consume rather than reading the raw @Rest(paths) annotation directly.  Each @Rest(paths)
2797         // element is SVL-resolved through a VarResolver session backed by the live bean store — so
2798         // ${C:key} consults whatever Config is currently registered (test overlay, @Bean factory, or the
2799         // framework's runtime Config) and ${E:NAME:default} / ${S:prop:default} use the bootstrap variable
2800         // catalog without needing any beans.  The session-with-beanstore form is what makes test-time
2801         // Config injection visible to SVL without firing the full runtime VarResolver memoizer.
2802         paths = resolveMountPaths(builder, resource.get(), getBootstrapVarResolver(), beanStore, getRestAnnotations());
2803
2804         // annotationWork was already built above (right after registerFrameworkDefaults(), well before
2805         // any step that could force-evaluate a memoizer reading it) — force-init beanContextBuilder
2806         // here so annotation work is applied before the builder is used by any other memoizer.
2807         beanContextBuilder.get();
2808
2809         // @formatter:off
2810         beanStore
2811            .addBean(RestContext.class, this)
2812            .addBean(Object.class, resource.get())
2813            .addBean(Builder.class, builder)
2814            .addBean(AnnotationWorkList.class, annotationWork);
2815         // @formatter:on
2816
2817      // Inject the remaining @Value-annotated env-driven defaults (debug level, uriAuthority, uriContext) onto
2818      // this RestContext instance so that the memoizer lambdas below (which run lazily on first .get() call)
2819      // read fully resolved values.
2820      ClassInfo.of(this).inject(this, beanStore);
2821
2822      // Startup-fail if @Rest(observability="true") is set but neither MetricsRecorder nor TracerHook is
2823      // supplied. The check runs after all @Bean method injection so that consumer-provided beans are visible.
2824      checkObservabilityBackendPresent();
2825
2826      // Startup-fail: if asyncCompletionExecutor is configured (either by annotation or
2827      // programmatically), force-evaluate the memoizer now so "bean not found" surfaces at context
2828      // init time rather than lazily on the first request.
2829      checkAsyncCompletionExecutorPresent();
2830
2831      if (isEagerInit()) {
2832            // Force-fire the framework-bean memoizers in dependency-friendly order so their @Rest()
2833            // annotation walks (e.g. `@Rest(partParser=…)`, `@Rest(partSerializer=…)`, `@Rest(encoders=…)`,
2834            // etc.) execute eagerly inside the try-catch.  These walks MUTATE the cached creators that
2835            // downstream RestOpContext memoizers later copy from, so they must run before
2836            // getRestOperations() builds the per-op contexts.  We do NOT re-add results to the bean
2837            // store — the default suppliers registered earlier already cover lookups.
2838            initializeFrameworkBeansForRestOps();
2839
2840            // Force-initialize restOperations and restChildren now so that any construction failures
2841            // (e.g. bad @RestOp method or invalid child class) surface here inside the try-catch.
2842            getRestOperations();
2843            getRestChildren();
2844         }
2845
2846         // produces/consumes are resolved lazily via the produces/consumes memoizers below
2847         // (April 2026 refactor, 2026-04-19) — they walk the @Rest(produces=...) / @Rest(consumes=...)
2848         // chain first, then fall back to deriving the intersection of opContexts' supported media types.
2849
2850      } catch (BasicHttpException e) {
2851         initExceptionTemp = e;
2852         throw e;
2853      } catch (Exception e) {
2854         initExceptionTemp = new InternalServerError(e);
2855         throw e;
2856      } finally {
2857         initException = initExceptionTemp;
2858      }
2859   }
2860
2861   @Override /* Overridden from Context */
2862   public RestSession.Builder createSession() {
2863      return RestSession.create(this);
2864   }
2865
2866   //---------------------------------------------------------------------------------------------
2867   // Memoized allowlist fields
2868   //---------------------------------------------------------------------------------------------
2869
2870   /**
2871    * Memoized parser session-option keys from {@code @Rest(allowedParserOptions)}, after SVL resolution and comma expansion.
2872    *
2873    * <p>
2874    * When inheritance is not blocked, keys from {@link #parentContext} are included first, then this resource's own tokens.
2875    * Leading-hyphen tokens (e.g. {@code -foo}) remove earlier positive tokens.
2876    */
2877   private final Memoizer<SortedSet<String>> allowedParserOptions = memoizer(() -> {
2878      var l = new ArrayList<String>();
2879      var p = "allowedParserOptions";
2880      var pc = parentContext();
2881      if (isInherited(p) && pc != null)
2882         l.addAll(pc.getAllowedParserOptions());
2883      getRestAnnotationsForProperty(p).forEach(x -> resolveCdl(x.getStringArray(p)).forEach(l::add));
2884      return u(treeSetCi(removeNegations(l)));
2885   });
2886
2887   /**
2888    * Memoized serializer session-option keys from {@code @Rest(allowedSerializerOptions)}, after SVL resolution and comma expansion.
2889    *
2890    * <p>
2891    * When inheritance is not blocked, keys from {@link #parentContext} are included first, then this resource's own tokens.
2892    * Leading-hyphen tokens remove earlier positive tokens.
2893    */
2894   private final Memoizer<SortedSet<String>> allowedSerializerOptions = memoizer(() -> {
2895      var l = new ArrayList<String>();
2896      var p = "allowedSerializerOptions";
2897      var pc = parentContext();
2898      if (isInherited(p) && pc != null)
2899         l.addAll(pc.getAllowedSerializerOptions());
2900      getRestAnnotationsForProperty(p).forEach(x -> resolveCdl(x.getStringArray(p)).forEach(l::add));
2901      return u(treeSetCi(removeNegations(l)));
2902   });
2903
2904   /**
2905    * Memoized value of the {@code noInherit} annotation attribute from the nearest {@code @Rest} annotation.
2906    *
2907    * <p>
2908    * {@code noInherit} itself is never inherited; it only applies to the {@code @Rest} that declares it.
2909    */
2910   private final Memoizer<SortedSet<String>> noInherit = memoizer(() -> {
2911      var out = treeSet(String.CASE_INSENSITIVE_ORDER,
2912         getRestAnnotation()
2913            .map(x -> x.getStringArray("noInherit").orElse(StringUtils.EMPTY_STRING_ARRAY))
2914            .map(x -> resolveCdl(x).toList())
2915            .orElseGet(Collections::emptyList));
2916      // Dual noInherit source: when this is a mixin sub-context built from a host @Mixin(noInherit=...),
2917      // the host-declared cutoff tokens union with the mixin class's own @Rest(noInherit=...).  A token from
2918      // EITHER source cuts the host→mixin inheritance walk for that property.
2919      var rmNoInherit = resolvedMixinField();
2920      if (rmNoInherit != null)
2921         resolveCdl(rmNoInherit.overrides().noInherit()).forEach(out::add);
2922      return out;
2923   });
2924
2925   /**
2926    * The host-declared {@code @Mixin} override values translated into a synthetic {@link Rest} annotation, for a
2927    * mixin sub-context that carries overrides.  {@code null} for non-mixin contexts and for mixins with no
2928    * overrides (bare classes).
2929    *
2930    * <p>
2931    * Built once at memoizer-init time (zero per-request cost).  The synthetic annotation is injected at the
2932    * most-derived position of {@link #getRestAnnotationsForProperty(String)} so the host override resolves as if
2933    * declared on the mixin class itself — list-shaped props append after the inherited host chain, replace-shaped
2934    * props win — but ahead of the mixin class's own {@code @Rest}, so the host override is authoritative.
2935    */
2936   private final Memoizer<AnnotationInfo<Rest>> mixinOverrideAnnotation = memoizer(() -> {
2937      var rm = resolvedMixinField();
2938      if (rm == null || rm.hasNoOverrides())
2939         return null;
2940      var rest = buildMixinOverrideRest(rm.overrides());
2941      return AnnotationInfo.of(ClassInfo.of(getResourceClass()), rest);
2942   });
2943
2944   /**
2945    * Translates a host-declared {@link Mixin @Mixin} into a synthetic {@link Rest @Rest} carrying only its
2946    * override slots, so the standard {@code @Rest} resolution chain applies the overrides uniformly.
2947    *
2948    * @param m The {@code @Mixin} override declaration.
2949    * @return A synthetic {@code @Rest} populated from {@code m}'s override slots.
2950    */
2951   private static Rest buildMixinOverrideRest(Mixin m) {
2952      // @formatter:off
2953      var b = RestAnnotation.create()
2954         .guards(m.guards())
2955         .roleGuard(m.roleGuard())
2956         .rolesDeclared(m.rolesDeclared())
2957         .converters(m.converters())
2958         .encoders(m.encoders())
2959         .serializers(m.serializers())
2960         .parsers(m.parsers())
2961         .responseProcessors(m.responseProcessors())
2962         .restOpArgs(m.restOpArgs())
2963         .partSerializer(m.partSerializer())
2964         .partParser(m.partParser())
2965         .messages(m.messages())
2966         .defaultRequestHeaders(m.defaultRequestHeaders())
2967         .defaultResponseHeaders(m.defaultResponseHeaders())
2968         .defaultRequestAttributes(m.defaultRequestAttributes())
2969         .produces(m.produces())
2970         .consumes(m.consumes())
2971         .defaultAccept(m.defaultAccept())
2972         .defaultContentType(m.defaultContentType())
2973         .defaultCharset(m.defaultCharset())
2974         .maxInput(m.maxInput());
2975      // @formatter:on
2976      return b.build();
2977   }
2978
2979   /**
2980    * The host-declared {@code @Child} seed values translated into a synthetic {@link Rest} annotation, for a
2981    * child sub-context that carries a seed. {@code null} for non-child contexts and for children with no seed
2982    * (bare classes).
2983    *
2984    * <p>
2985    * Built once at memoizer-init time (zero per-request cost). Unlike {@link #mixinOverrideAnnotation}, this is
2986    * injected at the <b>least-derived</b> slot of {@link #computeRawRestAnnotations()} — below the child's own
2987    * real {@code @Rest} declarations but above the synthesized {@code DefaultConfig} fallback — so the seed acts
2988    * as a default/fallback the child's own explicit configuration wins over (see {@link ContextKind} javadoc).
2989    */
2990   private final Memoizer<AnnotationInfo<Rest>> childSeedAnnotation = memoizer(() -> {
2991      var rc = resolvedChildField();
2992      if (rc == null || rc.hasNoSeed())
2993         return null;
2994      var rest = buildChildSeedRest(rc.seed());
2995      return AnnotationInfo.of(ClassInfo.of(getResourceClass()), rest);
2996   });
2997
2998   /**
2999    * Translates a host-declared {@link Child @Child} into a synthetic {@link Rest @Rest} carrying only its
3000    * seed slots (a restricted subset — no {@code encoders}/{@code serializers}/{@code parsers}/
3001    * {@code responseProcessors}/{@code restOpArgs}/{@code messages}/default headers or attributes/
3002    * {@code produces}/{@code consumes}), so the standard {@code @Rest} resolution chain applies the seed uniformly.
3003    *
3004    * @param c The {@code @Child} seed declaration.
3005    * @return A synthetic {@code @Rest} populated from {@code c}'s seed slots.
3006    */
3007   private static Rest buildChildSeedRest(Child c) {
3008      // @formatter:off
3009      var b = RestAnnotation.create()
3010         .guards(c.guards())
3011         .roleGuard(c.roleGuard())
3012         .rolesDeclared(c.rolesDeclared())
3013         .converters(c.converters())
3014         .partSerializer(c.partSerializer())
3015         .partParser(c.partParser())
3016         .defaultCharset(c.defaultCharset())
3017         .maxInput(c.maxInput());
3018      // @formatter:on
3019      return b.build();
3020   }
3021
3022   /**
3023    * Memoized list of every {@link Rest} annotation on the resource class and its supertypes, in child-to-parent order.
3024    *
3025    * <p>
3026    * For <b>host</b> contexts (top-level resources), {@link DefaultConfig} is always synthesized as the top-most
3027    * (parent-most) entry when not already present in the class hierarchy. This makes {@code DefaultConfig.@Rest(...)}
3028    * the framework's single source of truth for default lists (response processors, REST op args, encoders, parsers,
3029    * serializers, ...), while still letting bare {@code @Rest}-annotated resources inherit the framework defaults
3030    * without explicitly implementing {@link BasicUniversalConfig} or any other {@code DefaultConfig} descendant.
3031    * Resources that <i>do</i> implement {@code DefaultConfig} (transitively or directly) won't get a duplicate
3032    * entry — the list is dedup'd by the {@link Class} the annotation was declared on.
3033    *
3034    * <p>
3035    * For <b>mixin</b> sub-contexts the synthesized {@code DefaultConfig} fallback is omitted: the mixin's annotation
3036    * chain is composed with the host's chain by
3037    * {@link #getRestAnnotationsForProperty(String) getRestAnnotationsForProperty(...)}, and the host's chain already
3038    * supplies the {@code DefaultConfig} fallback (synthesized or transitive). Including it on the mixin too would
3039    * place a second {@code DefaultConfig} entry between the host's most-derived {@code @Rest} and the mixin's own
3040    * annotations in the combined parent-to-child walk, which would let the framework defaults silently override
3041    * a host's explicit per-property values for any property the mixin doesn't itself declare (e.g.
3042    * {@code partSerializer}, {@code partParser}).
3043    */
3044   private final Memoizer<List<AnnotationInfo<Rest>>> restAnnotations = memoizer(() -> prependBuilderRestAnnotation(computeRawRestAnnotations()));
3045
3046   /**
3047    * Computes the raw {@code @Rest} annotation chain (most-derived first), folding in the framework
3048    * {@code DefaultConfig} annotations for non-mixin contexts, and — for a {@linkplain ContextKind.Child child}
3049    * context carrying a host-declared {@code @Child} seed — injecting the seed's synthetic {@code @Rest} at the
3050    * least-derived slot: {@code raw ++ [seed] ++ defaultConfigAnnotations}. This ranks the seed below everything
3051    * the child itself declares (child-wins scalars resolve to the child's own value when present) but above the
3052    * framework's {@code DefaultConfig} fallback (the seed is never masked by framework defaults). This holds
3053    * uniformly whether {@code DefaultConfig} is separately synthesized (the common case) or already embedded
3054    * within {@code raw} because the child class transitively implements {@code DefaultConfig} itself (e.g. by
3055    * extending {@code BasicRestServlet}/{@code BasicRestServletGroup}) — in the embedded case, {@code raw} is
3056    * split around the embedded {@code DefaultConfig} entry/entries so the seed still lands between the child's
3057    * own declarations and that entry, rather than after it. Does not include the synthetic builder annotation.
3058    *
3059    * @return The raw annotation chain.
3060    */
3061   private List<AnnotationInfo<Rest>> computeRawRestAnnotations() {
3062      var raw = getAnnotationProvider().find(Rest.class, ClassInfo.of(getResourceClass()));
3063      if (isMixinContextField())
3064         return raw;
3065      var seed = childSeedAnnotation.get();  // null for non-child contexts and no-seed children
3066      // The framework's DefaultConfig fallback is synthesized/appended for EVERY non-mixin context that
3067      // doesn't already transitively implement DefaultConfig itself — this happens unconditionally,
3068      // regardless of whether this context also carries an @Child seed (that baseline behavior predates
3069      // and is independent of @Child). Partition raw into "the resource's own real declarations" and any
3070      // DefaultConfig entries already embedded within its own hierarchy (e.g. because it extends
3071      // BasicRestServlet/BasicRestServletGroup, which implement DefaultConfig), so that when a seed IS
3072      // present it can always be inserted between them — below everything the child itself declares, but
3073      // above DefaultConfig's fallback values, whether that fallback is embedded here or synthesized below.
3074      var embeddedDefaultConfig = raw.stream().filter(ai -> ai.getAnnotatable() instanceof ClassInfo ci && DefaultConfig.class.equals(ci.inner())).toList();
3075      if (!embeddedDefaultConfig.isEmpty()) {
3076         if (seed == null)
3077            return raw;
3078         var ownDeclarations = raw.stream().filter(ai -> !(ai.getAnnotatable() instanceof ClassInfo ci && DefaultConfig.class.equals(ci.inner()))).toList();
3079         var combined = new ArrayList<AnnotationInfo<Rest>>(raw.size() + 1);
3080         combined.addAll(ownDeclarations);
3081         combined.add(seed);
3082         combined.addAll(embeddedDefaultConfig);
3083         return u(combined);
3084      }
3085      var defaultConfigAnnotations = getAnnotationProvider().find(Rest.class, ClassInfo.of(DefaultConfig.class));
3086      if (defaultConfigAnnotations.isEmpty())
3087         return seed == null ? raw : appendAnnotation(raw, seed);
3088      var combined = new ArrayList<>(raw);
3089      if (seed != null)
3090         combined.add(seed);
3091      combined.addAll(defaultConfigAnnotations);
3092      return u(combined);
3093   }
3094
3095   /**
3096    * Returns a new unmodifiable list with {@code extra} appended after {@code base}.
3097    *
3098    * @param base The base list.
3099    * @param extra The entry to append.
3100    * @return An unmodifiable list of {@code base} followed by {@code extra}.
3101    */
3102   private static List<AnnotationInfo<Rest>> appendAnnotation(List<AnnotationInfo<Rest>> base, AnnotationInfo<Rest> extra) {
3103      var combined = new ArrayList<>(base);
3104      combined.add(extra);
3105      return u(combined);
3106   }
3107
3108   /**
3109    * Prepends the synthetic builder-supplied {@code @Rest} annotation at the most-derived (child)
3110    * position so its set members win in both child-first ({@code findFirst}) and parent-to-child
3111    * ({@code reduce-last}) resolution walks.  Returns {@code base} unchanged when there is no programmatic builder.
3112    *
3113    * @param base The raw annotation chain.
3114    * @return The chain with the synthetic annotation prepended (when present).
3115    */
3116   private List<AnnotationInfo<Rest>> prependBuilderRestAnnotation(List<AnnotationInfo<Rest>> base) {
3117      if (builderRestAnnotation == null)
3118         return base;
3119      var combined = new ArrayList<AnnotationInfo<Rest>>(base.size() + 1);
3120      combined.add(AnnotationInfo.of(ClassInfo.of(getResourceClass()), builderRestAnnotation));
3121      combined.addAll(base);
3122      return u(combined);
3123   }
3124
3125   /**
3126    * Non-reflectively reads the programmatic configuration builder stashed on a resource/mixin instance,
3127    * or returns <jk>null</jk> when the instance carries none or is not a builder-aware base type.
3128    *
3129    * @param r The resource instance.
3130    * @return The stashed builder, or <jk>null</jk> if <c>r</c> carries none or is not a builder-aware base type.
3131    */
3132   private static RestBuilder<?> stashedRestBuilder(Object r) {
3133      if (r instanceof RestServlet r2)
3134         return r2.getRestBuilder();
3135      if (r instanceof RestResource r2)
3136         return r2.getRestBuilder();
3137      if (r instanceof RestMixin r2)
3138         return r2.getRestBuilder();
3139      return null;
3140   }
3141
3142   /**
3143    * The {@code @Rest} annotation list for this resource in parent-to-child (top-down) order.
3144    *
3145    * <p>
3146    * This is the reverse of {@link #restAnnotations}: most-ancestor annotation first, most-derived last.
3147    * Use this when walking the annotation chain in inheritance order so that child values append after or
3148    * override parent values.
3149    */
3150   private final Memoizer<List<AnnotationInfo<Rest>>> restAnnotationsTopDown = memoizer(() -> {
3151      var list = new ArrayList<>(getRestAnnotations());
3152      Collections.reverse(list);
3153      return u(list);
3154   });
3155
3156   private Stream<AnnotationInfo<Rest>> restAnnotationsForPropertySortedByRank(String propertyName) {
3157      return getRestAnnotationsForProperty(propertyName).sorted(Comparator.comparingInt(AnnotationInfo::getRank));
3158   }
3159
3160   private static String leadingEnumToken(String s) {
3161      s = trim(s);
3162      if (isEmpty(s))
3163         return s;
3164      int i = 0;
3165      while (i < s.length() && (Character.isLetter(s.charAt(i)) || s.charAt(i) == '_'))
3166         i++;
3167      return s.substring(0, i);
3168   }
3169
3170   private <E extends Enum<E>> Optional<E> parseEnumConstant(Class<E> enumClass, String resolved) {
3171      var t = leadingEnumToken(trim(emptyIfNull(resolved)));
3172      if (isEmpty(t))
3173         return oe();
3174      try {
3175         return o(Enum.valueOf(enumClass, t));
3176      } catch (IllegalArgumentException ignored) {
3177         return oe();
3178      }
3179   }
3180
3181   String mergeReplacedStringAttribute(String propertyName, String initialFromEnvOrNull) {
3182      var v = new AtomicReference<>(initialFromEnvOrNull == null ? null : resolve(initialFromEnvOrNull));
3183      restAnnotationsForPropertySortedByRank(propertyName).forEach(ai ->
3184         ai.getString(propertyName)
3185            .filter(StringUtils::isNotBlank)
3186            .map(this::resolve)
3187            .filter(StringUtils::isNotBlank)
3188            .ifPresent(v::set));
3189      return v.get();
3190   }
3191
3192   private boolean mergeReplacedBooleanAttribute(String propertyName, boolean envDefault) {
3193      var v = new AtomicReference<>(envDefault);
3194      restAnnotationsForPropertySortedByRank(propertyName).forEach(ai ->
3195         ai.getString(propertyName)
3196            .filter(StringUtils::isNotBlank)
3197            .map(this::resolve)
3198            .filter(StringUtils::isNotBlank)
3199            .ifPresent(s -> v.set(Boolean.parseBoolean(s))));
3200      return v.get();
3201   }
3202
3203   // Resolves a raw RestContext.* boolean default carried on RestContextProperties: SVL variables in the raw seed
3204   // are resolved recursively through the resource var resolver (so a value such as ${S:flag} or ${C:...} resolves to
3205   // its target) before parsing to a boolean.  A blank or unresolved value parses to false.  This mirrors the enum
3206   // treatment (getUriRelativityRaw()/getUriResolutionRaw()) — the bean carries the raw string and RestContext owns
3207   // all SVL resolution and typing, since only RestContext holds the var resolver.
3208   private boolean resolveBooleanDefault(String raw) {
3209      return Boolean.parseBoolean(resolve(emptyIfNull(raw)));
3210   }
3211
3212   /**
3213    * Header names that may be passed via URL query parameter; resolved from {@code @Rest(allowedHeaderParams)},
3214    * default {@code "Accept"}.
3215    */
3216   private final Memoizer<Set<String>> allowedHeaderParams = memoizer(() ->
3217      u(newCaseInsensitiveSet(mergeReplacedStringAttribute("allowedHeaderParams", getRestContextProperties().getAllowedHeaderParams()))));
3218
3219   /**
3220    * HTTP method names that may be specified via a request header; resolved from {@code @Rest(allowedMethodHeaders)},
3221    * default empty.
3222    */
3223   private final Memoizer<Set<String>> allowedMethodHeaders = memoizer(() ->
3224      u(newCaseInsensitiveSet(mergeReplacedStringAttribute("allowedMethodHeaders", getRestContextProperties().getAllowedMethodHeaders()))));
3225
3226   /**
3227    * Response header names a client may request via {@code x-response-headers}; resolved from
3228    * {@code @Rest(allowedResponseHeaders)}, default empty (feature off).
3229    */
3230   private final Memoizer<Set<String>> allowedResponseHeaders = memoizer(() ->
3231      u(newCaseInsensitiveSet(mergeReplacedStringAttribute("allowedResponseHeaders", ""))));
3232
3233   /**
3234    * HTTP method names that may be specified via URL query parameter; resolved from {@code @Rest(allowedMethodParams)},
3235    * default {@code "HEAD,OPTIONS"}.
3236    */
3237   private final Memoizer<Set<String>> allowedMethodParams = memoizer(() ->
3238      u(newCaseInsensitiveSet(mergeReplacedStringAttribute("allowedMethodParams", getRestContextProperties().getAllowedMethodParams()))));
3239
3240   /**
3241    * Whether a {@code &content=} URL parameter may override the request body; resolved from
3242    * {@code @Rest(allowContentParam)}, default {@code false}.
3243    */
3244   private final Memoizer<Boolean> allowContentParam = memoizer(() ->
3245      mergeReplacedBooleanAttribute("allowContentParam", resolveBooleanDefault(getRestContextProperties().getAllowContentParamRaw())));
3246
3247   /**
3248    * Whether cross-site requests using unsafe methods are allowed; resolved from
3249    * {@code @Rest(allowCrossSite)}, default {@code false}.
3250    */
3251   private final Memoizer<Boolean> allowCrossSite = memoizer(() ->
3252      mergeReplacedBooleanAttribute("allowCrossSite", false));
3253
3254   /**
3255    * Trusted origins for the cross-site check; resolved from {@code @Rest(allowedOrigins)}, default empty.
3256    */
3257   private final Memoizer<Set<String>> allowedOrigins = memoizer(() ->
3258      u(newCaseInsensitiveSet(mergeReplacedStringAttribute("allowedOrigins", ""))));
3259
3260   /**
3261    * Whether exception stack traces are rendered in error responses; resolved from
3262    * {@code @Rest(renderResponseStackTraces)}.
3263    */
3264   private final Memoizer<Boolean> renderResponseStackTraces = memoizer(() ->
3265      mergeReplacedBooleanAttribute("renderResponseStackTraces", resolveBooleanDefault(getRestContextProperties().getRenderResponseStackTracesRaw())));
3266
3267   /**
3268    * Whether the resource emits RFC 7807 {@code application/problem+json} responses; resolved from
3269    * {@code @Rest(problemDetails)}.
3270    */
3271   private final Memoizer<Boolean> problemDetails = memoizer(() ->
3272      mergeReplacedBooleanAttribute("problemDetails", resolveBooleanDefault(getRestContextProperties().getProblemDetailsRaw())));
3273
3274   /**
3275    * Whether REST-driven serializer/parser debug behavior is enabled for this resource; resolved from
3276    * {@code @Rest(debugMarshalling)}.
3277    */
3278   private final Memoizer<Boolean> debugMarshalling = memoizer(() ->
3279      mergeReplacedBooleanAttribute("debugMarshalling", resolveBooleanDefault(getRestContextProperties().getDebugMarshallingRaw())));
3280
3281   /**
3282    * Whether the resource opts into per-request virtual-thread dispatch on Java 21+; resolved from
3283    * {@code @Rest(virtualThreads)}.
3284    *
3285    * <p>
3286    * Detection happens at context-init via {@link #mergeReplacedBooleanAttribute(String, boolean)}; on JVMs older
3287    * than Java 21 the flag is logged once and ignored — see {@link #virtualThreadExecutor}.
3288    */
3289   private final Memoizer<Boolean> virtualThreadsEnabled = memoizer(() ->
3290      mergeReplacedBooleanAttribute("virtualThreads", resolveBooleanDefault(getRestContextProperties().getVirtualThreadsRaw())));
3291
3292   /**
3293    * Env-driven component of {@link #isResponseTraceparent()}; resolved from the {@code RestContext.responseTraceparent}
3294    * env-driven default (no {@code @Rest} annotation member backs this setting).
3295    */
3296   private final Memoizer<Boolean> responseTraceparentDefault = memoizer(() ->
3297      resolveBooleanDefault(getRestContextProperties().getResponseTraceparentRaw()));
3298
3299   /**
3300    * Env-driven component of {@link #isMdcAsyncPropagation()}; resolved from the {@code RestContext.mdcAsyncPropagation}
3301    * env-driven default. The programmatic {@link Builder#mdcAsyncPropagation(boolean)} knob is applied in
3302    * {@link #isMdcAsyncPropagation()} instead of here because blank-final-field rules prevent the memoizer lambda
3303    * from safely capturing {@link #builder}.
3304    */
3305   private final Memoizer<Boolean> mdcAsyncPropagationDefault = memoizer(() ->
3306      resolveBooleanDefault(getRestContextProperties().getMdcAsyncPropagationRaw()));
3307
3308   /**
3309    * Resource-level observability tri-state from {@code @Rest(observability)}: {@code "true"} (strict opt-in),
3310    * {@code "false"} (explicit opt-out), or {@code null} / empty (default inherit behavior).
3311    *
3312    * <p>
3313    * Per-operation overrides (from verb / {@code @RestOp} annotations) are resolved independently in
3314    * {@link RestOpContext}.
3315    */
3316   private final Memoizer<String> observabilityAttribute = memoizer(() ->
3317      mergeReplacedStringAttribute("observability", null));
3318
3319   /**
3320    * Configurable async-response timeout (milliseconds) applied by {@code AsyncResponseProcessor} to
3321    * {@link CompletableFuture}-returning handlers; resolved from {@code @Rest(asyncTimeoutMillis)}.
3322    *
3323    * <p>
3324    * {@code 0} disables the timeout. The default 30-second fallback is applied by {@code AsyncResponseProcessor}
3325    * itself when neither the resource nor the operation declares a value.
3326    */
3327   private final Memoizer<Long> asyncTimeoutMillis = memoizer(() -> {
3328      var s = mergeReplacedStringAttribute("asyncTimeoutMillis", null);
3329      if (isEmpty(s))
3330         return -1L;
3331      try {
3332         return Long.parseLong(s.trim());
3333      } catch (NumberFormatException nfe) {
3334         ASYNC_LOG.log(Level.WARNING, () -> "Invalid @Rest(asyncTimeoutMillis) value '" + s + "' — falling back to default.");
3335         return -1L;
3336      }
3337   });
3338
3339   /**
3340    * The async-completion executor for this resource, resolved by name from the bean store; {@code null} when
3341    * {@code @Rest(asyncCompletionExecutor)} is blank (the common case).
3342    *
3343    * <p>
3344    * The memoizer throws {@link IllegalStateException} at first access if the bean name was supplied but no
3345    * matching {@link Executor} bean is found — this surfaces as a startup failure, not a silent no-op.
3346    */
3347   private final Memoizer<Executor> asyncCompletionExecutor = memoizer(() -> {
3348      // Programmatic override takes priority over the annotation chain.
3349      var name = resolveAsyncCompletionExecutorName();
3350      if (isBlank(name))
3351         return null;
3352      var resolved = beanStore().getBean(Executor.class, name);
3353      // Try ExecutorService as well (a common supertype users supply that is-a Executor).
3354      if (resolved.isEmpty())
3355         resolved = beanStore().getBean(ExecutorService.class, name).map(e -> (Executor) e);
3356      if (resolved.isEmpty())
3357         throw new IllegalStateException(
3358            "@Rest(asyncCompletionExecutor) on " + getResourceClass().getName()
3359               + " references bean name '" + name + "' but no Executor (or ExecutorService) bean"
3360               + " with that name is registered in the resource's bean store.");
3361      return resolved.get();
3362   });
3363
3364   // Extracted to a method so the compiler does not flag a blank-final-field access inside a field-initializer lambda.
3365   private String resolveAsyncCompletionExecutorName() {
3366      return builder.asyncCompletionExecutorName != null
3367         ? builder.asyncCompletionExecutorName
3368         : mergeReplacedStringAttribute("asyncCompletionExecutor", null);
3369   }
3370
3371   /**
3372    * Lazily-instantiated virtual-thread executor used by {@link RestOpInvoker} when
3373    * {@code @Rest(virtualThreads=true)} is set on this resource and the runtime is Java 21+.
3374    *
3375    * <p>
3376    * On Java 17/18/19/20 the supplier returns {@code null} and emits a one-shot {@code WARNING} log so the
3377    * resource degrades gracefully to caller-thread dispatch.
3378    */
3379   private final Memoizer<Executor> virtualThreadExecutor = memoizer(() -> {
3380      // NOTE: Intentionally not gated on resource-level {@code virtualThreadsEnabled.get()} — per-op
3381      // {@code @RestOp(virtualThreads="true")} can opt in even when the enclosing {@code @Rest} doesn't.
3382      // Callers ({@link RestOpInvoker#invokeOp}) only reach this method when the effective op-level flag is true,
3383      // so the warning emitted on Java &lt;21 is appropriate at first call regardless of where the flag is set.
3384      if (Runtime.version().feature() < 21) {
3385         ASYNC_LOG.log(Level.WARNING, () -> "virtualThreads=true configured on " + getResourceClass().getName()
3386            + " but runtime is Java " + Runtime.version().feature() + " — virtual-thread dispatch requires Java 21+. "
3387            + "Falling back to caller-thread dispatch.");
3388         return null;
3389      }
3390      try {
3391         var m = Executors.class.getMethod("newVirtualThreadPerTaskExecutor");
3392         return (Executor) m.invoke(null);
3393      } catch (ReflectiveOperationException e) {
3394         ASYNC_LOG.log(Level.WARNING, e, () -> "Reflective creation of virtual-thread executor failed on "
3395            + getResourceClass().getName() + " — falling back to caller-thread dispatch.");
3396         return null;
3397      }
3398   });
3399
3400   /** Logger for async / virtual-thread setup events. Used at memoizer init before {@link #getLogger()} may be wired up. */
3401   private static final RichLogger ASYNC_LOG = RichLogger.getLogger(RestContext.class.getName() + ".async");
3402
3403   /**
3404    * Whether framework memoizers and operation/child contexts should be force-initialized during constructor execution;
3405    * resolved from {@code @Rest(eagerInit)}.
3406    */
3407   private final Memoizer<Boolean> eagerInit = memoizer(() ->
3408      mergeReplacedBooleanAttribute("eagerInit", resolveBooleanDefault(getRestContextProperties().getEagerInitRaw())));
3409
3410   /**
3411    * Annotation + env-driven component of the lazy-children flag.
3412    *
3413    * <p>
3414    * Reads the {@link Rest#lazyChildren() @Rest(lazyChildren)} annotation chain and falls back to the
3415    * {@code RestContext.lazyChildren} env-driven default.  The programmatic
3416    * {@link Builder#lazyChildInit(boolean)} knob is applied in {@link #isLazyChildren()} instead of here
3417    * because blank-final-field rules prevent the memoizer lambda from safely capturing {@link #builder}.
3418    */
3419   private final Memoizer<Boolean> lazyChildrenAnnotation = memoizer(() ->
3420      mergeReplacedBooleanAttribute("lazyChildren", resolveBooleanDefault(getRestContextProperties().getLazyChildrenRaw())));
3421
3422   /**
3423    * The request header used for client-version matching; resolved from {@code @Rest(clientVersionHeader)},
3424    * default {@code "Client-Version"}.
3425    */
3426   private final Memoizer<String> clientVersionHeader = memoizer(() ->
3427      mergeReplacedStringAttribute("clientVersionHeader", getRestContextProperties().getClientVersionHeader()));
3428
3429   /**
3430    * The {@link UriRelativity} strategy for URI resolution in this resource.
3431    *
3432    * <p>
3433    * Resolved from {@code @Rest(uriRelativity)} annotations (most-derived non-blank wins), with env-var
3434    * fallback. Defaults to {@link UriRelativity#RESOURCE}.
3435    */
3436   private final Memoizer<UriRelativity> uriRelativity = memoizer(() -> {
3437      var v = new AtomicReference<>(
3438         parseEnumConstant(UriRelativity.class, resolve(emptyIfNull(getRestContextProperties().getUriRelativityRaw())))
3439            .orElse(UriRelativity.RESOURCE)
3440      );
3441      restAnnotationsForPropertySortedByRank("uriRelativity").forEach(ai -> ai.getString("uriRelativity").filter(StringUtils::isNotBlank).ifPresent(s ->
3442         parseEnumConstant(UriRelativity.class, resolve(s)).ifPresent(v::set)
3443      ));
3444      return v.get();
3445   });
3446
3447   /**
3448    * The URI authority (scheme + host + port) override for this resource.
3449    *
3450    * <p>
3451    * Resolved from {@code @Rest(uriAuthority)} annotations and env-var; inherited from parent when not
3452    * blocked by {@code noInherit}. {@code null} means no override.
3453    */
3454   private final Memoizer<String> uriAuthority = memoizer(() -> {
3455      String local = mergeReplacedStringAttribute("uriAuthority", defaultUriAuthority.orElse(null));
3456      if (nn(local))
3457         return local;
3458      var pc = parentContext();
3459      return isInherited("uriAuthority") && pc != null ? pc.getUriAuthority() : null;
3460   });
3461
3462   /**
3463    * The URI context path override for this resource.
3464    *
3465    * <p>
3466    * Resolved from {@code @Rest(uriContext)} annotations and env-var; inherited from parent when not
3467    * blocked by {@code noInherit}. {@code null} means no override.
3468    */
3469   private final Memoizer<String> uriContext = memoizer(() -> {
3470      String local = mergeReplacedStringAttribute("uriContext", defaultUriContext.orElse(null));
3471      if (nn(local))
3472         return local;
3473      var pc = parentContext();
3474      return isInherited("uriContext") && pc != null ? pc.getUriContext() : null;
3475   });
3476
3477   /**
3478    * The {@link UriResolution} strategy for URI resolution in this resource.
3479    *
3480    * <p>
3481    * Resolved from {@code @Rest(uriResolution)} annotations (most-derived non-blank wins), with env-var
3482    * fallback. Defaults to {@link UriResolution#ROOT_RELATIVE}.
3483    */
3484   private final Memoizer<UriResolution> uriResolution = memoizer(() -> {
3485      var v = new AtomicReference<>(
3486         parseEnumConstant(UriResolution.class, resolve(emptyIfNull(getRestContextProperties().getUriResolutionRaw())))
3487            .orElse(UriResolution.ROOT_RELATIVE)
3488      );
3489      restAnnotationsForPropertySortedByRank("uriResolution").forEach(ai -> ai.getString("uriResolution").filter(StringUtils::isNotBlank).ifPresent(s ->
3490         parseEnumConstant(UriResolution.class, resolve(s)).ifPresent(v::set)
3491      ));
3492      return v.get();
3493   });
3494
3495   /**
3496    * Property names that describe how a class is mounted on the URL tree, and therefore must NOT inherit from a
3497    * parent context when walking annotations on a {@linkplain #isMixinContext() mixin sub-context}.
3498    *
3499    * <p>
3500    * These properties are intentionally host-only:
3501    * <ul>
3502    *    <li>{@code path} / {@code paths} &mdash; top-level mount declarations only meaningful for the class registered
3503    *       with the servlet container.  A mixin sub-context inheriting the host's mount paths could cause
3504    *       nonsensical routing decisions.
3505    *    <li>{@code mixins} &mdash; the host owns the mixin discovery chain; a mixin sub-context inheriting the host's
3506    *       mixin list would loop or duplicate route registration.
3507    *    <li>{@code children} &mdash; child sub-resources are tied to the host's URL namespace, not the mixin's.
3508    * </ul>
3509    *
3510    * <p>
3511    * The host's {@link RestContext} reads {@code path}/{@code paths} from its own annotation chain only (via
3512    * {@link #getRestAnnotations()} rather than {@link #getRestAnnotationsForProperty(String)}); this allowlist
3513    * preserves that invariant when a mixin sub-context walks annotations for these properties.
3514    */
3515   private static final Set<String> HOST_ONLY_PROPERTIES = Set.of(
3516      "path", "paths", "mixins", "children"
3517   );
3518
3519   /**
3520    * The list-shaped {@code @Rest} contribution properties that {@link Mixin#mergeIntoHost() @Mixin(mergeIntoHost=true)}
3521    * folds from an adopted mixin's own {@code @Rest} chain into the <b>host</b> resource's corresponding chain.
3522    *
3523    * <p>
3524    * Mirrors the "List-shaped" override set documented on {@link Mixin}: these are append-semantics properties, so a
3525    * mixin's contributions can be safely concatenated after the host's own chain (with the individual list builders'
3526    * same-class de-duplication).  Replace-shaped properties (e.g. {@code restDebugFormatter}, {@code partSerializer}) and the
3527    * {@link #HOST_ONLY_PROPERTIES host-only} properties are deliberately excluded &mdash; merging them would be a
3528    * conflict-resolution / namespace concern, not an append, and is out of scope for this opt-in directive.
3529    */
3530   private static final Set<String> MERGEABLE_LIST_PROPERTIES = Set.of(
3531      "serializers", "parsers", "encoders", "converters", "guards",
3532      "responseProcessors", "restOpArgs", "defaultRequestHeaders",
3533      "defaultResponseHeaders", "defaultRequestAttributes", "produces", "consumes"
3534   );
3535
3536   /**
3537    * Returns the {@link Rest} annotations on the resource class hierarchy for the specified property,
3538    * in <b>parent-to-child</b> order, with {@code noInherit} cutoff applied.
3539    *
3540    * <p>
3541    * Used by both this class and {@link RestOpContext} to walk the class-level annotation chain when
3542    * computing memoized op-level settings that inherit from class-level {@code @Rest(...)} attributes.
3543    *
3544    * <p>
3545    * When this context is a {@linkplain #isMixinContext() mixin sub-context}, the parent context's annotation
3546    * chain is prepended to the mixin's own &mdash; serializers, parsers, encoders, converters, response
3547    * processors, guards, restDebugFormatter, messages, and other contribution lists inherit from the
3548    * host first, with the mixin's contributions appended.  The local {@code @Rest(noInherit)} on the mixin
3549    * cuts off the parent walk for any specific property; the {@link #HOST_ONLY_PROPERTIES} allowlist
3550    * unconditionally skips the parent walk for properties whose semantics are host-only (mount paths, the
3551    * mixin discovery chain, and child sub-resources).
3552    *
3553    * @param name The annotation property name (e.g. {@code "converters"}, {@code "guards"}).
3554    * @return A stream of {@link AnnotationInfo} entries in parent-to-child order, never {@code null}.
3555    */
3556   Stream<AnnotationInfo<Rest>> getRestAnnotationsForProperty(String name) {
3557      var localAnnotations = getRestAnnotations();
3558      List<AnnotationInfo<Rest>> annotations;
3559      if (isMixinContextField() && parentContext != null && !HOST_ONLY_PROPERTIES.contains(name) && !noInherit.get().contains(name)) {
3560         var combined = new ArrayList<AnnotationInfo<Rest>>(localAnnotations.size() + parentContext.getRestAnnotations().size());
3561         // Local (child-to-parent) annotations first; then parent's (child-to-parent).
3562         // Since the final stream is reversed by rstream(), the combined order becomes:
3563         //   parent's parent-to-child, then mixin's parent-to-child — i.e. host annotations come first, then mixin.
3564         combined.addAll(localAnnotations);
3565         combined.addAll(parentContext.getRestAnnotations());
3566         annotations = combined;
3567      } else {
3568         annotations = localAnnotations;
3569      }
3570      var cutoff = annotations.size();
3571      for (var i = 0; i < annotations.size(); i++) {
3572         if (resolveCdl(annotations.get(i).getStringArray("noInherit")).anyMatch(name::equalsIgnoreCase)) {
3573            cutoff = i + 1;
3574            break;
3575         }
3576      }
3577      var resolved = annotations.subList(0, cutoff);
3578      // Mixin override injection: for a mixin sub-context carrying host @Mixin overrides, the
3579      // synthetic override annotation is the most-derived contribution.  `resolved` is in child-to-parent order
3580      // (it is reversed to parent-to-child by rstream below), so prepending here places the override LAST in the
3581      // emitted stream — list-shaped props append it after the inherited host+mixin chain, replace-shaped props
3582      // take it as the final (winning) value.  It is added after the noInherit cutoff scan so it is never itself
3583      // cut, and HOST_ONLY_PROPERTIES are excluded (path/paths/mixins/children are not @Mixin override slots).
3584      var override = HOST_ONLY_PROPERTIES.contains(name) ? null : mixinOverrideAnnotation.get();
3585      Stream<AnnotationInfo<Rest>> hostStream;
3586      if (override == null) {
3587         hostStream = rstream(resolved);
3588      } else {
3589         var withOverride = new ArrayList<AnnotationInfo<Rest>>(resolved.size() + 1);
3590         withOverride.add(override);
3591         withOverride.addAll(resolved);
3592         hostStream = rstream(withOverride);
3593      }
3594      // Opt-in @Mixin(mergeIntoHost=true) directive: for a host context and a list-shaped property, append the
3595      // adopted mixin(s)' own @Rest contributions AFTER the host's chain (parent-to-child), so the host's own
3596      // endpoints pick up the mixin's list-shaped attributes.  Default behavior (no opted-in mixin) is unchanged.
3597      if (! isMixinContextField()) {
3598         if (MERGEABLE_LIST_PROPERTIES.contains(name)) {
3599            var merged = mergeIntoHostMixinAnnotations.get();
3600            if (! merged.isEmpty())
3601               hostStream = Stream.concat(hostStream, merged.stream());
3602         }
3603         // Mixin-declared @Rest(mergeResponseProcessorsIntoHost=true) opt-in: fold the opted-in mixin's OWN response
3604         // processors into the host's chain — response-processor-scoped only (never other list-shaped attributes).
3605         if (eq(name, "responseProcessors")) {
3606            var mergedRp = mergeResponseProcessorsIntoHostMixinAnnotations.get();
3607            if (! mergedRp.isEmpty())
3608               hostStream = Stream.concat(hostStream, mergedRp.stream());
3609         }
3610      }
3611      return hostStream;
3612   }
3613
3614   /**
3615    * The {@code @Rest} annotation chains (parent-to-child, framework {@code DefaultConfig} entries excluded) of any
3616    * mixin the host opted into merging via {@link Mixin#mergeIntoHost() @Mixin(mergeIntoHost=true)}, appended by
3617    * {@link #getRestAnnotationsForProperty(String)} for each {@link #MERGEABLE_LIST_PROPERTIES mergeable} list-shaped
3618    * property so the mixin's list-shaped {@code @Rest} attributes fold into the host's own chains.
3619    *
3620    * <p>
3621    * Empty for mixin sub-contexts and for hosts with no opted-in mixins &mdash; keeping the default (drop) behavior
3622    * for every existing resource.  Built once at memoizer-init time (zero per-request cost).
3623    */
3624   private final Memoizer<List<AnnotationInfo<Rest>>> mergeIntoHostMixinAnnotations = memoizer(() -> {
3625      if (isMixinContextField())
3626         return List.of();
3627      var out = new ArrayList<AnnotationInfo<Rest>>();
3628      for (var rm : getResolvedMixins()) {
3629         if (! rm.overrides().mergeIntoHost() || rm.type() == resourceClass())
3630            continue;
3631         // Fold in the mixin class's OWN @Rest chain (parent-to-child), excluding the framework DefaultConfig
3632         // entries — those are already contributed by the host's own chain, so re-adding them would double-count.
3633         rstream(getAnnotationProvider().find(Rest.class, ClassInfo.of(rm.type())))
3634            .filter(ai -> ! (ai.getAnnotatable() instanceof ClassInfo ci && DefaultConfig.class.equals(ci.inner())))
3635            .forEach(out::add);
3636      }
3637      return u(out);
3638   });
3639
3640   /**
3641    * The OWN {@code @Rest} annotation chains (parent-to-child, framework {@code DefaultConfig} entries excluded) of any
3642    * mixin that opts into folding its response processors into the host via
3643    * {@link Rest#mergeResponseProcessorsIntoHost() @Rest(mergeResponseProcessorsIntoHost=true)} on its own class,
3644    * appended by {@link #getRestAnnotationsForProperty(String)} for the {@code responseProcessors} property only so the
3645    * mixin's {@code responseProcessors} fold into the host's own chain under a plain {@link Rest#mixins() mixins=}
3646    * reference.
3647    *
3648    * <p>
3649    * This is the mixin-declared, response-processor-scoped counterpart to the host-declared
3650    * {@link Mixin#mergeIntoHost() @Mixin(mergeIntoHost=true)} directive handled by
3651    * {@link #mergeIntoHostMixinAnnotations}: it folds <b>only</b> {@code responseProcessors}, never other list-shaped
3652    * attributes.  Empty for mixin sub-contexts and for hosts with no opted-in mixins &mdash; keeping the default (drop)
3653    * behavior for every mixin that does not declare the opt-in.  Built once at memoizer-init time (zero per-request
3654    * cost).
3655    */
3656   private final Memoizer<List<AnnotationInfo<Rest>>> mergeResponseProcessorsIntoHostMixinAnnotations = memoizer(() -> {
3657      if (isMixinContextField())
3658         return List.of();
3659      var out = new ArrayList<AnnotationInfo<Rest>>();
3660      for (var rm : getResolvedMixins()) {
3661         if (rm.type() == resourceClass())
3662            continue;
3663         // Fold in the mixin class's OWN @Rest chain (parent-to-child), excluding the framework DefaultConfig
3664         // entries, but only when the mixin's own @Rest declares the mergeResponseProcessorsIntoHost opt-in.
3665         var mixinRest = rstream(getAnnotationProvider().find(Rest.class, ClassInfo.of(rm.type())))
3666            .filter(ai -> ! (ai.getAnnotatable() instanceof ClassInfo ci && DefaultConfig.class.equals(ci.inner())))
3667            .toList();
3668         if (mixinRest.stream().anyMatch(ai -> ai.inner().mergeResponseProcessorsIntoHost()))
3669            out.addAll(mixinRest);
3670      }
3671      return u(out);
3672   });
3673
3674   /**
3675    * For a {@linkplain #isMixinContext() mixin sub-context}, returns the <b>host</b> resource class's
3676    * class-level annotation infos (host class chain, in parent-to-child order) so a mixin operation can
3677    * inherit the host's class-level {@link ContextApply @ContextApply} config
3678    * (e.g. {@link HtmlDocConfig @HtmlDocConfig},
3679    * {@link SerializerConfig @SerializerConfig}).
3680    *
3681    * <p>
3682    * Used by {@link RestOpContext.Builder} to prepend the host's class-level config annotations <i>ahead of</i>
3683    * the mixin class's own class annotations in the op's annotation work-list, so the effective precedence is
3684    * method &gt; mixin-class &gt; host-class.  This is the page-decoration counterpart of the context-level
3685    * inheritance walk in {@link #getRestAnnotationsForProperty(String)}: that walk inherits {@code @Rest}
3686    * properties (serializers, parsers, guards, ...) from the host, while this method inherits standalone
3687    * class-level config annotations that are not {@code @Rest} attributes.
3688    *
3689    * <p>
3690    * Inheritance is automatic for every mixin sub-context.  A mixin can opt out of inheriting a specific host
3691    * config annotation by naming its annotation type in {@link Rest#noInherit() @Rest(noInherit)} on the mixin
3692    * class (e.g. {@code @Rest(noInherit={"HtmlDocConfig"})}), reusing the same {@code noInherit} resolution that
3693    * gates the context-level walk so the opt-out is uniform.  For non-mixin contexts (top-level resources and
3694    * child resources) this returns an empty stream &mdash; only mixin ops inherit from a composition host.
3695    *
3696    * @param ap The annotation provider to resolve the host class chain with.
3697    * @return The host class chain's annotation infos in parent-to-child order, or an empty stream when this is
3698    *    not a mixin sub-context (or has no parent).
3699    */
3700   Stream<AnnotationInfo<?>> getInheritedHostClassAnnotations(AnnotationProvider ap) {
3701      if (! isMixinContextField() || parentContext == null)
3702         return Stream.empty();
3703      var blocked = noInherit.get();
3704      return rstream(ap.find(ClassInfo.of(parentContext.getResourceClass()), SELF, PARENTS))
3705         .filter(ai -> ! blocked.contains(ai.annotationType().getSimpleName()));
3706   }
3707
3708   /**
3709    * Returns all {@link Rest} annotations on the resource class hierarchy, in child-to-parent order.
3710    *
3711    * @return An unmodifiable list of {@link AnnotationInfo} for {@link Rest}, never {@code null}.
3712    */
3713   protected List<AnnotationInfo<Rest>> getRestAnnotations() {
3714      return restAnnotations.get();
3715   }
3716
3717   /**
3718    * Returns the nearest {@link Rest} annotation on this resource.
3719    *
3720    * @return An {@link Optional} containing the first (most-derived) {@link Rest} {@link AnnotationInfo}.
3721    */
3722   protected Optional<AnnotationInfo<Rest>> getRestAnnotation() {
3723      return getRestAnnotations().stream().findFirst();
3724   }
3725
3726   /**
3727    * Returns the {@link Rest} annotations for this resource in parent-to-child (top-down) order.
3728    *
3729    * <p>
3730    * This is the reverse of {@link #getRestAnnotations()}: most-ancestor annotation first,
3731    * most-derived last. Use this when annotation values should accumulate in inheritance order
3732    * (e.g. parent values are applied first and child values append or override them).
3733    *
3734    * @return An unmodifiable list of {@link AnnotationInfo} for {@link Rest}, never {@code null}.
3735    */
3736   protected List<AnnotationInfo<Rest>> getRestAnnotationsTopDown() {
3737      return restAnnotationsTopDown.get();
3738   }
3739
3740   /**
3741    * Returns {@code true} if values for the given annotation attribute may be inherited from {@link #parentContext}.
3742    *
3743    * <p>
3744    * Inheritance is blocked when the nearest {@code @Rest(noInherit)} lists the property name (case-insensitive).
3745    *
3746    * @param property The annotation attribute name (e.g. {@code "allowedSerializerOptions"}).
3747    * @return {@code true} if parent values should be included.
3748    */
3749   protected boolean isInherited(String property) {
3750      return parentContext != null && !noInherit.get().contains(property);
3751   }
3752
3753   /**
3754    * Returns {@code true} if the local {@code @Rest(noInherit=...)} list contains {@code property} as a literal token.
3755    *
3756    * <p>
3757    * Unlike the {@link #noInherit} memoizer this performs a raw, SVL-free, comma-split check on the local
3758    * {@code @Rest} annotation. It exists for callers that are themselves on the dependency chain of the
3759    * {@code varResolver} memoizer (e.g. the {@code messages} memoizer) — those callers can't reach the
3760    * regular {@link #noInherit} memoizer without inducing a cycle, because the regular path runs
3761    * {@code resolveCdl(...)} → {@link #getVarResolver()} → {@link #getMessages()} → back to messages.
3762    *
3763    * @param property The property name (e.g. {@code "messages"}). Case-insensitive comparison.
3764    * @return {@code true} if {@code property} is named as a literal token in the local {@code @Rest(noInherit=...)}.
3765    */
3766   private boolean isNoInheritLiteral(String property) {
3767      var fromRest = getRestAnnotation()
3768         .map(x -> x.getStringArray("noInherit").orElse(StringUtils.EMPTY_STRING_ARRAY))
3769         .stream()
3770         .flatMap(Arrays::stream)
3771         .filter(Objects::nonNull)
3772         .flatMap(s -> StringUtils.split(s, ',').stream())
3773         .map(String::trim)
3774         .filter(StringUtils::isNotBlank)
3775         .anyMatch(property::equalsIgnoreCase);
3776      if (fromRest)
3777         return true;
3778      // Also honor a host @Mixin(noInherit=...) token (raw / SVL-free, same as the @Rest path above) so the
3779      // messages memoizer's cutoff check sees both noInherit sources without inducing the resolver cycle.
3780      if (resolvedMixin != null) {
3781         for (var s : resolvedMixin.overrides().noInherit())
3782            for (var t : StringUtils.split(s, ','))
3783               if (eqic(property, t.trim()))
3784                  return true;
3785      }
3786      return false;
3787   }
3788
3789   /**
3790    * Resolves comma-delimited annotation values with SVL variable substitution.
3791    *
3792    * @param values Raw annotation attribute values.
3793    * @return A stream of trimmed, non-blank tokens.
3794    */
3795   private Stream<String> resolveCdl(String...values) {
3796      if (values == null || values.length == 0)
3797         return Stream.empty();
3798      return Arrays.stream(values)
3799         .filter(Objects::nonNull)
3800         .map(this::resolve)
3801         .map(StringUtils::split)
3802         .flatMap(Collection::stream)
3803         .map(String::trim)
3804         .filter(StringUtils::isNotBlank);
3805   }
3806
3807   private Stream<String> resolveCdl(Optional<String[]> values) {
3808      return values.isEmpty() ? Stream.empty() : resolveCdl(values.get());
3809   }
3810
3811   /**
3812    * Resolves SVL variables in the given string.
3813    *
3814    * @param s The raw string. Can be {@code null}.
3815    * @return The resolved string.
3816    */
3817   protected String resolve(String s) {
3818      return getVarResolver().resolve(s);
3819   }
3820
3821   /**
3822    * Returns the parser session-option keys allowed for this resource.
3823    *
3824    * @return An unmodifiable case-insensitive sorted set, never {@code null}.
3825    */
3826   public SortedSet<String> getAllowedParserOptions() {
3827      return allowedParserOptions.get();
3828   }
3829
3830   /**
3831    * Returns the serializer session-option keys allowed for this resource.
3832    *
3833    * @return An unmodifiable case-insensitive sorted set, never {@code null}.
3834    */
3835   public SortedSet<String> getAllowedSerializerOptions() {
3836      return allowedSerializerOptions.get();
3837   }
3838
3839   /**
3840    * Called during servlet destruction to invoke all {@link RestDestroy} methods.
3841    *
3842    * <p>
3843    * Fires this context's own {@code @RestDestroy} methods first, then walks any mixin sub-contexts
3844    * (host destroys before each mixin's), then any {@code @Rest(children=...)} sub-resources, then closes
3845    * the bean store. Mixin sub-contexts recursively destroy themselves via the same path; flat-inheritance
3846    * guarantees no further mixin descent occurs from inside a mixin sub-context.
3847    */
3848   public void destroy() {
3849      for (var x : destroyInvokerPair.get().invokers) {
3850         try {
3851            x.invoke(beanStore, getResource());
3852         } catch (Exception e) {
3853            getLogger().log(Level.WARNING, unwrap(e), () -> f("Error occurred invoking servlet-destroy method '%s'.", x.getFullName()));
3854         }
3855      }
3856      if (!isMixinContext) {
3857         for (var mctx : mixinContexts.get().values()) {
3858            try {
3859               mctx.destroy();
3860            } catch (Exception e) {
3861               getLogger().log(Level.WARNING, unwrap(e), () -> f("Error occurred destroying mixin sub-context '%s'.", mctx.getResourceClass().getName()));
3862            }
3863         }
3864      }
3865      var childrenRef = getRestChildren();
3866      if (nn(childrenRef))
3867         childrenRef.destroy();
3868      try {
3869         beanStore.close();
3870      } catch (Exception e) {
3871         getLogger().log(Level.WARNING, unwrap(e), () -> "Error occurred closing bean store.");
3872      }
3873   }
3874
3875   /**
3876    * The main service method.
3877    *
3878    * <p>
3879    * Subclasses can optionally override this method if they want to tailor the behavior of requests.
3880    *
3881    * @param resource
3882    *    The REST servlet or bean that this context defines.
3883    *    <br>Note that this bean may not be the same bean used during initialization as it may have been replaced at runtime.
3884    * @param r1 The incoming HTTP servlet request object.
3885    * @param r2 The incoming HTTP servlet response object.
3886    * @throws ServletException General servlet exception.
3887    * @throws IOException Thrown by underlying stream.
3888    */
3889   public void execute(Object resource, HttpServletRequest r1, HttpServletResponse r2) throws ServletException, IOException {
3890
3891      // Must be careful not to bleed thread-locals.
3892      if (nn(localSession.get()))
3893         LOG.warning("WARNING:  Thread-local call object was not cleaned up from previous request.  %s, thread=[%s]", this, Thread.currentThread().getName());
3894
3895      RestSession.Builder sb = createSession().resource(resource).req(r1).res(r2);
3896
3897      try {
3898
3899         if (nn(initException))
3900            throw initException;
3901
3902         // If the resource path contains variables (e.g. @Rest(path="/f/{a}/{b}"), then we want to resolve
3903         // those variables and push the servletPath to include the resolved variables.  The new pathInfo will be
3904         // the remainder after the new servletPath.
3905         // Only do this for the top-level resource because the logic for child resources are processed next.
3906         if (pathMatcher.hasVars() && parentContext == null) {
3907            var sp = sb.req().getServletPath();
3908            var pi = sb.getPathInfoUndecoded();
3909            var upi2 = UrlPath.of(pi == null ? sp : sp + pi);
3910            var uppm = pathMatcher.match(upi2);
3911         if (nn(uppm) && ! uppm.hasEmptyVars()) {
3912            sb.pathVars(uppm.getVars());
3913            var pathInfo = o(validatePathInfo(nie(urlDecode(uppm.getSuffix())))).orElse("\u0000");
3914            var servletPath = validateServletPath(uppm.getPrefix());
3915            sb.req(new HttpServletRequestWrapper(sb.req()) {
3916               @Override
3917               public String getPathInfo() {
3918                  return pathInfo.charAt(0) == (char)0 ? null : pathInfo;
3919               }
3920               @Override
3921               public String getServletPath() {
3922                  return servletPath;
3923               }
3924            });
3925         } else {
3926               var call = sb.build();
3927               installCaptureIfNeeded(call);
3928               call.status(SC_NOT_FOUND).finish();
3929               return;
3930            }
3931         }
3932
3933         // If this resource has child resources, try to recursively call them.
3934         var childMatch = getRestChildren().findMatch(sb);
3935         if (childMatch.isPresent()) {
3936            var uppm = childMatch.get().getPathMatch();
3937            var rc = childMatch.get().getChildContext();
3938            if (! uppm.hasEmptyVars()) {
3939               sb.pathVars(uppm.getVars());
3940               var pathInfo = o(validatePathInfo(nie(urlDecode(uppm.getSuffix())))).orElse("\u0000");
3941               var servletPath = validateServletPath(sb.req().getServletPath() + uppm.getPrefix());
3942               var childRequest = new HttpServletRequestWrapper(sb.req()) {
3943                  @Override
3944                  public String getPathInfo() {
3945                     return pathInfo.charAt(0) == (char)0 ? null : pathInfo;
3946                  }
3947                  @Override
3948                  public String getServletPath() {
3949                     return servletPath;
3950                  }
3951               };
3952               rc.execute(rc.getResource(), childRequest, sb.res());
3953            } else {
3954               var call = sb.build();
3955               installCaptureIfNeeded(call);
3956               call.status(SC_NOT_FOUND).finish();
3957            }
3958            return;
3959         }
3960
3961      } catch (Exception e) {
3962         // This throwaway error session opens a requestId LogContext scope in its constructor but never reaches
3963         // finish(); close it here so the (possibly pooled) request thread does not leak the scope. The subsequent
3964         // build() below re-resolves to the same id via the honor-existing-attribute rung.
3965         var errorSession = sb.build();
3966         try {
3967            handleError(errorSession, convertThrowable(e));
3968         } finally {
3969            errorSession.closeRequestIdScope();
3970         }
3971      }
3972
3973      var s = sb.build();
3974
3975      try {
3976         localSession.set(s);
3977         installCaptureIfNeeded(s);
3978         startCall(s);
3979         s.run();
3980      } catch (Exception e) {
3981         handleError(s, convertThrowable(e));
3982      } finally {
3983         try {
3984            s.finish();
3985            endCall(s);
3986            // For mixin endpoints, dual-fire endCall on the mixin sub-context after the host's so host
3987            // hooks fire first, then the mixin's. Skip when no operation was resolved (e.g. 404 paths).
3988            var os = s.getOpSessionOrNull();
3989            if (os != null) {
3990               var opRestContext = os.getContext().getContext();
3991               if (opRestContext.isMixinContext)
3992                  opRestContext.endCall(s);
3993            }
3994         } finally {
3995            localSession.remove();
3996         }
3997      }
3998   }
3999
4000   /**
4001    * Allowed header URL parameters.
4002    *
4003    * <h4 class='section'>See Also:</h4><ul>
4004    *    <li class='ja'>{@link Rest#allowedHeaderParams}
4005    * </ul>
4006    *
4007    * @return
4008    *    The header names allowed to be passed as URL parameters.
4009    *    <br>The set is case-insensitive ordered and unmodifiable.
4010    */
4011   public Set<String> getAllowedHeaderParams() { return allowedHeaderParams.get(); }
4012
4013   /**
4014    * Allowed method headers.
4015    *
4016    * <h4 class='section'>See Also:</h4><ul>
4017    *    <li class='ja'>{@link Rest#allowedMethodHeaders}
4018    * </ul>
4019    *
4020    * @return
4021    *    The method names allowed to be passed as <c>X-Method</c>, <c>X-HTTP-Method-Override</c>, <c>X-HTTP-Method</c> or <c>X-Method-Override</c> headers.
4022    *    <br>The set is case-insensitive ordered and unmodifiable.
4023    */
4024   public Set<String> getAllowedMethodHeaders() { return allowedMethodHeaders.get(); }
4025
4026   /**
4027    * Allowed response headers.
4028    *
4029    * <h4 class='section'>See Also:</h4><ul>
4030    *    <li class='ja'>{@link Rest#allowedResponseHeaders}
4031    * </ul>
4032    *
4033    * @return
4034    *    The header names a client may ask the server to add to the response via <c>x-response-headers</c>.
4035    *    <br>The set is case-insensitive ordered and unmodifiable; empty by default.
4036    */
4037   public Set<String> getAllowedResponseHeaders() { return allowedResponseHeaders.get(); }
4038
4039   /**
4040    * Allowed method URL parameters.
4041    *
4042    * <h4 class='section'>See Also:</h4><ul>
4043    *    <li class='ja'>{@link Rest#allowedMethodParams}
4044    * </ul>
4045    *
4046    * @return
4047    *    The method names allowed to be passed as <c>method</c> URL parameters.
4048    *    <br>The set is case-insensitive ordered and unmodifiable.
4049    */
4050   public Set<String> getAllowedMethodParams() { return allowedMethodParams.get(); }
4051
4052   /**
4053    * Returns the annotations applied to this context.
4054    *
4055    * @return The annotations applied to this context.
4056    */
4057   public AnnotationWorkList getAnnotations() { return annotationWork; }
4058
4059   /**
4060    * Returns the marshalling context associated with this context.
4061    *
4062    * @return The marshalling context associated with this context.
4063    */
4064   public MarshallingContext getMarshallingContext() { return beanStore.getBean(MarshallingContext.class).orElse(null); }
4065
4066   MarshallingContext.Builder         getBeanContextBuilder()          { return beanContextBuilder.get(); }
4067   EncoderSet.Builder          getEncodersBuilder()             { return encodersBuilder.get(); }
4068   JsonSchemaGenerator.Builder getJsonSchemaGeneratorBuilder()  { return jsonSchemaGeneratorBuilder.get(); }
4069   ParserSet.Builder           getParsersBuilder()              { return parsersBuilder.get(); }
4070   HttpPartParser.Creator      getPartParserCreator()           { return partParserCreator.get(); }
4071   HttpPartSerializer.Creator  getPartSerializerCreator()       { return partSerializerCreator.get(); }
4072   SerializerSet.Builder       getSerializersBuilder()          { return serializersBuilder.get(); }
4073
4074   /**
4075    * Returns the bean store associated with this context.
4076    *
4077    * <p>
4078    * The bean store is used for instantiating child resource classes.
4079    *
4080    * @return The bean store associated with this context.
4081    */
4082   public WritableBeanStore getBeanStore() { return beanStore; }
4083
4084   /**
4085    * Returns the builder that created this context.
4086    *
4087    * @return The builder that created this context.
4088    */
4089   public ServletConfig getBuilder() { return builder; }
4090
4091   /**
4092    * Returns the debug formatter to use for this resource.
4093    *
4094    * <p>
4095    * Resolution precedence: the resource class itself implementing {@link RestDebugFormatter} &gt; a
4096    * {@link RestDebugFormatter} bean registered in the bean store (or a {@link Bean @Bean}-annotated factory method)
4097    * &gt; {@link BasicRestDebugFormatter}.
4098    *
4099    * <h4 class='section'>See Also:</h4><ul>
4100    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerLoggingAndDebugging">Logging / Debugging</a>
4101    * </ul>
4102    *
4103    * @return
4104    *    The debug formatter to use for this resource.
4105    *    <br>Never <jk>null</jk>.
4106    */
4107   public RestDebugFormatter getRestDebugFormatter() {
4108      if (resource.get() instanceof RestDebugFormatter f)
4109         return f;
4110      return beanStore.getBean(RestDebugFormatter.class).orElse(null);
4111   }
4112
4113   /**
4114    * Returns the effective {@link RequestIdSettings} for this resource's always-on request-id correlation resolver.
4115    *
4116    * <p>
4117    * Resolved once (memoized) via the three-rung precedence: registered bean, {@code @Bean} factory method, then the
4118    * built-in defaults.  Consumed by {@link RestSession} at build time to mint or honor the {@code X-Request-Id}
4119    * correlation id for every request.
4120    *
4121    * @return The effective request-id settings.  Never <jk>null</jk>.
4122    * @since 10.0.0
4123    */
4124   public RequestIdSettings getRequestIdSettings() {
4125      return requestIdSettings.get();
4126   }
4127
4128   /**
4129    * Returns the name of the client version header name used by this resource.
4130    *
4131    * <h4 class='section'>See Also:</h4><ul>
4132    *    <li class='ja'>{@link Rest#clientVersionHeader}
4133    * </ul>
4134    *
4135    * @return
4136    *    The name of the client version header used by this resource.
4137    *    <br>Never <jk>null</jk>.
4138    */
4139   public String getClientVersionHeader() { return clientVersionHeader.get(); }
4140
4141   /**
4142    * Returns the config file associated with this servlet.
4143    *
4144    * <p>
4145    * The config file is identified via {@link Rest#config()}.
4146    *
4147    * @return
4148    *    The resolving config file associated with this servlet.
4149    *    <br>Never <jk>null</jk>.
4150    */
4151   public Config getConfig() { return beanStore.getBean(Config.class).orElse(null); }
4152
4153   /**
4154    * Returns the explicit list of supported content types for this resource.
4155    *
4156    * <p>
4157    * Consists of the media types for consumption common to all operations on this class.
4158    *
4159    * <p>
4160    * Derived from {@link Rest#consumes()} across the resource annotation chain.
4161    *
4162    * @return
4163    *    An unmodifiable list of supported <c>Content-Type</c> header values for this resource.
4164    *    <br>Never <jk>null</jk>.
4165    */
4166   public List<MediaType> getConsumes() { return consumes.get(); }
4167
4168   /**
4169    * Returns the default request attributes for this resource.
4170    *
4171    * <h4 class='section'>See Also:</h4><ul>
4172    *    <li class='ja'>{@link Rest#defaultRequestAttributes()}
4173    * </ul>
4174    *
4175    * @return
4176    *    The default request headers for this resource in an unmodifiable list.
4177    *    <br>Never <jk>null</jk>.
4178    */
4179   public NamedAttributeMap getDefaultRequestAttributes() { return beanStore.getBean(NamedAttributeMap.class, "defaultRequestAttributes").orElse(null); }
4180
4181   /**
4182    * Returns the default request headers for this resource.
4183    *
4184    * <h4 class='section'>See Also:</h4><ul>
4185    *    <li class='ja'>{@link Rest#defaultRequestHeaders()}
4186    * </ul>
4187    *
4188    * @return
4189    *    The default request headers for this resource in an unmodifiable list.
4190    *    <br>Never <jk>null</jk>.
4191    */
4192   public HttpHeaderList getDefaultRequestHeaders() { return beanStore.getBean(HttpHeaderList.class, "defaultRequestHeaders").orElse(null); }
4193
4194   /**
4195    * Returns the default response headers for this resource.
4196    *
4197    * <h4 class='section'>See Also:</h4><ul>
4198    *    <li class='ja'>{@link Rest#defaultResponseHeaders()}
4199    * </ul>
4200    *
4201    * @return
4202    *    The default response headers for this resource in an unmodifiable list.
4203    *    <br>Never <jk>null</jk>.
4204    */
4205   public HttpHeaderList getDefaultResponseHeaders() { return beanStore.getBean(HttpHeaderList.class, "defaultResponseHeaders").orElse(null); }
4206
4207   /**
4208    * Returns the encoders associated with this context.
4209    *
4210    * @return The encoders associated with this context.
4211    */
4212   public EncoderSet getEncoders() { return beanStore.getBean(EncoderSet.class).orElse(null); }
4213
4214   /**
4215    * Returns the path for this resource as defined by the {@link Rest#path() @Rest(path)} annotation or
4216    * {@link Rest#path()} annotation attribute concatenated with those on all parent classes.
4217    *
4218    * <p>
4219    * If path is not specified, returns <js>""</js>.
4220    *
4221    * <h4 class='section'>See Also:</h4><ul>
4222    *    <li class='ja'>{@link Rest#path()}
4223    * </ul>
4224    *
4225    * @return The full path.
4226    */
4227   public String getFullPath() { return fullPath; }
4228
4229   /**
4230    * Returns the JSON-Schema generator associated with this resource.
4231    *
4232    * @return
4233    *    The HTTP-part serializer associated with this resource.
4234    *    <br>Never <jk>null</jk>.
4235    */
4236   public JsonSchemaGenerator getJsonSchemaGenerator() { return beanStore.getBean(JsonSchemaGenerator.class).orElse(null); }
4237
4238   /**
4239    * Returns the HTTP call for the current request.
4240    *
4241    * @return The HTTP call for the current request, never <jk>null</jk>.
4242    * @throws InternalServerError If no active request exists on the current thread.
4243    */
4244   public RestSession getLocalSession() {
4245      var rc = localSession.get();
4246      if (rc == null)
4247         throw new InternalServerError("No active request on current thread.");
4248      return rc;
4249   }
4250
4251   /**
4252    * Returns the logger associated with this context.
4253    *
4254    * @return
4255    *    The logger for this resource.
4256    *    <br>Never <jk>null</jk>.
4257    */
4258   public RichLogger getLogger() { return beanStore.getBean(RichLogger.class).orElse(null); }
4259
4260   /**
4261    * Returns the resource bundle used by this resource.
4262    *
4263    * @return
4264    *    The resource bundle for this resource.
4265    *    <br>Never <jk>null</jk>.
4266    */
4267   public Messages getMessages() { return beanStore.getBean(Messages.class).orElse(null); }
4268
4269   /**
4270    * Returns the timing statistics on all method executions on this class.
4271    *
4272    * @return The timing statistics on all method executions on this class.
4273    */
4274   public MethodExecStore getMethodExecStore() { return beanStore.getBean(MethodExecStore.class).orElse(null); }
4275
4276   /**
4277    * Returns the parsers associated with this context.
4278    *
4279    * @return The parsers associated with this context.
4280    */
4281   public ParserSet getParsers() { return beanStore.getBean(ParserSet.class).orElse(null); }
4282
4283   /**
4284    * Returns the HTTP-part parser associated with this resource.
4285    *
4286    * @return
4287    *    The HTTP-part parser associated with this resource.
4288    *    <br>Never <jk>null</jk>.
4289    */
4290   public HttpPartParser getPartParser() { return beanStore.getBean(HttpPartParser.class).orElse(null); }
4291
4292   /**
4293    * Returns the HTTP-part serializer associated with this resource.
4294    *
4295    * @return
4296    *    The HTTP-part serializer associated with this resource.
4297    *    <br>Never <jk>null</jk>.
4298    */
4299   public HttpPartSerializer getPartSerializer() { return beanStore.getBean(HttpPartSerializer.class).orElse(null); }
4300
4301   /**
4302    * Returns the path for this resource as defined by the {@link Rest#path() @Rest(path)} annotation or
4303    * {@link Rest#path()} annotation attribute.
4304    *
4305    * <p>
4306    * If path is not specified, returns <js>""</js>.
4307    *
4308    * <h4 class='section'>See Also:</h4><ul>
4309    *    <li class='ja'>{@link Rest#path()}
4310    * </ul>
4311    *
4312    * @return The servlet path.
4313    */
4314   public String getPath() { return path; }
4315
4316   /**
4317    * Returns the resolved top-level mount paths for this resource.
4318    *
4319    * <p>
4320    * Computed once during {@link RestContext} construction by walking the runtime-override resolution chain
4321    * (highest precedence first):
4322    * <ol>
4323    *    <li><b>Programmatic</b> &mdash; {@link Builder#paths(String...)} setter (or {@link Args#paths()} record
4324    *       field). Highest precedence; an empty array (not {@code null}) explicitly clears the mount list.
4325    *    <li><b>Getter</b> &mdash; the resource's {@code getPaths()} virtual method (defined on
4326    *       {@code RestServlet} and {@code RestResource}). {@code null} return inherits; non-{@code null} (including
4327    *       empty array) wins over the annotation default.
4328    *    <li><b>Annotation default</b> &mdash; {@link Rest#paths()}, walked top-down across the resource-class
4329    *       hierarchy with the most-derived non-empty value winning. Each element is
4330    *       <a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerSvlVariables">REST Server SVL Variables</a>-resolved
4331    *       against the bootstrap {@link VarResolver VarResolver}, then comma-split (trim
4332    *       each piece, drop empties).  A single element like {@code "${C:health.paths}"} can therefore expand
4333    *       to multiple mount paths.
4334    * </ol>
4335    *
4336    * <p>
4337    * The resolved array is what hosting runtimes &mdash; Jetty's auto-discovery flow in
4338    * {@code JettyServerComponent}, and Spring Boot's {@code ServletRegistrationBean} wiring &mdash; should
4339    * consume when mounting the resource at the top level.
4340    *
4341    * <h4 class='section'>Notes:</h4><ul>
4342    *    <li class='note'>
4343    *       Returns an empty array (not {@code null}) when none of the rungs resolve. Hosting runtimes interpret
4344    *       an empty array as &quot;no top-level mounts&quot; and surface a clear error naming the resource.
4345    *    <li class='note'>
4346    *       The scalar {@link #getPath()} accessor remains orthogonal to this method.
4347    * </ul>
4348    *
4349    * <h4 class='section'>See Also:</h4><ul>
4350    *    <li class='ja'>{@link Rest#paths()}
4351    * </ul>
4352    *
4353    * @return The resolved mount paths (never {@code null}; possibly empty).
4354    * @since 10.0.0
4355    */
4356   public String[] getPaths() { return cp(paths); }
4357
4358   /**
4359    * Returns the path matcher for this context.
4360    *
4361    * @return The path matcher for this context.
4362    */
4363   public UrlPathMatcher getPathMatcher() { return pathMatcher; }
4364
4365   /**
4366    * Returns the explicit list of supported accept types for this resource.
4367    *
4368    * <p>
4369    * Consists of the media types for production common to all operations on this class.
4370    *
4371    * <p>
4372    * Derived from {@link Rest#produces()} across the resource annotation chain.
4373    *
4374    * @return
4375    *    An unmodifiable list of supported <c>Accept</c> header values for this resource.
4376    *    <br>Never <jk>null</jk>.
4377    */
4378   public List<MediaType> getProduces() { return produces.get(); }
4379
4380   /**
4381    * Returns the resource object.
4382    *
4383    * <p>
4384    * This is the instance of the class annotated with the {@link Rest @Rest} annotation, usually
4385    * an instance of {@link RestServlet}.
4386    *
4387    * @return
4388    *    The resource object.
4389    *    <br>Never <jk>null</jk>.
4390    */
4391   public Object getResource() { return resource.get(); }
4392
4393   /**
4394    * Returns the resource class type.
4395    *
4396    * @return The resource class type.
4397    */
4398   public Class<?> getResourceClass() { return resourceClass; }
4399
4400   /**
4401    * Returns the response processors registered on this resource.
4402    *
4403    * <p>
4404    * Returned in the order they're invoked by {@link #processResponse(RestOpSession)}.
4405    * The returned array is the live backing array — callers must not mutate it.
4406    *
4407    * <h4 class='section'>See Also:</h4><ul>
4408    *    <li class='ja'>{@link Rest#responseProcessors}
4409    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ResponseProcessors">Response Processors</a>
4410    * </ul>
4411    *
4412    * @return
4413    *    The response processors for this resource.
4414    *    <br>Never <jk>null</jk>.
4415    */
4416   public ResponseProcessor[] getResponseProcessors() { return beanStore.getBean(ResponseProcessor[].class).orElse(null); }
4417
4418   /**
4419    * Returns the {@link RestOpArg} classes registered on this resource.
4420    *
4421    * <p>
4422    * Per-op {@link RestOpArg} instances are resolved separately at per-op setup via the bean store
4423    * (see {@link #findRestOperationArgs(Method, BeanStore)}); this getter returns the class list
4424    * that drives that resolution.
4425    *
4426    * <h4 class='section'>See Also:</h4><ul>
4427    *    <li class='ja'>{@link Rest#restOpArgs}
4428    * </ul>
4429    *
4430    * @return
4431    *    The REST-op-arg classes for this resource.
4432    *    <br>Never <jk>null</jk>.
4433    */
4434   public Class<? extends RestOpArg>[] getRestOpArgs() { return cp(restOpArgs.get()); }
4435
4436   /**
4437    * Returns the child resources associated with this servlet.
4438    *
4439    * @return
4440    *    An unmodifiable map of child resources.
4441    *    Keys are the {@link Rest#path() @Rest(path)} annotation defined on the child resource.
4442    */
4443   public RestChildren getRestChildren() { return beanStore.getBean(RestChildren.class).orElse(null); }
4444
4445   /**
4446    * Returns the REST Java methods defined in this resource.
4447    *
4448    * <p>
4449    * These are the methods annotated with the {@link RestOp @RestOp} annotation.
4450    *
4451    * @return
4452    *    An unmodifiable map of Java method names to call method objects.
4453    */
4454   public RestOperations getRestOperations() { return beanStore.getBean(RestOperations.class).orElse(null); }
4455
4456   /**
4457    * Returns the bootstrap bean store for this context.
4458    *
4459    * <p>
4460    * This is the bean store inherited from the parent resource and does not include
4461    * any beans added by this class.  For a {@link Rest#children() @Rest(children)} sub-resource, this is the
4462    * parent's {@link #getInheritableBeanStore() inheritable bean store}.
4463    *
4464    * @return The bootstrap bean store for this context.
4465    */
4466   public WritableBeanStore getBootstrapBeanStore() { return bootstrapBeanStore; }
4467
4468   /**
4469    * Returns the bean store that this resource exposes to its {@link Rest#children() @Rest(children)} sub-resources.
4470    *
4471    * <p>
4472    * This store layers this resource's own {@link Bean @Bean} method results and non-<jk>null</jk>
4473    * {@link Bean @Bean} field values on top of the {@link #getBootstrapBeanStore() bootstrap bean store}, and is
4474    * used as the bootstrap bean store of every child.  Since each child's inheritable store sits on top of its
4475    * parent's, a grandchild sees the beans of its parent, its grandparent, and so on up to the root (including
4476    * any Spring context bridged in at the root by {@code SpringRestServlet}).
4477    *
4478    * <p>
4479    * Precedence and isolation:
4480    * <ul>
4481    *    <li>A child's own {@code @Bean} of the same type and name wins over the inherited one.
4482    *    <li>Framework-managed types (serializers, parsers, {@link MethodExecStore}, {@link RestChildren}, ...) are
4483    *       <i>not</i> exported; each child builds its own from its own {@code @Rest} configuration.
4484    *    <li>Beans flow down only: a child's beans are never visible to its parent or its siblings.
4485    * </ul>
4486    *
4487    * <h4 class='section'>Example:</h4>
4488    * <p class='bjava'>
4489    *    <ja>@Rest</ja>(children={PetResource.<jk>class</jk>, OrderResource.<jk>class</jk>})
4490    *    <jk>public class</jk> RootResources <jk>extends</jk> BasicRestServletGroup {
4491    *
4492    *       <jc>// One store shared by every child resource.</jc>
4493    *       <ja>@Bean</ja>
4494    *       <jk>public</jk> PetStore petStore() {
4495    *          <jk>return new</jk> PetStore();
4496    *       }
4497    *    }
4498    *
4499    *    <ja>@Rest</ja>(path=<js>"/pets"</js>)
4500    *    <jk>public class</jk> PetResource <jk>extends</jk> BasicRestResource {
4501    *
4502    *       <ja>@Inject</ja> PetStore <jf>store</jf>;  <jc>// Resolved from the group's @Bean method.</jc>
4503    *
4504    *       <ja>@RestGet</ja>(<js>"/"</js>)
4505    *       <jk>public</jk> Collection&lt;Pet&gt; getPets() {
4506    *          <jk>return</jk> <jf>store</jf>.getPets();
4507    *       }
4508    *    }
4509    * </p>
4510    *
4511    * @return The bean store exposed to child resources.
4512    * @since 10.0.0
4513    */
4514   public WritableBeanStore getInheritableBeanStore() { return inheritableBeanStore; }
4515
4516   /**
4517    * Returns the serializers associated with this context.
4518    *
4519    * @return The serializers associated with this context.
4520    */
4521   public SerializerSet getSerializers() { return beanStore.getBean(SerializerSet.class).orElse(null); }
4522
4523   /**
4524    * Returns the servlet init parameter returned by {@link ServletConfig#getInitParameter(String)}.
4525    *
4526    * @param name The init parameter name.
4527    * @return The servlet init parameter, or <jk>null</jk> if not found.
4528    */
4529   public String getServletInitParameter(String name) {
4530      return builder.getInitParameter(name);
4531   }
4532
4533   /**
4534    * Returns the static files associated with this context.
4535    *
4536    * @return
4537    *    The static files for this resource.
4538    *    <br>Never <jk>null</jk>.
4539    */
4540   public StaticFiles getStaticFiles() { return beanStore.getBean(StaticFiles.class).orElse(null); }
4541
4542   /**
4543    * Gives access to the internal statistics on this context.
4544    *
4545    * @return The context statistics.
4546    */
4547   public RestContextStats getStats() { return new RestContextStats(startTime, getMethodExecStore().getStatsByTotalTime()); }
4548
4549   /**
4550    * Returns the swagger for the REST resource.
4551    *
4552    * @param locale The locale of the swagger to return.  Must not be <jk>null</jk>.
4553    * @return The swagger as an {@link Optional}.  Never <jk>null</jk>.
4554    */
4555   public Optional<Swagger> getSwagger(Locale locale) {
4556      Swagger s = swaggerCache.get(locale);
4557      if (s == null) {
4558         try {
4559            var provider = getSwaggerProvider();
4560            if (provider == null)
4561               return oe();
4562            s = provider.getSwagger(this, locale);
4563            if (nn(s))
4564               swaggerCache.put(locale, s);
4565         } catch (Exception e) {
4566            throw new InternalServerError(e);
4567         }
4568      }
4569      return o(s);
4570   }
4571
4572   /**
4573    * Returns the Swagger provider used by this resource.
4574    *
4575    * <h4 class='section'>See Also:</h4><ul>
4576    *    <li class='ja'>{@link Rest#swaggerProvider()}
4577    * </ul>
4578    *
4579    * @return
4580    *    The information provider for this resource.
4581    *    <br>May be <jk>null</jk>.
4582    */
4583   public SwaggerProvider getSwaggerProvider() { return beanStore.getBean(SwaggerProvider.class).orElse(null); }
4584
4585   /**
4586    * Returns the OpenAPI 3.1 document for the REST resource.
4587    *
4588    * @param locale The locale of the document to return.  Must not be <jk>null</jk>.
4589    * @return The OpenAPI document as an {@link Optional}.  Never <jk>null</jk>.
4590    */
4591   public Optional<OpenApi> getOpenApi(Locale locale) {
4592      OpenApi o = openApiCache.get(locale);
4593      if (o == null) {
4594         try {
4595            var provider = getOpenApiProvider();
4596            if (provider == null)
4597               return oe();
4598            o = provider.getOpenApi(this, locale);
4599            if (nn(o))
4600               openApiCache.put(locale, o);
4601         } catch (Exception e) {
4602            throw new InternalServerError(e);
4603         }
4604      }
4605      return o(o);
4606   }
4607
4608   /**
4609    * Returns the OpenAPI 3.1 provider used by this resource.
4610    *
4611    * <h4 class='section'>See Also:</h4><ul>
4612    *    <li class='ja'>{@link Rest#openApiProvider()}
4613    * </ul>
4614    *
4615    * @return
4616    *    The OpenAPI 3.1 provider for this resource.
4617    *    <br>May be <jk>null</jk>.
4618    */
4619   public OpenApiProvider getOpenApiProvider() { return beanStore.getBean(OpenApiProvider.class).orElse(null); }
4620
4621   /**
4622    * Returns the stack trace database associated with this context.
4623    *
4624    * @return
4625    *    The stack trace database for this resource.
4626    *    <br>Never <jk>null</jk>.
4627    */
4628   public ThrownStore getThrownStore() { return beanStore.getBean(ThrownStore.class).orElse(null); }
4629
4630   /**
4631    * Returns the authority path of the resource.
4632    *
4633    * <h4 class='section'>See Also:</h4><ul>
4634    *    <li class='ja'>{@link Rest#uriAuthority()}
4635    * </ul>
4636    *
4637    * @return
4638    *    The authority path of this resource.
4639    *    <br>If not specified, returns the context path of the ascendant resource.
4640    */
4641   public String getUriAuthority() {
4642      return uriAuthority.get();
4643   }
4644
4645   /**
4646    * Returns the context path of the resource.
4647    *
4648    * <h4 class='section'>See Also:</h4><ul>
4649    *    <li class='ja'>{@link Rest#uriContext()}
4650    * </ul>
4651    *
4652    * @return
4653    *    The context path of this resource.
4654    *    <br>If not specified, returns the context path of the ascendant resource.
4655    */
4656   public String getUriContext() {
4657      return uriContext.get();
4658   }
4659
4660   /**
4661    * Returns the setting on how relative URIs should be interpreted as relative to.
4662    *
4663    * <h4 class='section'>See Also:</h4><ul>
4664    *    <li class='ja'>{@link Rest#uriRelativity()}
4665    * </ul>
4666    *
4667    * @return
4668    *    The URI-resolution relativity setting value.
4669    *    <br>Never <jk>null</jk>.
4670    */
4671   public UriRelativity getUriRelativity() { return uriRelativity.get(); }
4672
4673   /**
4674    * Returns the setting on how relative URIs should be resolved.
4675    *
4676    * <h4 class='section'>See Also:</h4><ul>
4677    *    <li class='ja'>{@link Rest#uriResolution()}
4678    * </ul>
4679    *
4680    * @return
4681    *    The URI-resolution setting value.
4682    *    <br>Never <jk>null</jk>.
4683    */
4684   public UriResolution getUriResolution() { return uriResolution.get(); }
4685
4686   /**
4687    * Returns the variable resolver for this servlet.
4688    *
4689    * <p>
4690    * Variable resolvers are used to replace variables in property values.
4691    * They can be nested arbitrarily deep.
4692    * They can also return values that themselves contain other variables.
4693    *
4694    * <h4 class='figure'>Example:</h4>
4695    * <p class='bjava'>
4696    *    <ja>@Rest</ja>(
4697    *       messages=<js>"nls/Messages"</js>,
4698    *       properties={
4699    *          <ja>@Property</ja>(name=<js>"title"</js>,value=<js>"${L:title}"</js>),  <jc>// Localized variable in Messages.properties</jc>
4700    *          <ja>@Property</ja>(name=<js>"javaVendor"</js>,value=<js>"${S:java.vendor:Oracle}"</js>),  <jc>// System property with default value</jc>
4701    *          <ja>@Property</ja>(name=<js>"foo"</js>,value=<js>"bar"</js>),
4702    *          <ja>@Property</ja>(name=<js>"bar"</js>,value=<js>"baz"</js>),
4703    *          <ja>@Property</ja>(name=<js>"v1"</js>,value=<js>"${R:foo}"</js>),  <jc>// Request variable.  value="bar"</jc>
4704    *          <ja>@Property</ja>(name=<js>"v1"</js>,value=<js>"${R:foo:bar}"</js>),  <jc>// Request variable.  value="bar"</jc>
4705    *       }
4706    *    )
4707    *    <jk>public class</jk> MyRestResource <jk>extends</jk> BasicRestServlet {
4708    * </p>
4709    *
4710    * <p>
4711    * A typical usage pattern involves using variables inside the {@link HtmlDocConfig @HtmlDocConfig} annotation:
4712    * <p class='bjava'>
4713    *    <ja>@RestGet</ja>(<js>"/{name}/*"</js>)
4714    *    <ja>@HtmlDocConfig</ja>(
4715    *       navlinks={
4716    *          <js>"up: ${R:requestParentURI}"</js>,
4717    *          <js>"api: servlet:/api"</js>,
4718    *          <js>"stats: servlet:/stats"</js>,
4719    *          <js>"editLevel: servlet:/editLevel?logger=${A:attribute.name: OFF}"</js>
4720    *       }
4721    *       header={
4722    *          <js>"&lt;h1&gt;${L:MyLocalizedPageTitle}&lt;/h1&gt;"</js>
4723    *       },
4724    *       aside={
4725    *          <js>"${F:resources/AsideText.html}"</js>
4726    *       }
4727    *    )
4728    *    <jk>public</jk> LoggerEntry getLogger(RestRequest <jv>req</jv>, <ja>@Path</ja> String <jv>name</jv>) <jk>throws</jk> Exception {
4729    * </p>
4730    *
4731    * <h4 class='section'>See Also:</h4><ul>
4732    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerSvlVariables">REST Server SVL Variables</a>
4733    * </ul>
4734    *
4735    * @return The var resolver in use by this resource.
4736    */
4737   public VarResolver getVarResolver() { return beanStore.getBean(VarResolver.class).orElse(null); }
4738
4739   /**
4740    * Returns the bootstrap (pre-runtime) variable resolver used during context construction.
4741    *
4742    * <p>
4743    * The bootstrap resolver has the same {@link Var} catalog as {@link #getVarResolver()} but does not have
4744    * {@link Messages} or {@link Config} beans wired in — it is used to resolve annotation attribute values
4745    * (e.g. <c>@Rest(messages=...)</c>) before those beans are built. Override via
4746    * {@link Bean @Bean(name="bootstrapVarResolver")} on a static method of the resource class.
4747    *
4748    * @return The bootstrap var resolver in use by this resource.
4749    */
4750   public VarResolver getBootstrapVarResolver() { return bootstrapVarResolver.get(); }
4751
4752   /**
4753    * Returns whether the <js>"content"</js> URL parameter may be used to supply the request body.
4754    *
4755    * <p>
4756    * When this returns <jk>true</jk> (the default), {@link RestRequest} still only honors the parameter on
4757    * <c>PUT</c>/<c>POST</c> requests, so a simple cross-origin <c>GET</c> can't use it to smuggle a body past
4758    * an endpoint's real <c>Content-Type</c> gate.
4759    *
4760    * <h4 class='section'>See Also:</h4><ul>
4761    *    <li class='ja'>{@link Rest#allowContentParam()}
4762    * </ul>
4763    *
4764    * @return <jk>true</jk> if setting is enabled.
4765    */
4766   public boolean isAllowContentParam() { return allowContentParam.get(); }
4767
4768   /**
4769    * Whether cross-site requests using unsafe methods are allowed.
4770    *
4771    * <h5 class='section'>See Also:</h5><ul>
4772    *    <li class='ja'>{@link Rest#allowCrossSite()}
4773    * </ul>
4774    *
4775    * @return <jk>true</jk> if cross-site requests are not refused.
4776    */
4777   public boolean isAllowCrossSite() { return allowCrossSite.get(); }
4778
4779   /**
4780    * Origins trusted by the cross-site check.
4781    *
4782    * <h5 class='section'>See Also:</h5><ul>
4783    *    <li class='ja'>{@link Rest#allowedOrigins()}
4784    * </ul>
4785    *
4786    * @return An unmodifiable case-insensitive set of origins.  Never <jk>null</jk>.
4787    */
4788   public Set<String> getAllowedOrigins() { return allowedOrigins.get(); }
4789
4790   /**
4791    * Returns whether it's safe to render stack traces in HTTP responses.
4792    *
4793    * <p>
4794    * Besides the full stack trace, this setting also gates the {@code Thrown} error-response header and the
4795    * message text of any error-body exception that wasn't itself deliberately thrown by application code as a
4796    * {@link BasicHttpException BasicHttpException} (see
4797    * {@link #handleError(RestSession, Throwable)}). Leave this off (the default) outside of local debugging so
4798    * that unplanned exception types (a database driver error, a file-system exception, and the like) don't
4799    * incidentally echo their class name or message back to the caller.
4800    *
4801    * @return <jk>true</jk> if setting is enabled.
4802    */
4803   public boolean isRenderResponseStackTraces() { return renderResponseStackTraces.get(); }
4804
4805   /**
4806    * Returns whether this resource is opted into
4807    * <a class="doclink" href="https://www.rfc-editor.org/rfc/rfc7807">RFC 7807</a>
4808    * {@code application/problem+json} error responses.
4809    *
4810    * <p>
4811    * When {@code true}:
4812    * <ul class='spaced-list'>
4813    *    <li>Thrown {@code BasicHttpException}s are serialized as {@code application/problem+json} via
4814    *       {@code RestContext.handleError} &mdash; regardless of the client's {@code Accept} header.
4815    *    <li>{@code @RestOp} methods that return a {@link Problem} (or throw a
4816    *       {@link ProblemException}) are serialized by
4817    *       {@link ProblemDetailsProcessor}, but only when the client's
4818    *       {@code Accept} header matches {@code application/problem+json} (or {@code *&#47;*}).
4819    * </ul>
4820    *
4821    * <h4 class='section'>See Also:</h4><ul>
4822    *    <li class='ja'>{@link Rest#problemDetails()}
4823    * </ul>
4824    *
4825    * @return <jk>true</jk> if RFC 7807 problem-details responses are enabled on this resource.
4826    */
4827   public boolean isProblemDetails() { return problemDetails.get(); }
4828
4829   /**
4830    * Returns whether REST-driven serializer/parser debug behavior is enabled on this resource via
4831    * {@code @Rest(debugMarshalling="true")}.
4832    *
4833    * <p>
4834    * When {@code true}, the REST layer forces {@code Context.debug} on the serializer/parser sessions it creates to
4835    * handle requests &mdash; engaging recursion-detection-that-throws, parse-input buffering, and stack-trace-prefixed
4836    * marshalling exceptions. This is independent of the JUL logger level.
4837    *
4838    * <h4 class='section'>See Also:</h4><ul>
4839    *    <li class='ja'>{@link Rest#debugMarshalling()}
4840    * </ul>
4841    *
4842    * @return <jk>true</jk> if REST-driven marshalling debug is enabled on this resource.
4843    */
4844   public boolean isDebugMarshalling() { return debugMarshalling.get(); }
4845
4846   /**
4847    * Returns whether the resource opted into per-request virtual-thread dispatch (Java 21+) via
4848    * {@code @Rest(virtualThreads=true)}.
4849    *
4850    * <p>
4851    * The flag is honored only when {@link #getVirtualThreadExecutor()} returns a non-{@code null} executor; on
4852    * runtimes older than Java 21 the executor is {@code null} and the flag is logged once at context init.
4853    *
4854    * @return <jk>true</jk> if virtual-thread dispatch is configured on this resource.
4855    */
4856   public boolean isVirtualThreadsEnabled() { return virtualThreadsEnabled.get(); }
4857
4858   /**
4859    * Returns the raw resource-level observability attribute value from {@code @Rest(observability)}.
4860    *
4861    * <ul class='values'>
4862    *    <li>{@code "true"} &mdash; strict opt-in: all operations on this resource require a wired backend.
4863    *    <li>{@code "false"} &mdash; explicit opt-out: the observability block is disabled for all operations.
4864    *    <li>{@code null} / empty &mdash; default (inherit / no-op fallback) behavior.
4865    * </ul>
4866    *
4867    * <p>
4868    * Per-operation overrides from {@link RestOp#observability()} (and verb
4869    * annotations) take precedence over this value; they are resolved in {@link RestOpContext}.
4870    *
4871    * @return The resolved {@code @Rest(observability)} string, or {@code null} when not set.
4872    */
4873   public String getObservabilityAttribute() { return observabilityAttribute.get(); }
4874
4875   /**
4876    * Returns whether the resource explicitly opted out of observability via {@code @Rest(observability="false")}.
4877    *
4878    * @return <jk>true</jk> when the resource-level observability is disabled.
4879    */
4880   public boolean isObservabilityDisabled() {
4881      var v = observabilityAttribute.get();
4882      return v != null && eqic(v, "false");
4883   }
4884
4885   /**
4886    * Returns whether the server writes W3C {@code traceparent} / {@code tracestate} response headers when a
4887    * {@link TracerHook} is active on the request.
4888    *
4889    * <p>
4890    * Defaults to {@code true} (on-when-tracer); resolved from the {@code RestContext.responseTraceparent}
4891    * env-driven default. When {@code true}, a {@link TraceContextResponseProcessor} is registered in the
4892    * response-processor chain &mdash; it writes the headers only when a non-no-op {@code TracerHook} stashed a
4893    * trace context for the request, so it stays zero-cost on the no-tracer path. When {@code false}, the
4894    * processor is not registered at all.
4895    *
4896    * @return <jk>true</jk> if trace-context response-header propagation is enabled on this resource.
4897    */
4898   public boolean isResponseTraceparent() { return responseTraceparentDefault.get(); }
4899
4900   /**
4901    * Returns whether SLF4J MDC propagation is enabled for {@link CompletableFuture}
4902    * completion threads on this resource.
4903    *
4904    * <p>
4905    * Defaults to {@code true}; resolved first from the programmatic {@link Builder#mdcAsyncPropagation(boolean)}
4906    * override (if set), then from the {@code RestContext.mdcAsyncPropagation} env-driven default.
4907    * When {@code true}, {@link MdcAsyncListener} wraps the
4908    * {@link CompletionStage#whenComplete(BiConsumer) whenComplete} callback
4909    * registered by {@link AsyncResponseProcessor} so the completion thread sees
4910    * the request thread's MDC context. When {@code false}, no MDC work is done.
4911    *
4912    * @return <jk>true</jk> if MDC async propagation is enabled on this resource.
4913    */
4914   public boolean isMdcAsyncPropagation() {
4915      return builder.mdcAsyncPropagation != null ? builder.mdcAsyncPropagation : mdcAsyncPropagationDefault.get();
4916   }
4917
4918   /**
4919    * Returns the bound {@link RestContextProperties} for this resource.
4920    *
4921    * <p>
4922    * These are the env-driven {@code RestContext.*} defaults that seed this context's resolved settings before the
4923    * {@code @Rest} annotation chain is applied. The same instance is registered in this resource's bean store, so
4924    * it is also retrievable via {@code beanStore().getBean(RestContextProperties.class)} &mdash; unless the
4925    * resource registers its own {@code RestContextProperties} bean, in which case that bean wins in the store while
4926    * this method continues to return the instance bound for this context. For a
4927    * {@linkplain #isMixinContext() mixin sub-context}, this is the mixin's own bound instance, distinct from the
4928    * host resource's.
4929    *
4930    * @return The bound instance. Never <jk>null</jk>.
4931    * @since 10.0.0
4932    */
4933   public RestContextProperties getRestContextProperties() {
4934      return restContextProperties.get();
4935   }
4936
4937   /**
4938    * Returns the lazily-instantiated virtual-thread executor for this resource, or {@code null} when
4939    * {@code @Rest(virtualThreads=true)} is unset, the runtime is older than Java 21, or executor construction
4940    * failed (in which case a {@code WARNING} was logged at context init).
4941    *
4942    * @return The executor, or {@code null} if virtual-thread dispatch is not active for this resource.
4943    */
4944   public Executor getVirtualThreadExecutor() { return virtualThreadExecutor.get(); }
4945
4946   /**
4947    * Returns the configured async-response timeout (milliseconds) for this resource. {@code -1} indicates that no
4948    * value was supplied at the resource level — the per-op value (or {@code AsyncResponseProcessor}'s 30-second
4949    * default) applies in that case.
4950    *
4951    * @return The async timeout in milliseconds, or {@code -1} when unset.
4952    */
4953   public long getAsyncTimeoutMillis() { return asyncTimeoutMillis.get(); }
4954
4955   /**
4956    * Returns the {@link Executor} configured for routing
4957    * {@link CompletableFuture} completion callbacks on this resource, or
4958    * {@code null} when {@code @Rest(asyncCompletionExecutor)} is unset (natural completion thread).
4959    *
4960    * @return The executor, or {@code null} if no async-completion executor is configured.
4961    * @since 10.0.0
4962    */
4963   public Executor getAsyncCompletionExecutor() { return asyncCompletionExecutor.get(); }
4964
4965   /**
4966    * Returns whether framework beans and operation/child contexts are eagerly initialized at construction time.
4967    *
4968    * <h4 class='section'>See Also:</h4><ul>
4969    *    <li class='ja'>{@link Rest#eagerInit()}
4970    * </ul>
4971    *
4972    * @return <jk>true</jk> if eager initialization is enabled.
4973    */
4974   public boolean isEagerInit() { return eagerInit.get(); }
4975
4976   /**
4977    * Returns whether this resource's {@code @Rest(children=...)} entries are built lazily on first invocation
4978    * rather than eagerly at parent startup.
4979    *
4980    * <p>
4981    * Resolution order (highest wins):
4982    * <ol>
4983    *   <li>{@link Builder#lazyChildInit(boolean)} programmatic knob (if explicitly set).</li>
4984    *   <li>{@link Rest#lazyChildren() @Rest(lazyChildren)} annotation chain (most-derived wins).</li>
4985    *   <li>{@code RestContext.lazyChildren} env-driven default (default {@code false}).</li>
4986    * </ol>
4987    *
4988    * <h4 class='section'>See Also:</h4><ul>
4989    *    <li class='ja'>{@link Rest#lazyChildren()}
4990    *    <li class='jm'>{@link Builder#lazyChildInit(boolean)}
4991    * </ul>
4992    *
4993    * @return <jk>true</jk> if lazy child initialization is enabled.
4994    * @since 10.0.0
4995    */
4996   public boolean isLazyChildren() {
4997      return builder.lazyChildInit != null ? builder.lazyChildInit : lazyChildrenAnnotation.get();
4998   }
4999
5000   /**
5001    * Called during servlet initialization to invoke all {@link RestPostInit} child-last methods.
5002    *
5003    * @return This object.
5004    * @throws ServletException Error occurred.
5005    */
5006   public synchronized RestContext postInit() throws ServletException {
5007      if (initialized.get())
5008         return this;
5009      var resource2 = getResource();
5010      initializeResourceContext(resource2);
5011      for (var x : postInitInvokerPair.get().invokers) {
5012         try {
5013            x.invoke(beanStore, getResource());
5014         } catch (Exception e) {
5015            throw new ServletException(unwrap(e));
5016         }
5017      }
5018      getRestChildren().postInit();
5019      return this;
5020   }
5021
5022   private void initializeResourceContext(Object resource2) {
5023      var mi = ClassInfo.of(resource2).getMethod(x -> x.hasName("setContext") && x.hasParameterTypes(RestContext.class)).orElse(null);
5024      if (nn(mi)) {
5025         try {
5026            mi.accessible().invoke(resource2, this);
5027         } catch (ExecutableException e) {
5028            throw new RuntimeException(e.unwrap());
5029         }
5030      }
5031   }
5032
5033   /**
5034    * Called during servlet initialization to invoke all {@link RestPostInit} child-first methods.
5035    *
5036    * @return This object.
5037    * @throws ServletException Error occurred.
5038    */
5039   public RestContext postInitChildFirst() throws ServletException {
5040      if (initialized.get())
5041         return this;
5042      getRestChildren().postInitChildFirst();
5043      for (var x : postInitChildFirstInvokerPair.get().invokers) {
5044         try {
5045            x.invoke(beanStore, getResource());
5046         } catch (Exception e) {
5047            throw new ServletException(unwrap(e));
5048         }
5049      }
5050      initialized.set(true);
5051      return this;
5052   }
5053
5054   /**
5055    * Installs bounded body-caching wrappers on the call when this resource's logger is loggable at
5056    * {@link Level#FINEST FINEST}. Used on the resource-level (404/no-op) paths; per-operation capture is installed by
5057    * {@link RestOpContext#createSession(RestSession)}.
5058    *
5059    * @param call The current call.
5060    * @throws IOException If the request/response streams could not be wrapped.
5061    */
5062   private void installCaptureIfNeeded(RestSession call) throws IOException {
5063      if (getLogger().isLoggable(Level.FINEST))
5064         call.installCapture();
5065   }
5066
5067   /**
5068    * Validates that when {@code @Rest(observability="true")} is declared on this resource, at least one real
5069    * observability backend ({@link MetricsRecorder} or
5070    * {@link TracerHook}) is registered in the bean store.
5071    *
5072    * <p>
5073    * Called once during {@link RestContext} construction, after all {@code @Bean} method injection has run.
5074    * If the attribute is {@code "true"} and both beans resolve to their {@code NoOp} singletons, construction
5075    * fails with a {@link BasicHttpException InternalServerError} whose message precisely
5076    * identifies the missing backends.
5077    *
5078    * <p>
5079    * Per-operation {@code @RestOp(observability="true")} startup-fails are handled the same way inside
5080    * {@link RestOpContext}.
5081    *
5082    * @throws InternalServerError when {@code @Rest(observability="true")} is set but no backend is wired.
5083    */
5084   private void checkObservabilityBackendPresent() {
5085      var attr = observabilityAttribute.get();
5086      if (neqic("true", attr))
5087         return;
5088      var recorder = beanStore.getBean(MetricsRecorder.class).orElse(null);
5089      var tracer = beanStore.getBean(TracerHook.class).orElse(null);
5090      boolean hasRecorder = recorder != null && !(recorder instanceof NoOpMetricsRecorder);
5091      boolean hasTracer = tracer != null && !(tracer instanceof NoOpTracerHook);
5092      if (!hasRecorder && !hasTracer)
5093         throw new InternalServerError(
5094            "@Rest(observability=\"true\") is set on " + getResourceClass().getSimpleName()
5095            + " but no MetricsRecorder or TracerHook @Bean is registered. "
5096            + "Either wire a backend or change observability to \"\" (inherit) or \"false\" (opt-out).");
5097   }
5098
5099   /**
5100    * Eagerly evaluates the {@link #asyncCompletionExecutor} memoizer when the annotation or programmatic
5101    * override is non-blank, ensuring "bean not found" surfaces as a startup failure.
5102    *
5103    * @throws IllegalStateException if the named executor bean is not in the bean store.
5104    */
5105   private void checkAsyncCompletionExecutorPresent() {
5106      var name = builder.asyncCompletionExecutorName != null
5107         ? builder.asyncCompletionExecutorName
5108         : mergeReplacedStringAttribute("asyncCompletionExecutor", null);
5109      if (inb(name))
5110         asyncCompletionExecutor.get(); // throws IllegalStateException if bean is missing
5111   }
5112
5113   private void initializeFrameworkBeansForRestOps() {
5114      getMarshallingContext();
5115      getEncoders();
5116      getSerializers();
5117      getParsers();
5118      getLogger();
5119      getThrownStore();
5120      getMethodExecStore();
5121      getMessages();
5122      getVarResolver();
5123      getConfig();
5124      getResponseProcessors();
5125      getRestDebugFormatter();
5126      getPartSerializer();
5127      getPartParser();
5128      getJsonSchemaGenerator();
5129      getStaticFiles();
5130      getDefaultRequestHeaders();
5131      getDefaultResponseHeaders();
5132      getDefaultRequestAttributes();
5133      getSwaggerProvider();
5134      getOpenApiProvider();
5135   }
5136
5137   private static Set<String> newCaseInsensitiveSet(String value) {
5138      var s = new TreeSet<>(String.CASE_INSENSITIVE_ORDER) {
5139         private static final long serialVersionUID = 1L;
5140
5141         @Override
5142         public boolean contains(Object v) {
5143            return v != null && super.contains(v);
5144         }
5145      };
5146      StringUtils.split(value, s::add);
5147      return u(s);
5148   }
5149
5150   private LifecycleInvokerPair buildLifecycleInvokerPair(Supplier<MethodList> methods) {
5151      var ml = MethodList.of(methods.get());
5152      var inv = ml.stream().map(this::toMethodInvoker).toArray(MethodInvoker[]::new);
5153      return new LifecycleInvokerPair(ml, inv);
5154   }
5155
5156   private MethodInvoker toMethodInvoker(Method m) {
5157      return new MethodInvoker(m, getMethodExecStats(m));
5158   }
5159
5160   private static Throwable unwrap(Throwable t) {
5161      if (t instanceof InvocationTargetException t2)
5162         return t2.getTargetException();
5163      return t;
5164   }
5165
5166   /**
5167    * Method that can be subclassed to allow uncaught throwables to be treated as other types of throwables.
5168    *
5169    * <p>
5170    * The default implementation looks at the throwable class name to determine whether it can be converted to another type:
5171    *
5172    * <ul>
5173    *    <li>{@link BeanQuerySyntaxException} - Converted to {@link BadRequest} carrying the exception's message and an
5174    *       {@value BeanQueryRequest#ERROR_HEADER} header set to its {@link BeanQuerySyntaxException#code() code()}.
5175    *    <li>{@link BeanQueryExecutionException} - Converted to {@link InternalServerError} with the generic message
5176    *       <js>"Query execution failed."</js>; the original exception (and its cause) stays attached for logging.
5177    *    <li><js>"*AccessDenied*"</js> - Converted to {@link Unauthorized}.
5178    *    <li><js>"*Empty*"</js>,<js>"*NotFound*"</js> - Converted to {@link NotFound}.
5179    *    <li>Any other exception - Converted to {@link InternalServerError} with the generic message
5180    *       <js>"Internal Server Error."</js>; the original exception stays attached as the cause.
5181    *       Returned unchanged when {@link #isRenderResponseStackTraces()} is enabled, or when the throwable is a
5182    *       problem-details exception, a legacy HTTP response exception, or has a registered {@link ProblemMapper}.
5183    * </ul>
5184    *
5185    * @param t The thrown object.
5186    * @return The converted thrown object.
5187    */
5188   public Throwable convertThrowable(Throwable t) {
5189
5190      if (t instanceof InvocationTargetException t2)
5191         t = t2.getTargetException();
5192
5193      if (t instanceof ExecutableException t2)
5194         t = t2.getTargetException();
5195
5196      if (t instanceof BasicHttpException t2)
5197         return t2;
5198
5199      var ci = ClassInfo.of(t);
5200
5201      if (ci.hasAnnotation(Response.class))
5202         return t;
5203
5204      if (ci.isAssignableTo(ParseException.class) || ci.is(InvalidDataConversionException.class))
5205         return new BadRequest(t);
5206
5207      if (t instanceof BeanQuerySyntaxException e)
5208         return new BadRequest(e).setHeader(BeanQueryRequest.ERROR_HEADER, e.code().name());
5209
5210      // The cause may carry SQL or table names: keep it attached for logging, but never in the client-facing message.
5211      if (t instanceof BeanQueryExecutionException e)
5212         return new InternalServerError(e, "Query execution failed.");
5213
5214      String n = cn(t);
5215
5216      if (co(n, "AccessDenied") || co(n, "Unauthorized"))
5217         return new Unauthorized(t);
5218
5219      if (co(n, "Empty") || co(n, "NotFound"))
5220         return new NotFound(t);
5221
5222      // Any other exception is an unplanned failure: its class name and message were never written for a client audience,
5223      // so hide them behind a generic 500 (the original stays attached as the cause for logging and for RRPC).
5224      if (isRenderResponseStackTraces() || isIntentionalResponse(t))
5225         return t;
5226      return new InternalServerError(t, "Internal Server Error.");
5227   }
5228
5229   private static final Class<?> LEGACY_HTTP_RESPONSE = loadClassOrNull("org.apache.http.HttpResponse");
5230
5231   private static Class<?> loadClassOrNull(String name) {
5232      try {
5233         return Class.forName(name);
5234      } catch (ClassNotFoundException e) {
5235         return null;
5236      }
5237   }
5238
5239   /**
5240    * Returns <jk>true</jk> if the throwable is itself a response the application chose to send (a problem-details
5241    * exception, a legacy HTTP response exception, or a type with a registered problem mapper) rather than an unplanned failure.
5242    */
5243   private boolean isIntentionalResponse(Throwable t) {
5244      if (t instanceof ProblemException || (nn(LEGACY_HTTP_RESPONSE) && LEGACY_HTTP_RESPONSE.isInstance(t)))
5245         return true;
5246      var bs = getBeanStore();
5247      var list = bs.getBean(ProblemMapperList.class).map(ProblemMapperList::asList).orElse(List.of());
5248      for (var m : list)
5249         if (m.getExceptionType().isInstance(t))
5250            return true;
5251      return list.isEmpty() && bs.getBean(ProblemMapper.class).map(m -> m.getExceptionType().isInstance(t)).orElse(false);
5252   }
5253
5254   /**
5255    * Called at the end of a request to invoke all {@link RestEndCall} methods on this context.
5256    *
5257    * <p>
5258    * Fires this context's own {@code @RestEndCall} methods against its own resource instance. The host's
5259    * {@code endCall(...)} is invoked from {@link #execute(Object, HttpServletRequest, HttpServletResponse)};
5260    * for mixin-endpoint requests, that path additionally calls {@code endCall} on the mixin sub-context
5261    * after the host's so host hooks fire first, then the mixin's.
5262    *
5263    * @param session The current request.
5264    */
5265   protected void endCall(RestSession session) {
5266      for (var x : endCallInvokerPair.get().invokers) {
5267         try {
5268            x.invoke(session.getBeanStore(), getResource());
5269         } catch (Exception e) {
5270            getLogger().log(Level.WARNING, unwrap(e), () -> f("Error occurred invoking finish-call method '%s'.", x.getFullName()));
5271         }
5272      }
5273   }
5274
5275   /**
5276    * Finds the {@link RestOpArg} instances to handle resolving objects on the calls to the specified Java method.
5277    *
5278    * @param m The Java method being called.
5279    * @param beanStore
5280    *    The factory used for creating beans and retrieving injected beans.
5281    *    <br>Created during context bootstrap.
5282    * @return The array of resolvers.
5283    */
5284   protected RestOpArg[] findRestOperationArgs(Method m, BeanStore beanStore) {
5285
5286      var mi = MethodInfo.of(m);
5287      var params = mi.getParameters();
5288      var ra = new RestOpArg[params.size()];
5289
5290      var bs = new BasicBeanStore(beanStore);
5291      var roa = getRestOpArgs();
5292
5293      for (var i = 0; i < params.size(); i++) {
5294         var pi = params.get(i);
5295         bs.addBean(ParameterInfo.class, pi);
5296         for (var c : roa) {
5297            try {
5298               ra[i] = BeanInstantiator.of(RestOpArg.class, bs)
5299                  .type(c)
5300                  .factoryMethodNames("getInstance", "create")
5301                  .factoryAbstainOnNull()
5302                  .run();
5303               if (nn(ra[i]))
5304                  break;
5305            } catch (ExecutableException e) {
5306               throw new InternalServerError(e.unwrap(), "Could not resolve parameter %s on method %s.", i, mi.getNameFull());
5307            }
5308         }
5309         if (ra[i] == null)
5310            throw new InternalServerError("Could not resolve parameter %s on method %s.", i, mi.getNameFull());
5311      }
5312
5313      return ra;
5314   }
5315
5316   /**
5317    * Returns the time statistics gatherer for the specified method.
5318    *
5319    * @param m The method to get statistics for.
5320    * @return The cached time-stats object.
5321    */
5322   protected MethodExecStats getMethodExecStats(Method m) {
5323      return getMethodExecStore().getStats(m);
5324   }
5325
5326   /**
5327    * Returns the list of methods to invoke after the actual REST method is called.
5328    *
5329    * @return The list of methods to invoke after the actual REST method is called.
5330    */
5331   public MethodList getPostCallMethods() { return postCallMethods.get(); }
5332
5333   /**
5334    * Returns the list of methods to invoke before the actual REST method is called.
5335    *
5336    * @return The list of methods to invoke before the actual REST method is called.
5337    */
5338   public MethodList getPreCallMethods() { return preCallMethods.get(); }
5339
5340   /**
5341    * Returns the list of methods to invoke during servlet destruction.
5342    *
5343    * @return The destroy method list, never {@code null}.
5344    */
5345   public MethodList getDestroyMethods() { return destroyInvokerPair.get().methods; }
5346
5347   /**
5348    * Returns the list of methods to invoke at the end of each HTTP request.
5349    *
5350    * @return The end-call method list, never {@code null}.
5351    */
5352   public MethodList getEndCallMethods() { return endCallInvokerPair.get().methods; }
5353
5354   /**
5355    * Returns the list of methods to invoke during servlet post-initialization (child-last phase).
5356    *
5357    * @return The post-init method list, never {@code null}.
5358    */
5359   public MethodList getPostInitMethods() { return postInitInvokerPair.get().methods; }
5360
5361   /**
5362    * Returns the list of methods to invoke during servlet post-initialization (child-first phase).
5363    *
5364    * @return The post-init-child-first method list, never {@code null}.
5365    */
5366   public MethodList getPostInitChildFirstMethods() { return postInitChildFirstInvokerPair.get().methods; }
5367
5368   /**
5369    * Returns the list of methods to invoke at the start of each HTTP request.
5370    *
5371    * @return The start-call method list, never {@code null}.
5372    */
5373   public MethodList getStartCallMethods() { return startCallInvokerPair.get().methods; }
5374
5375   /**
5376    * Method for handling response errors.
5377    *
5378    * <p>
5379    * Subclasses can override this method to provide their own custom error response handling.
5380    *
5381    * <p>
5382    * The {@code Thrown} response header and the cause-chain detail normally appended to the error body are both
5383    * gated behind {@link #isRenderResponseStackTraces()} (see {@code @Rest(renderResponseStackTraces)}), which is
5384    * off by default. With that flag off, only a message the calling code deliberately supplied via a thrown
5385    * {@link BasicHttpException} (its subclasses, e.g. {@code NotFound} or {@code BadRequest}) is echoed back;
5386    * the class name and message text of any other, unplanned exception type bubbling up from application code
5387    * is kept out of both the header and the body, since that text was never authored with a client audience in
5388    * mind and may otherwise incidentally carry implementation detail (file paths, driver/database error text,
5389    * and the like). Turn the flag on for local debugging to get the full detail back.
5390    *
5391    * <p>
5392    * The {@code Thrown} header is still always set for RRPC dispatch responses (an operation invoked through
5393    * {@code @RestOp(method=HttpMethod.RRPC)}), regardless of {@link #isRenderResponseStackTraces()}. The RRPC/
5394    * {@code @Remote} client stub has no other channel for learning the server-side exception's class in order to
5395    * reconstruct and rethrow the equivalent type locally, so that one header is part of the RPC contract rather
5396    * than incidental debug detail. The error body's cause-chain message is unaffected by this exemption and
5397    * remains suppressed the same as any other operation.
5398    *
5399    * @param session The rest call.
5400    * @param e The exception that occurred.
5401    * @throws IOException Can be thrown if a problem occurred trying to write to the output stream.
5402    */
5403   protected synchronized void handleError(RestSession session, Throwable e) throws IOException {
5404
5405      // Client disconnected mid-response: routine.  Don't record it, log it, or try to write an error to a dead socket.
5406      if (session.logContainerClientAbort(e))
5407         return;
5408
5409      session.exception(e);
5410
5411      if (getLogger().isLoggable(Level.FINE))
5412         getLogger().log(Level.WARNING, e, () -> "Error occurred during REST call.");
5413
5414      int code = 500;
5415
5416      var ci = ClassInfo.of(e);
5417      var r = ci.getAnnotations(StatusCode.class).findFirst().map(AnnotationInfo::inner).orElse(null);
5418      if (nn(r) && r.value().length > 0)
5419         code = r.value()[0];
5420
5421      var appThrown = e instanceof BasicHttpException;
5422      var e2 = (e instanceof BasicHttpException e3 ? e3 : new BasicHttpException(code, null, e));
5423
5424      var req = session.getRequest();
5425      var res = session.getResponse();
5426
5427      var t2 = resolveThrownHeader(e2, isRenderResponseStackTraces(), isRpcDispatch(session));
5428      if (nn(t2))
5429         res.setHeader(t2.getName(), t2.getValue());
5430
5431      // Matches the op-method path (HttpResponseProcessor / ProblemDetailsProcessor), which sends this header too.
5432      e2.getHeaders().stream()
5433         .filter(h -> BeanQueryRequest.ERROR_HEADER.equals(h.getName()))
5434         .findFirst()
5435         .ifPresent(h -> res.setHeader(h.getName(), h.getValue()));
5436
5437      // RFC 9110 requires Allow on a 405; the framework's own 405s carry it on the exception.
5438      e2.getHeaders().stream()
5439         .filter(h -> eqic("Allow", h.getName()))
5440         .findFirst()
5441         .ifPresent(h -> res.setHeader("Allow", h.getValue()));
5442
5443      try {
5444         var statusCode = e2.getStatusLine().getStatusCode();
5445
5446         if (e2 instanceof ValidationException e3 && writeValidationErrorBody(res, e3, statusCode, isProblemDetails()))
5447            return;
5448
5449         if (isProblemDetails() && writeProblemDetailsBody(res, e2, statusCode))
5450            return;
5451
5452         res.setContentType("text/plain");
5453         res.setHeader("Content-Encoding", "identity");
5454         res.setStatus(statusCode);
5455
5456         PrintWriter w = getResponseWriter(res);
5457
5458         try (PrintWriter w2 = w) {
5459            var httpMessage = RestUtils.getHttpResponseText(statusCode);
5460            if (nn(httpMessage))
5461               w2.append("HTTP ").append(String.valueOf(statusCode)).append(": ").append(httpMessage).append("\n\n");
5462            if (isRenderResponseStackTraces())
5463               e.printStackTrace(w2);
5464            else
5465               w2.append(suppressedErrorBodyMessage(e2, appThrown));
5466         }
5467
5468      } catch (Exception e1) {
5469         req.setAttribute("Exception", e1);
5470      }
5471   }
5472
5473   /**
5474    * Determines the {@code Thrown} response header to set for a reported error, if any.
5475    *
5476    * <p>
5477    * Package-private (rather than folded directly into {@link #handleError(RestSession, Throwable)}) so the
5478    * gating decision can be exercised directly in unit tests without standing up a full request/response cycle.
5479    *
5480    * @param e2 The (possibly wrapped) exception being reported. Must not be {@code null}.
5481    * @param renderResponseStackTraces The resolved {@code renderResponseStackTraces} setting for the call.
5482    * @param rpcDispatch {@code true} if the call being reported on is an RRPC dispatch (see
5483    *    {@link #isRpcDispatch(RestSession)}), in which case the header is included even when
5484    *    {@code renderResponseStackTraces} is off, since the RRPC/{@code @Remote} client depends on it to
5485    *    reconstruct the original exception type.  In that case only the exception class name is included; the
5486    *    message is added only when {@code renderResponseStackTraces} is on.
5487    * @return The header to set, or {@code null} if none should be set (neither condition permits it, or
5488    *    there's no distinct root cause to report).
5489    */
5490   static Thrown resolveThrownHeader(BasicHttpException e2, boolean renderResponseStackTraces, boolean rpcDispatch) {
5491      if (!renderResponseStackTraces && !rpcDispatch)
5492         return null;
5493      var t = e2.getRootCause();
5494      if (t == null)
5495         return null;
5496      if (renderResponseStackTraces)
5497         return Thrown.of(t);
5498      // RRPC callers need the exception class to rebuild it locally; the message text stays server-side.
5499      return Thrown.of(urlEncode(UnmodifiableBean.logicalType(t).getName()) + ";");
5500   }
5501
5502   /**
5503    * Determines whether the operation matched for the given session is an RRPC dispatch target (an operation
5504    * declared with {@code @RestOp(method=HttpMethod.RRPC)}, backing a {@code getRrpcInterface()}/{@code @Remote}
5505    * client proxy).
5506    *
5507    * <p>
5508    * Used by {@link #handleError(RestSession, Throwable)} to decide whether the {@code Thrown} header should be
5509    * included regardless of {@link #isRenderResponseStackTraces()}; see {@link #resolveThrownHeader}.
5510    *
5511    * @param session The rest call. Must not be {@code null}.
5512    * @return {@code true} if the matched operation (if any) is an RRPC dispatch target.
5513    */
5514   static boolean isRpcDispatch(RestSession session) {
5515      var opSession = session.getOpSessionOrNull();
5516      return nn(opSession) && opSession.getContext() instanceof RrpcRestOpContext;
5517   }
5518
5519   /**
5520    * Determines the message written to the plain-text error response body when
5521    * {@code renderResponseStackTraces} is off.
5522    *
5523    * <p>
5524    * Package-private for the same unit-testability reason as {@link #resolveThrownHeader(BasicHttpException, boolean)}.
5525    *
5526    * @param e2 The (possibly wrapped) exception being reported. Must not be {@code null}.
5527    * @param appThrown {@code true} if the original, unwrapped exception was itself a {@link BasicHttpException}
5528    *    (i.e. deliberately thrown by application code with a client-facing message in mind).
5529    * @return The scrubbed message to write, or an empty string if nothing should be written (the exception
5530    *    wasn't application-authored, so its message is treated as internal detail).
5531    */
5532   static String suppressedErrorBodyMessage(BasicHttpException e2, boolean appThrown) {
5533      return appThrown ? scrubForXss(e2.getMessage()) : "";
5534   }
5535
5536   /**
5537    * Replaces {@code <}, {@code >}, and {@code &} in a message about to be written into a {@code text/plain}
5538    * error response body, as a simple defense against the body being reflected into an HTML context downstream.
5539    *
5540    * @param msg The message to scrub. Can be {@code null}.
5541    * @return The scrubbed message, or an empty string if {@code msg} was {@code null}.
5542    */
5543   private static String scrubForXss(String msg) {
5544      return msg == null ? "" : msg.replace('<', ' ').replace('>', ' ').replace('&', ' ');
5545   }
5546
5547   /**
5548    * Writes a {@code BasicHttpException} as an {@code application/problem+json} body. The {@code Accept}
5549    * header is intentionally ignored on the error path so opted-in resources always emit Problem JSON for thrown
5550    * exceptions.
5551    *
5552    * @return {@code true} if the body was written (response committed). {@code false} on serialization failure so
5553    *    the caller can fall back to the legacy {@code text/plain} writer.
5554    */
5555   private static boolean writeProblemDetailsBody(HttpServletResponse res, BasicHttpException e, int statusCode) {
5556      try {
5557         var problem = ProblemAdapters.fromException(e);
5558         e.getHeaders().stream()
5559            .filter(h -> BeanQueryRequest.ERROR_HEADER.equals(h.getName()))
5560            .findFirst()
5561            .ifPresent(h -> problem.set("code", h.getValue()));
5562         res.setStatus(statusCode);
5563         res.setContentType(ContentType.APPLICATION_PROBLEM_JSON.getValue());
5564         res.setHeader("Content-Encoding", "identity");
5565         var os = res.getOutputStream();
5566         Json.DEFAULT.write(problem, os);
5567         os.flush();
5568         return true;
5569      } catch (Exception ex) {
5570         return false;
5571      }
5572   }
5573
5574   /**
5575    * Writes a {@link ValidationException} as a structured JSON body carrying the per-field
5576    * {@link ValidationViolation} list, so client UIs can render field-level errors.
5577    *
5578    * <p>
5579    * Two shapes depending on the resource's {@code @Rest(problemDetails)} opt-in:
5580    * <ul class='spaced-list'>
5581    *    <li><b>Problem-details ON</b> &mdash; emits {@code application/problem+json} with the standard
5582    *       RFC 7807 {@code status}/{@code title}/{@code detail} members plus an {@code errors[]} extension
5583    *       array populated from {@link ValidationException#getViolations()}. Bypasses the generic
5584    *       {@link ProblemAdapters#fromException(BasicHttpException)} path because that adapter is
5585    *       intentionally narrow (no extensions) &mdash; validation needs its own per-field payload.
5586    *    <li><b>Problem-details OFF (default)</b> &mdash; emits {@code application/json} with the simple
5587    *       {@code { "status":400, "errors":[ ... ] }} envelope. Keeps the response usable from clients that
5588    *       can't parse {@code application/problem+json} without making validation responses look like a
5589    *       text/plain stack trace.
5590    * </ul>
5591    *
5592    * @return {@code true} if the body was written (response committed). {@code false} on serialization
5593    *    failure so the caller can fall back to the legacy {@code text/plain} writer.
5594    */
5595   private static boolean writeValidationErrorBody(HttpServletResponse res, ValidationException ve, int statusCode, boolean problemDetails) {
5596      try {
5597         res.setStatus(statusCode);
5598         res.setHeader("Content-Encoding", "identity");
5599         var os = res.getOutputStream();
5600         if (problemDetails) {
5601            var problem = new Problem()
5602               .setStatus(statusCode)
5603               .setTitle(ve.getStatusLine().getReasonPhrase())
5604               .setDetail(ve.getMessage())
5605               .set("errors", ve.getViolations());
5606            res.setContentType(ContentType.APPLICATION_PROBLEM_JSON.getValue());
5607            Json.DEFAULT.write(problem, os);
5608         } else {
5609            var envelope = new LinkedHashMap<String,Object>();
5610            envelope.put("status", statusCode);
5611            envelope.put("errors", ve.getViolations());
5612            res.setContentType("application/json");
5613            Json.DEFAULT.write(envelope, os);
5614         }
5615         os.flush();
5616         return true;
5617      } catch (Exception ex) {
5618         return false;
5619      }
5620   }
5621
5622   private static PrintWriter getResponseWriter(HttpServletResponse res) throws IOException {
5623      try {
5624         return res.getWriter();
5625      } catch (@SuppressWarnings("unused") IllegalStateException x) {
5626         return new PrintWriter(new OutputStreamWriter(res.getOutputStream(), UTF8));
5627      }
5628   }
5629
5630   protected void handleNotFound(RestSession session) throws Exception {
5631      var pathInfo = session.getPathInfo();
5632      var methodUC = session.getMethod();
5633      var rc = session.getStatus();
5634      var onPath = pathInfo == null ? " on no pathInfo" : (" on path '" + pathInfo + "'");
5635      if (rc == SC_NOT_FOUND)
5636         throw new NotFound("Method '%s' not found on resource with matching pattern%s.", methodUC, onPath);
5637      else if (rc == SC_PRECONDITION_FAILED)
5638         throw new PreconditionFailed("Method '%s' not found on resource%s with matching matcher.", methodUC, onPath);
5639      else if (rc == SC_METHOD_NOT_ALLOWED) {
5640         var e = new MethodNotAllowed("Method '%s' not found on resource%s.", methodUC, onPath);
5641         e.setHeader("Allow", getRestOperations().allowedMethods(session));
5642         throw e;
5643      }
5644      else if (rc < SC_BAD_REQUEST)
5645         // Reaching this method means no operation matched, so a still-successful or unset status must resolve to a
5646         // 404 rather than a 500.  Under a real servlet container the response status defaults to 200 (never the
5647         // mock response's coincidental 0), so throwing "Invalid method response" for a non-error status would turn
5648         // every unmatched path into an HTTP 500 in production while staying invisible to the mock-based tests.
5649         throw new NotFound("Method '%s' not found on resource with matching pattern%s.", methodUC, onPath);
5650      else if (rc < SC_INTERNAL_SERVER_ERROR)
5651         // A start-call hook left another client-error status (e.g. 400, 401, 403, 409) and nothing matched:
5652         // keep that status rather than converting it to a 500.
5653         throw new BasicHttpException(rc, null, "Method '%s' not found on resource%s.", methodUC, onPath);
5654      else
5655         throw new ServletException("Invalid method response: " + rc, session.getException());
5656   }
5657
5658   /**
5659    * Called during a request to invoke all {@link RestPostCall} methods.
5660    *
5661    * <p>
5662    * For mixin-endpoint requests, fires the host's {@code @RestPostCall} methods first (via the host's
5663    * {@code localPostCallInvokers}), then the mixin's per-op invokers ({@link RestOpContext#getPostCallMethods()}).
5664    * Host-endpoint requests fire only the host's per-op invokers (the established path; unchanged from pre-10.0.0).
5665    *
5666    * @param session The current request.
5667    * @throws Exception If thrown from call methods.
5668    */
5669   protected void postCall(RestOpSession session) throws Exception {
5670      var opCtx = session.getContext().getContext();
5671      if (opCtx.isMixinContext && opCtx.parentContext != null)
5672         for (var m : opCtx.parentContext.localPostCallInvokers.get())
5673            m.invoke(session);
5674      for (var m : session.getContext().getPostCallMethods())
5675         m.invoke(session);
5676   }
5677
5678   /**
5679    * Called during a request to invoke all {@link RestPreCall} methods.
5680    *
5681    * <p>
5682    * For mixin-endpoint requests, fires the host's {@code @RestPreCall} methods first (via the host's
5683    * {@code localPreCallInvokers}), then the mixin's per-op invokers ({@link RestOpContext#getPreCallMethods()}).
5684    * Host-endpoint requests fire only the host's per-op invokers (the established path; unchanged from pre-10.0.0).
5685    *
5686    * @param session The current request.
5687    * @throws Exception If thrown from call methods.
5688    */
5689   protected void preCall(RestOpSession session) throws Exception {
5690      var opCtx = session.getContext().getContext();
5691      if (opCtx.isMixinContext && opCtx.parentContext != null)
5692         for (var m : opCtx.parentContext.localPreCallInvokers.get())
5693            m.invoke(session);
5694      for (var m : session.getContext().getPreCallMethods())
5695         m.invoke(session);
5696   }
5697
5698   /**
5699    * The main method for serializing POJOs passed in through the {@link RestResponse#setContent(Object)} method or
5700    * returned by the Java method.
5701    *
5702    * <p>
5703    * Subclasses may override this method if they wish to modify the way the output is rendered or support other output
5704    * formats.
5705    *
5706    * <p>
5707    * The default implementation simply iterates through the response handlers on this resource
5708    * looking for the first one whose {@link ResponseProcessor#process(RestOpSession)} method returns
5709    * <jk>true</jk>.
5710    *
5711    * @param opSession The HTTP call.
5712    * @throws IOException Thrown by underlying stream.
5713    * @throws BasicHttpException Non-200 response.
5714    * @throws NotImplemented No registered response processors could handle the call.
5715    */
5716   @SuppressWarnings({
5717      "java:S127" // Loop counter i resets to -1 on RESTART
5718   })
5719   public void processResponse(RestOpSession opSession) throws IOException, BasicHttpException, NotImplemented {
5720
5721      // Loop until we find the correct processor for the POJO.
5722      int loops = 5;
5723      var rp = getResponseProcessors();
5724      for (var i = 0; i < rp.length; i++) {
5725         var j = rp[i].process(opSession);
5726         if (j == FINISHED)
5727            return;
5728         if (j == RESTART) {
5729            if (loops-- < 0)
5730               throw new InternalServerError("Too many processing loops.");
5731            i = -1;  // Start over.
5732         }
5733      }
5734
5735      var output = opSession.getResponse().getContent().orElse(null);
5736      throw new NotImplemented("No response processors found to process output of type '%s'", cn(output));
5737   }
5738
5739   @Override /* Overridden from Context */
5740   protected FluentMap<String,Object> properties() {
5741      return super.properties()
5742         .a("allowContentParam", isAllowContentParam())
5743         .a("allowCrossSite", isAllowCrossSite())
5744         .a("allowedHeaderParams", getAllowedHeaderParams())
5745         .a("allowedOrigins", getAllowedOrigins())
5746         .a("allowedMethodHeaders", getAllowedMethodHeaders())
5747         .a("allowedMethodParams", getAllowedMethodParams())
5748         .a("allowedResponseHeaders", getAllowedResponseHeaders())
5749         .a("beanStore", beanStore)
5750         .a("clientVersionHeader", getClientVersionHeader())
5751         .a("consumes", getConsumes())
5752         .a("defaultRequestHeaders", getDefaultRequestHeaders())
5753         .a("defaultResponseHeaders", getDefaultResponseHeaders())
5754         .a("partParser", getPartParser())
5755         .a("partSerializer", getPartSerializer())
5756         .a("produces", getProduces())
5757         .a("renderResponseStackTraces", isRenderResponseStackTraces())
5758         .a("responseProcessors", getResponseProcessors())
5759         .a("restOpArgs", getRestOpArgs())
5760         .a("staticFiles", getStaticFiles())
5761         .a("swaggerProvider", getSwaggerProvider())
5762         .a("openApiProvider", getOpenApiProvider())
5763         .a("uriAuthority", getUriAuthority())
5764         .a("uriContext", getUriContext())
5765         .a("uriRelativity", getUriRelativity())
5766         .a("uriResolution", getUriResolution());
5767   }
5768
5769   /**
5770    * Called at the start of a request to invoke all {@link RestStartCall} methods on this context.
5771    *
5772    * <p>
5773    * Fires this context's own {@code @RestStartCall} methods against its own resource instance. The host
5774    * version is invoked from {@link #execute(Object, HttpServletRequest, HttpServletResponse)} before the
5775    * operation is resolved; once the operation is known to belong to a mixin sub-context,
5776    * {@link RestSession#run()} additionally calls {@code startCall} on the mixin context so host hooks fire
5777    * first, then the mixin's.
5778    *
5779    * @param session The current request.
5780    * @throws BasicHttpException If thrown from call methods.
5781    */
5782   protected void startCall(RestSession session) throws BasicHttpException {
5783      for (var x : startCallInvokerPair.get().invokers) {
5784         try {
5785            x.invoke(session.getBeanStore(), getResource());
5786         } catch (IllegalAccessException | IllegalArgumentException e) {
5787            throw new InternalServerError(e, "Error occurred invoking start-call method '%s'.", x.getFullName());
5788         } catch (InvocationTargetException e) {
5789            var t = e.getTargetException();
5790            if (t instanceof BasicHttpException t2)
5791               throw t2;
5792            throw new InternalServerError(t);
5793         }
5794      }
5795   }
5796}