1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
29
30
31
32
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
69
70
71
72
73
74 protected abstract ByteBuf encodeMessage(ChannelHandlerContext ctx, M msg);
75
76
77
78
79
80
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
97
98
99
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 }