1 20 package org.apache.mina.example.sumup.codec; 21 22 import org.apache.mina.common.ByteBuffer; 23 import org.apache.mina.common.IoSession; 24 import org.apache.mina.example.sumup.message.AbstractMessage; 25 import org.apache.mina.filter.codec.ProtocolDecoderOutput; 26 import org.apache.mina.filter.codec.demux.MessageDecoder; 27 import org.apache.mina.filter.codec.demux.MessageDecoderResult; 28 29 36 public abstract class AbstractMessageDecoder implements MessageDecoder { 37 private final int type; 38 39 private int sequence; 40 41 private boolean readHeader; 42 43 protected AbstractMessageDecoder(int type) { 44 this.type = type; 45 } 46 47 public MessageDecoderResult decodable(IoSession session, ByteBuffer in) { 48 if (in.remaining() < Constants.HEADER_LEN) { 50 return MessageDecoderResult.NEED_DATA; 51 } 52 53 if (type == in.getShort()) { 55 return MessageDecoderResult.OK; 56 } 57 58 return MessageDecoderResult.NOT_OK; 60 } 61 62 public MessageDecoderResult decode(IoSession session, ByteBuffer in, 63 ProtocolDecoderOutput out) throws Exception { 64 if (!readHeader) { 66 in.getShort(); sequence = in.getInt(); readHeader = true; 69 } 70 71 AbstractMessage m = decodeBody(session, in); 73 if (m == null) { 75 return MessageDecoderResult.NEED_DATA; 76 } else { 77 readHeader = false; } 79 m.setSequence(sequence); 80 out.write(m); 81 82 return MessageDecoderResult.OK; 83 } 84 85 88 protected abstract AbstractMessage decodeBody(IoSession session, 89 ByteBuffer in); 90 } 91 | Popular Tags |