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
25 public class DirectionalLoggingInputStream extends LoggingInputStream {
26
27
28 protected boolean flag = true;
29
30
31
32
33
34
35 public DirectionalLoggingInputStream(InputStream inputStream, OutputStream logOutputStream) {
36 super(inputStream, logOutputStream);
37 }
38
39 @Override
40 public int read() throws IOException {
41 int i = inputStream.read();
42 if (i >= 0) {
43 if (ptr >= marked) {
44 if (logging) { flag = output(flag, logOutputStream, '>', i); }
45 marked = marked + 1;
46 }
47 ptr = ptr + 1;
48 }
49 return i;
50 }
51
52 @Override
53 public int read(byte[] b, int off, int len) throws IOException {
54 int i = inputStream.read(b, off, len);
55 if (i > 0) {
56 if (ptr >= marked) {
57 if (logging) { flag = output(flag, logOutputStream, '>', b, off, i); }
58 marked = marked + i;
59 } else if (ptr + i >= marked) {
60 int skip = marked - ptr;
61 if (i-skip > 0) {
62 if (logging) { flag = output(flag, logOutputStream, '>', b, off+skip, i-skip); }
63 }
64 marked = marked + i-skip;
65 }
66 ptr = ptr + i;
67 }
68 return i;
69 }
70
71
72
73
74
75
76
77
78
79
80 public static boolean output(boolean flag, OutputStream out, char direction, int i) throws IOException {
81 if (flag) {
82 out.write(direction);
83 out.write(' ');
84 }
85 flag = false;
86 out.write(i);
87 if (i == '\n') {
88 flag = true;
89 }
90 return flag;
91 }
92
93
94
95
96
97
98
99
100
101
102
103
104 public static boolean output(boolean flag, OutputStream out, char direction, byte[] buf, int off, int len) throws IOException {
105 if (len == 0) {
106 return flag;
107 }
108
109 int start = off;
110 for (int i = off; i < off + len; i++) {
111 if (buf[i] == '\n') {
112 if (flag) {
113 out.write(direction);
114 out.write(' ');
115 }
116 out.write(buf, start, i - start + 1);
117 start = i + 1;
118 flag = true;
119 }
120 }
121 if (start < off + len) {
122 if (flag) {
123 out.write(direction);
124 out.write(' ');
125 }
126 out.write(buf, start, off + len - start);
127 flag = false;
128 }
129 return flag;
130 }
131
132 }