View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, 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.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 javax.servlet.ServletInputStream;
22  import javax.servlet.http.HttpServletRequest;
23  
24  class TeeServletInputStream extends ServletInputStream {
25  
26    InputStream in;
27    byte[] inputBuffer;
28  
29    TeeServletInputStream(HttpServletRequest request) {
30      duplicateInputStream(request);
31    }
32  
33    @Override
34    public int read() throws IOException {
35      return in.read();
36    }
37  
38    private void duplicateInputStream(HttpServletRequest request) {
39      ServletInputStream originalSIS = null;
40      try {
41        originalSIS = request.getInputStream();
42        inputBuffer = consumeBufferAndReturnAsByteArray(originalSIS);
43        this.in = new ByteArrayInputStream(inputBuffer);
44      } catch (IOException e) {
45        e.printStackTrace();
46      } finally {
47        closeStrean(originalSIS);
48      }
49    }
50  
51    byte[] consumeBufferAndReturnAsByteArray(InputStream is) throws IOException {
52      int len = 1024;
53      byte[] temp = new byte[len];
54      int c = -1;
55      ByteArrayOutputStream baos = new ByteArrayOutputStream();
56      while ((c = is.read(temp, 0, len)) != -1) {
57        baos.write(temp, 0, c);
58      }
59      return baos.toByteArray();
60    }
61  
62  
63    void closeStrean(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  }