1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28 package org.apache.http.nio.testserver;
29
30 import java.nio.ByteBuffer;
31
32 import org.apache.commons.logging.Log;
33
34 class Wire {
35
36 private final Log log;
37 private final String id;
38
39 public Wire(final Log log, final String id) {
40 super();
41 this.log = log;
42 this.id = id;
43 }
44
45 private void wire(final String header, final byte[] b, final int pos, final int off) {
46 final StringBuilder buffer = new StringBuilder();
47 for (int i = 0; i < off; i++) {
48 final int ch = b[pos + i];
49 if (ch == 13) {
50 buffer.append("[\\r]");
51 } else if (ch == 10) {
52 buffer.append("[\\n]\"");
53 buffer.insert(0, "\"");
54 buffer.insert(0, header);
55 this.log.debug(this.id + " " + buffer.toString());
56 buffer.setLength(0);
57 } else if ((ch < 32) || (ch > 127)) {
58 buffer.append("[0x");
59 buffer.append(Integer.toHexString(ch));
60 buffer.append("]");
61 } else {
62 buffer.append((char) ch);
63 }
64 }
65 if (buffer.length() > 0) {
66 buffer.append('\"');
67 buffer.insert(0, '\"');
68 buffer.insert(0, header);
69 this.log.debug(this.id + " " + buffer.toString());
70 }
71 }
72
73
74 public boolean isEnabled() {
75 return this.log.isDebugEnabled();
76 }
77
78 public void output(final byte[] b, final int pos, final int off) {
79 wire("<< ", b, pos, off);
80 }
81
82 public void input(final byte[] b, final int pos, final int off) {
83 wire(">> ", b, pos, off);
84 }
85
86 public void output(final byte[] b) {
87 output(b, 0, b.length);
88 }
89
90 public void input(final byte[] b) {
91 input(b, 0, b.length);
92 }
93
94 public void output(final int b) {
95 output(new byte[] {(byte) b});
96 }
97
98 public void input(final int b) {
99 input(new byte[] {(byte) b});
100 }
101
102 public void output(final ByteBuffer b) {
103 if (b.hasArray()) {
104 output(b.array(), b.arrayOffset() + b.position(), b.remaining());
105 } else {
106 final byte[] tmp = new byte[b.remaining()];
107 b.get(tmp);
108 output(tmp);
109 }
110 }
111
112 public void input(final ByteBuffer b) {
113 if (b.hasArray()) {
114 input(b.array(), b.arrayOffset() + b.position(), b.remaining());
115 } else {
116 final byte[] tmp = new byte[b.remaining()];
117 b.get(tmp);
118 input(tmp);
119 }
120 }
121
122 }