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