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 @Override
63 protected Object decode(
64 ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
65
66 ChannelBuffer frame = (ChannelBuffer) super.decode(ctx, channel, buffer);
67 if (frame == null) {
68 return null;
69 }
70
71 Unmarshaller unmarshaller = provider.getUnmarshaller(ctx);
72 ByteInput input = new ChannelBufferByteInput(frame);
73
74 try {
75 unmarshaller.start(input);
76 Object obj = unmarshaller.readObject();
77 unmarshaller.finish();
78 return obj;
79 } finally {
80
81
82 unmarshaller.close();
83 }
84 }
85
86 @Override
87 protected ChannelBuffer extractFrame(ChannelBuffer buffer, int index, int length) {
88 return buffer.slice(index, length);
89 }
90 }