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;
17  
18  import io.netty.buffer.ByteBuf;
19  import io.netty.buffer.Unpooled;
20  import io.netty.channel.ChannelHandlerContext;
21  import io.netty.channel.FileRegion;
22  import io.netty.handler.codec.MessageToMessageEncoder;
23  import io.netty.util.internal.StringUtil;
24  
25  import java.util.List;
26  
27  /**
28   * A general purpose {@link AbstractMemcacheObjectEncoder} that encodes {@link MemcacheMessage}s.
29   * <p/>
30   * <p>Note that this class is designed to be extended, especially because both the binary and ascii protocol
31   * require different treatment of their messages. Since the content chunk writing is the same for both, the encoder
32   * abstracts this right away.</p>
33   */
34  public abstract class AbstractMemcacheObjectEncoder<M extends MemcacheMessage> extends MessageToMessageEncoder<Object> {
35  
36      private boolean expectingMoreContent;
37  
38      @Override
39      protected void encode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
40          if (msg instanceof MemcacheMessage) {
41              if (expectingMoreContent) {
42                  throw new IllegalStateException("unexpected message type: " + StringUtil.simpleClassName(msg));
43              }
44  
45              @SuppressWarnings({ "unchecked", "CastConflictsWithInstanceof" })
46              final M m = (M) msg;
47              out.add(encodeMessage(ctx, m));
48          }
49  
50          if (msg instanceof MemcacheContent || msg instanceof ByteBuf || msg instanceof FileRegion) {
51              int contentLength = contentLength(msg);
52              if (contentLength > 0) {
53                  out.add(encodeAndRetain(msg));
54              } else {
55                  out.add(Unpooled.EMPTY_BUFFER);
56              }
57  
58              expectingMoreContent = !(msg instanceof LastMemcacheContent);
59          }
60      }
61  
62      @Override
63      public boolean acceptOutboundMessage(Object msg) throws Exception {
64          return msg instanceof MemcacheObject || msg instanceof ByteBuf || msg instanceof FileRegion;
65      }
66  
67      /**
68       * Take the given {@link MemcacheMessage} and encode it into a writable {@link ByteBuf}.
69       *
70       * @param ctx the channel handler context.
71       * @param msg the message to encode.
72       * @return the {@link ByteBuf} representation of the message.
73       */
74      protected abstract ByteBuf encodeMessage(ChannelHandlerContext ctx, M msg);
75  
76      /**
77       * Determine the content length of the given object.
78       *
79       * @param msg the object to determine the length of.
80       * @return the determined content length.
81       */
82      private static int contentLength(Object msg) {
83          if (msg instanceof MemcacheContent) {
84              return ((MemcacheContent) msg).content().readableBytes();
85          }
86          if (msg instanceof ByteBuf) {
87              return ((ByteBuf) msg).readableBytes();
88          }
89          if (msg instanceof FileRegion) {
90              return (int) ((FileRegion) msg).count();
91          }
92          throw new IllegalStateException("unexpected message type: " + StringUtil.simpleClassName(msg));
93      }
94  
95      /**
96       * Encode the content, depending on the object type.
97       *
98       * @param msg the object to encode.
99       * @return the encoded object.
100      */
101     private static Object encodeAndRetain(Object msg) {
102         if (msg instanceof ByteBuf) {
103             return ((ByteBuf) msg).retain();
104         }
105         if (msg instanceof MemcacheContent) {
106             return ((MemcacheContent) msg).content().retain();
107         }
108         if (msg instanceof FileRegion) {
109             return ((FileRegion) msg).retain();
110         }
111         throw new IllegalStateException("unexpected message type: " + StringUtil.simpleClassName(msg));
112     }
113 
114 }