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 * https://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.CodedOutputByteBufferNano;
19 import com.google.protobuf.nano.MessageNano;
20
21 import java.util.List;
22
23 import io.netty.buffer.ByteBuf;
24 import io.netty.channel.ChannelHandler;
25 import io.netty.channel.ChannelHandlerContext;
26 import io.netty.channel.ChannelPipeline;
27 import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
28 import io.netty.handler.codec.LengthFieldPrepender;
29 import io.netty.handler.codec.MessageToMessageEncoder;
30
31 /**
32 * Encodes the requested <a href="https://github.com/google/protobuf">Google
33 * Protocol Buffers</a> {@link MessageNano} into a
34 * {@link ByteBuf}. A typical setup for TCP/IP would be:
35 * <pre>
36 * {@link ChannelPipeline} pipeline = ...;
37 *
38 * // Decoders
39 * pipeline.addLast("frameDecoder",
40 * new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
41 * pipeline.addLast("protobufDecoder",
42 * new {@link ProtobufDecoderNano}(MyMessage.getDefaultInstance()));
43 *
44 * // Encoder
45 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
46 * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoderNano}());
47 * </pre>
48 * and then you can use a {@code MyMessage} instead of a {@link ByteBuf}
49 * as a message:
50 * <pre>
51 * void channelRead({@link ChannelHandlerContext} ctx, Object msg) {
52 * MyMessage req = (MyMessage) msg;
53 * MyMessage res = MyMessage.newBuilder().setText(
54 * "Did you say '" + req.getText() + "'?").build();
55 * ch.write(res);
56 * }
57 * </pre>
58 */
59 @ChannelHandler.Sharable
60 public class ProtobufEncoderNano extends MessageToMessageEncoder<MessageNano> {
61 @Override
62 protected void encode(
63 ChannelHandlerContext ctx, MessageNano msg, List<Object> out) throws Exception {
64 final int size = msg.getSerializedSize();
65 final ByteBuf buffer = ctx.alloc().heapBuffer(size, size);
66 final byte[] array = buffer.array();
67 CodedOutputByteBufferNano cobbn = CodedOutputByteBufferNano.newInstance(array,
68 buffer.arrayOffset(), buffer.capacity());
69 msg.writeTo(cobbn);
70 buffer.writerIndex(size);
71 out.add(buffer);
72 }
73 }