1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2015, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.access.common.servlet;
15  
16  import java.io.BufferedReader;
17  import java.io.IOException;
18  import java.io.InputStreamReader;
19  
20  import ch.qos.logback.access.common.AccessConstants;
21  import jakarta.servlet.ServletInputStream;
22  import jakarta.servlet.http.HttpServletRequest;
23  import jakarta.servlet.http.HttpServletRequestWrapper;
24  
25  /**
26   * As the "tee" program on Unix, duplicate the request's input stream.
27   *
28   * @author Ceki Gülcü
29   */
30  class TeeHttpServletRequest extends HttpServletRequestWrapper {
31  
32      private TeeServletInputStream inStream;
33      private BufferedReader reader;
34      boolean postedParametersMode = false;
35  
36      TeeHttpServletRequest(HttpServletRequest request) {
37          super(request);
38          // we can't access the input stream and access the request parameters
39          // at the same time
40          if (Util.isFormUrlEncoded(request)) {
41              postedParametersMode = true;
42          } else {
43              inStream = new TeeServletInputStream(request);
44              // add the contents of the input buffer as an attribute of the request
45              request.setAttribute(AccessConstants.LB_INPUT_BUFFER, inStream.getInputBuffer());
46              reader = new BufferedReader(new InputStreamReader(inStream));
47          }
48  
49      }
50  
51      byte[] getInputBuffer() {
52          if (postedParametersMode) {
53              throw new IllegalStateException("Call disallowed in postedParametersMode");
54          }
55          return inStream.getInputBuffer();
56      }
57  
58      @Override
59      public ServletInputStream getInputStream() throws IOException {
60          if (!postedParametersMode) {
61              return inStream;
62          } else {
63              return super.getInputStream();
64          }
65      }
66  
67      //
68  
69      @Override
70      public BufferedReader getReader() throws IOException {
71          if (!postedParametersMode) {
72              return reader;
73          } else {
74              return super.getReader();
75          }
76      }
77  
78      public boolean isPostedParametersMode() {
79          return postedParametersMode;
80      }
81  
82  }