View Javadoc
1   /*
2    * Copyright 2012 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, MyMessage req) {
57   *     MyMessage res = MyMessage.newBuilder().setText(
58   *                               "Did you say '" + req.getText() + "'?").build();
59   *     ch.write(res);
60   * }
61   * </pre>
62   */
63  @Sharable
64  public class ProtobufDecoder extends MessageToMessageDecoder<ByteBuf> {
65  
66      private static final boolean HAS_PARSER;
67  
68      static {
69          boolean hasParser = false;
70          try {
71              // MessageLite.getParserForType() is not available until protobuf 2.5.0.
72              MessageLite.class.getDeclaredMethod("getParserForType");
73              hasParser = true;
74          } catch (Throwable t) {
75              // Ignore
76          }
77  
78          HAS_PARSER = hasParser;
79      }
80  
81      private final MessageLite prototype;
82      private final ExtensionRegistryLite extensionRegistry;
83  
84      /**
85       * Creates a new instance.
86       */
87      public ProtobufDecoder(MessageLite prototype) {
88          this(prototype, null);
89      }
90  
91      public ProtobufDecoder(MessageLite prototype, ExtensionRegistry extensionRegistry) {
92          this(prototype, (ExtensionRegistryLite) extensionRegistry);
93      }
94  
95      public ProtobufDecoder(MessageLite prototype, ExtensionRegistryLite extensionRegistry) {
96          if (prototype == null) {
97              throw new NullPointerException("prototype");
98          }
99          this.prototype = prototype.getDefaultInstanceForType();
100         this.extensionRegistry = extensionRegistry;
101     }
102 
103     @Override
104     protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
105         final byte[] array;
106         final int offset;
107         final int length = msg.readableBytes();
108         if (msg.hasArray()) {
109             array = msg.array();
110             offset = msg.arrayOffset() + msg.readerIndex();
111         } else {
112             array = new byte[length];
113             msg.getBytes(msg.readerIndex(), array, 0, length);
114             offset = 0;
115         }
116 
117         if (extensionRegistry == null) {
118             if (HAS_PARSER) {
119                 out.add(prototype.getParserForType().parseFrom(array, offset, length));
120             } else {
121                 out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build());
122             }
123         } else {
124             if (HAS_PARSER) {
125                 out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry));
126             } else {
127                 out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build());
128             }
129         }
130     }
131 }
132