1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.jboss.netty.handler.codec.protobuf;
17
18 import static org.jboss.netty.buffer.ChannelBuffers.*;
19
20 import org.jboss.netty.buffer.ChannelBuffer;
21 import org.jboss.netty.buffer.ChannelBufferOutputStream;
22 import org.jboss.netty.channel.Channel;
23 import org.jboss.netty.channel.ChannelHandlerContext;
24 import org.jboss.netty.channel.ChannelHandler.Sharable;
25 import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
26
27 import com.google.protobuf.CodedOutputStream;
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48 @Sharable
49 public class ProtobufVarint32LengthFieldPrepender extends OneToOneEncoder {
50
51
52
53
54 public ProtobufVarint32LengthFieldPrepender() {
55 super();
56 }
57
58 @Override
59 protected Object encode(ChannelHandlerContext ctx, Channel channel,
60 Object msg) throws Exception {
61 if (!(msg instanceof ChannelBuffer)) {
62 return msg;
63 }
64
65 ChannelBuffer body = (ChannelBuffer) msg;
66 int length = body.readableBytes();
67 ChannelBuffer header =
68 channel.getConfig().getBufferFactory().getBuffer(
69 body.order(),
70 CodedOutputStream.computeRawVarint32Size(length));
71 CodedOutputStream codedOutputStream = CodedOutputStream
72 .newInstance(new ChannelBufferOutputStream(header));
73 codedOutputStream.writeRawVarint32(length);
74 codedOutputStream.flush();
75 return wrappedBuffer(header, body);
76 }
77
78 }