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.common.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 * <h5 class='section'>See Also:</h5><ul> 030 * </ul> 031 */ 032public class CachingHttpServletRequest extends HttpServletRequestWrapper { 033 034 private final byte[] content; 035 036 /** 037 * Wraps the specified request inside a {@link CachingHttpServletRequest} if it isn't already. 038 * 039 * @param req The request to wrap. 040 * @return The wrapped request. 041 * @throws IOException Thrown by underlying content stream. 042 */ 043 public static CachingHttpServletRequest wrap(HttpServletRequest req) throws IOException { 044 if (req instanceof CachingHttpServletRequest) 045 return (CachingHttpServletRequest)req; 046 return new CachingHttpServletRequest(req); 047 } 048 049 /** 050 * Constructor. 051 * 052 * @param req The request being wrapped. 053 * @throws IOException If content could not be loaded into memory. 054 */ 055 protected CachingHttpServletRequest(HttpServletRequest req) throws IOException { 056 super(req); 057 this.content = readBytes(req.getInputStream()); 058 } 059 060 @Override 061 public ServletInputStream getInputStream() { 062 return new BoundedServletInputStream(content); 063 } 064 065 /** 066 * Returns the content of the servlet request without consuming the stream. 067 * 068 * @return The content of the request. 069 */ 070 public byte[] getContent() { 071 return content; 072 } 073}