1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.marshalling;
17
18 import java.io.StreamCorruptedException;
19
20 import org.jboss.marshalling.ByteInput;
21 import org.jboss.marshalling.Unmarshaller;
22 import org.jboss.netty.buffer.ChannelBuffer;
23 import org.jboss.netty.channel.Channel;
24 import org.jboss.netty.channel.ChannelHandlerContext;
25 import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
26 import org.jboss.netty.handler.codec.frame.TooLongFrameException;
27
28
29
30
31
32
33
34 public class MarshallingDecoder extends LengthFieldBasedFrameDecoder {
35
36 private final UnmarshallerProvider provider;
37
38
39
40
41
42
43
44
45 public MarshallingDecoder(UnmarshallerProvider provider) {
46 this(provider, 1048576);
47 }
48
49
50
51
52
53
54
55
56
57 public MarshallingDecoder(UnmarshallerProvider provider, int maxObjectSize) {
58 super(maxObjectSize, 0, 4, 0, 4);
59 this.provider = provider;
60 }
61
62
63 @Override
64 protected Object decode(
65 ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
66
67 ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
68 if (frame == null) {
69 return null;
70 }
71
72 Unmarshaller unmarshaller = provider.getUnmarshaller(ctx);
73 ByteInput input = new ChannelBufferByteInput(frame);
74
75 try {
76 unmarshaller.start(input);
77 Object obj = unmarshaller.readObject();
78 unmarshaller.finish();
79 return obj;
80 } finally {
81
82
83 unmarshaller.close();
84 }
85 }
86
87 @Override
88 protected ChannelBuffer extractFrame(ChannelBuffer buffer, int index, int length) {
89 return buffer.slice(index, length);
90 }
91 }