1420c9859SShuo Chenpackage muduo.codec; 2420c9859SShuo Chen 3420c9859SShuo Chenimport java.util.zip.Adler32; 4420c9859SShuo Chen 5420c9859SShuo Chenimport org.jboss.netty.buffer.BigEndianHeapChannelBuffer; 6420c9859SShuo Chenimport org.jboss.netty.buffer.ChannelBuffer; 7420c9859SShuo Chenimport org.jboss.netty.channel.Channel; 8420c9859SShuo Chenimport org.jboss.netty.channel.ChannelHandler.Sharable; 9420c9859SShuo Chenimport org.jboss.netty.channel.ChannelHandlerContext; 10420c9859SShuo Chenimport org.jboss.netty.handler.codec.oneone.OneToOneEncoder; 11420c9859SShuo Chen 12420c9859SShuo Chenimport com.google.protobuf.Message; 13420c9859SShuo Chen 14420c9859SShuo Chen@Sharable 15420c9859SShuo Chenpublic class ProtobufEncoder extends OneToOneEncoder { 16420c9859SShuo Chen 17420c9859SShuo Chen public ProtobufEncoder() { 18420c9859SShuo Chen super(); 19420c9859SShuo Chen } 20420c9859SShuo Chen 21420c9859SShuo Chen @Override 22420c9859SShuo Chen public Object encode(ChannelHandlerContext ctx, Channel channel, Object obj) 23420c9859SShuo Chen throws Exception { 24420c9859SShuo Chen if (!(obj instanceof Message)) { 25420c9859SShuo Chen return obj; 26420c9859SShuo Chen } 27420c9859SShuo Chen Message message = (Message) obj; 28420c9859SShuo Chen String name = message.getDescriptorForType().getFullName(); 29420c9859SShuo Chen int size = message.getSerializedSize(); 30420c9859SShuo Chen ChannelBuffer buffer = new BigEndianHeapChannelBuffer(4 + name.length() + 1 + size + 4); 31420c9859SShuo Chen buffer.writeInt(name.length() + 1); 32420c9859SShuo Chen buffer.writeBytes(name.getBytes()); 33420c9859SShuo Chen buffer.writeZero(1); 34420c9859SShuo Chen buffer.writeBytes(message.toByteArray()); 35420c9859SShuo Chen 36420c9859SShuo Chen Adler32 checksum = new Adler32(); 37420c9859SShuo Chen checksum.update(buffer.array(), buffer.arrayOffset(), buffer.readableBytes()); 38420c9859SShuo Chen buffer.writeInt((int) checksum.getValue()); 39420c9859SShuo Chen 40420c9859SShuo Chen return buffer; 41420c9859SShuo Chen } 42420c9859SShuo Chen} 43