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.nano.MessageNano;
19  
20  import java.util.List;
21  
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.MessageToMessageDecoder;
29  import io.netty.util.internal.ObjectUtil;
30  
31  /**
32   * Decodes a received {@link ByteBuf} into a
33   * <a href="https://github.com/google/protobuf">Google Protocol Buffers</a>
34   * {@link MessageNano}. Please note that this decoder must
35   * be used with a proper {@link ByteToMessageDecoder} such as {@link LengthFieldBasedFrameDecoder}
36   * if you are using a stream-based transport such as TCP/IP. A typical setup for TCP/IP would be:
37   * <pre>
38   * {@link ChannelPipeline} pipeline = ...;
39   *
40   * // Decoders
41   * pipeline.addLast("frameDecoder",
42   *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
43   * pipeline.addLast("protobufDecoder",
44   *                  new {@link ProtobufDecoderNano}(MyMessage.getDefaultInstance()));
45   *
46   * // Encoder
47   * pipeline.addLast("frameEncoder", new {@link io.netty.handler.codec.LengthFieldPrepender}(4));
48   * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoderNano}());
49   * </pre>
50   * and then you can use a {@code MyMessage} instead of a {@link ByteBuf}
51   * as a message:
52   * <pre>
53   * void channelRead({@link ChannelHandlerContext} ctx, Object msg) {
54   *     MyMessage req = (MyMessage) msg;
55   *     MyMessage res = MyMessage.newBuilder().setText(
56   *                               "Did you say '" + req.getText() + "'?").build();
57   *     ch.write(res);
58   * }
59   * </pre>
60   */
61  @Sharable
62  public class ProtobufDecoderNano extends MessageToMessageDecoder<ByteBuf> {
63      private final Class<? extends MessageNano> clazz;
64      /**
65       * Creates a new instance.
66       */
67      public ProtobufDecoderNano(Class<? extends MessageNano> clazz) {
68          this.clazz = ObjectUtil.checkNotNull(clazz, "You must provide a Class");
69      }
70  
71      @Override
72      protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out)
73              throws Exception {
74          final byte[] array;
75          final int offset;
76          final int length = msg.readableBytes();
77          if (msg.hasArray()) {
78              array = msg.array();
79              offset = msg.arrayOffset() + msg.readerIndex();
80          } else {
81              array = new byte[length];
82              msg.getBytes(msg.readerIndex(), array, 0, length);
83              offset = 0;
84          }
85          MessageNano prototype = clazz.getConstructor().newInstance();
86          out.add(MessageNano.mergeFrom(prototype, array, offset, length));
87      }
88  }