1
2
3
4
5
6
7
8
9
10
11
12
13 package org.abstracthorizon.danube.support.logging;
14
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.OutputStream;
18
19
20
21
22
23
24 public class LoggingInputStream extends InputStream {
25
26
27 protected InputStream inputStream;
28
29
30 protected OutputStream logOutputStream;
31
32
33 protected int marked = -1;
34
35
36 protected int ptr = 0;
37
38
39 protected boolean logging = true;
40
41
42
43
44
45
46 public LoggingInputStream(InputStream inputStream, OutputStream logOutputStream) {
47 this.inputStream = inputStream;
48 this.logOutputStream = logOutputStream;
49 }
50
51
52
53
54
55 public void setLogging(boolean logging) {
56 this.logging = logging;
57 }
58
59
60
61
62
63 public boolean isLogging() {
64 return logging;
65 }
66
67 @Override
68 public int available() throws IOException {
69 return inputStream.available();
70 }
71
72 @Override
73 public void close() throws IOException {
74 inputStream.close();
75 }
76
77 @Override
78 public void mark(int readlimit) {
79 inputStream.mark(readlimit);
80 marked = marked - ptr;
81 ptr = 0;
82 }
83
84 @Override
85 public boolean markSupported() {
86 return inputStream.markSupported();
87 }
88
89 @Override
90 public int read() throws IOException {
91 int i = inputStream.read();
92 if (i >= 0) {
93 if (ptr >= marked) {
94 if (logging) { logOutputStream.write(i); }
95 marked = marked + 1;
96 }
97 ptr = ptr + 1;
98 }
99 return i;
100 }
101
102 @Override
103 public int read(byte[] b) throws IOException {
104 return read(b, 0, b.length);
105 }
106
107 @Override
108 public int read(byte[] b, int off, int len) throws IOException {
109 int i = inputStream.read(b, off, len);
110 if (i > 0) {
111 if (ptr >= marked) {
112 if (logging) { logOutputStream.write(b, off, i); }
113 marked = marked + i;
114 } else if (ptr + i >= marked) {
115 int skip = marked - ptr;
116 if (i-skip > 0) {
117 if (logging) { logOutputStream.write(b, off+skip, i-skip); }
118 }
119 marked = marked + i-skip;
120 }
121 ptr = ptr + i;
122 }
123 return i;
124 }
125
126 @Override
127 public void reset() throws IOException {
128 inputStream.reset();
129 ptr = 0;
130 }
131
132 @Override
133 public long skip(long n) throws IOException {
134 ptr = ptr + (int)n;
135 return inputStream.skip(n);
136 }
137 }