View Javadoc
1   /*
2    * Copyright 2015 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.handler.codec.protobuf;
17  
18  import com.google.protobuf.ExtensionRegistry;
19  import com.google.protobuf.ExtensionRegistryLite;
20  import com.google.protobuf.Message;
21  import com.google.protobuf.MessageLite;
22  import io.netty.buffer.ByteBuf;
23  import io.netty.channel.ChannelHandler.Sharable;
24  import io.netty.channel.ChannelHandlerContext;
25  import io.netty.channel.ChannelPipeline;
26  import io.netty.handler.codec.ByteToMessageDecoder;
27  import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
28  import io.netty.handler.codec.LengthFieldPrepender;
29  import io.netty.handler.codec.MessageToMessageDecoder;
30  
31  import java.util.List;
32  
33  /**
34   * Decodes a received {@link ByteBuf} into a
35   * <a href="https://github.com/google/protobuf">Google Protocol Buffers</a>
36   * {@link Message} and {@link MessageLite}. Please note that this decoder must
37   * be used with a proper {@link ByteToMessageDecoder} such as {@link ProtobufVarint32FrameDecoder}
38   * or {@link LengthFieldBasedFrameDecoder} if you are using a stream-based
39   * transport such as TCP/IP. A typical setup for TCP/IP would be:
40   * <pre>
41   * {@link ChannelPipeline} pipeline = ...;
42   *
43   * // Decoders
44   * pipeline.addLast("frameDecoder",
45   *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
46   * pipeline.addLast("protobufDecoder",
47   *                  new {@link ProtobufDecoder}(MyMessage.getDefaultInstance()));
48   *
49   * // Encoder
50   * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
51   * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoder}());
52   * </pre>
53   * and then you can use a {@code MyMessage} instead of a {@link ByteBuf}
54   * as a message:
55   * <pre>
56   * void channelRead({@link ChannelHandlerContext} ctx, Object msg) {
57   *     MyMessage req = (MyMessage) msg;
58   *     MyMessage res = MyMessage.newBuilder().setText(
59   *                               "Did you say '" + req.getText() + "'?").build();
60   *     ch.write(res);
61   * }
62   * </pre>
63   */
64  @Sharable
65  public class ProtobufDecoder extends MessageToMessageDecoder<ByteBuf> {
66  
67      private static final boolean HAS_PARSER;
68  
69      static {
70          boolean hasParser = false;
71          try {
72              // MessageLite.getParserForType() is not available until protobuf 2.5.0.
73              MessageLite.class.getDeclaredMethod("getParserForType");
74              hasParser = true;
75          } catch (Throwable t) {
76              // Ignore
77          }
78  
79          HAS_PARSER = hasParser;
80      }
81  
82      private final MessageLite prototype;
83      private final ExtensionRegistryLite extensionRegistry;
84  
85      /**
86       * Creates a new instance.
87       */
88      public ProtobufDecoder(MessageLite prototype) {
89          this(prototype, null);
90      }
91  
92      public ProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry) {
93          this(prototype, (ExtensionRegistryLite) extensionRegistry);
94      }
95  
96      public ProtobufDecoder(MessageLite prototype, ExtensionRegistryLite extensionRegistry) {
97          if (prototype == null) {
98              throw new NullPointerException("prototype");
99          }
100         this.prototype = prototype.getDefaultInstanceForType();
101         this.extensionRegistry = extensionRegistry;
102     }
103 
104     @Override
105     protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
106             throws Exception {
107         final byte[] array;
108         final int offset;
109         final int length = msg.readableBytes();
110         if (msg.hasArray()) {
111             array = msg.array();
112             offset = msg.arrayOffset() + msg.readerIndex();
113         } else {
114             array = new byte[length];
115             msg.getBytes(msg.readerIndex(), array, 0, length);
116             offset = 0;
117         }
118 
119         if (extensionRegistry == null) {
120             if (HAS_PARSER) {
121                 out.add(prototype.getParserForType().parseFrom(array, offset, length));
122             } else {
123                 out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build());
124             }
125         } else {
126             if (HAS_PARSER) {
127                 out.add(prototype.getParserForType().parseFrom(
128                         array, offset, length, extensionRegistry));
129             } else {
130                 out.add(prototype.newBuilderForType().mergeFrom(
131                         array, offset, length, extensionRegistry).build());
132             }
133         }
134     }
135 }