001// *************************************************************************************************************************** 002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file * 003// * distributed with this work for additional information regarding copyright ownership. The ASF licenses this file * 004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance * 005// * with the License. You may obtain a copy of the License at * 006// * * 007// * http://www.apache.org/licenses/LICENSE-2.0 * 008// * * 009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an * 010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * 011// * specific language governing permissions and limitations under the License. * 012// *************************************************************************************************************************** 013package org.apache.juneau.rest.util; 014 015import static org.apache.juneau.common.internal.IOUtils.*; 016 017import java.io.IOException; 018 019import jakarta.servlet.ServletInputStream; 020import jakarta.servlet.http.HttpServletRequest; 021import jakarta.servlet.http.HttpServletRequestWrapper; 022 023/** 024 * Wraps an {@link HttpServletRequest} and preloads the content into memory for debugging purposes. 025 * 026 * <h5 class='section'>See Also:</h5><ul> 027 * </ul> 028 */ 029public class CachingHttpServletRequest extends HttpServletRequestWrapper { 030 031 private final byte[] content; 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) 042 return (CachingHttpServletRequest)req; 043 return new CachingHttpServletRequest(req); 044 } 045 046 /** 047 * Constructor. 048 * 049 * @param req The request being wrapped. 050 * @throws IOException If content could not be loaded into memory. 051 */ 052 protected CachingHttpServletRequest(HttpServletRequest req) throws IOException { 053 super(req); 054 this.content = readBytes(req.getInputStream()); 055 } 056 057 @Override 058 public ServletInputStream getInputStream() { 059 return new BoundedServletInputStream(content); 060 } 061 062 /** 063 * Returns the content of the servlet request without consuming the stream. 064 * 065 * @return The content of the request. 066 */ 067 public byte[] getContent() { 068 return content; 069 } 070}