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.util;
018
019import static org.apache.juneau.commons.utils.IoUtils.*;
020
021import java.io.*;
022
023import jakarta.servlet.*;
024import jakarta.servlet.http.*;
025
026/**
027 * Wraps an {@link HttpServletRequest} and preloads the content into memory for debugging purposes.
028 *
029 */
030@SuppressWarnings("resource")
031public class CachingHttpServletRequest extends HttpServletRequestWrapper {
032
033   /**
034    * Wraps the specified request inside a {@link CachingHttpServletRequest} if it isn't already.
035    *
036    * @param req The request to wrap.
037    * @return The wrapped request.
038    * @throws IOException Thrown by underlying content stream.
039    */
040   public static CachingHttpServletRequest wrap(HttpServletRequest req) throws IOException {
041      if (req instanceof CachingHttpServletRequest req2)
042         return req2;
043      return new CachingHttpServletRequest(req);
044   }
045
046   private final byte[] content;
047
048   /**
049    * Constructor.
050    *
051    * @param req The request being wrapped.
052    * @throws IOException If content could not be loaded into memory.
053    */
054   protected CachingHttpServletRequest(HttpServletRequest req) throws IOException {
055      super(req);
056      this.content = readBytes(req.getInputStream());
057   }
058
059   /**
060    * Returns the content of the servlet request without consuming the stream.
061    *
062    * @return The content of the request.
063    */
064   public byte[] getContent() { return content; }
065
066   @Override
067   public ServletInputStream getInputStream() { return new BoundedServletInputStream(content); }
068}