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.httppart;
018
019import static org.apache.juneau.commons.utils.IoUtils.*;
020import static org.apache.juneau.commons.utils.Shorts.*;
021import static org.apache.juneau.commons.utils.StringUtils.*;
022import static org.apache.juneau.commons.utils.ThrowableUtils.*;
023
024import java.io.*;
025import java.lang.reflect.*;
026import java.util.*;
027
028import org.apache.juneau.commons.conversion.*;
029import org.apache.juneau.commons.http.*;
030import org.apache.juneau.commons.httppart.*;
031import org.apache.juneau.commons.io.*;
032import org.apache.juneau.http.header.*;
033import org.apache.juneau.http.response.*;
034import org.apache.juneau.marshall.*;
035import org.apache.juneau.marshall.collections.*;
036import org.apache.juneau.marshall.encoders.*;
037import org.apache.juneau.marshall.httppart.*;
038import org.apache.juneau.marshall.marshaller.*;
039import org.apache.juneau.marshall.parser.*;
040import org.apache.juneau.rest.server.*;
041import org.apache.juneau.rest.server.util.*;
042
043import jakarta.servlet.*;
044
045/**
046 * Contains the content of the HTTP request.
047 *
048 * <p>
049 *    The {@link RequestContent} object is the API for accessing the content of an HTTP request.
050 *    It can be accessed by passing it as a parameter on your REST Java method:
051 * </p>
052 * <p class='bjava'>
053 *    <ja>@RestPost</ja>(...)
054 *    <jk>public</jk> Object myMethod(RequestContent <jv>content</jv>) {...}
055 * </p>
056 *
057 * <h2 class='figure'>Example:</h2>
058 * <p class='bjava'>
059 *    <ja>@RestPost</ja>(...)
060 *    <jk>public void</jk> doPost(RequestContent <jv>content</jv>) {
061 *       <jc>// Convert content to a linked list of Person objects.</jc>
062 *       List&lt;Person&gt; <jv>list</jv> = <jv>content</jv>.as(LinkedList.<jk>class</jk>, Person.<jk>class</jk>);
063 *       ...
064 *    }
065 * </p>
066 *
067 * <p>
068 *    Some important methods on this class are:
069 * </p>
070 * <ul class='javatree'>
071 *    <li class='jc'>{@link RequestContent}
072 *    <ul class='spaced-list'>
073 *       <li>Methods for accessing the raw contents of the request content:
074 *       <ul class='javatreec'>
075 *          <li class='jm'>{@link RequestContent#asBytes() asBytes()}
076 *          <li class='jm'>{@link RequestContent#asHex() asHex()}
077 *          <li class='jm'>{@link RequestContent#asSpacedHex() asSpacedHex()}
078 *          <li class='jm'>{@link RequestContent#asString() asString()}
079 *          <li class='jm'>{@link RequestContent#getInputStream() getInputStream()}
080 *          <li class='jm'>{@link RequestContent#getReader() getReader()}
081 *       </ul>
082 *       <li>Methods for parsing the contents of the request content:
083 *       <ul class='javatreec'>
084 *          <li class='jm'>{@link RequestContent#as(Class) as(Class)}
085 *          <li class='jm'>{@link RequestContent#as(Type, Type...) as(Type, Type...)}
086 *          <li class='jm'>{@link RequestContent#setSchema(HttpPartSchema) setSchema(HttpPartSchema)}
087 *       </ul>
088 *       <li>Other methods:
089 *       <ul class='javatreec'>
090 *          <li class='jm'>{@link RequestContent#cache() cache()}
091 *          <li class='jm'>{@link RequestContent#getParserMatch() getParserMatch()}
092 *       </ul>
093 *    </ul>
094 * </ul>
095 *
096 * <h2 class='section'>See Also:</h2><ul>
097 *    <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/RestServerHttpParts">HTTP parts in REST servers</a>
098 * </ul>
099 */
100@SuppressWarnings({
101   "resource", // Resource management handled externally
102   "unchecked" // Type erasure requires unchecked casts in content parsing
103})
104public class RequestContent {
105
106   private byte[] content;
107   private final RestRequest req;
108   private EncoderSet encoders;
109   private Encoder encoder;
110   @SuppressWarnings({
111      "java:S1450" // Field backs the public fluent parsers(ParserSet) setter; the value is set externally and consumed later in getParserMatch(), so it cannot be a local variable.
112   })
113   private ParserSet parsers;
114   private long maxInput;
115   private int contentLength;
116   private MediaType mediaType;
117   private Parser parser;
118   private HttpPartSchema schema;
119
120   /**
121    * Constructor.
122    *
123    * @param req The request creating this bean.
124    */
125   public RequestContent(RestRequest req) {
126      this.req = req;
127   }
128
129   /**
130    * Reads the input from the HTTP request parsed into a POJO.
131    *
132    * <p>
133    * The parser used is determined by the matching <c>Content-Type</c> header on the request.
134    *
135    * <p>
136    * If type is <jk>null</jk> or <code>Object.<jk>class</jk></code>, then the actual type will be determined
137    * automatically based on the following input:
138    * <table class='styled'>
139    *    <caption>Input types and return types</caption>
140    *    <tr><th>Type</th><th>JSON input</th><th>XML input</th><th>Return type</th></tr>
141    *    <tr>
142    *       <td>object</td>
143    *       <td><js>"{...}"</js></td>
144    *       <td><code><xt>&lt;object&gt;</xt>...<xt>&lt;/object&gt;</xt></code><br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'object'</xs><xt>&gt;</xt>...<xt>&lt;/x&gt;</xt></code></td>
145    *       <td>{@link JsonMap}</td>
146    *    </tr>
147    *    <tr>
148    *       <td>array</td>
149    *       <td><js>"[...]"</js></td>
150    *       <td><code><xt>&lt;array&gt;</xt>...<xt>&lt;/array&gt;</xt></code><br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'array'</xs><xt>&gt;</xt>...<xt>&lt;/x&gt;</xt></code></td>
151    *       <td>{@link JsonList}</td>
152    *    </tr>
153    *    <tr>
154    *       <td>string</td>
155    *       <td><js>"'...'"</js></td>
156    *       <td><code><xt>&lt;string&gt;</xt>...<xt>&lt;/string&gt;</xt></code><br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'string'</xs><xt>&gt;</xt>...<xt>&lt;/x&gt;</xt></code></td>
157    *       <td>{@link String}</td>
158    *    </tr>
159    *    <tr>
160    *       <td>number</td>
161    *       <td><c>123</c></td>
162    *       <td><code><xt>&lt;number&gt;</xt>123<xt>&lt;/number&gt;</xt></code><br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'number'</xs><xt>&gt;</xt>...<xt>&lt;/x&gt;</xt></code></td>
163    *       <td>{@link Number}</td>
164    *    </tr>
165    *    <tr>
166    *       <td>boolean</td>
167    *       <td><jk>true</jk></td>
168    *       <td><code><xt>&lt;boolean&gt;</xt>true<xt>&lt;/boolean&gt;</xt></code><br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'boolean'</xs><xt>&gt;</xt>...<xt>&lt;/x&gt;</xt></code></td>
169    *       <td>{@link Boolean}</td>
170    *    </tr>
171    *    <tr>
172    *       <td>null</td>
173    *       <td><jk>null</jk> or blank</td>
174    *       <td><code><xt>&lt;null/&gt;</xt></code> or blank<br><code><xt>&lt;x</xt> <xa>type</xa>=<xs>'null'</xs><xt>/&gt;</xt></code></td>
175    *       <td><jk>null</jk></td>
176    *    </tr>
177    * </table>
178    *
179    * <p>
180    * Refer to <a class="doclink" href="https://juneau.apache.org/docs/topics/PojoCategories">POJO Categories</a> for a complete definition of supported POJOs.
181    *
182    * <h4 class='section'>Examples:</h4>
183    * <p class='bjava'>
184    *    <jc>// Parse into an integer.</jc>
185    *    <jk>int</jk> <jv>content1</jv> = <jv>req</jv>.getContent().as(<jk>int</jk>.<jk>class</jk>);
186    *
187    *    <jc>// Parse into an int array.</jc>
188    *    <jk>int</jk>[] <jv>content2</jv> = <jv>req</jv>.getContent().as(<jk>int</jk>[].<jk>class</jk>);
189    * 
190    *    <jc>// Parse into a bean.</jc>
191    *    MyBean <jv>content3</jv> = <jv>req</jv>.getContent().as(MyBean.<jk>class</jk>);
192    *
193    *    <jc>// Parse into a linked-list of objects.</jc>
194    *    List <jv>content4</jv> = <jv>req</jv>.getContent().as(LinkedList.<jk>class</jk>);
195    *
196    *    <jc>// Parse into a map of object keys/values.</jc>
197    *    Map <jv>content5</jv> = <jv>req</jv>.getContent().as(TreeMap.<jk>class</jk>);
198    * </p>
199    *
200    * <h4 class='section'>Notes:</h4><ul>
201    *    <li class='note'>
202    *       If {@code allowContentParam} init parameter is true, then first looks for {@code &content=xxx} in the URL query string.
203    * </ul>
204    *
205    * @param type
206    *    The class type to instantiate.
207    *    <br>Can be <jk>null</jk> or <code>Object.<jk>class</jk></code> to auto-detect the type based on the input.
208    * @param <T> The class type to instantiate.
209    * @return The input parsed to a POJO.
210    * @throws BadRequest Thrown if input could not be parsed or fails schema validation.
211    * @throws UnsupportedMediaType Thrown if the Content-Type header value is not supported by one of the parsers.
212    * @throws InternalServerError Thrown if an {@link IOException} occurs.
213    */
214   public <T> T as(Class<T> type) throws BadRequest, UnsupportedMediaType, InternalServerError {
215      return getInner(getClassMeta(type));
216   }
217
218   /**
219    * Reads the input from the HTTP request parsed into a POJO.
220    *
221    * <p>
222    * This is similar to {@link #as(Class)} but allows for complex collections of POJOs to be created.
223    *
224    * <h4 class='section'>Examples:</h4>
225    * <p class='bjava'>
226    *    <jc>// Parse into a linked-list of strings.</jc>
227    *    List&lt;String&gt; <jv>content1</jv> = <jv>req</jv>.getContent().as(LinkedList.<jk>class</jk>, String.<jk>class</jk>);
228    *
229    *    <jc>// Parse into a linked-list of linked-lists of strings.</jc>
230    *    List&lt;List&lt;String&gt;&gt; <jv>content2</jv> = <jv>req</jv>.getContent().as(LinkedList.<jk>class</jk>, LinkedList.<jk>class</jk>, String.<jk>class</jk>);
231    *
232    *    <jc>// Parse into a map of string keys/values.</jc>
233    *    Map&lt;String,String&gt; <jv>content3</jv> = <jv>req</jv>.getContent().as(TreeMap.<jk>class</jk>, String.<jk>class</jk>, String.<jk>class</jk>);
234    *
235    *    <jc>// Parse into a map containing string keys and values of lists containing beans.</jc>
236    *    Map&lt;String,List&lt;MyBean&gt;&gt; <jv>content4</jv> = <jv>req</jv>.getContent().as(TreeMap.<jk>class</jk>, String.<jk>class</jk>, List.<jk>class</jk>, MyBean.<jk>class</jk>);
237    * </p>
238    *
239    * <h4 class='section'>Notes:</h4><ul>
240    *    <li class='note'>
241    *       <c>Collections</c> must be followed by zero or one parameter representing the value type.
242    *    <li class='note'>
243    *       <c>Maps</c> must be followed by zero or two parameters representing the key and value types.
244    *    <li class='note'>
245    *       If {@code allowContentParam} init parameter is true, then first looks for {@code &content=xxx} in the URL query string.
246    * </ul>
247    *
248    * @param type
249    *    The type of object to create.
250    *    <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
251    * @param args
252    *    The type arguments of the class if it's a collection or map.
253    *    <br>Can be any of the following: {@link ClassMeta}, {@link Class}, {@link ParameterizedType}, {@link GenericArrayType}
254    *    <br>Ignored if the main type is not a map or collection.
255    * @param <T> The class type to instantiate.
256    * @return The input parsed to a POJO.
257    * @throws BadRequest Thrown if input could not be parsed or fails schema validation.
258    * @throws UnsupportedMediaType Thrown if the Content-Type header value is not supported by one of the parsers.
259    * @throws InternalServerError Thrown if an {@link IOException} occurs.
260    */
261   public <T> T as(Type type, Type...args) throws BadRequest, UnsupportedMediaType, InternalServerError {
262      return getInner(this.<T>getClassMeta(type, args));
263   }
264
265   /**
266    * Returns the HTTP content as a byte array.
267    *
268    * <h4 class='section'>Notes:</h4><ul>
269    *    <li class='note'>
270    *       If {@code allowContentParam} init parameter is true, then first looks for {@code &content=xxx} in the URL query string.
271    * </ul>
272    *
273    * @return The incoming input from the connection as a byte array.
274    * @throws IOException If a problem occurred trying to read from the reader.
275    */
276   public byte[] asBytes() throws IOException {
277      cache();
278      return content;
279   }
280
281   /**
282    * Returns the HTTP content content as a simple hexadecimal character string.
283    *
284    * <h4 class='section'>Example:</h4>
285    * <p class='bcode'>
286    *    0123456789ABCDEF
287    * </p>
288    *
289    * @return The incoming input from the connection as a plain string.
290    * @throws IOException If a problem occurred trying to read from the reader.
291    */
292   public String asHex() throws IOException {
293      cache();
294      return toHex(content);
295   }
296
297   /**
298    * Returns the HTTP content content as a simple space-delimited hexadecimal character string.
299    *
300    * <h4 class='section'>Example:</h4>
301    * <p class='bcode'>
302    *    01 23 45 67 89 AB CD EF
303    * </p>
304    *
305    * @return The incoming input from the connection as a plain string.
306    * @throws IOException If a problem occurred trying to read from the reader.
307    */
308   public String asSpacedHex() throws IOException {
309      cache();
310      return toSpacedHex(content);
311   }
312
313   /**
314    * Returns the HTTP content content as a plain string.
315    *
316    * <h4 class='section'>Notes:</h4><ul>
317    *    <li class='note'>
318    *       If {@code allowContentParam} init parameter is true, then first looks for {@code &content=xxx} in the URL query string.
319    * </ul>
320    *
321    * @return The incoming input from the connection as a plain string.
322    * @throws IOException If a problem occurred trying to read from the reader.
323    */
324   public String asString() throws IOException {
325      cache();
326      return new String(content, UTF8);
327   }
328
329   /**
330    * Caches the content in memory for reuse.
331    *
332    * @return This object.
333    * @throws IOException If error occurs while reading stream.
334    */
335   public RequestContent cache() throws IOException {
336      if (content == null)
337         content = readBytes(getInputStream());
338      return this;
339   }
340
341   /**
342    * Sets the contents of this content.
343    *
344    * @param value The new value for this setting.
345    * @return This object.
346    */
347   public RequestContent content(byte[] value) {
348      content = value;
349      return this;
350   }
351
352   /**
353    * Sets the encoders to use for decoding this content.
354    *
355    * @param value The new value for this setting.
356    * @return This object.
357    */
358   public RequestContent encoders(EncoderSet value) {
359      encoders = value;
360      return this;
361   }
362
363   /**
364    * Returns the content length of the content.
365    *
366    * @return The content length of the content in bytes.
367    */
368   public int getContentLength() { return contentLength == 0 ? req.getHttpServletRequest().getContentLength() : contentLength; }
369
370   /**
371    * Returns the HTTP content content as an {@link InputStream}.
372    *
373    * @return The negotiated input stream.
374    * @throws IOException If any error occurred while trying to get the input stream or wrap it in the GZIP wrapper.
375    */
376   public ServletInputStream getInputStream() throws IOException {
377
378      if (nn(content))
379         return new BoundedServletInputStream(content);
380
381      var enc = getEncoder();
382
383      var is = req.getHttpServletRequest().getInputStream();
384
385      if (enc == null)
386         return new BoundedServletInputStream(is, maxInput);
387
388      return new BoundedServletInputStream(enc.getInputStream(is), maxInput);
389   }
390
391   /**
392    * Returns the parser and media type matching the request <c>Content-Type</c> header.
393    *
394    * @return
395    *    The parser matching the request <c>Content-Type</c> header, or {@link Optional#empty()} if no matching parser was
396    *    found.
397    *    Includes the matching media type.
398    */
399   public Optional<ParserMatch> getParserMatch() {
400      if (nn(mediaType) && nn(parser))
401         return o(new ParserMatch(mediaType, parser));
402      var mt = getMediaType();
403      return o(mt).flatMap(parsers::getParserMatch);
404   }
405
406   /**
407    * Returns the HTTP content content as a {@link Reader}.
408    *
409    * <h4 class='section'>Notes:</h4><ul>
410    *    <li class='note'>
411    *       If {@code allowContentParam} init parameter is true, then first looks for {@code &content=xxx} in the URL query string.
412    *    <li class='note'>
413    *       Automatically handles GZipped input streams.
414    *    <li class='note'>
415    *       The initial buffer is sized off the request's declared {@code Content-Length}, but never past the
416    *       effective {@code @Rest(maxInput)} ceiling &mdash; a client can send whatever length it likes in that
417    *       header, regardless of how much (or little) content actually follows.
418    * </ul>
419    *
420    * @return The content contents as a reader.
421    * @throws IOException Thrown by underlying stream.
422    */
423   public BufferedReader getReader() throws IOException {
424      var r = getUnbufferedReader();
425      if (r instanceof BufferedReader r2)
426         return r2;
427      int len = req.getHttpServletRequest().getContentLength();
428      return new BufferedReader(r, computeReaderBufferSize(len, maxInput));
429   }
430
431   /**
432    * Computes the initial char-buffer size for {@link #getReader()}.
433    *
434    * <p>
435    * Package-private (rather than folded directly into {@link #getReader()}) so the sizing decision can be
436    * exercised directly in unit tests independent of a live servlet request.
437    *
438    * @param declaredContentLength The request's declared {@code Content-Length}, as returned by
439    *    {@code HttpServletRequest.getContentLength()}. May be {@code <= 0} if absent/unparsable.
440    * @param maxInput The effective {@code @Rest(maxInput)} ceiling in bytes. Values {@code <= 0} are
441    *    treated as "no additional ceiling beyond {@code Integer.MAX_VALUE}".
442    * @return The buffer size to use, at least the historical {@code 8192}-byte default and never past
443    *    {@code min(maxInput, Integer.MAX_VALUE)}.
444    */
445   static int computeReaderBufferSize(int declaredContentLength, long maxInput) {
446      long ceiling = maxInput > 0 ? maxInput : Integer.MAX_VALUE;
447      long buffSize = declaredContentLength <= 0 ? 8192 : Math.min(Math.max(declaredContentLength, 8192), ceiling);
448      return (int)Math.min(buffSize, Integer.MAX_VALUE);
449   }
450
451   /**
452    * Sets the max input value for this content.
453    *
454    * @param value The new value for this setting.
455    * @return This object.
456    */
457   public RequestContent maxInput(long value) {
458      maxInput = value;
459      return this;
460   }
461
462   /**
463    * Sets the media type of this content.
464    *
465    * @param value The new value for this setting.
466    * @return This object.
467    */
468   public RequestContent mediaType(MediaType value) {
469      mediaType = value;
470      return this;
471   }
472
473   /**
474    * Sets the parser to use for this content.
475    *
476    * @param value The new value for this setting.
477    * @return This object.
478    */
479   public RequestContent parser(Parser value) {
480      parser = value;
481      return this;
482   }
483
484   /**
485    * Sets the parsers to use for parsing this content.
486    *
487    * @param value The new value for this setting.
488    * @return This object.
489    */
490   public RequestContent parsers(ParserSet value) {
491      parsers = value;
492      return this;
493   }
494
495   /**
496    * Sets the schema for this content.
497    *
498    * @param schema The new schema for this content.
499    * @return This object.
500    */
501   public RequestContent setSchema(HttpPartSchema schema) {
502      this.schema = schema;
503      return this;
504   }
505
506   private <T> ClassMeta<T> getClassMeta(Class<T> type) {
507      return req.getMarshallingSession().getClassMeta(type);
508   }
509
510   private <T> ClassMeta<T> getClassMeta(Type type, Type...args) {
511      return req.getMarshallingSession().getClassMeta(type, args);
512   }
513
514   private Encoder getEncoder() throws UnsupportedMediaType {
515      if (encoder == null) {
516         var ce = req.getHeaderParam("content-encoding").orElse(null);
517         if (ine(ce)) {
518            ce = ce.trim();
519            encoder = encoders.getEncoder(ce);
520            if (encoder == null)
521               throw new UnsupportedMediaType("Unsupported encoding in request header 'Content-Encoding': '%s'\n\tSupported codings: %s",
522                  req.getHeaderParam("content-encoding").orElse(null), Json5.of(encoders.getSupportedEncodings()));
523         }
524
525         if (nn(encoder))
526            contentLength = -1;
527      }
528      // Note that if this is the identity encoder, we want to return null
529      // so that we don't needlessly wrap the input stream.
530      if (encoder == IdentityEncoder.INSTANCE)
531         return null;
532      return encoder;
533   }
534
535   private <T> T getInner(ClassMeta<T> cm) throws BadRequest, UnsupportedMediaType, InternalServerError {
536      try {
537         return parse(cm);
538      } catch (UnsupportedMediaType e) {
539         throw e;
540      } catch (SchemaValidationException e) {
541         throw new BadRequest("Validation failed on request content. " + localizedMessage(e));
542      } catch (ParseException e) {
543         throw new BadRequest(e, "Could not convert request content content to class type '%s'.", cm);
544      } catch (IOException e) {
545         throw new InternalServerError(e, "I/O exception occurred while parsing request content.");
546      } catch (Exception e) {
547         throw new InternalServerError(e, "Exception occurred while parsing request content.");
548      }
549   }
550
551   private MediaType getMediaType() {
552      if (nn(mediaType))
553         return mediaType;
554      var ct = req.getHeader(ContentType.class);
555      if (! ct.isPresent() && nn(content))
556         return MediaType.UON;
557      return ct.isPresent() ? ct.get().asMediaType().orElse(null) : null;
558   }
559
560   /* Workhorse method */
561   @SuppressWarnings({
562      "java:S3776" // Cognitive complexity acceptable for content parsing/schema validation
563   })
564   private <T> T parse(ClassMeta<T> cm) throws SchemaValidationException, ParseException, UnsupportedMediaType, IOException {
565
566      if (cm.isReader())
567         return (T)getReader();
568
569      if (cm.isInputStream())
570         return (T)getInputStream();
571
572      var timeZone = req.getTimeZone();
573      var locale = req.getLocale();
574      var pm = getParserMatch().orElse(null);
575
576      if (schema == null)
577         schema = HttpPartSchema.DEFAULT;
578
579      if (nn(pm)) {
580         var p = pm.getParser();
581         var mediaType2 = pm.getMediaType();
582         // @formatter:off
583         var session = p
584            .createSession()
585            .properties(req.getParserSessionPropertyMap())
586            .javaMethod(req.getOpContext().getJavaMethod())
587            .locale(locale)
588            .timeZone(timeZone.orElse(null))
589            .mediaType(mediaType2)
590            .apply(ReaderParser.Builder.class, x -> x.streamCharset(req.getCharset()))
591            .schema(schema)
592            .debug(req.isDebugMarshalling() ? true : null)
593            .build();
594         // @formatter:on
595
596         try (Closeable in = session.isReaderParser() ? getUnbufferedReader() : getInputStream()) {
597            var o = session.read(in, cm);
598            drainQuietly(in);
599            if (nn(schema))
600               schema.validateOutput(o);
601            return o;
602         }
603      }
604
605      if (cm.hasReaderMutater())
606         return convertUnparsed(getReader(), cm);
607
608      if (cm.hasInputStreamMutater())
609         return convertUnparsed(getInputStream(), cm);
610
611      var mt = getMediaType();
612
613      if ((isEmpty(s(mt)) || mt.toString().startsWith("text/plain")) && cm.hasStringMutater())
614         return BasicConverter.INSTANCE.to(asString(), cm.inner());
615
616      throw unsupportedMediaType(null);
617   }
618
619   // Converts the unparsed content using the type's own Reader/InputStream constructor or factory method.
620   //
621   // When the request named a Content-Type that matched no parser, a conversion failure means the content was in a
622   // media type nobody here understands (for example JSON5 into the strict-JSON JsonMap(Reader) constructor), so it is
623   // reported as 415 rather than as a 500.  Without a Content-Type the failure propagates as before.
624   private <T> T convertUnparsed(Object in, ClassMeta<T> cm) throws UnsupportedMediaType {
625      try {
626         return BasicConverter.INSTANCE.to(in, cm.inner());
627      } catch (RuntimeException e) {
628         if (isEmpty(s(req.getHeader(ContentType.class).flatMap(ContentType::asMediaType).orElse(null))))
629            throw e;
630         throw unsupportedMediaType(e);
631      }
632   }
633
634   private UnsupportedMediaType unsupportedMediaType(Throwable cause) {
635      var ct = req.getHeader(ContentType.class);
636      return new UnsupportedMediaType(cause, "Unsupported media-type in request header 'Content-Type': '%s'\n\tSupported media-types: %s",
637         ct.isPresent() ? ct.get().asMediaType().orElse(null) : "not-specified", Json5.of(req.getOpContext().getParsers().getSupportedMediaTypes()));
638   }
639
640   // Reads and discards whatever remains of the request entity after a parser has returned.
641   //
642   // A parser stops as soon as the top-level value is complete, leaving the end of the entity unread: for a
643   // Transfer-Encoding: chunked request, at least the zero-length terminating chunk whenever the client flushes it
644   // separately from the content.  If that is still unread when the response completes, the container finds
645   // unconsumed request content and aborts the connection.  By then the response is usually committed, so no
646   // Connection: close can be added, and a client reusing the pooled keep-alive connection fails its next request
647   // with an immediate EOF.  Draining here (blocking until end-of-stream) keeps the connection reusable.
648   //
649   // Best effort: the stream is still bounded by @Rest(maxInput), and any failure (limit exceeded, client gone)
650   // just falls back to the container's own unconsumed-content handling.
651   /**
652    * Same as {@link #getReader()}, but doesn't encapsulate the result in a {@link BufferedReader};
653    *
654    * @return An unbuffered reader.
655    * @throws IOException Thrown by underlying stream.
656    */
657   protected Reader getUnbufferedReader() throws IOException {
658      if (nn(content))
659         return new CharSequenceReader(new String(content, UTF8));
660      return new InputStreamReader(getInputStream(), req.getCharset());
661   }
662
663   boolean isLoaded() { return nn(content); }
664}