View Javadoc
1   /*
2    * Copyright 2013 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.memcache.binary;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.channel.ChannelHandlerContext;
20  import io.netty.handler.codec.MessageToByteEncoder;
21  import io.netty.handler.codec.memcache.AbstractMemcacheObjectEncoder;
22  import io.netty.util.CharsetUtil;
23  
24  /**
25   * A {@link MessageToByteEncoder} that encodes binary memache messages into bytes.
26   */
27  public abstract class AbstractBinaryMemcacheEncoder<M extends BinaryMemcacheMessage>
28      extends AbstractMemcacheObjectEncoder<M> {
29  
30      /**
31       * Every binary memcache message has at least a 24 bytes header.
32       */
33      private static final int DEFAULT_BUFFER_SIZE = 24;
34  
35      @Override
36      protected ByteBuf encodeMessage(ChannelHandlerContext ctx, M msg) {
37          ByteBuf buf = ctx.alloc().buffer(DEFAULT_BUFFER_SIZE);
38  
39          encodeHeader(buf, msg);
40          encodeExtras(buf, msg.extras());
41          encodeKey(buf, msg.key());
42  
43          return buf;
44      }
45  
46      /**
47       * Encode the extras.
48       *
49       * @param buf    the {@link ByteBuf} to write into.
50       * @param extras the extras to encode.
51       */
52      private static void encodeExtras(ByteBuf buf, ByteBuf extras) {
53          if (extras == null || !extras.isReadable()) {
54              return;
55          }
56  
57          buf.writeBytes(extras);
58      }
59  
60      /**
61       * Encode the key.
62       *
63       * @param buf the {@link ByteBuf} to write into.
64       * @param key the key to encode.
65       */
66      private static void encodeKey(ByteBuf buf, String key) {
67          if (key == null || key.isEmpty()) {
68              return;
69          }
70  
71          buf.writeBytes(key.getBytes(CharsetUtil.UTF_8));
72      }
73  
74      /**
75       * Encode the header.
76       * <p/>
77       * This methods needs to be implemented by a sub class because the header is different
78       * for both requests and responses.
79       *
80       * @param buf the {@link ByteBuf} to write into.
81       * @param msg the message to encode.
82       */
83      protected abstract void encodeHeader(ByteBuf buf, M msg);
84  
85  }