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.ChannelHandler.Sharable;
20 import io.netty.channel.ChannelHandlerContext;
21 import io.netty.handler.codec.MessageToByteEncoder;
22
23 import org.jboss.marshalling.Marshaller;
24
25
26
27
28
29
30
31
32
33
34
35
36
37 @Sharable
38 public class MarshallingEncoder extends MessageToByteEncoder<Object> {
39
40 private static final byte[] LENGTH_PLACEHOLDER = new byte[4];
41 private final MarshallerProvider provider;
42
43
44
45
46
47
48 public MarshallingEncoder(MarshallerProvider provider) {
49 super(Object.class);
50 this.provider = provider;
51 }
52
53 @Override
54 protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
55 Marshaller marshaller = provider.getMarshaller(ctx);
56 int lengthPos = out.writerIndex();
57 out.writeBytes(LENGTH_PLACEHOLDER);
58 ChannelBufferByteOutput output = new ChannelBufferByteOutput(out);
59 marshaller.start(output);
60 marshaller.writeObject(msg);
61 marshaller.finish();
62 marshaller.close();
63
64 out.setInt(lengthPos, out.writerIndex() - lengthPos - 4);
65 }
66 }