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.hc.core5.testing.classic;
29
30 import java.nio.ByteBuffer;
31
32 import org.apache.hc.core5.http.Chars;
33 import org.slf4j.Logger;
34
35 public class Wire {
36
37 private final Logger log;
38 private final String id;
39
40 public Wire(final Logger log, final String id) {
41 super();
42 this.log = log;
43 this.id = id;
44 }
45
46 private void wire(final String header, final byte[] b, final int pos, final int off) {
47 final StringBuilder buffer = new StringBuilder();
48 for (int i = 0; i < off; i++) {
49 final int ch = b[pos + i];
50 if (ch == Chars.CR) {
51 buffer.append("[\\r]");
52 } else if (ch == Chars.LF) {
53 buffer.append("[\\n]\"");
54 buffer.insert(0, "\"");
55 buffer.insert(0, header);
56 this.log.debug("{} {}", this.id, buffer);
57 buffer.setLength(0);
58 } else if ((ch < Chars.SP) || (ch >= Chars.DEL)) {
59 buffer.append("[0x");
60 buffer.append(Integer.toHexString(ch));
61 buffer.append("]");
62 } else {
63 buffer.append((char) ch);
64 }
65 }
66 if (buffer.length() > 0) {
67 buffer.append('\"');
68 buffer.insert(0, '\"');
69 buffer.insert(0, header);
70 this.log.debug("{} {}", this.id, buffer);
71 }
72 }
73
74
75 public boolean isEnabled() {
76 return this.log.isDebugEnabled();
77 }
78
79 public void output(final byte[] b, final int pos, final int off) {
80 wire(">> ", b, pos, off);
81 }
82
83 public void input(final byte[] b, final int pos, final int off) {
84 wire("<< ", b, pos, off);
85 }
86
87 public void output(final byte[] b) {
88 output(b, 0, b.length);
89 }
90
91 public void input(final byte[] b) {
92 input(b, 0, b.length);
93 }
94
95 public void output(final int b) {
96 output(new byte[] {(byte) b});
97 }
98
99 public void input(final int b) {
100 input(new byte[] {(byte) b});
101 }
102
103 public void output(final ByteBuffer b) {
104 if (b.hasArray()) {
105 output(b.array(), b.arrayOffset() + b.position(), b.remaining());
106 } else {
107 final byte[] tmp = new byte[b.remaining()];
108 b.get(tmp);
109 output(tmp);
110 }
111 }
112
113 public void input(final ByteBuffer b) {
114 if (b.hasArray()) {
115 input(b.array(), b.arrayOffset() + b.position(), b.remaining());
116 } else {
117 final byte[] tmp = new byte[b.remaining()];
118 b.get(tmp);
119 input(tmp);
120 }
121 }
122
123 }