comparison src/org/dancres/blitz/remote/transport/MessageEncoder.java @ 0:3dc0c5604566

Initial checkin of blitz 2.0 fcs - no installer yet.
author Dan Creswell <dan.creswell@gmail.com>
date Sat, 21 Mar 2009 11:00:06 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:3dc0c5604566
1 package org.dancres.blitz.remote.transport;
2
3 import java.io.Serializable;
4 import java.io.NotSerializableException;
5 import java.io.IOException;
6
7 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
8 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
9 import org.apache.mina.common.IoSession;
10 import org.apache.mina.common.ByteBuffer;
11
12 /**
13 */
14 public class MessageEncoder extends ProtocolEncoderAdapter {
15 private int maxObjectSize = MessageCodecFactory.DEFAULT_MAX_OBJECT_SIZE;
16
17 /**
18 * Creates a new instance.
19 */
20 public MessageEncoder() {
21 }
22
23 /**
24 * Returns the allowed maximum size of the encoded object.
25 * If the size of the encoded object exceeds this value, this encoder
26 * will throw a {@link IllegalArgumentException}. The default value
27 * is {@link Integer#MAX_VALUE}.
28 */
29 public int getMaxObjectSize() {
30 return maxObjectSize;
31 }
32
33 /**
34 * Sets the allowed maximum size of the encoded object.
35 * If the size of the encoded object exceeds this value, this encoder
36 * will throw a {@link IllegalArgumentException}. The default value
37 * is {@link Integer#MAX_VALUE}.
38 */
39 public void setMaxObjectSize(int maxObjectSize) {
40 if (maxObjectSize <= 0) {
41 throw new IllegalArgumentException(
42 "maxObjectSize: " + maxObjectSize);
43 }
44
45 this.maxObjectSize = maxObjectSize;
46 }
47
48 public void encode(IoSession session, Object message,
49 ProtocolEncoderOutput out) throws Exception {
50 if (!(message instanceof Message)) {
51 throw new IOException("I'm only good for Messages");
52 }
53
54
55 Message myMessage = (Message) message;
56
57 ByteBuffer buf = ByteBuffer.allocate(1024);
58 buf.setAutoExpand(true);
59
60 /*
61 Ensure the message payload is within size limit
62 Write length field to buffer,
63 Write conversationId and
64 payload array.
65 Post bytebuffer to "out"
66 */
67 if ((myMessage.getPayload().length + 8) > maxObjectSize)
68 throw new IOException("Message is too large");
69
70 buf.putInt(4 + myMessage.getPayload().length);
71 buf.putInt(myMessage.getConversationId());
72 buf.put(myMessage.getPayload());
73
74 buf.flip();
75 out.write(buf);
76 }
77 }