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 java.time.format.DateTimeFormatter.*;
020import static org.apache.juneau.commons.httppart.HttpPartType.*;
021import static org.apache.juneau.commons.utils.IoUtils.*;
022import static org.apache.juneau.commons.utils.ObjectUtils.*;
023import static org.apache.juneau.commons.utils.Shorts.*;
024import static org.apache.juneau.commons.utils.StringUtils.*;
025import static org.apache.juneau.commons.utils.ThrowableUtils.*;
026import static org.apache.juneau.rest.RestSharedConstants.*;
027
028import java.io.*;
029import java.lang.reflect.*;
030import java.lang.reflect.Proxy;
031import java.net.*;
032import java.nio.charset.*;
033import java.security.*;
034import java.text.*;
035import java.time.*;
036import java.time.format.*;
037import java.time.temporal.*;
038import java.util.*;
039import java.util.concurrent.atomic.*;
040import java.util.function.*;
041import java.util.stream.*;
042
043import org.apache.juneau.bean.openapi3.OpenApi;
044import org.apache.juneau.bean.swagger.Operation;
045import org.apache.juneau.bean.swagger.Swagger;
046import org.apache.juneau.commons.bean.*;
047import org.apache.juneau.commons.http.*;
048import org.apache.juneau.commons.http.MediaType;
049import org.apache.juneau.commons.httppart.*;
050import org.apache.juneau.commons.logging.*;
051import org.apache.juneau.commons.svl.*;
052import org.apache.juneau.commons.utils.*;
053import org.apache.juneau.config.*;
054import org.apache.juneau.http.*;
055import org.apache.juneau.http.header.*;
056import org.apache.juneau.http.header.Date;
057import org.apache.juneau.http.request.*;
058import org.apache.juneau.http.response.*;
059import org.apache.juneau.httppart.bean.*;
060import org.apache.juneau.marshall.*;
061import org.apache.juneau.marshall.collections.*;
062import org.apache.juneau.marshall.cp.Messages;
063import org.apache.juneau.marshall.httppart.*;
064import org.apache.juneau.marshall.marshaller.*;
065import org.apache.juneau.marshall.marshaller.Uon;
066import org.apache.juneau.marshall.parser.ParseException;
067import org.apache.juneau.marshall.uon.*;
068import org.apache.juneau.rest.server.arg.*;
069import org.apache.juneau.rest.server.assertions.*;
070import org.apache.juneau.rest.server.auth.*;
071import org.apache.juneau.rest.server.guard.*;
072import org.apache.juneau.rest.server.httppart.*;
073import org.apache.juneau.rest.server.staticfile.*;
074import org.apache.juneau.rest.server.util.*;
075import org.apache.juneau.bct.assertions.*;
076
077import jakarta.servlet.*;
078import jakarta.servlet.http.*;
079
080/**
081 * Represents an HTTP request for a REST resource.
082 *
083 * <p>
084 *    The {@link RestRequest} object is an extension of the <l>HttpServletRequest</l> class
085 *    with various built-in convenience methods for use in building REST interfaces.
086 *    It can be accessed by passing it as a parameter on your REST Java method:
087 * </p>
088 *
089 * <p class='bjava'>
090 *    <ja>@RestPost</ja>(...)
091 *    <jk>public</jk> Object myMethod(RestRequest <jv>req</jv>) {...}
092 * </p>
093 *
094 * <p>
095 *    The primary methods on this class are:
096 * </p>
097 * <ul class='javatree'>
098 *    <li class='jc'>{@link RestRequest}
099 *    <ul class='spaced-list'>
100 *       <li>Methods for accessing the request content:
101 *       <ul class='javatreec'>
102 *          <li class='jm'>{@link RestRequest#getContent() getContent()}
103 *          <li class='jm'>{@link RestRequest#getInputStream() getInputStream()}
104 *          <li class='jm'>{@link RestRequest#getReader() getReader()}
105 *       </ul>
106 *       <li>Methods for accessing HTTP parts:
107 *       <ul class='javatreec'>
108 *          <li class='jm'>{@link RestRequest#checkPreconditions(RestResponse) checkPreconditions(RestResponse)}
109 *          <li class='jm'>{@link RestRequest#containsFormParam(String) containsFormParam(String)}
110 *          <li class='jm'>{@link RestRequest#containsHeader(String) containsHeader(String)}
111 *          <li class='jm'>{@link RestRequest#containsQueryParam(String) containsQueryParam(String)}
112 *          <li class='jm'>{@link RestRequest#getHeader(Class) getHeader(Class)}
113 *          <li class='jm'>{@link RestRequest#getHeader(String) getHeader(String)}
114 *          <li class='jm'>{@link RestRequest#getHeaders() getHeaders()}
115 *          <li class='jm'>{@link RestRequest#getFormParam(Class) getFormParam(Class)}
116 *          <li class='jm'>{@link RestRequest#getFormParam(String) getFormParam(String)}
117 *          <li class='jm'>{@link RestRequest#getFormParams() getFormParams()}
118 *          <li class='jm'>{@link RestRequest#getPathParam(Class) getPathParam(Class)}
119 *          <li class='jm'>{@link RestRequest#getPathParam(String) getPathParam(String)}
120 *          <li class='jm'>{@link RestRequest#getPathParams() getPathParams()}
121 *          <li class='jm'>{@link RestRequest#getPathRemainder() getPathRemainder()}
122 *          <li class='jm'>{@link RestRequest#getQueryParam(Class) getQueryParam(Class)}
123 *          <li class='jm'>{@link RestRequest#getQueryParam(String) getQueryParam(String)}
124 *          <li class='jm'>{@link RestRequest#getQueryParams() getQueryParams()}
125 *          <li class='jm'>{@link RestRequest#getQueryString() getQueryString()}
126 *       </ul>
127 *       <li>Methods for localization:
128 *       <ul class='javatreec'>
129 *          <li class='jm'>{@link RestRequest#getLocale() getLocale()}
130 *          <li class='jm'>{@link RestRequest#getMessage(String,Object...) getMessage(String,Object...)}
131 *          <li class='jm'>{@link RestRequest#getMessages() getMessages()}
132 *          <li class='jm'>{@link RestRequest#getTimeZone() getTimeZone()}
133 *       </ul>
134 *       <li>Methods for accessing static files:
135 *       <ul class='javatreec'>
136 *          <li class='jm'>{@link RestRequest#getVarResolverSession() getVarResolverSession()}
137 *       </ul>
138 *       <li>Methods for assertions:
139 *       <ul class='javatreec'>
140 *          <li class='jm'>{@link RestRequest#assertContent() assertContent()}
141 *          <li class='jm'>{@link RestRequest#assertCharset() assertCharset()}
142 *          <li class='jm'>{@link RestRequest#assertFormParam(String) assertFormParam(String)}
143 *          <li class='jm'>{@link RestRequest#assertHeader(String) assertHeader(String)}
144 *          <li class='jm'>{@link RestRequest#assertQueryParam(String) assertQueryParam(String)}
145 *          <li class='jm'>{@link RestRequest#assertRequestLine() assertRequestLine()}
146 *       </ul>
147 *       <li>Other:
148 *       <ul class='javatreec'>
149 *          <li class='jm'>{@link RestRequest#getAttribute(String) getAttribute(String)}
150 *          <li class='jm'>{@link RestRequest#getAttributes() getAttributes()}
151 *          <li class='jm'>{@link RestRequest#getAuthorityPath() getAuthorityPath()}
152 *          <li class='jm'>{@link RestRequest#getMarshallingSession() getMarshallingSession()}
153 *          <li class='jm'>{@link RestRequest#getCharset() getCharset()}
154 *          <li class='jm'>{@link RestRequest#getConfig() getConfig()}
155 *          <li class='jm'>{@link RestRequest#getContext() getContext()}
156 *          <li class='jm'>{@link RestRequest#getContextPath() getContextPath()}
157 *          <li class='jm'>{@link RestRequest#getHttpServletRequest() getHttpServletRequest()}
158 *          <li class='jm'>{@link RestRequest#getMethod() getMethod()}
159 *          <li class='jm'>{@link RestRequest#getOpContext() getOpContext()}
160 *          <li class='jm'>{@link RestRequest#getOperationSwagger() getOperationSwagger()}
161 *          <li class='jm'>{@link RestRequest#getPartParserSession() getPartParserSession()}
162 *          <li class='jm'>{@link RestRequest#getPartSerializerSession() getPartSerializerSession()}
163 *          <li class='jm'>{@link RestRequest#getPathInfo() getPathInfo()}
164 *          <li class='jm'>{@link RestRequest#getProtocolVersion() getProtocolVersion()}
165 *          <li class='jm'>{@link RestRequest#getRequest(Class) getRequest(Class)}
166 *          <li class='jm'>{@link RestRequest#getRequestLine() getRequestLine()}
167 *          <li class='jm'>{@link RestRequest#getRequestURI() getRequestURI()}
168 *          <li class='jm'>{@link RestRequest#getRequestURL() getRequestURL()}
169 *          <li class='jm'>{@link RestRequest#getServletPath() getServletPath()}
170 *          <li class='jm'>{@link RestRequest#getSession() getSession()}
171 *          <li class='jm'>{@link RestRequest#getSwagger() getSwagger()}
172 *          <li class='jm'>{@link RestRequest#getUriContext() getUriContext()}
173 *          <li class='jm'>{@link RestRequest#getUriResolver() getUriResolver()}
174 *          <li class='jm'>{@link RestRequest#isDebug() isDebug()}
175 *          <li class='jm'>{@link RestRequest#isDebugMarshalling() isDebugMarshalling()}
176 *          <li class='jm'>{@link RestRequest#isPlainText() isPlainText()}
177 *          <li class='jm'>{@link RestRequest#isUserInRole(String) isUserInRole(String)}
178 *          <li class='jm'>{@link RestRequest#setAttribute(String,Object) setAttribute(String,Object)}
179 *          <li class='jm'>{@link RestRequest#setCharset(Charset) setCharset(Charset)}
180 *          <li class='jm'>{@link RestRequest#setException(Throwable) setException(Throwable)}
181 *          <li class='jm'>{@link RestRequest#setNoTrace() setNoTrace()}
182 *       </ul>
183 *    </ul>
184 * </ul>
185 *
186 */
187@SuppressWarnings({
188   "java:S3776", // checkPreconditions() walks the chained RFC 7232 If-Match/If-Unmodified-Since/If-None-Match/If-Modified-Since steps in order; splitting would obscure the precedence rules
189   "java:S6539", // Collection.toArray() usage intentional
190   "javabugs:S2259", // Null accesses are guarded by nn() checks; Sonar's flow analysis does not track nn() as a null guard
191   "rawtypes", // Collection constructed from ClassMeta.newInstance() is untyped.
192   "resource", // Streams returned to servlet container; lifecycle managed by the container
193   "unchecked", // Type erasure requires unchecked casts in REST client operations
194   "unused" // Unused parameters in HttpServletRequest overrides and helper methods
195})
196public class RestRequest extends HttpServletRequestWrapper {
197
198   /**
199    * Request-attribute name under which the per-response Content-Security-Policy nonce is cached.
200    *
201    * <p>
202    * Set by {@link RestResponse} when an emitted CSP header contains a nonce placeholder, and read by the
203    * serialization layer (to stamp the matching {@code nonce="..."} on inline {@code <script>}/{@code <style>} tags)
204    * so the header and the markup share the same nonce.
205    */
206   public static final String CSP_NONCE_ATTR = "CspNonce";
207
208   /**
209    * Returns {@code true} if {@code method} is one of the methods the {@code content} URL-parameter body
210    * override (see {@link Rest#allowContentParam()}) is documented to apply to.
211    *
212    * <p>
213    * Package-private for direct unit-test coverage. Restricting the override to {@code PUT}/{@code POST} (its
214    * documented scope all along) keeps a plain cross-origin {@code GET} &mdash; the kind a browser will issue
215    * with no preflight and no custom header for something as simple as an <code>&lt;img src=...&gt;</code> tag
216    * &mdash; from ever having its body-carrying {@code Content-Type} gate bypassed via a query string, without
217    * touching the {@link Rest#allowContentParam()} default itself.
218    *
219    * @param method The request's HTTP method. Can be {@code null} (returns {@code false}).
220    * @return {@code true} if {@code method} is {@code PUT} or {@code POST}, case-insensitively.
221    */
222   static boolean isContentParamMethod(String method) {
223      return eqic("PUT", method) || eqic("POST", method);
224   }
225
226   private static final java.util.regex.Pattern LANG_RE = java.util.regex.Pattern.compile("[A-Za-z]{2,8}");
227   private static final java.util.regex.Pattern SCRIPT_RE = java.util.regex.Pattern.compile("[A-Za-z]{4}");
228   private static final java.util.regex.Pattern REGION_RE = java.util.regex.Pattern.compile("[A-Za-z]{2}|\\d{3}");
229
230   /*
231    * Converts an Accept-Language range to a Locale.
232    * Grammar (split on '-'): language (2-8 ASCII letters), optional script (4 ASCII letters, 2nd part),
233    * optional region (LAST part; 2 ASCII letters or 3 digits).
234    * Anything else (variants, extensions, extra/empty parts, non-ASCII, '.', '/', '\\', '%', '_', '*') returns null
235    * so the range is ignored.  The script is accepted but not used (zh-Hans-CN -> zh_CN, zh-Hans -> zh).
236    */
237   @SuppressWarnings({
238      "java:S1874" // The new Locale(String,String) constructor is not deprecated on the Java 17 baseline; its replacement Locale.of(...) was only added in Java 19.
239   })
240   static Locale toLocale(String lang) {
241      if (lang == null)
242         return null;
243      var parts = lang.trim().split("-", -1);
244      if (! LANG_RE.matcher(parts[0]).matches())
245         return null;
246      var i = 1;
247      if (i < parts.length && SCRIPT_RE.matcher(parts[i]).matches())
248         i++;
249      var country = "";
250      if (i < parts.length) {
251         if (i != parts.length - 1 || ! REGION_RE.matcher(parts[i]).matches())
252            return null;
253         country = parts[i];
254      }
255      return new Locale(parts[0], country);
256   }
257
258   // Constructor initialized.
259   private final HttpServletRequest inner;
260   private final RestContext context;
261   private final RestOpContext opContext;
262   private final RequestContent content;
263   private final MarshallingSession marshallingSession;
264   private final RequestQueryParamList queryParams;
265   private final RequestPathParamList pathParams;
266   private final RequestHeaderList headers;
267   private final RequestAttributes attrs;
268   private final HttpPartParserSession partParserSession;
269
270   private final RestSession session;
271   // Lazy initialized.
272   private VarResolverSession varSession;
273   private RequestFormParamList formParams;
274   private UriContext uriContext;
275   private String authorityPath;
276   private Config config;
277   private Swagger swagger;
278
279   private Charset charset;
280   private Map<String,Object> serializerSessionProperties;
281   private Map<String,Object> parserSessionProperties;
282
283   // Framework-set resource-level authentication result; may be null.
284   private AuthResult authResult;
285
286   /**
287    * Constructor.
288    */
289   RestRequest(RestOpContext opContext, RestSession session) {
290      super(session.getRequest());
291      this.session = session;
292      this.opContext = opContext;
293
294      inner = session.getRequest();
295      context = session.getContext();
296
297      attrs = new RequestAttributes(this);
298
299      queryParams = new RequestQueryParamList(this, session.getQueryParams(), true);
300
301      headers = new RequestHeaderList(this, queryParams, false);
302
303      content = new RequestContent(this);
304
305      if (context.isAllowContentParam() && isContentParamMethod(inner.getMethod())) {
306         var b = queryParams.get("content").asString().orElse(null);
307         if (b != null) {
308            headers.set("Content-Type", UonSerializer.DEFAULT.getResponseContentType());
309            content.mediaType(MediaType.UON).parser(UonParser.DEFAULT).content(b.getBytes(UTF8));
310         }
311      }
312
313      pathParams = new RequestPathParamList(session, this, true);
314
315      marshallingSession = opContext.getMarshallingContext().getSession();
316
317      partParserSession = new LazyPartParserSession(opContext.getPartParser());
318
319      pathParams.parser(partParserSession);
320
321      // @formatter:off
322      queryParams
323         .addDefault(opContext.getDefaultRequestQueryData().getAll())
324         .parser(partParserSession);
325
326      headers
327         .addDefault(opContext.getDefaultRequestHeaders().getAll())
328         .addDefault(context.getDefaultRequestHeaders().getAll())
329         .parser(partParserSession);
330
331      content
332         .encoders(opContext.getEncoders())
333         .parsers(opContext.getParsers())
334         .maxInput(opContext.getMaxInput());
335
336      attrs
337         .addDefault(opContext.getDefaultRequestAttributes())
338         .addDefault(context.getDefaultRequestAttributes());
339      // @formatter:on
340
341      // Body-caching wrappers are installed by the two-phase debug pipeline before this object is
342      // constructed, based on the resolved logger's level. Nothing to wrap here.
343   }
344
345   /**
346    * Provides the ability to perform fluent-style assertions on the response character encoding.
347    *
348    * <h4 class='section'>Examples:</h4>
349    * <p class='bjava'>
350    *    <jc>// Validates that the response content charset is UTF-8.</jc>
351    *    <jv>request</jv>
352    *       .assertCharset().is(<js>"utf-8"</js>);
353    * </p>
354    *
355    * @return A new fluent assertion object.
356    * @throws BasicHttpException If REST call failed.
357    */
358   public FluentStringAssertion<RestRequest> assertCharset() {
359      return new FluentStringAssertion<>(getCharset().name(), this);
360   }
361
362   /**
363    * Returns a fluent assertion for the request content.
364    *
365    * <h4 class='section'>Example:</h4>
366    * <p class='bjava'>
367    *    <jc>// Validates the request content contains "foo".</jc>
368    *    <jv>request</jv>
369    *       .assertContent().asString().is(<js>"foo"</js>);
370    * </p>
371    *
372    * @return A new fluent assertion on the content, never <jk>null</jk>.
373    */
374   public FluentRequestContentAssertion<RestRequest> assertContent() {
375      return new FluentRequestContentAssertion<>(getContent(), this);
376   }
377
378   /**
379    * Returns a fluent assertion for the specified form parameter.
380    *
381    * <h4 class='section'>Example:</h4>
382    * <p class='bjava'>
383    *    <jc>// Validates the content type is JSON.</jc>
384    *    <jv>request</jv>
385    *       .assertFormParam(<js>"foo"</js>).asString().contains(<js>"bar"</js>);
386    * </p>
387    *
388    * @param name The query parameter name.
389    * @return A new fluent assertion on the parameter, never <jk>null</jk>.
390    */
391   public FluentRequestFormParamAssertion<RestRequest> assertFormParam(String name) {
392      return new FluentRequestFormParamAssertion<>(getFormParam(name), this);
393   }
394
395   /**
396    * Returns a fluent assertion for the specified header.
397    *
398    * <h4 class='section'>Example:</h4>
399    * <p class='bjava'>
400    *    <jc>// Validates the content type is JSON.</jc>
401    *    <jv>request</jv>
402    *       .assertHeader(<js>"Content-Type"</js>).asString().is(<js>"application/json"</js>);
403    * </p>
404    *
405    * @param name The header name.
406    * @return A new fluent assertion on the parameter, never <jk>null</jk>.
407    */
408   public FluentRequestHeaderAssertion<RestRequest> assertHeader(String name) {
409      return new FluentRequestHeaderAssertion<>(getHeaderParam(name), this);
410   }
411
412   /**
413    * Returns a fluent assertion for the specified query parameter.
414    *
415    * <h4 class='section'>Example:</h4>
416    * <p class='bjava'>
417    *    <jc>// Validates the content type is JSON.</jc>
418    *    <jv>request</jv>
419    *       .assertQueryParam(<js>"foo"</js>).asString().contains(<js>"bar"</js>);
420    * </p>
421    *
422    * @param name The query parameter name.
423    * @return A new fluent assertion on the parameter, never <jk>null</jk>.
424    */
425   public FluentRequestQueryParamAssertion<RestRequest> assertQueryParam(String name) {
426      return new FluentRequestQueryParamAssertion<>(getQueryParam(name), this);
427   }
428
429   /**
430    * Returns an assertion on the request line returned by {@link #getRequestLine()}.
431    *
432    * <h4 class='section'>Example:</h4>
433    * <p class='bjava'>
434    *    <jc>// Validates the request content contains "foo".</jc>
435    *    <jv>request</jv>
436    *       .assertRequestLine().protocol().minor().is(1);
437    * </p>
438    *
439    * @return A new assertion object.
440    */
441   public FluentRequestLineAssertion<RestRequest> assertRequestLine() {
442      return new FluentRequestLineAssertion<>(getRequestLine(), this);
443   }
444
445   /**
446    * Evaluates the conditional-request headers on this request against the response's currently-set
447    * <c>ETag</c> and <c>Last-Modified</c> values.
448    *
449    * <p>
450    * Implements the precondition-evaluation order defined by
451    * <a class='doclink' href='https://www.rfc-editor.org/rfc/rfc7232#section-6'>RFC 7232 §6</a>:
452    * <ol>
453    *    <li><c>If-Match</c> — strong comparison; returns <c>412 Precondition Failed</c> on mismatch.
454    *    <li><c>If-Unmodified-Since</c> — only consulted when <c>If-Match</c> is absent;
455    *       returns <c>412 Precondition Failed</c> when the response's <c>Last-Modified</c> is
456    *       strictly after the supplied date.
457    *    <li><c>If-None-Match</c> — weak comparison; returns <c>304 Not Modified</c> on match
458    *       (for safe methods, per RFC 7232 §6).
459    *    <li><c>If-Modified-Since</c> — only consulted when <c>If-None-Match</c> is absent;
460    *       returns <c>304 Not Modified</c> when the response's <c>Last-Modified</c> is at-or-before
461    *       the supplied date.
462    * </ol>
463    *
464    * <h4 class='section'>Usage:</h4>
465    *
466    * <p>
467    * Set the response's <c>ETag</c> and/or <c>Last-Modified</c> <b>first</b>, then call this method.
468    * The check reads the headers currently on the response, so any value set after the call is not
469    * considered.
470    *
471    * <p class='bjava'>
472    *    <ja>@RestGet</ja>(<js>"/{id}"</js>)
473    *    <jk>public</jk> Order get(<ja>@Path</ja> <jk>long</jk> <jv>id</jv>, RestRequest <jv>req</jv>, RestResponse <jv>res</jv>) {
474    *       <jk>var</jk> <jv>order</jv> = <jv>repo</jv>.find(<jv>id</jv>);
475    *       <jv>res</jv>.eTag(<js>"\""</js> + <jv>order</jv>.version() + <js>"\""</js>).lastModified(<jv>order</jv>.updated());
476    *       <jv>req</jv>.checkPreconditions(<jv>res</jv>).ifPresent(<jv>e</jv> -&gt; { <jk>throw</jk> <jv>e</jv>; });
477    *       <jk>return</jk> <jv>order</jv>;
478    *    }
479    * </p>
480    *
481    * <h4 class='section'>Notes:</h4><ul>
482    *    <li class='note'>Returns an {@link Optional} so the caller controls how to handle the failure
483    *       (throw inline, hand off to a logger, etc.). Both the returned <c>304</c> and <c>412</c>
484    *       failures are {@link BasicHttpException} instances, which are {@link RuntimeException}s,
485    *       so {@code ifPresent(e -&gt; { throw e; })} compiles cleanly.
486    *    <li class='note'><c>If-None-Match: *</c> matches any present <c>ETag</c>; <c>If-Match: *</c>
487    *       fails only when no <c>ETag</c> is set on the response.
488    *    <li class='note'>Per RFC 7232 §3.1, <c>If-Match</c> requires strong comparison: a weak
489    *       <c>ETag</c> on the response side never satisfies an <c>If-Match</c>.
490    *    <li class='note'>Per RFC 7232 §3.2, <c>If-None-Match</c> uses weak comparison: the weak/strong
491    *       flag is ignored when comparing tag values.
492    * </ul>
493    *
494    * <h4 class='section'>See Also:</h4><ul>
495    *    <li class='jm'>{@link RestResponse#eTag(String) RestResponse.eTag(String)}
496    *    <li class='jm'>{@link RestResponse#lastModified(Instant) RestResponse.lastModified(Instant)}
497    * </ul>
498    *
499    * @param response The response carrying the resource's current <c>ETag</c> and/or <c>Last-Modified</c>.
500    *    Must not be <jk>null</jk>.
501    * @return Empty if all preconditions pass; otherwise an {@link Optional} holding either a
502    *    <c>304 Not Modified</c> {@link BasicHttpException} (when the request's cache copy is still
503    *    fresh) or a {@link PreconditionFailed} (when an <c>If-Match</c> / <c>If-Unmodified-Since</c>
504    *    guard failed).
505    * @throws IllegalArgumentException If {@code response} is <jk>null</jk>.
506    */
507   public Optional<BasicHttpException> checkPreconditions(RestResponse response) {
508      reqnn("response", response);
509      var resTagStr = response.getHeader(ETag.NAME);
510      var resTag = nn(resTagStr) ? EntityTag.of(resTagStr) : null;
511      var resLastModStr = response.getHeader(LastModified.NAME);
512      var resLastMod = nn(resLastModStr) ? parseHttpDate(resLastModStr) : null;
513
514      // RFC 7232 §6 step 1: If-Match (strong comparison; 412 on failure).
515      var ifMatch = getHeaderParam(IfMatch.NAME).orElse(null);
516      if (nn(ifMatch)) {
517         if (! matchesAnyStrong(EntityTags.of(ifMatch), resTag))
518            return o(preconditionFailed(IfMatch.NAME));
519      } else {
520         // RFC 7232 §6 step 2: If-Unmodified-Since (only when If-Match absent).
521         var ius = getHeaderParam(IfUnmodifiedSince.NAME).orElse(null);
522         if (nn(ius)) {
523            var iusDate = parseHttpDate(ius);
524            if (nn(iusDate) && nn(resLastMod) && resLastMod.toInstant().isAfter(iusDate.toInstant()))
525               return o(preconditionFailed(IfUnmodifiedSince.NAME));
526         }
527      }
528
529      // RFC 7232 §6 step 3: If-None-Match (weak comparison; 304 on match for safe methods).
530      var ifNoneMatch = getHeaderParam(IfNoneMatch.NAME).orElse(null);
531      if (nn(ifNoneMatch)) {
532         if (matchesAnyWeak(EntityTags.of(ifNoneMatch), resTag))
533            return o(notModified());
534      } else {
535         // RFC 7232 §6 step 4: If-Modified-Since (only when If-None-Match absent; only for GET/HEAD).
536         if (isSafeMethod()) {
537            var ims = getHeaderParam(IfModifiedSince.NAME).orElse(null);
538            if (nn(ims)) {
539               var imsDate = parseHttpDate(ims);
540               if (nn(imsDate) && nn(resLastMod) && ! resLastMod.toInstant().isAfter(imsDate.toInstant()))
541                  return o(notModified());
542            }
543         }
544      }
545
546      return oe();
547   }
548
549   private boolean isSafeMethod() {
550      var m = getMethod();
551      return eqic("GET", m) || eqic("HEAD", m);
552   }
553
554   private static ZonedDateTime parseHttpDate(String value) {
555      try {
556         return ZonedDateTime.from(RFC_1123_DATE_TIME.parse(value)).truncatedTo(ChronoUnit.SECONDS);
557      } catch (@SuppressWarnings("unused") DateTimeParseException e) {
558         return null;
559      }
560   }
561
562   private static boolean matchesAnyStrong(EntityTags clientTags, EntityTag resTag) {
563      if (clientTags == null)
564         return false;
565      for (var t : clientTags.toArray()) {
566         if (t.isAny())
567            return resTag != null;
568         // Strong comparison: both sides must be strong AND opaque-tag values must be equal.
569         if (! t.isWeak() && resTag != null && ! resTag.isWeak() && eq(t.getEntityValue(), resTag.getEntityValue()))
570            return true;
571      }
572      return false;
573   }
574
575   private static boolean matchesAnyWeak(EntityTags clientTags, EntityTag resTag) {
576      if (clientTags == null)
577         return false;
578      for (var t : clientTags.toArray()) {
579         if (t.isAny())
580            return resTag != null;
581         // Weak comparison: opaque-tag values must be equal; weak/strong flag is ignored.
582         if (resTag != null && eq(t.getEntityValue(), resTag.getEntityValue()))
583            return true;
584      }
585      return false;
586   }
587
588   private static BasicHttpException notModified() {
589      return new BasicHttpException(NotModified.STATUS_CODE, NotModified.REASON_PHRASE);
590   }
591
592   private static PreconditionFailed preconditionFailed(String headerName) {
593      return new PreconditionFailed("Precondition '%s' failed.", headerName);
594   }
595
596   /**
597    * Returns <jk>true</jk> if this request contains the specified header.
598    *
599    * @param name The header name.
600    * @return <jk>true</jk> if this request contains the specified header.
601    */
602   public boolean containsFormParam(String name) {
603      return getFormParams().contains(name);
604   }
605
606   /**
607    * Returns <jk>true</jk> if this request contains the specified header.
608    *
609    * @param name The header name.
610    * @return <jk>true</jk> if this request contains the specified header.
611    */
612   public boolean containsHeader(String name) {
613      return headers.contains(name);
614   }
615
616   /**
617    * Returns <jk>true</jk> if this request contains the specified header.
618    *
619    * @param name The header name.
620    * @return <jk>true</jk> if this request contains the specified header.
621    */
622   public boolean containsQueryParam(String name) {
623      return queryParams.contains(name);
624   }
625
626   /**
627    * Returns the request attribute with the specified name.
628    *
629    * @param name The attribute name.
630    * @return The attribute value, never <jk>null</jk>.
631    */
632   @Override
633   public RequestAttribute getAttribute(String name) {
634      return attrs.get(name);
635   }
636
637   /**
638    * Request attributes.
639    *
640    * <p>
641    * Returns a {@link RequestAttributes} object that encapsulates access to attributes on the request.
642    *
643    * <h4 class='section'>Example:</h4>
644    * <p class='bjava'>
645    *    <ja>@RestPost</ja>(...)
646    *    <jk>public</jk> Object myMethod(RestRequest <jv>req</jv>) {
647    *
648    *       <jc>// Get access to attributes.</jc>
649    *       RequestAttributes <jv>attributes</jv> = <jv>req</jv>.getAttributes();
650    *
651    *    <jc>// Get a header value as a POJO.</jc>
652    *       UUID <jv>etag</jv> = <jv>attributes</jv>.get(<js>"ETag"</js>, UUID.<jk>class</jk>);
653    *    }
654    * </p>
655    *
656    * <h4 class='section'>Notes:</h4><ul>
657    *    <li class='note'>
658    *       This object is modifiable.
659    *    <li class='note'>
660    *       Values are converted from strings using the registered part parser on the resource class.
661    *    <li class='note'>
662    *       The {@link RequestAttributes} object can also be passed as a parameter on the method.
663    *    <li class='note'>
664    *       The {@link Attr @Attr} annotation can be used to access individual attribute values.
665    * </ul>
666    *
667    * <h4 class='section'>See Also:</h4><ul>
668    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
669    * </ul>
670    *
671    * @return
672    *    The headers on this request.
673    *    <br>Never <jk>null</jk>.
674    */
675   public RequestAttributes getAttributes() { return attrs; }
676
677   /**
678    * Returns the URI authority portion of the request.
679    *
680    * @return The URI authority portion of the request.
681    */
682   public String getAuthorityPath() {
683      if (authorityPath == null)
684         authorityPath = context.getUriAuthority();
685      if (authorityPath == null) {
686         var scheme = inner.getScheme();
687         var port = inner.getServerPort();
688         var sb = new StringBuilder(inner.getScheme()).append("://").append(inner.getServerName());
689         if (! (port == 80 && eq(scheme, "http") || port == 443 && eq(scheme, "https")))
690            sb.append(':').append(port);
691         authorityPath = sb.toString();
692      }
693      return authorityPath;
694   }
695
696   /**
697    * Returns the {@link MarshallingSession} associated with this request.
698    *
699    * @return The request bean session.
700    */
701   public MarshallingSession getMarshallingSession() { return marshallingSession; }
702
703   /**
704    * Returns the charset specified on the <c>Content-Type</c> header, or <js>"UTF-8"</js> if not specified.
705    *
706    * @return The charset to use to decode the request content.
707    */
708   public Charset getCharset() {
709      if (charset == null) {
710         // Determine charset
711         // NOTE:  Don't use super.getCharacterEncoding() because the spec is implemented inconsistently.
712         // Jetty returns the default charset instead of null if the character is not specified on the request.
713         var h = getHeaderParam("Content-Type").orElse(null);
714         if (nn(h)) {
715            var i = h.indexOf(";charset=");
716            if (i > 0)
717               charset = Charset.forName(h.substring(i + 9).trim());
718         }
719         if (charset == null)
720            charset = opContext.getDefaultCharset();
721         if (charset == null)
722            charset = StandardCharsets.UTF_8;
723      }
724      return charset;
725   }
726
727   /**
728    * Config file associated with the resource.
729    *
730    * <p>
731    * Returns a config file with session-level variable resolution.
732    *
733    * The config file is identified via {@link Rest#config()}.
734    *
735    * <h4 class='section'>Example:</h4>
736    * <p class='bjava'>
737    *    <ja>@RestGet</ja>(...)
738    *    <jk>public void</jk> doGet(RestRequest <jv>req</jv>) {
739    *
740    *       <jc>// Get config file.</jc>
741    *       Config <jv>config</jv> = <jv>req</jv>.getConfig();
742    *
743    *       <jc>// Get simple values from config file.</jc>
744    *       <jk>int</jk> <jv>timeout</jv> = <jv>config</jv>.get(<js>"MyResource/timeout"</js>).asInteger().orElse(=10000);
745    *
746    *       <jc>// Get complex values from config file.</jc>
747    *       MyBean <jv>bean</jv> = <jv>config</jv>.get(<js>"MyResource/myBean"</js>).as(MyBean.<jk>class</jk>).orElse(<jk>null</jk>);
748    *    }
749    * </p>
750    *
751    * <h4 class='section'>Notes:</h4><ul>
752    *    <li class='note'>
753    *       The {@link Config} object can also be passed as a parameter on the method.
754    * </ul>
755    *
756    * <h4 class='section'>See Also:</h4><ul>
757    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ConfigurationFiles">Configuration Files</a>
758    * </ul>
759    *
760    * @return
761    *    The config file associated with the resource, or <jk>null</jk> if resource does not have a config file
762    *    associated with it.
763    */
764   public Config getConfig() {
765      if (config == null)
766         config = context.getConfig().resolving(getVarResolverSession());
767      return config;
768   }
769
770   /**
771    * Request content.
772    *
773    * <p>
774    * Returns a {@link RequestContent} object that encapsulates access to the HTTP request content.
775    *
776    * <h4 class='section'>Example:</h4>
777    * <p class='bjava'>
778    *    <ja>@RestPost</ja>(...)
779    *    <jk>public void</jk> doPost(RestRequest <jv>req</jv>) {
780    *
781    *       <jc>// Convert content to a linked list of Person objects.</jc>
782    *       List&lt;Person&gt; <jv>list</jv> = <jv>req</jv>.getContent().as(LinkedList.<jk>class</jk>, Person.<jk>class</jk>);
783    *       ..
784    *    }
785    * </p>
786    *
787    * <h4 class='section'>Notes:</h4><ul>
788    *    <li class='note'>
789    *       The {@link RequestContent} object can also be passed as a parameter on the method.
790    *    <li class='note'>
791    *       The {@link Content @Content} annotation can be used to access the content as well.
792    * </ul>
793    *
794    * <h4 class='section'>See Also:</h4><ul>
795    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
796    * </ul>
797    *
798    * @return
799    *    The content of this HTTP request.
800    *    <br>Never <jk>null</jk>.
801    */
802   public RequestContent getContent() { return content; }
803
804   /**
805    * Returns the resource context handling the request.
806    *
807    * <p>
808    * Can be used to access servlet-init parameters or annotations during requests, such as in calls to
809    * {@link RestGuard#guard(RestRequest, RestResponse)}..
810    *
811    * @return The resource context handling the request.
812    */
813   public RestContext getContext() { return context; }
814
815   /**
816    * Returns the correlation id resolved for this request (mint-or-honor), cached at session-build time.
817    *
818    * <p>
819    * Delegates to {@link RestSession#getRequestId()} &mdash; the synchronous, session-cached value, never a live
820    * public/custom-key attribute re-read.  This is the {@code X-Request-Id} correlation id echoed on the response and
821    * carried in the {@code requestId} log-context field.
822    *
823    * @return The resolved request id.  Never <jk>null</jk> (unless a custom id supplier returned <jk>null</jk>).
824    * @since 10.0.0
825    */
826   @Override /* Overridden from ServletRequest (jakarta.servlet-api 6.1+ default method) */
827   public String getRequestId() { return session.getRequestId(); }
828
829   /**
830    * Returns the portion of the request URI that indicates the context of the request.
831    *
832    * <p>The context path always comes first in a request URI.
833    * The path starts with a <js>"/"</js> character but does not end with a <js>"/"</js> character.
834    * For servlets in the default (root) context, this method returns <js>""</js>.
835    * The container does not decode this string.
836    *
837    * @return The context path, never <jk>null</jk>.
838    * @see HttpServletRequest#getContextPath()
839    */
840   @Override
841   public String getContextPath() {
842      var cp = context.getUriContext();
843      return cp == null ? inner.getContextPath() : cp;
844   }
845
846   /**
847    * Returns the request form-data parameter of the specified type.
848    *
849    * <p>
850    * Type must have a name specified via the {@link FormData} annotation
851    * and a public constructor that takes in either <c>value</c> or <c>name,value</c> as strings.
852    *
853    * @param <T> The bean type to create.
854    * @param type The bean type to create.
855    * @return The parsed form-data parameter on the request, never <jk>null</jk>.
856    */
857   public <T> Optional<T> getFormParam(Class<T> type) {
858      return getFormParams().get(type);
859   }
860
861   /**
862    * Shortcut for calling <c>getFormParams().get(name)</c>.
863    *
864    * @param name The form data parameter name.
865    * @return The form data parameter, never <jk>null</jk>.
866    */
867   public RequestFormParam getFormParam(String name) {
868      return getFormParams().get(name);
869   }
870
871   /**
872    * Form-data.
873    *
874    * <p>
875    * Returns a {@link RequestFormParamList} object that encapsulates access to form post parameters.
876    *
877    * <p>
878    * Similar to {@link HttpServletRequest#getParameterMap()}, but only looks for form data in the HTTP content.
879    *
880    * <h4 class='section'>Example:</h4>
881    * <p class='bjava'>
882    *    <ja>@RestPost</ja>(...)
883    *    <jk>public void</jk> doPost(RestRequest <jv>req</jv>) {
884    *
885    *       <jc>// Get access to parsed form data parameters.</jc>
886    *       RequestFormParamList <jv>formParams</jv> = <jv>req</jv>.getFormParams();
887    *
888    *       <jc>// Get form data parameters converted to various types.</jc>
889    *       <jk>int</jk> <jv>p1</jv> = <jv>formParams</jv>.get(<js>"p1"</js>).asInteger().orElse(0);
890    *       String <jv>p2</jv> = <jv>formParams</jv>.get(<js>"p2"</js>).asString().orElse(<jk>null</jk>);
891    *       UUID <jv>p3</jv> = <jv>formParams</jv>.get(<js>"p3"</js>).as(UUID.<jk>class</jk>).orElse(<jk>null</jk>);
892    *    }
893    * </p>
894    *
895    * <h4 class='section'>Notes:</h4><ul>
896    *    <li class='note'>
897    *       This object is modifiable.
898    *    <li class='note'>
899    *       Values are converted from strings using the registered part parser on the resource class.
900    *    <li class='note'>
901    *       The {@link RequestFormParamList} object can also be passed as a parameter on the method.
902    *    <li class='note'>
903    *       The {@link FormData @FormDAta} annotation can be used to access individual form data parameter values.
904    * </ul>
905    *
906    * <h4 class='section'>See Also:</h4><ul>
907    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
908    * </ul>
909    *
910    * @return
911    *    The URL-encoded form data from the request.
912    *    <br>Never <jk>null</jk>.
913    * @throws InternalServerError If query parameters could not be parsed.
914    * @see FormData
915    */
916   public RequestFormParamList getFormParams() throws InternalServerError {
917      try {
918         if (formParams == null)
919            formParams = new RequestFormParamList(this, true).parser(partParserSession);
920         formParams.addDefault(opContext.getDefaultRequestFormData().getAll());
921         return formParams;
922      } catch (Exception e) {
923         throw new InternalServerError(e);
924      }
925   }
926
927   /**
928    * Returns the request header of the specified type.
929    *
930    * <p>
931    * Type must have a name specified via the {@link Header} annotation
932    * and a public constructor that takes in either <c>value</c> or <c>name,value</c> as strings.
933    *
934    * <p>
935    * Typically any of the following:
936    * <ul class='javatreec'>
937    *    <li class='jc'>{@link Accept}
938    *    <li class='jc'>{@link AcceptCharset}
939    *    <li class='jc'>{@link AcceptEncoding}
940    *    <li class='jc'>{@link AcceptLanguage}
941    *    <li class='jc'>{@link AcceptRanges}
942    *    <li class='jc'>{@link Authorization}
943    *    <li class='jc'>{@link CacheControl}
944    *    <li class='jc'>{@link ClientVersion}
945    *    <li class='jc'>{@link Connection}
946    *    <li class='jc'>{@link ContentDisposition}
947    *    <li class='jc'>{@link ContentEncoding}
948    *    <li class='jc'>{@link ContentLength}
949    *    <li class='jc'>{@link ContentType}
950    *    <li class='jc'>{@link Date}
951    *    <li class='jc'>{@link Debug}
952    *    <li class='jc'>{@link Expect}
953    *    <li class='jc'>{@link Forwarded}
954    *    <li class='jc'>{@link From}
955    *    <li class='jc'>{@link Host}
956    *    <li class='jc'>{@link IfMatch}
957    *    <li class='jc'>{@link IfModifiedSince}
958    *    <li class='jc'>{@link IfNoneMatch}
959    *    <li class='jc'>{@link IfRange}
960    *    <li class='jc'>{@link IfUnmodifiedSince}
961    *    <li class='jc'>{@link MaxForwards}
962    *    <li class='jc'>{@link NoTrace}
963    *    <li class='jc'>{@link Origin}
964    *    <li class='jc'>{@link Pragma}
965    *    <li class='jc'>{@link ProxyAuthorization}
966    *    <li class='jc'>{@link Range}
967    *    <li class='jc'>{@link Referer}
968    *    <li class='jc'>{@link TE}
969    *    <li class='jc'>{@link Thrown}
970    *    <li class='jc'>{@link Upgrade}
971    *    <li class='jc'>{@link UserAgent}
972    *    <li class='jc'>{@link Warning}
973    * </ul>
974    *
975    * @param <T> The bean type to create.
976    * @param type The bean type to create.
977    * @return The parsed header on the request, never <jk>null</jk>.
978    */
979   public <T> Optional<T> getHeader(Class<T> type) {
980      return headers.get(type);
981   }
982
983   /**
984    * Returns the last header with a specified name of this message.
985    *
986    * <p>
987    * If there is more than one matching header in the message the last element of <c>getHeaders(String)</c> is returned.
988    * <br>If there is no matching header in the message, an empty request header object is returned.
989    *
990    * <h4 class='section'>Example:</h4>
991    * <p class='bjava'>
992    *    <jc>// Gets a header and throws a BadRequest if it doesn't exist.</jc>
993    *    <jv>request</jv>
994    *       .getHeader(<js>"Foo"</js>)
995    *       .assertValue().exists()
996    *       .get();
997    * </p>
998    *
999    * @param name The header name.
1000    * @return The request header object, never <jk>null</jk>.
1001    */
1002   public RequestHeader getHeaderParam(String name) {
1003      return headers.getLast(name);
1004   }
1005
1006   /**
1007    * Request headers.
1008    *
1009    * <p>
1010    * Returns a {@link RequestHeaderList} object that encapsulates access to HTTP headers on the request.
1011    *
1012    * <h4 class='section'>Example:</h4>
1013    * <p class='bjava'>
1014    *    <ja>@RestPost</ja>(...)
1015    *    <jk>public</jk> Object myMethod(RestRequest <jv>req</jv>) {
1016    *
1017    *       <jc>// Get access to headers.</jc>
1018    *       RequestHeaderList <jv>headers</jv> = <jv>req</jv>.getRequestHeaders();
1019    *
1020    *       <jc>// Add a default value.</jc>
1021    *       <jv>headers</jv>.addDefault(<js>"ETag"</js>, <jsf>DEFAULT_UUID</jsf>);
1022    *
1023    *    <jc>// Get a header value as a POJO.</jc>
1024    *       UUID etag = <jv>headers</jv>.get(<js>"ETag"</js>).as(UUID.<jk>class</jk>).orElse(<jk>null</jk>);
1025    *
1026    *       <jc>// Get a standard header.</jc>
1027    *       Optional&lt;CacheControl&gt; = <jv>headers</jv>.getCacheControl();
1028    *    }
1029    * </p>
1030    *
1031    * <h4 class='section'>Notes:</h4><ul>
1032    *    <li class='note'>
1033    *       This object is modifiable.
1034    *    <li class='note'>
1035    *       Values are converted from strings using the registered part parser on the resource class.
1036    *    <li class='note'>
1037    *       The {@link RequestHeaderList} object can also be passed as a parameter on the method.
1038    *    <li class='note'>
1039    *       The {@link Header @Header} annotation can be used to access individual header values.
1040    * </ul>
1041    *
1042    * <h4 class='section'>See Also:</h4><ul>
1043    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
1044    * </ul>
1045    *
1046    * @return
1047    *    The headers on this request.
1048    *    <br>Never <jk>null</jk>.
1049    */
1050   public RequestHeaderList getHeaders() { return headers; }
1051
1052   /**
1053    * Returns the wrapped servlet request.
1054    *
1055    * @return The wrapped servlet request.
1056    */
1057   public HttpServletRequest getHttpServletRequest() { return inner; }
1058
1059   /**
1060    * Returns the HTTP content content as an {@link InputStream}.
1061    *
1062    * <p>
1063    * Automatically handles GZipped input streams.
1064    *
1065    * <p>
1066    * This method is equivalent to calling <c>getContent().getInputStream()</c>.
1067    *
1068    * @return The negotiated input stream.
1069    * @throws IOException If any error occurred while trying to get the input stream or wrap it in the GZIP wrapper.
1070    */
1071   @Override
1072   public ServletInputStream getInputStream() throws IOException { return getContent().getInputStream(); }
1073
1074   /**
1075    * Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
1076    *
1077    * <p>
1078    * If the client request doesn't provide an <c>Accept-Language</c> header, this method returns the default locale for the server.
1079    *
1080    * @return The preferred Locale that the client will accept content in.  Never <jk>null</jk>.
1081    */
1082   @Override
1083   public Locale getLocale() {
1084      var best = inner.getLocale();
1085      var h = headers.get("Accept-Language").asString().orElse(null);
1086      if (nn(h)) {
1087         var sr = StringRanges.of(h);
1088         float qValue = 0;
1089         for (var r : sr.toList()) {
1090            if (r.getQValue() > qValue) {
1091               var l = toLocale(r.getName());
1092               if (nn(l)) {
1093                  best = l;
1094                  qValue = r.getQValue();
1095               }
1096            }
1097         }
1098      }
1099      return best;
1100   }
1101
1102   /**
1103    * Shortcut method for calling {@link RestRequest#getMessages()} and {@link Messages#getString(String,Object...)}.
1104    *
1105    * @param key The message key.
1106    * @param args Optional {@link MessageFormat}-style arguments.
1107    * @return The localized message.
1108    */
1109   public String getMessage(String key, Object...args) {
1110      return getMessages().getString(key, args);
1111   }
1112
1113   /**
1114    * Returns the resource bundle for the request locale.
1115    *
1116    * <h4 class='section'>Example:</h4>
1117    * <p class='bjava'>
1118    *    <ja>@RestGet</ja>
1119    *    <jk>public</jk> String hello(RestRequest <jv>req</jv>, <ja>@Query</ja>(<js>"user"</js>) String <jv>user</jv>) {
1120    *
1121    *       <jc>// Return a localized message.</jc>
1122    *       <jk>return</jk> <jv>req</jv>.getMessages().getString(<js>"hello.message"</js>, <jv>user</jv>);
1123    *    }
1124    * </p>
1125    *
1126    * <h4 class='section'>Notes:</h4><ul>
1127    *    <li class='note'>
1128    *       The {@link Messages} object can also be passed as a parameter on the method.
1129    * </ul>
1130    *
1131    * <h4 class='section'>See Also:</h4><ul>
1132    *    <li class='jm'>{@link RestRequest#getMessage(String,Object...)}
1133    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/LocalizedMessages">Localized Messages</a>
1134    * </ul>
1135    *
1136    * @return
1137    *    The resource bundle.
1138    *    <br>Never <jk>null</jk>.
1139    */
1140   public Messages getMessages() { return context.getMessages().forLocale(getLocale()); }
1141
1142   /**
1143    * Returns the HTTP method of this request.
1144    *
1145    * <p>
1146    * If <c>allowHeaderParams</c> init parameter is <jk>true</jk>, then first looks for
1147    * <c>&amp;method=xxx</c> in the URL query string.
1148    *
1149    * @return The HTTP method of this request.
1150    */
1151   @Override
1152   public String getMethod() { return session.getMethod(); }
1153
1154   /**
1155    * Returns access to the inner {@link RestOpContext} of this method.
1156    *
1157    * @return The {@link RestOpContext} of this method.  May be <jk>null</jk> if method has not yet been found.
1158    */
1159   public RestOpContext getOpContext() { return opContext; }
1160
1161   /**
1162    * Returns the swagger for the Java method invoked.
1163    *
1164    * @return The swagger for the Java method as an {@link Optional}.  Never <jk>null</jk>.
1165    */
1166   public Optional<Operation> getOperationSwagger() {
1167
1168      var swagger2 = getSwagger();
1169      if (! swagger2.isPresent())
1170         return oe();
1171
1172      return o(swagger2.get().getOperation(opContext.getPathPattern(), lcr(getMethod())));
1173   }
1174
1175   /**
1176    * Returns the part parser session associated with this request.
1177    *
1178    * @return The part parser session associated with this request.
1179    */
1180   public HttpPartParserSession getPartParserSession() { return partParserSession; }
1181
1182   /**
1183    * Returns the part serializer session for this request.
1184    *
1185    * @return The part serializer session for this request.
1186    */
1187   public HttpPartSerializerSession getPartSerializerSession() { return opContext.getPartSerializer().getPartSession(); }
1188
1189   /**
1190    * Returns the request path parameter of the specified type.
1191    *
1192    * <p>
1193    * Type must have a name specified via the {@link Path} annotation
1194    * and a public constructor that takes in either <c>value</c> or <c>name,value</c> as strings.
1195    *
1196    * @param <T> The bean type to create.
1197    * @param type The bean type to create.
1198    * @return The parsed path parameter on the request, never <jk>null</jk>.
1199    */
1200   public <T> Optional<T> getPathParam(Class<T> type) {
1201      return pathParams.get(type);
1202   }
1203
1204   /**
1205    * Shortcut for calling <c>getPathParams().get(<jv>name</jv>)</c>.
1206    *
1207    * @param name The path parameter name.
1208    * @return The path parameter, never <jk>null</jk>.
1209    */
1210   public RequestPathParam getPathParam(String name) {
1211      return pathParams.get(name);
1212   }
1213
1214   /**
1215    * Path parameters.
1216    *
1217    * <p>
1218    * Returns a {@link RequestPathParamList} object that encapsulates access to URL path parameters.
1219    *
1220    * <h4 class='section'>Example:</h4>
1221    * <p class='bjava'>
1222    *    <ja>@RestGet</ja>(<js>"/{foo}/{bar}/{baz}/*"</js>)
1223    *    <jk>public void</jk> doGet(RestRequest <jv>req</jv>) {
1224    *
1225    *       <jc>// Get access to path data.</jc>
1226    *       RequestPathParamList <jv>pathParams</jv> = <jv>req</jv>.getPathParams();
1227    *
1228    *       <jc>// Example URL:  /123/qux/true/quux</jc>
1229    *
1230    *       <jk>int</jk> <jv>foo</jv> = <jv>pathParams</jv>.get(<js>"foo"</js>).asInteger().orElse(-1);  <jc>// =123</jc>
1231    *       String <jv>bar</jv> = <jv>pathParams</jv>.get(<js>"bar"</js>).orElse(<jk>null</jk>);  <jc>// =qux</jc>
1232    *       <jk>boolean</jk> <jv>baz</jv> = <jv>pathParams</jv>.get(<js>"baz"</js>).asBoolean().orElse(<jk>false</jk>);  <jc>// =true</jc>
1233    *       String <jv>remainder</jv> = <jv>pathParams</jv>.getRemainder().orElse(<jk>null</jk>);  <jc>// =quux</jc>
1234    *    }
1235    * </p>
1236    *
1237    * <h4 class='section'>Notes:</h4><ul>
1238    *    <li class='note'>
1239    *       This object is modifiable.
1240    * </ul>
1241    *
1242    * @return
1243    *    The path parameters.
1244    *    <br>Never <jk>null</jk>.
1245    */
1246   public RequestPathParamList getPathParams() { return pathParams; }
1247
1248   /**
1249    * Shortcut for calling <c>getPathParams().getRemainder()</c>.
1250    *
1251    * @return The path remainder value, never <jk>null</jk>.
1252    */
1253   public RequestPathParam getPathRemainder() { return pathParams.getRemainder(); }
1254
1255   /**
1256    * Returns the protocol version from the request line of this request.
1257    *
1258    * @return The protocol version from the request line of this request.
1259    */
1260   public HttpProtocolVersion getProtocolVersion() { return getRequestLine().getProtocolVersion(); }
1261
1262   /**
1263    * Returns the request query parameter of the specified type.
1264    *
1265    * <p>
1266    * Type must have a name specified via the {@link Query} annotation
1267    * and a public constructor that takes in either <c>value</c> or <c>name,value</c> as strings.
1268    *
1269    * @param <T> The bean type to create.
1270    * @param type The bean type to create.
1271    * @return The parsed query parameter on the request, never <jk>null</jk>.
1272    */
1273   public <T> Optional<T> getQueryParam(Class<T> type) {
1274      return queryParams.get(type);
1275   }
1276
1277   /**
1278    * Shortcut for calling <c>getRequestQuery().getLast(<jv>name</jv>)</c>.
1279    *
1280    * @param name The query parameter name.
1281    * @return The query parameter, never <jk>null</jk>.
1282    */
1283   public RequestQueryParam getQueryParam(String name) {
1284      return queryParams.get(name);
1285   }
1286
1287   /**
1288    * Query parameters.
1289    *
1290    * <p>
1291    * Returns a {@link RequestQueryParamList} object that encapsulates access to URL GET parameters.
1292    *
1293    * <p>
1294    * Similar to {@link HttpServletRequest#getParameterMap()} but only looks for query parameters in the URL and not form posts.
1295    *
1296    * <h4 class='section'>Example:</h4>
1297    * <p class='bjava'>
1298    *    <ja>@RestGet</ja>(...)
1299    *    <jk>public void</jk> doGet(RestRequest <jv>req</jv>) {
1300    *
1301    *       <jc>// Get access to query parameters on the URL.</jc>
1302    *       RequestQueryParamList <jv>query</jv> = <jv>req</jv>.getQuery();
1303    *
1304    *       <jc>// Get query parameters converted to various types.</jc>
1305    *       <jk>int</jk> <jv>p1/</jv> = <jv>query</jv>.getInteger(<js>"p1"</js>).orElse(<jk>null</jk>);
1306    *       String <jv>p2</jv> = <jv>query</jv>.getString(<js>"p2"</js>).orElse(<jk>null</jk>);
1307    *       UUID <jv>p3</jv> = <jv>query</jv>.get(<js>"p3"</js>).as(UUID.<jk>class</jk>).orElse(<jk>null</jk>);
1308    *    }
1309    * </p>
1310    *
1311    * <h4 class='section'>Notes:</h4><ul>
1312    *    <li class='note'>
1313    *       This object is modifiable.
1314    * </ul>
1315    *
1316    * <h4 class='section'>See Also:</h4><ul>
1317    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
1318    * </ul>
1319    *
1320    * @return
1321    *    The query parameters as a modifiable map.
1322    *    <br>Never <jk>null</jk>.
1323    */
1324   public RequestQueryParamList getQueryParams() { return queryParams; }
1325
1326   /**
1327    * Returns the HTTP content content as a {@link Reader}.
1328    *
1329    * <p>
1330    * If {@code allowHeaderParams} init parameter is true, then first looks for {@code &content=xxx} in the URL query
1331    * string.
1332    *
1333    * <p>
1334    * Automatically handles GZipped input streams.
1335    *
1336    * <p>
1337    * This method is equivalent to calling <c>getContent().getReader()</c>.
1338    *
1339    * @return The HTTP content content as a {@link Reader}.
1340    * @throws IOException If content could not be read.
1341    */
1342   @Override
1343   public BufferedReader getReader() throws IOException { return getContent().getReader(); }
1344
1345   /**
1346    * Creates a proxy interface to retrieve HTTP parts of this request as a proxy bean.
1347    *
1348    * <h4 class='section'>Examples:</h4>
1349    * <p class='bjava'>
1350    *    <ja>@RestPost</ja>(<js>"/mypath/{p1}/{p2}/*"</js>)
1351    *    <jk>public void</jk> myMethod(<ja>@Request</ja> MyRequest <jv>requestBean</jv>) {...}
1352    *
1353    *    <jk>public interface</jk> MyRequest {
1354    *
1355    *       <ja>@Path</ja> <jc>// Path variable name inferred from getter.</jc>
1356    *       String getP1();
1357    *
1358    *       <ja>@Path</ja>(<js>"p2"</js>)
1359    *       String getX();
1360    *
1361    *       <ja>@Path</ja>(<js>"/*"</js>)
1362    *       String getRemainder();
1363    *
1364    *       <ja>@Query</ja>
1365    *       String getQ1();
1366    *
1367    *    <jc>// Schema-based query parameter:  Pipe-delimited lists of comma-delimited lists of integers.</jc>
1368    *       <ja>@Query</ja>(
1369    *          collectionFormat=<js>"pipes"</js>
1370    *          items=<ja>@Items</ja>(
1371    *             items=<ja>@SubItems</ja>(
1372    *                collectionFormat=<js>"csv"</js>
1373    *                type=<js>"integer"</js>
1374    *             )
1375    *          )
1376    *       )
1377    *       <jk>int</jk>[][] getQ3();
1378    *
1379    *       <ja>@Header</ja>(<js>"*"</js>)
1380    *       Map&lt;String,Object&gt; getHeaders();
1381    * </p>
1382    *
1383    * @param <T> The request bean interface to instantiate.
1384    * @param c The request bean interface to instantiate.
1385    * @return A new request bean proxy for this REST request.
1386    */
1387   public <T> T getRequest(Class<T> c) {
1388      return getRequest(RequestBeanMeta.create(c, getContext().getAnnotations()));
1389   }
1390
1391   /**
1392    * Same as {@link #getRequest(Class)} but used on pre-instantiated {@link RequestBeanMeta} objects.
1393    *
1394    * @param <T> The request bean interface to instantiate.
1395    * @param rbm The metadata about the request bean interface to create.
1396    *    <br>Must not be <jk>null</jk>.
1397    * @return A new request bean proxy for this REST request.
1398    */
1399   public <T> T getRequest(RequestBeanMeta rbm) {
1400      return getRequest(rbm, null);
1401   }
1402
1403   /**
1404    * Same as {@link #getRequest(RequestBeanMeta)}, but reuses setters already resolved when the {@code @RestOp}'s
1405    * arguments were built instead of resolving them on this call.
1406    *
1407    * @param <T> The request bean interface to instantiate.
1408    * @param rbm The metadata about the request bean interface to create.
1409    *    <br>Must not be <jk>null</jk>.
1410    * @param setters
1411    *    The pre-resolved constructor/setters for a concrete bean class, or <jk>null</jk> to resolve them on this call
1412    *    (callers such as {@code Queryable} that only have a {@link Class}, not a registered {@link RequestBeanArg}).
1413    *    Resolving here throws the same {@link IllegalArgumentException} message as {@link RequestBeanArg},
1414    *    wrapped the same way as any other exception from this method.
1415    * @return A new request bean proxy or instance for this REST request.
1416    */
1417   public <T> T getRequest(RequestBeanMeta rbm, RequestBeanSetters setters) {
1418      try {
1419         var c = (Class<T>)rbm.getBeanInfo().inner();
1420         final MarshallingSession bs = getMarshallingSession();
1421         if (c.isInterface())
1422            return (T)Proxy.newProxyInstance(c.getClassLoader(), a(c), (InvocationHandler)(proxy, method, args) -> {
1423               RequestBeanPropertyMeta pm = rbm.getProperty(method.getName());
1424               if (nn(pm))
1425                  return resolveRequestBeanProperty(pm, method, bs);
1426               return null;
1427            });
1428         return newRequestBean(rbm, bs, nn(setters) ? setters : RequestBeanSetters.resolve(c, rbm));
1429      } catch (Exception e) {
1430         throw toRex(e);
1431      }
1432   }
1433
1434   /**
1435    * Instantiates a concrete {@link Request @Request} bean class via the resolved {@link RequestBeanSetters} and
1436    * populates it by invoking the setter matching each annotated getter.  Absent parameters (a <jk>null</jk> resolved
1437    * value) are left at their default.
1438    */
1439   private <T> T newRequestBean(RequestBeanMeta rbm, MarshallingSession bs, RequestBeanSetters setters) throws Exception {
1440      T bean = setters.newInstance();
1441      for (var pm : rbm.getProperties()) {
1442         var getter = pm.getGetter();
1443         var value = resolveRequestBeanProperty(pm, getter, bs);
1444         if (value == null)
1445            continue;
1446         setters.set(bean, getter, value);
1447      }
1448      return bean;
1449   }
1450
1451   private Object resolveRequestBeanProperty(RequestBeanPropertyMeta pm, java.lang.reflect.Method method, MarshallingSession bs) throws Exception {
1452      HttpPartParserSession pp = pm.getParser(getPartParserSession());
1453      HttpPartSchema schema = pm.getSchema();
1454      String name = pm.getPartName();
1455      var type = bs.getClassMeta(method.getGenericReturnType());
1456      HttpPartType pt = pm.getPartType();
1457      if (pt == HttpPartType.BODY)
1458         return getContent().setSchema(schema).as(type);
1459      if (schema.getCollectionFormat() == HttpPartCollectionFormat.MULTI) {
1460         var valueType = type.isOptional() ? type.getElementType() : type;
1461         if (valueType.isMap())
1462            return resolveRequestBeanMultiMap(pt, name, schema, type);
1463         if (valueType.isCollectionOrArray())
1464            return resolveRequestBeanMultiCollection(pt, name, pp, schema, type);
1465      }
1466      var part = requestBeanPartLast(pt, name);
1467      if (part == null)
1468         return type.isOptional() ? Optional.empty() : null;
1469      return part.parser(pp).schema(schema).def(schema.getDefault()).as(type).orElse(null);
1470   }
1471
1472   private Object resolveRequestBeanMultiMap(HttpPartType pt, String name, HttpPartSchema schema, ClassMeta<?> type) {
1473      try {
1474         var parts = requestBeanParts(pt, name);
1475         var optional = type.isOptional();
1476         if (parts.isEmpty()) {
1477            if (optional) {
1478               if (ine(schema.getDefault()))
1479                  return Optional.of(UonUtils.mergePairs(schema.getDefault()));
1480               return Optional.empty();
1481            }
1482            return JsonMap.create();
1483         }
1484         var dest = JsonMap.create();
1485         for (var p : parts)
1486            UonUtils.mergePair(dest, p.getValue());
1487         return optional ? o(dest) : dest;
1488      } catch (ParseException | SchemaValidationException e) {
1489         throw new BadRequest(e, "Could not parse query parameter '%s'.", name);
1490      }
1491   }
1492
1493   private Object resolveRequestBeanMultiCollection(HttpPartType pt, String name, HttpPartParserSession pp, HttpPartSchema schema, ClassMeta<?> type) throws Exception {
1494      var optional = type.isOptional();
1495      var raw = optional ? type.getElementType() : type;
1496      var elemType = raw.getElementType();
1497      var parts = requestBeanParts(pt, name);
1498      if (parts.isEmpty()) {
1499         if (optional) {
1500            if (ine(schema.getDefault()))
1501               return Optional.of(readDefaultCollection(schema.getDefault(), raw, elemType, pp, schema, pt));
1502            return Optional.empty();
1503         }
1504         return emptyCollection(raw, elemType);
1505      }
1506      Collection c = newCollection(raw);
1507      for (var p : parts) {
1508         if (elemType.is(String.class)) {
1509            var v = p.getValue();
1510            c.add(v == null ? "" : v);
1511         } else {
1512            c.add(p.parser(pp).schema(schema).as(elemType).orElse(null));
1513         }
1514      }
1515      if (optional && elemType.is(String.class) && c.stream().allMatch(x -> isBlank(s(x))))
1516         return Optional.of(emptyCollection(raw, elemType));
1517      var collected = raw.isArray() ? CollectionUtils.toArray(c, elemType.inner()) : c;
1518      return optional ? o(collected) : collected;
1519   }
1520
1521   @SuppressWarnings({
1522      "java:S112" // throws Exception intentional - HttpPartParserSession.read declares Exception
1523   })
1524   private Object readDefaultCollection(String def, ClassMeta<?> raw, ClassMeta<?> elemType, HttpPartParserSession pp, HttpPartSchema schema, HttpPartType pt) throws Exception {
1525      try {
1526         var one = pp.read(pt, schema, def, elemType);
1527         var c = newCollection(raw);
1528         c.add(one);
1529         return raw.isArray() ? CollectionUtils.toArray(c, elemType.inner()) : c;
1530      } catch (ParseException | SchemaValidationException e) {
1531         throw new BadRequest(e, "Could not parse %s parameter '%s'.", pt.toString().toLowerCase(), schema.getName());
1532      }
1533   }
1534
1535   private static Collection newCollection(ClassMeta<?> raw) {
1536      if (raw.isArray())
1537         return CollectionUtils.list();
1538      if (raw.canCreateNewInstance())
1539         return (Collection)raw.newInstance();
1540      return new JsonList();
1541   }
1542
1543   private static Object emptyCollection(ClassMeta<?> raw, ClassMeta<?> elemType) {
1544      var c = newCollection(raw);
1545      return raw.isArray() ? CollectionUtils.toArray(c, elemType.inner()) : c;
1546   }
1547
1548   private List<? extends RequestHttpPart> requestBeanParts(HttpPartType pt, String name) {
1549      return switch (pt) {
1550         case QUERY -> getQueryParams().getAll(name);
1551         case FORMDATA -> getFormParams().getAll(name);
1552         case HEADER -> getHeaders().getAll(name);
1553         case PATH -> getPathParams().getAll(name);
1554         default -> List.of();
1555      };
1556   }
1557
1558   private RequestHttpPart requestBeanPartLast(HttpPartType pt, String name) {
1559      return switch (pt) {
1560         case QUERY -> getQueryParams().getLast(name);
1561         case FORMDATA -> getFormParams().getLast(name);
1562         case HEADER -> getHeaderParam(name);
1563         case PATH -> getPathParams().getLast(name);
1564         default -> null;
1565      };
1566   }
1567
1568   /**
1569    * Returns the request line of this request.
1570    *
1571    * @return The request line of this request.
1572    */
1573   public HttpRequestLine getRequestLine() {
1574      var x = inner.getProtocol();
1575      var i = x.indexOf('/');
1576      var j = x.indexOf('.', i);
1577      var pv = HttpProtocolVersion.of(x.substring(0, i), StringUtils.parseInt(x.substring(i + 1, j)), StringUtils.parseInt(x.substring(j + 1)));
1578      return HttpRequestLineBean.of(inner.getMethod(), inner.getRequestURI(), pv);
1579   }
1580
1581   /**
1582    * Returns the HTTP response associated with this request.
1583    *
1584    * <p>
1585    * Only safe to call once the REST call has reached the point of invoking the matched Java method, e.g. from inside
1586    * a {@link org.apache.juneau.rest.server.converter.RestConverter}, which only ever runs after method invocation.
1587    * Calling it any earlier throws {@link InternalServerError}.
1588    *
1589    * @return The response associated with this request.
1590    */
1591   public RestResponse getResponse() {
1592      return session.getOpSession().getResponse();
1593   }
1594
1595   /**
1596    * Returns the part of this request's URL that calls the servlet.
1597    *
1598    * <p>
1599    * This path starts with a <js>"/"</js> character and includes either the servlet name or a path to the servlet,
1600    * but does not include any extra path information or a query string.
1601    *
1602    * @return The servlet path, never <jk>null</jk>.
1603    * @see HttpServletRequest#getServletPath()
1604    */
1605   @Override
1606   public String getServletPath() {
1607      var cp = context.getUriContext();
1608      var sp = inner.getServletPath();
1609      return cp == null || ! sp.startsWith(cp) ? sp : sp.substring(cp.length());
1610   }
1611
1612   /**
1613    * Returns the static files associated with the resource.
1614    *
1615    * <p>
1616    * Shortcut for {@link RestContext#getStaticFiles()}.
1617    *
1618    * @return
1619    *    The static files for this resource.
1620    *    <br>Never <jk>null</jk>.
1621    */
1622   public StaticFiles getStaticFiles() { return context.getStaticFiles(); }
1623
1624   /**
1625    * Returns the localized swagger associated with the resource.
1626    *
1627    * <p>
1628    * A shortcut for calling <c>getInfoProvider().getSwagger(request);</c>
1629    *
1630    * <h4 class='section'>Example:</h4>
1631    * <p class='bjava'>
1632    *    <ja>@RestGet</ja>
1633    *    <jk>public</jk> List&lt;Tag&gt; swaggerTags(RestRequest <jv>req</jv>) {
1634    *       <jk>return</jk> <jv>req</jv>.getSwagger().getTags();
1635    *    }
1636    * </p>
1637    *
1638    * <h4 class='section'>Notes:</h4><ul>
1639    *    <li class='note'>
1640    *       The {@link Swagger} object can also be passed as a parameter on the method.
1641    * </ul>
1642    *
1643    * <h4 class='section'>See Also:</h4><ul>
1644    *    <li class='ja'>{@link Rest#swaggerProvider()}
1645    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/JuneauBeanSwagger2">juneau-bean-swagger-v2</a>
1646    * </ul>
1647    *
1648    * @return
1649    *    The swagger associated with the resource.
1650    *    <br>Never <jk>null</jk>.
1651    */
1652   public Optional<Swagger> getSwagger() { return context.getSwagger(getLocale()); }
1653
1654   /**
1655    * Returns the localized OpenAPI 3.1 document associated with the resource.
1656    *
1657    * <p>
1658    * Sibling of {@link #getSwagger()} for the OpenAPI 3.1 emission path.
1659    *
1660    * <h4 class='section'>See Also:</h4><ul>
1661    *    <li class='ja'>{@link Rest#openApiProvider()}
1662    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/ApiDocsMixins">API-Docs Mixin Pack</a>
1663    * </ul>
1664    *
1665    * @return The OpenAPI 3.1 document associated with the resource. Never <jk>null</jk>.
1666    */
1667   public Optional<OpenApi> getOpenApi() { return context.getOpenApi(getLocale()); }
1668
1669   /**
1670    * Returns the <c>Time-Zone</c> header value on the request if there is one.
1671    *
1672    * <p>
1673    * Example: <js>"GMT"</js>.
1674    *
1675    * @return The parsed header on the request, never <jk>null</jk>.
1676    */
1677   public Optional<TimeZone> getTimeZone() {
1678      var tz = headers.get("Time-Zone").asString().orElse(null);
1679      if (nn(tz))
1680         return o(TimeZone.getTimeZone(tz));
1681      return oe();
1682   }
1683
1684   /**
1685    * Returns the URI for this request.
1686    *
1687    * <p>
1688    * Similar to {@link #getRequestURI()} but returns the value as a {@link URI}.
1689    * It also gives you the capability to override the query parameters (e.g. add new query parameters to the existing
1690    * URI).
1691    *
1692    * @param includeQuery If <jk>true</jk> include the query parameters on the request.
1693    * @param addQueryParams Augment the request URI with the specified query parameters.
1694    *    <br>Can be <jk>null</jk> (no additional parameters are added).
1695    * @return A new URI.
1696    */
1697   public URI getUri(boolean includeQuery, Map<String,Object> addQueryParams) {
1698      var uri = inner.getRequestURI();
1699      if (includeQuery || nn(addQueryParams)) {
1700         var sb = new StringBuilder(uri);
1701         var rq = queryParams.copy();
1702         if (nn(addQueryParams))
1703            for (var e : addQueryParams.entrySet())
1704               rq.set(e.getKey(), e.getValue());
1705         if (! rq.isEmpty())
1706            sb.append('?').append(rq.asQueryString());
1707         uri = sb.toString();
1708      }
1709      try {
1710         return new URI(uri);
1711      } catch (URISyntaxException e) {
1712         // Shouldn't happen.
1713         throw toRex(e);
1714      }
1715   }
1716
1717   /**
1718    * Returns the URI context of the request.
1719    *
1720    * <p>
1721    * The URI context contains all the information about the URI of the request, such as the servlet URI, context
1722    * path, etc...
1723    *
1724    * @return The URI context of the request.
1725    */
1726   public UriContext getUriContext() {
1727      if (uriContext == null)
1728         uriContext = UriContext.of(getAuthorityPath(), getContextPath(), getServletPath(), urlEncodePath(inner.getPathInfo()));
1729      return uriContext;
1730   }
1731
1732   /**
1733    * Shortcut for calling {@link #getUriResolver()} using {@link UriResolution#ROOT_RELATIVE} and
1734    * {@link UriRelativity#RESOURCE}
1735    *
1736    * @return The URI resolver for this request.
1737    */
1738   public UriResolver getUriResolver() { return UriResolver.of(context.getUriResolution(), context.getUriRelativity(), getUriContext()); }
1739
1740   /**
1741    * Returns a URI resolver that can be used to convert URIs to absolute or root-relative form.
1742    *
1743    * @param resolution The URI resolution rule.
1744    * @param relativity The relative URI relativity rule.
1745    * @return The URI resolver for this request.
1746    */
1747   public UriResolver getUriResolver(UriResolution resolution, UriRelativity relativity) {
1748      return UriResolver.of(resolution, relativity, getUriContext());
1749   }
1750
1751   /**
1752    * Request-level variable resolver session.
1753    *
1754    * <p>
1755    * Used to resolve SVL variables in text.
1756    *
1757    * <h4 class='section'>Example:</h4>
1758    * <p class='bjava'>
1759    *    <ja>@RestGet</ja>
1760    *    <jk>public</jk> String hello(RestRequest <jv>req</jv>) {
1761    *
1762    *       <jc>// Get var resolver session.</jc>
1763    *       VarResolverSession <jv>session</jv> = getVarResolverSession();
1764    *
1765    *       <jc>// Use it to construct a customized message from a query parameter.</jc>
1766    *       <jk>return</jk> <jv>session</jv>.resolve(<js>"Hello ${RQ:user}!"</js>);
1767    *    }
1768    * </p>
1769    *
1770    * <h4 class='section'>Notes:</h4><ul>
1771    *    <li class='note'>
1772    *       The {@link VarResolverSession} object can also be passed as a parameter on the method.
1773    * </ul>
1774    *
1775    * <h4 class='section'>See Also:</h4><ul>
1776    *    <li class='jm'>{@link RestContext#getVarResolver()}
1777    *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerSvlVariables">REST Server SVL Variables</a>
1778    * </ul>
1779    *
1780    * @return The variable resolver for this request.
1781    */
1782   public VarResolverSession getVarResolverSession() {
1783      // @formatter:off
1784      if (varSession == null)
1785         varSession = context
1786            .getVarResolver()
1787            .createSession(session.getBeanStore())
1788            .bean(RestRequest.class, this)
1789            .bean(RestSession.class, session);
1790      return varSession;
1791      // @formatter:on
1792   }
1793
1794   /**
1795    * Log-level query only: returns whether this request's resolved (per-operation) JUL logger is loggable at
1796    * {@link java.util.logging.Level#FINE FINE}-or-finer.
1797    *
1798    * <p>
1799    * This is read-only; there is no request attribute or setter driving it. It reports <b>logging verbosity</b> only
1800    * and is <b>not</b> consulted by any framework behavior. Do <b>not</b> key security or marshalling behavior on this
1801    * method &mdash; use the explicit, non-logging controls instead:
1802    * <ul class='spaced-list'>
1803    *    <li>Echo-endpoint reachability &rarr; {@link org.apache.juneau.rest.server.ops.EchoMixin.Builder#enabled(Boolean) EchoMixin enablement}.
1804    *    <li>Serializer/parser debug behavior &rarr; {@link #isDebugMarshalling()} / {@link Rest#debugMarshalling() @Rest(debugMarshalling)}.
1805    * </ul>
1806    *
1807    * @return <jk>true</jk> if the resolved logger is loggable at {@code FINE}-or-finer.
1808    */
1809   public boolean isDebug() { return opContext.getLogger().isLoggable(java.util.logging.Level.FINE); }
1810
1811   /**
1812    * Returns the resolved per-operation {@link RichLogger} for this request.
1813    *
1814    * <p>
1815    * This is the same logger {@link #isDebug()} queries (`opContext.getLogger()`, delegating to
1816    * {@link RestOpContext#getLogger()}), so anything logged through it &mdash; including the
1817    * {@code fine}/{@code info}/&hellip; convenience methods below &mdash; rides the existing parent-chain capture
1818    * propagation: a {@code LogRecordCapture} attached at a resource-class-level logger name still
1819    * observes these per-operation emissions.
1820    *
1821    * <p>
1822    * These convenience methods are for <b>application handler code</b> that wants to emit its own ad hoc log statements
1823    * <i>during</i> request processing and have them automatically carry whatever {@link RichLogger#context() LogContext}
1824    * is active (most notably {@code requestId}). They are complementary to &mdash; not a replacement for &mdash; the
1825    * REST debug pipeline's one cumulative per-request record; they produce independent, additional {@code LogRecord}s.
1826    *
1827    * @return The resolved per-operation logger. Never <jk>null</jk>.
1828    */
1829   public RichLogger getLogger() { return opContext.getLogger(); }
1830
1831   /**
1832    * Logs a formatted message at {@link java.util.logging.Level#SEVERE SEVERE} through this request's {@link #getLogger() logger}.
1833    *
1834    * @param pattern The {@link java.util.Formatter}-style message pattern.
1835    * @param args The message arguments.
1836    */
1837   public void severe(String pattern, Object...args) { getLogger().severe(pattern, args); }
1838
1839   /**
1840    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#SEVERE SEVERE}.
1841    *
1842    * @param thrown The throwable to associate with the record.
1843    * @param pattern The {@link java.util.Formatter}-style message pattern.
1844    * @param args The message arguments.
1845    */
1846   public void severe(Throwable thrown, String pattern, Object...args) { getLogger().severe(thrown, pattern, args); }
1847
1848   /**
1849    * Logs a formatted message at {@link java.util.logging.Level#WARNING WARNING} through this request's {@link #getLogger() logger}.
1850    *
1851    * @param pattern The {@link java.util.Formatter}-style message pattern.
1852    * @param args The message arguments.
1853    */
1854   public void warning(String pattern, Object...args) { getLogger().warning(pattern, args); }
1855
1856   /**
1857    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#WARNING WARNING}.
1858    *
1859    * @param thrown The throwable to associate with the record.
1860    * @param pattern The {@link java.util.Formatter}-style message pattern.
1861    * @param args The message arguments.
1862    */
1863   public void warning(Throwable thrown, String pattern, Object...args) { getLogger().warning(thrown, pattern, args); }
1864
1865   /**
1866    * Logs a formatted message at {@link java.util.logging.Level#INFO INFO} through this request's {@link #getLogger() logger}.
1867    *
1868    * @param pattern The {@link java.util.Formatter}-style message pattern.
1869    * @param args The message arguments.
1870    */
1871   public void info(String pattern, Object...args) { getLogger().info(pattern, args); }
1872
1873   /**
1874    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#INFO INFO}.
1875    *
1876    * @param thrown The throwable to associate with the record.
1877    * @param pattern The {@link java.util.Formatter}-style message pattern.
1878    * @param args The message arguments.
1879    */
1880   public void info(Throwable thrown, String pattern, Object...args) { getLogger().info(thrown, pattern, args); }
1881
1882   /**
1883    * Logs a formatted message at {@link java.util.logging.Level#CONFIG CONFIG} through this request's {@link #getLogger() logger}.
1884    *
1885    * @param pattern The {@link java.util.Formatter}-style message pattern.
1886    * @param args The message arguments.
1887    */
1888   public void config(String pattern, Object...args) { getLogger().config(pattern, args); }
1889
1890   /**
1891    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#CONFIG CONFIG}.
1892    *
1893    * @param thrown The throwable to associate with the record.
1894    * @param pattern The {@link java.util.Formatter}-style message pattern.
1895    * @param args The message arguments.
1896    */
1897   public void config(Throwable thrown, String pattern, Object...args) { getLogger().config(thrown, pattern, args); }
1898
1899   /**
1900    * Logs a formatted message at {@link java.util.logging.Level#FINE FINE} through this request's {@link #getLogger() logger}.
1901    *
1902    * @param pattern The {@link java.util.Formatter}-style message pattern.
1903    * @param args The message arguments.
1904    */
1905   public void fine(String pattern, Object...args) { getLogger().fine(pattern, args); }
1906
1907   /**
1908    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#FINE FINE}.
1909    *
1910    * @param thrown The throwable to associate with the record.
1911    * @param pattern The {@link java.util.Formatter}-style message pattern.
1912    * @param args The message arguments.
1913    */
1914   public void fine(Throwable thrown, String pattern, Object...args) { getLogger().fine(thrown, pattern, args); }
1915
1916   /**
1917    * Logs a formatted message at {@link java.util.logging.Level#FINER FINER} through this request's {@link #getLogger() logger}.
1918    *
1919    * @param pattern The {@link java.util.Formatter}-style message pattern.
1920    * @param args The message arguments.
1921    */
1922   public void finer(String pattern, Object...args) { getLogger().finer(pattern, args); }
1923
1924   /**
1925    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#FINER FINER}.
1926    *
1927    * @param thrown The throwable to associate with the record.
1928    * @param pattern The {@link java.util.Formatter}-style message pattern.
1929    * @param args The message arguments.
1930    */
1931   public void finer(Throwable thrown, String pattern, Object...args) { getLogger().finer(thrown, pattern, args); }
1932
1933   /**
1934    * Logs a formatted message at {@link java.util.logging.Level#FINEST FINEST} through this request's {@link #getLogger() logger}.
1935    *
1936    * @param pattern The {@link java.util.Formatter}-style message pattern.
1937    * @param args The message arguments.
1938    */
1939   public void finest(String pattern, Object...args) { getLogger().finest(pattern, args); }
1940
1941   /**
1942    * Logs a formatted message with an associated throwable at {@link java.util.logging.Level#FINEST FINEST}.
1943    *
1944    * @param thrown The throwable to associate with the record.
1945    * @param pattern The {@link java.util.Formatter}-style message pattern.
1946    * @param args The message arguments.
1947    */
1948   public void finest(Throwable thrown, String pattern, Object...args) { getLogger().finest(thrown, pattern, args); }
1949
1950   /**
1951    * Returns whether REST-driven serializer/parser debug behavior is enabled for this request's operation.
1952    *
1953    * <p>
1954    * Resolved from the cascading {@link Rest#debugMarshalling() @Rest(debugMarshalling)} /
1955    * {@link RestOp#debugMarshalling() @RestOp(debugMarshalling)} setting (default OFF), <b>independent</b> of the JUL
1956    * logger level. When enabled, the REST layer forces {@code Context.debug} on the serializer/parser session used to
1957    * handle this request &mdash; engaging recursion-detection-that-throws, parse-input buffering, and stack-trace-prefixed
1958    * marshalling exceptions.
1959    *
1960    * @return <jk>true</jk> if REST-driven marshalling debug is enabled for this operation.
1961    */
1962   public boolean isDebugMarshalling() { return opContext.isDebugMarshalling(); }
1963
1964   /**
1965    * Returns the captured (bounded) request body bytes for debug logging.
1966    *
1967    * <p>
1968    * Populated by the two-phase debug pipeline only when the resolved logger is loggable at
1969    * {@link java.util.logging.Level#FINEST FINEST}; otherwise returns <jk>null</jk>. The captured copy is capped at the
1970    * formatter's body cap (default 8&nbsp;KB); use {@link #getCachedContentLength()} for the full byte count.
1971    *
1972    * @return The captured request body bytes, or <jk>null</jk> if body caching was not installed.
1973    */
1974   public byte[] getCachedContent() {
1975      return inner instanceof CachingHttpServletRequest c ? c.getContent() : null;
1976   }
1977
1978   /**
1979    * Returns the total number of request body bytes read, including any beyond the capture cap.
1980    *
1981    * @return The total request body length in bytes, or {@code -1} if body caching was not installed.
1982    */
1983   public long getCachedContentLength() {
1984      return inner instanceof CachingHttpServletRequest c ? c.getTotalLength() : -1;
1985   }
1986
1987   /**
1988    * Returns the exception thrown while processing this request, if any.
1989    *
1990    * @return The thrown exception, or <jk>null</jk> if none occurred.
1991    */
1992   public Throwable getException() {
1993      return session.getException();
1994   }
1995
1996   /**
1997    * Returns the total request execution time in milliseconds, if it has been recorded.
1998    *
1999    * @return The execution time in milliseconds, or <jk>null</jk> if not yet recorded.
2000    */
2001   public Long getExecTime() {
2002      return getAttribute("ExecTime").as(Long.class).orElse(null);
2003   }
2004
2005   /**
2006    * Returns <jk>true</jk> if <c>&amp;plainText=true</c> was specified as a URL parameter.
2007    *
2008    * <p>
2009    * This indicates that the <c>Content-Type</c> of the output should always be set to <js>"text/plain"</js>
2010    * to make it easy to render in a browser.
2011    *
2012    * <p>
2013    * This feature is useful for debugging.
2014    *
2015    * @return <jk>true</jk> if {@code &amp;plainText=true} was specified as a URL parameter
2016    */
2017   public boolean isPlainText() { return eq(queryParams.get("plainText").asString().orElse("false"), "true"); }
2018
2019   /**
2020    * Sets a request attribute.
2021    *
2022    * @param name The attribute name.
2023    * @param value The attribute value.
2024    */
2025   @Override
2026   public void setAttribute(String name, Object value) {
2027      attrs.set(name, value);
2028   }
2029
2030   /**
2031    * Sets the resolved resource-level authentication result.
2032    *
2033    * <p>
2034    * Invoked by the framework after the {@link RestAuthenticator} fold resolves
2035    * an identity for this request.  The stored result drives {@link #getUserPrincipal()}, {@link #isUserInRole(String)},
2036    * and {@link #getRemoteUser()}, and (when a principal is present) stashes the principal under
2037    * {@code "juneau.principal"} so {@code @Auth} argument injection resolves it.
2038    *
2039    * @param value The result. Can be <jk>null</jk> to unset.
2040    * @return This object.
2041    * @since 10.0.0
2042    */
2043   public RestRequest setAuthResult(AuthResult value) {
2044      authResult = value;
2045      if (value != null && value.getPrincipal() != null)
2046         setAttribute("juneau.principal", value.getPrincipal());
2047      return this;
2048   }
2049
2050   @Override /* Overridden from HttpServletRequestWrapper */
2051   public Principal getUserPrincipal() {
2052      var p = authResult == null ? null : authResult.getPrincipal();
2053      return p != null ? p : super.getUserPrincipal();
2054   }
2055
2056   @Override /* Overridden from HttpServletRequestWrapper */
2057   public boolean isUserInRole(String role) {
2058      if (authResult != null && authResult.getRoles().contains(role))
2059         return true;
2060      return super.isUserInRole(role);
2061   }
2062
2063   @Override /* Overridden from HttpServletRequestWrapper */
2064   public String getRemoteUser() {
2065      var p = authResult == null ? null : authResult.getPrincipal();
2066      return p != null ? p.getName() : super.getRemoteUser();
2067   }
2068
2069   /**
2070    * Sets a serializer session property programmatically.
2071    *
2072    * <p>
2073    * Session properties override context-level properties and can be used to customize serializer behavior for this request only.
2074    *
2075    * @param name The property name (e.g. {@code "escapeSolidus"}).
2076    * @param value The property value.
2077    * @return This object.
2078    */
2079   public RestRequest setSerializerSessionProperty(String name, Object value) {
2080      if (serializerSessionProperties == null)
2081         serializerSessionProperties = m();
2082      serializerSessionProperties.put(name, value);
2083      return this;
2084   }
2085
2086   /**
2087    * Sets a parser session property programmatically.
2088    *
2089    * <p>
2090    * Session properties override context-level properties and can be used to customize parser behavior for this request only.
2091    *
2092    * @param name The property name (e.g. {@code "trimStrings"}).
2093    * @param value The property value.
2094    * @return This object.
2095    */
2096   public RestRequest setParserSessionProperty(String name, Object value) {
2097      if (parserSessionProperties == null)
2098         parserSessionProperties = m();
2099      parserSessionProperties.put(name, value);
2100      return this;
2101   }
2102
2103   /**
2104    * Sets multiple serializer session properties programmatically.
2105    *
2106    * @param values The properties to set. Can be {@code null}.
2107    * @return This object.
2108    */
2109   public RestRequest setSerializerSessionProperties(Map<String,Object> values) {
2110      if (ine(values)) {
2111         if (serializerSessionProperties == null)
2112            serializerSessionProperties = m();
2113         serializerSessionProperties.putAll(values);
2114      }
2115      return this;
2116   }
2117
2118   /**
2119    * Sets multiple parser session properties programmatically.
2120    *
2121    * @param values The properties to set. Can be {@code null}.
2122    * @return This object.
2123    */
2124   public RestRequest setParserSessionProperties(Map<String,Object> values) {
2125      if (ine(values)) {
2126         if (parserSessionProperties == null)
2127            parserSessionProperties = m();
2128         parserSessionProperties.putAll(values);
2129      }
2130      return this;
2131   }
2132
2133   /**
2134    * Returns the merged serializer session property map for this request.
2135    *
2136    * <p>
2137    * Merges (in order of increasing priority):
2138    * <ol>
2139    *    <li>Request attributes (from {@link #getAttributes()}, e.g. {@code defaultRequestAttributes})
2140    *    <li>UON-encoded {@code juneauSerializerOptions} query parameter
2141    *    <li>JSON5-encoded {@code X-Juneau-Serializer-Options} header
2142    *    <li>Programmatically-set properties via {@link #setSerializerSessionProperty}
2143    * </ol>
2144    *
2145    * <p>
2146    * Client-supplied keys are validated against the allowlist from {@link RestOpContext#getAllowedSerializerOptions()}.
2147    * Keys not in the allowlist cause a {@code 400 Bad Request} response.
2148    *
2149    * @return An unmodifiable map of session properties; may be empty but never {@code null}.
2150    */
2151   public Map<String,Object> getSerializerSessionPropertyMap() {
2152      var allowlist = opContext.getAllowedSerializerOptions();
2153      Map<String,Object> m1 = null;
2154      Map<String,Object> m2 = null;
2155
2156      var q = getQueryParams().get(QUERY_juneauSerializerOptions).asString().orElse(null);
2157      if (inb(q)) {
2158         m1 = parseUonMap(q, e -> badRequest(e, "Could not parse UON session options from query parameter '%s'.", QUERY_juneauSerializerOptions));
2159         var invalid = m1.keySet().stream().filter(k -> !allowlist.contains(k)).collect(Collectors.joining(","));
2160         if (!invalid.isEmpty())
2161            badRequest("Invalid session options in query parameter '%s': '%s'", QUERY_juneauSerializerOptions, invalid);
2162      }
2163
2164      var h = getHeaderParam(HEADER_JuneauSerializerOptions).asString().orElse(null);
2165      if (inb(h)) {
2166         m2 = parseJsonMap(h, e -> badRequest(e, "Could not parse JSON5 session options from header '%s'.", HEADER_JuneauSerializerOptions));
2167         var invalid = m2.keySet().stream().filter(k -> !allowlist.contains(k)).collect(Collectors.joining(","));
2168         if (!invalid.isEmpty())
2169            badRequest("Invalid session options in header '%s': '%s'", HEADER_JuneauSerializerOptions, invalid);
2170      }
2171
2172      return mergeSessionMaps(getAttributes().asMap(), m1, m2, serializerSessionProperties);
2173   }
2174
2175   /**
2176    * Returns the merged parser session property map for this request.
2177    *
2178    * <p>
2179    * Merges (in order of increasing priority):
2180    * <ol>
2181    *    <li>Request attributes (from {@link #getAttributes()}, e.g. {@code defaultRequestAttributes})
2182    *    <li>UON-encoded {@code juneauParserOptions} query parameter
2183    *    <li>JSON5-encoded {@code X-Juneau-Parser-Options} header
2184    *    <li>Programmatically-set properties via {@link #setParserSessionProperty}
2185    * </ol>
2186    *
2187    * <p>
2188    * Client-supplied keys are validated against the allowlist from {@link RestOpContext#getAllowedParserOptions()}.
2189    * Keys not in the allowlist cause a {@code 400 Bad Request} response.
2190    *
2191    * @return An unmodifiable map of session properties; may be empty but never {@code null}.
2192    */
2193   public Map<String,Object> getParserSessionPropertyMap() {
2194      var allowlist = opContext.getAllowedParserOptions();
2195      Map<String,Object> m1 = null;
2196      Map<String,Object> m2 = null;
2197
2198      var q = getQueryParams().get(QUERY_juneauParserOptions).asString().orElse(null);
2199      if (inb(q)) {
2200         m1 = parseUonMap(q, e -> badRequest(e, "Could not parse UON session options from query parameter '%s'.", QUERY_juneauParserOptions));
2201         var invalid = m1.keySet().stream().filter(k -> !allowlist.contains(k)).collect(Collectors.joining(","));
2202         if (!invalid.isEmpty())
2203            badRequest("Invalid session options in query parameter '%s': '%s'", QUERY_juneauParserOptions, invalid);
2204      }
2205
2206      var h = getHeaderParam(HEADER_JuneauParserOptions).asString().orElse(null);
2207      if (inb(h)) {
2208         m2 = parseJsonMap(h, e -> badRequest(e, "Could not parse JSON5 session options from header '%s'.", HEADER_JuneauParserOptions));
2209         var invalid = m2.keySet().stream().filter(k -> !allowlist.contains(k)).collect(Collectors.joining(","));
2210         if (!invalid.isEmpty())
2211            badRequest("Invalid session options in header '%s': '%s'", HEADER_JuneauParserOptions, invalid);
2212      }
2213
2214      return mergeSessionMaps(getAttributes().asMap(), m1, m2, parserSessionProperties);
2215   }
2216
2217   @SafeVarargs
2218   private static Map<String,Object> mergeSessionMaps(Map<String,Object>...maps) {
2219      Map<String,Object> result = null;
2220      for (var map : maps) {
2221         if (ine(map)) {
2222            if (result == null)
2223               result = new LinkedHashMap<>(map);
2224            else
2225               result.putAll(map);
2226         }
2227      }
2228      return result != null ? u(result) : Collections.emptyMap();
2229   }
2230
2231   private static void badRequest(String msg, Object...args) {
2232      throw new BadRequest(msg, args);
2233   }
2234
2235   private static void badRequest(Exception causedBy, String msg, Object...args) {
2236      throw new BadRequest(causedBy, msg, args);
2237   }
2238
2239   private static Map<String,Object> parseUonMap(String input, Consumer<ParseException> onError) {
2240      try {
2241         var m = Uon.to(input, JsonMap.class);
2242         return m != null ? m : Collections.emptyMap();
2243      } catch (ParseException e) {
2244         onError.accept(e);
2245         return Collections.emptyMap();
2246      }
2247   }
2248
2249   private static Map<String,Object> parseJsonMap(String input, Consumer<ParseException> onError) {
2250      try {
2251         var m = Json5.to(input, JsonMap.class);
2252         return m != null ? m : Collections.emptyMap();
2253      } catch (ParseException e) {
2254         onError.accept(e);
2255         return Collections.emptyMap();
2256      }
2257   }
2258
2259   /**
2260    * Sets the charset to expect on the request content.
2261    *
2262    * @param value The new charset to use for the request content.
2263    *    <br>Can be <jk>null</jk> (resets to the negotiated/default charset on the next {@link #getCharset()} call).
2264    */
2265   public void setCharset(Charset value) { this.charset = value; }
2266
2267   /**
2268    * Sets the <js>"Exception"</js> attribute to the specified throwable.
2269    *
2270    * <p>
2271    * This exception is surfaced by the debug pipeline as the {@code thrown} of the emitted log record.
2272    *
2273    * @param t The attribute value.
2274    * @return This object.
2275    */
2276   public RestRequest setException(Throwable t) {
2277      setAttribute("Exception", t);
2278      return this;
2279   }
2280
2281   /**
2282    * Shortcut for calling <c>setNoTrace(<jk>true</jk>)</c>.
2283    *
2284    * @return This object.
2285    */
2286   public RestRequest setNoTrace() {
2287      return setNoTrace(true);
2288   }
2289
2290   /**
2291    * Sets the <js>"NoTrace"</js> attribute to the specified boolean.
2292    *
2293    * <p>
2294    * This flag tells the framework not to trace the current request: the access-log record for the call is still
2295    * emitted, but without the exception's stack trace.  A <c>No-Trace: true</c> request header has the same effect; when both are present, the attribute wins.
2296    *
2297    * @param b The attribute value.
2298    * @return This object.
2299    */
2300   public RestRequest setNoTrace(Boolean b) {
2301      setAttribute("NoTrace", b);
2302      return this;
2303   }
2304
2305   @Override /* Overridden from Object */
2306   public String toString() {
2307      var sb = new StringBuilder("\n").append(getRequestLine()).append("\n");
2308      sb.append("---Headers---\n");
2309      getHeaders().forEach(x -> sb.append("\t").append(x).append("\n"));
2310      var m = getMethod();
2311      if (eqa(m, "PUT", "POST")) {
2312         try {
2313            sb.append("---Content UTF-8---\n");
2314            sb.append(content.asString()).append("\n");
2315            sb.append("---Content Hex---\n");
2316            sb.append(content.asSpacedHex()).append("\n");
2317         } catch (Exception e1) {
2318            sb.append(localizedMessage(e1));
2319         }
2320      }
2321      return sb.toString();
2322   }
2323
2324   /* Called by RestSession.finish() */
2325   void close() {
2326      if (nn(config)) {
2327         config.close();
2328      }
2329   }
2330
2331   /**
2332    * Creates the underlying part-parser session only when a part actually has to be parsed.
2333    *
2334    * <p>
2335    * Most requests never parse a header, query, path or form value into a schema-typed object, so building the
2336    * (comparatively heavy) OpenAPI parser session up front is wasted work.
2337    */
2338   private static final class LazyPartParserSession implements HttpPartParserSession {
2339      private final HttpPartParser parser;
2340      private final AtomicReference<HttpPartParserSession> session = new AtomicReference<>();
2341
2342      LazyPartParserSession(HttpPartParser parser) {
2343         this.parser = parser;
2344      }
2345
2346      @Override /* Overridden from HttpPartParserSession */
2347      public <T> T read(HttpPartType partType, HttpPartSchema schema, String in, ClassMeta<T> toType) throws ParseException, SchemaValidationException {
2348         var s = session.get();
2349         if (s == null) {
2350            s = parser.getPartSession();
2351            session.set(s);
2352         }
2353         return s.read(partType, schema, in, toType);
2354      }
2355   }
2356}