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