01: /*
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
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.common;
21:
22: /**
23: * Provides utility methods for an {@link IoBuffer}.
24: *
25: * @author The Apache MINA Project (dev@mina.apache.org)
26: * @version $Rev: 581239 $, $Date: 2007-10-02 07:51:26 -0600 (Tue, 02 Oct 2007) $
27: */
28: class IoBufferHexDumper {
29: private static final byte[] highDigits;
30:
31: private static final byte[] lowDigits;
32:
33: // initialize lookup tables
34: static {
35: final byte[] digits = { '0', '1', '2', '3', '4', '5', '6', '7',
36: '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
37:
38: int i;
39: byte[] high = new byte[256];
40: byte[] low = new byte[256];
41:
42: for (i = 0; i < 256; i++) {
43: high[i] = digits[i >>> 4];
44: low[i] = digits[i & 0x0F];
45: }
46:
47: highDigits = high;
48: lowDigits = low;
49: }
50:
51: public static String getHexdump(IoBuffer in, int lengthLimit) {
52: if (lengthLimit == 0) {
53: throw new IllegalArgumentException("lengthLimit: "
54: + lengthLimit + " (expected: 1+)");
55: }
56:
57: boolean truncate = in.remaining() > lengthLimit;
58: int size;
59: if (truncate) {
60: size = lengthLimit;
61: } else {
62: size = in.remaining();
63: }
64:
65: if (size == 0) {
66: return "empty";
67: }
68:
69: StringBuffer out = new StringBuffer(in.remaining() * 3 - 1);
70:
71: int mark = in.position();
72:
73: // fill the first
74: int byteValue = in.get() & 0xFF;
75: out.append((char) highDigits[byteValue]);
76: out.append((char) lowDigits[byteValue]);
77: size--;
78:
79: // and the others, too
80: for (; size > 0; size--) {
81: out.append(' ');
82: byteValue = in.get() & 0xFF;
83: out.append((char) highDigits[byteValue]);
84: out.append((char) lowDigits[byteValue]);
85: }
86:
87: in.position(mark);
88:
89: if (truncate) {
90: out.append("...");
91: }
92:
93: return out.toString();
94: }
95: }
|