1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package io.netty.handler.codec;
17
18 import io.netty.channel.ChannelHandlerContext;
19 import io.netty.channel.ChannelOutboundHandler;
20 import io.netty.channel.ChannelOutboundHandlerAdapter;
21 import io.netty.channel.ChannelPipeline;
22 import io.netty.channel.ChannelPromise;
23 import io.netty.util.ReferenceCountUtil;
24 import io.netty.util.ReferenceCounted;
25 import io.netty.util.internal.StringUtil;
26 import io.netty.util.internal.TypeParameterMatcher;
27
28 import java.util.List;
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51 public abstract class MessageToMessageEncoder<I> extends ChannelOutboundHandlerAdapter {
52
53 private final TypeParameterMatcher matcher;
54
55
56
57
58 protected MessageToMessageEncoder() {
59 matcher = TypeParameterMatcher.find(this, MessageToMessageEncoder.class, "I");
60 }
61
62
63
64
65
66
67 protected MessageToMessageEncoder(Class<? extends I> outboundMessageType) {
68 matcher = TypeParameterMatcher.get(outboundMessageType);
69 }
70
71
72
73
74
75 public boolean acceptOutboundMessage(Object msg) throws Exception {
76 return matcher.match(msg);
77 }
78
79 @Override
80 public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
81 CodecOutputList out = null;
82 try {
83 if (acceptOutboundMessage(msg)) {
84 out = CodecOutputList.newInstance();
85 @SuppressWarnings("unchecked")
86 I cast = (I) msg;
87 try {
88 encode(ctx, cast, out);
89 } finally {
90 ReferenceCountUtil.release(cast);
91 }
92
93 if (out.isEmpty()) {
94 out.recycle();
95 out = null;
96
97 throw new EncoderException(
98 StringUtil.simpleClassName(this) + " must produce at least one message.");
99 }
100 } else {
101 ctx.write(msg, promise);
102 }
103 } catch (EncoderException e) {
104 throw e;
105 } catch (Throwable t) {
106 throw new EncoderException(t);
107 } finally {
108 if (out != null) {
109 final int sizeMinusOne = out.size() - 1;
110 if (sizeMinusOne == 0) {
111 ctx.write(out.get(0), promise);
112 } else if (sizeMinusOne > 0) {
113
114
115 ChannelPromise voidPromise = ctx.voidPromise();
116 boolean isVoidPromise = promise == voidPromise;
117 for (int i = 0; i < sizeMinusOne; i ++) {
118 ChannelPromise p;
119 if (isVoidPromise) {
120 p = voidPromise;
121 } else {
122 p = ctx.newPromise();
123 }
124 ctx.write(out.getUnsafe(i), p);
125 }
126 ctx.write(out.getUnsafe(sizeMinusOne), promise);
127 }
128 out.recycle();
129 }
130 }
131 }
132
133
134
135
136
137
138
139
140
141
142
143 protected abstract void encode(ChannelHandlerContext ctx, I msg, List<Object> out) throws Exception;
144 }