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.ByteArrayInputStream;
17  import java.io.ByteArrayOutputStream;
18  import java.io.IOException;
19  import java.io.InputStream;
20  
21  import jakarta.servlet.ReadListener;
22  import jakarta.servlet.ServletInputStream;
23  import jakarta.servlet.http.HttpServletRequest;
24  
25  class TeeServletInputStream extends ServletInputStream {
26  
27      InputStream in;
28      byte[] inputBuffer;
29  
30      TeeServletInputStream(HttpServletRequest request) {
31          duplicateInputStream(request);
32      }
33  
34      private void duplicateInputStream(HttpServletRequest request) {
35          ServletInputStream originalSIS = null;
36          try {
37              originalSIS = request.getInputStream();
38              inputBuffer = consumeBufferAndReturnAsByteArray(originalSIS);
39              this.in = new ByteArrayInputStream(inputBuffer);
40          } catch (IOException e) {
41              e.printStackTrace();
42          } finally {
43              closeStream(originalSIS);
44          }
45      }
46  
47      @Override
48      public int read() throws IOException {
49          return in.read();
50      }
51  
52      byte[] consumeBufferAndReturnAsByteArray(InputStream is) throws IOException {
53          int len = 1024;
54          byte[] temp = new byte[len];
55          int c = -1;
56          ByteArrayOutputStream baos = new ByteArrayOutputStream();
57          while ((c = is.read(temp, 0, len)) != -1) {
58              baos.write(temp, 0, c);
59          }
60          return baos.toByteArray();
61      }
62  
63      void closeStream(ServletInputStream is) {
64          if (is != null) {
65              try {
66                  is.close();
67              } catch (IOException e) {
68              }
69          }
70      }
71  
72      byte[] getInputBuffer() {
73          return inputBuffer;
74      }
75  
76      @Override
77      public boolean isFinished() {
78          throw new RuntimeException("Not yet implemented");
79      }
80  
81      @Override
82      public boolean isReady() {
83          throw new RuntimeException("Not yet implemented");
84      }
85  
86      @Override
87      public void setReadListener(ReadListener listener) {
88          throw new RuntimeException("Not yet implemented");
89      }
90  }