1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.asn1.codec.stateful.examples;
18
19 import java.nio.ByteBuffer;
20
21 import org.apache.asn1.codec.EncoderException;
22 import org.apache.asn1.codec.stateful.EncoderCallback;
23 import org.apache.asn1.codec.stateful.EncoderMonitor;
24 import org.apache.asn1.codec.stateful.EncoderMonitorAdapter;
25 import org.apache.asn1.codec.stateful.StatefulEncoder;
26
27
28 /***
29 * Document me.
30 *
31 * @author <a href="mailto:dev@directory.apache.org"> Apache Directory
32 * Project</a> $Rev: 161723 $
33 */
34 public class HexEncoder implements StatefulEncoder
35 {
36 private static final int CHUNK_SZ = 128;
37 private ByteBuffer buf = ByteBuffer.allocate( CHUNK_SZ );
38 private EncoderMonitor monitor = new EncoderMonitorAdapter();
39 private EncoderCallback cb = new EncoderCallback() {
40 public void encodeOccurred( StatefulEncoder encoder, Object encoded )
41 {
42 }
43 };
44 private final byte[] HEXCHAR_LUT = {
45 (byte)'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
46 'a', 'b', 'c', 'd', 'e', 'f'
47 };
48
49
50 /***
51 * Transforms a decoded ByteArray of binary data into a stream of ASCII hex
52 * characters.
53 *
54 * @param obj
55 * @throws org.apache.asn1.codec.EncoderException
56 */
57 public void encode( Object obj ) throws EncoderException
58 {
59 ByteBuffer raw = ( ByteBuffer ) obj;
60
61 if ( raw == null || ! raw.hasRemaining() )
62 {
63 return;
64 }
65
66
67
68
69
70
71 while( raw.hasRemaining() )
72 {
73 if ( ! buf.hasRemaining() )
74 {
75 buf.flip();
76 cb.encodeOccurred( this, buf );
77 monitor.callbackOccured( this, cb, buf );
78 buf.clear();
79 }
80
81 byte bite = raw.get();
82 buf.put( HEXCHAR_LUT[( bite >> 4 ) & 0x0000000F] );
83 buf.put( HEXCHAR_LUT[bite & 0x0000000F] );
84 }
85
86 buf.flip();
87 cb.encodeOccurred( this, buf );
88 monitor.callbackOccured( this, cb, buf );
89 buf.clear();
90 }
91
92
93 public void setCallback( EncoderCallback cb )
94 {
95 EncoderCallback old = this.cb;
96 this.cb = cb;
97 monitor.callbackSet( this, old, cb );
98 }
99
100
101 public void setEncoderMonitor( EncoderMonitor monitor )
102 {
103 this.monitor = monitor;
104 }
105 }