1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.mina.filter.codec.serialization;
21
22 import java.io.NotSerializableException;
23 import java.io.Serializable;
24
25 import org.apache.mina.core.buffer.IoBuffer;
26 import org.apache.mina.core.session.IoSession;
27 import org.apache.mina.filter.codec.ProtocolEncoder;
28 import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
29 import org.apache.mina.filter.codec.ProtocolEncoderOutput;
30
31
32
33
34
35
36
37 public class ObjectSerializationEncoder extends ProtocolEncoderAdapter {
38 private int maxObjectSize = Integer.MAX_VALUE;
39
40
41
42
43 public ObjectSerializationEncoder() {
44
45 }
46
47
48
49
50
51
52
53 public int getMaxObjectSize() {
54 return maxObjectSize;
55 }
56
57
58
59
60
61
62
63 public void setMaxObjectSize(int maxObjectSize) {
64 if (maxObjectSize <= 0) {
65 throw new IllegalArgumentException("maxObjectSize: "
66 + maxObjectSize);
67 }
68
69 this.maxObjectSize = maxObjectSize;
70 }
71
72 public void encode(IoSession session, Object message,
73 ProtocolEncoderOutput out) throws Exception {
74 if (!(message instanceof Serializable)) {
75 throw new NotSerializableException();
76 }
77
78 IoBuffer buf = IoBuffer.allocate(64);
79 buf.setAutoExpand(true);
80 buf.putObject(message);
81
82 int objectSize = buf.position() - 4;
83 if (objectSize > maxObjectSize) {
84 throw new IllegalArgumentException(
85 "The encoded object is too big: " + objectSize + " (> "
86 + maxObjectSize + ')');
87 }
88
89 buf.flip();
90 out.write(buf);
91 }
92 }