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.Message; 19 import com.google.protobuf.MessageLite; 20 import com.google.protobuf.MessageLiteOrBuilder; 21 import io.netty.buffer.ByteBuf; 22 import io.netty.channel.ChannelHandler.Sharable; 23 import io.netty.channel.ChannelHandlerContext; 24 import io.netty.channel.ChannelPipeline; 25 import io.netty.handler.codec.LengthFieldBasedFrameDecoder; 26 import io.netty.handler.codec.LengthFieldPrepender; 27 import io.netty.handler.codec.MessageToMessageEncoder; 28 29 import java.util.List; 30 31 import static io.netty.buffer.Unpooled.*; 32 33 /** 34 * Encodes the requested <a href="https://github.com/google/protobuf">Google 35 * Protocol Buffers</a> {@link Message} and {@link MessageLite} into a 36 * {@link ByteBuf}. 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 ProtobufDecoder}(MyMessage.getDefaultInstance())); 45 * 46 * // Encoder 47 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4)); 48 * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoder}()); 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 ProtobufEncoder extends MessageToMessageEncoder<MessageLiteOrBuilder> { 63 @Override 64 protected void encode(ChannelHandlerContext ctx, MessageLiteOrBuilder msg, List<Object> out) 65 throws Exception { 66 if (msg instanceof MessageLite) { 67 out.add(wrappedBuffer(((MessageLite) msg).toByteArray())); 68 return; 69 } 70 if (msg instanceof MessageLite.Builder) { 71 out.add(wrappedBuffer(((MessageLite.Builder) msg).build().toByteArray())); 72 } 73 } 74 }