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