1 /*
2 * Copyright 2009 Red Hat, Inc.
3 *
4 * Red Hat licenses this file to you under the Apache License, version 2.0
5 * (the "License"); you may not use this file except in compliance with the
6 * 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 org.jboss.netty.handler.codec.protobuf;
17
18 import static org.jboss.netty.buffer.ChannelBuffers.*;
19
20 import org.jboss.netty.buffer.ChannelBuffer;
21 import org.jboss.netty.buffer.ChannelBufferOutputStream;
22 import org.jboss.netty.channel.Channel;
23 import org.jboss.netty.channel.ChannelHandlerContext;
24 import org.jboss.netty.channel.ChannelHandler.Sharable;
25 import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
26
27 import com.google.protobuf.CodedOutputStream;
28
29 /**
30 * An encoder that prepends the the Google Protocol Buffers
31 * <a href="http://code.google.com/apis/protocolbuffers/docs/encoding.html#varints">Base
32 * 128 Varints</a> integer length field. For example:
33 * <pre>
34 * BEFORE DECODE (300 bytes) AFTER DECODE (302 bytes)
35 * +---------------+ +--------+---------------+
36 * | Protobuf Data |-------------->| Length | Protobuf Data |
37 * | (300 bytes) | | 0xAC02 | (300 bytes) |
38 * +---------------+ +--------+---------------+
39 * </pre> *
40 *
41 * @see com.google.protobuf.CodedOutputStream
42 *
43 * @author <a href="http://www.jboss.org/netty/">The Netty Project</a>
44 * @author Tomasz Blachowicz (tblachowicz@gmail.com)
45 * @author <a href="http://gleamynode.net/">Trustin Lee</a>
46 * @version $Rev: 2315 $, $Date: 2010-06-23 14:16:47 +0900 (Wed, 23 Jun 2010) $
47 */
48 @Sharable
49 public class ProtobufVarint32LengthFieldPrepender extends OneToOneEncoder {
50
51 /**
52 * Creates a new instance.
53 */
54 public ProtobufVarint32LengthFieldPrepender() {
55 super();
56 }
57
58 @Override
59 protected Object encode(ChannelHandlerContext ctx, Channel channel,
60 Object msg) throws Exception {
61 if (!(msg instanceof ChannelBuffer)) {
62 return msg;
63 }
64
65 ChannelBuffer body = (ChannelBuffer) msg;
66 int length = body.readableBytes();
67 ChannelBuffer header =
68 channel.getConfig().getBufferFactory().getBuffer(
69 body.order(),
70 CodedOutputStream.computeRawVarint32Size(length));
71 CodedOutputStream codedOutputStream = CodedOutputStream
72 .newInstance(new ChannelBufferOutputStream(header));
73 codedOutputStream.writeRawVarint32(length);
74 codedOutputStream.flush();
75 return wrappedBuffer(header, body);
76 }
77
78 }