1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.mitosis.service.protocol.codec;
21
22
23 import org.apache.directory.mitosis.service.protocol.message.BaseMessage;
24 import org.apache.mina.common.ByteBuffer;
25 import org.apache.mina.common.IoSession;
26 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
27 import org.apache.mina.filter.codec.demux.MessageEncoder;
28
29
30 public abstract class BaseMessageEncoder implements MessageEncoder
31 {
32 public BaseMessageEncoder()
33 {
34 }
35
36
37 public final void encode( IoSession session, Object in, ProtocolEncoderOutput out ) throws Exception
38 {
39 BaseMessage m = ( BaseMessage ) in;
40 ByteBuffer buf = ByteBuffer.allocate( 16 );
41 buf.setAutoExpand( true );
42 buf.put( ( byte ) m.getType() );
43 buf.putInt( m.getSequence() );
44 buf.putInt( 0 );
45
46 final int bodyStartPos = buf.position();
47 encodeBody( m, buf );
48 final int bodyEndPos = buf.position();
49 final int bodyLength = bodyEndPos - bodyStartPos;
50
51
52 buf.position( bodyStartPos - 4 );
53 buf.putInt( bodyLength );
54 buf.position( bodyEndPos );
55
56 buf.flip();
57 out.write( buf );
58 }
59
60
61 protected abstract void encodeBody( BaseMessage in, ByteBuffer out ) throws Exception;
62 }