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 com.google.protobuf.ExtensionRegistry;
19 import com.google.protobuf.Message;
20 import com.google.protobuf.MessageLite;
21 import org.jboss.netty.buffer.ChannelBuffer;
22 import org.jboss.netty.channel.Channel;
23 import org.jboss.netty.channel.ChannelHandler.Sharable;
24 import org.jboss.netty.channel.ChannelHandlerContext;
25 import org.jboss.netty.channel.ChannelPipeline;
26 import org.jboss.netty.channel.MessageEvent;
27 import org.jboss.netty.handler.codec.frame.FrameDecoder;
28 import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder;
29 import org.jboss.netty.handler.codec.frame.LengthFieldPrepender;
30 import org.jboss.netty.handler.codec.oneone.OneToOneDecoder;
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65 @Sharable
66 public class ProtobufDecoder extends OneToOneDecoder {
67 private static final boolean HAS_PARSER;
68
69 static {
70 boolean hasParser = false;
71 try {
72
73 MessageLite.class.getDeclaredMethod("getParserForType");
74 hasParser = true;
75 } catch (Throwable t) {
76
77 }
78
79 HAS_PARSER = hasParser;
80 }
81 private final MessageLite prototype;
82 private final ExtensionRegistry extensionRegistry;
83
84
85
86
87 public ProtobufDecoder(MessageLite prototype) {
88 this(prototype, null);
89 }
90
91 public ProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry) {
92 if (prototype == null) {
93 throw new NullPointerException("prototype");
94 }
95 this.prototype = prototype.getDefaultInstanceForType();
96 this.extensionRegistry = extensionRegistry;
97 }
98
99 @Override
100 protected Object decode(
101 ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
102 if (!(msg instanceof ChannelBuffer)) {
103 return msg;
104 }
105
106 ChannelBuffer buf = (ChannelBuffer) msg;
107 final byte[] array;
108 final int offset;
109 final int length = buf.readableBytes();
110
111 if (buf.hasArray()) {
112 array = buf.array();
113 offset = buf.arrayOffset() + buf.readerIndex();
114 } else {
115 array = new byte[length];
116 buf.getBytes(buf.readerIndex(), array, 0, length);
117 offset = 0;
118 }
119
120 if (extensionRegistry == null) {
121 if (HAS_PARSER) {
122 return prototype.getParserForType().parseFrom(array, offset, length);
123 } else {
124 return prototype.newBuilderForType().mergeFrom(array, offset, length).build();
125 }
126 } else {
127 if (HAS_PARSER) {
128 return prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry);
129 } else {
130 return prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build();
131 }
132 }
133 }
134 }