1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20 package org.apache.mina.core.buffer;
21
22 /**
23 * Provides utility methods to dump an {@link IoBuffer} into a hex formatted string.
24 *
25 * @author <a href="http://mina.apache.org">Apache MINA Project</a>
26 */
27 class IoBufferHexDumper {
28
29 /**
30 * The high digits lookup table.
31 */
32 private static final byte[] highDigits;
33
34 /**
35 * The low digits lookup table.
36 */
37 private static final byte[] lowDigits;
38
39 /**
40 * Initialize lookup tables.
41 */
42 static {
43 final byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
44
45 int i;
46 byte[] high = new byte[256];
47 byte[] low = new byte[256];
48
49 for (i = 0; i < 256; i++) {
50 high[i] = digits[i >>> 4];
51 low[i] = digits[i & 0x0F];
52 }
53
54 highDigits = high;
55 lowDigits = low;
56 }
57
58 /**
59 * Dumps an {@link IoBuffer} to a hex formatted string.
60 *
61 * @param in the buffer to dump
62 * @param lengthLimit the limit at which hex dumping will stop
63 * @return a hex formatted string representation of the <i>in</i> {@link Iobuffer}.
64 */
65 public static String getHexdump(IoBuffer in, int lengthLimit) {
66 if (lengthLimit == 0) {
67 throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)");
68 }
69
70 boolean truncate = in.remaining() > lengthLimit;
71 int size;
72 if (truncate) {
73 size = lengthLimit;
74 } else {
75 size = in.remaining();
76 }
77
78 if (size == 0) {
79 return "empty";
80 }
81
82 StringBuilder out = new StringBuilder(size * 3 + 3);
83
84 int mark = in.position();
85
86 // fill the first
87 int byteValue = in.get() & 0xFF;
88 out.append((char) highDigits[byteValue]);
89 out.append((char) lowDigits[byteValue]);
90 size--;
91
92 // and the others, too
93 for (; size > 0; size--) {
94 out.append(' ');
95 byteValue = in.get() & 0xFF;
96 out.append((char) highDigits[byteValue]);
97 out.append((char) lowDigits[byteValue]);
98 }
99
100 in.position(mark);
101
102 if (truncate) {
103 out.append("...");
104 }
105
106 return out.toString();
107 }
108 }