View Javadoc

1   /*
2    * Copyright 2012 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;
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   * {@link ChannelOutboundHandlerAdapter} which encodes from one message to an other message
32   *
33   * For example here is an implementation which decodes an {@link Integer} to an {@link String}.
34   *
35   * <pre>
36   *     public class IntegerToStringEncoder extends
37   *             {@link MessageToMessageEncoder}&lt;{@link Integer}&gt; {
38   *
39   *         {@code @Override}
40   *         public void encode({@link ChannelHandlerContext} ctx, {@link Integer} message, List&lt;Object&gt; out)
41   *                 throws {@link Exception} {
42   *             out.add(message.toString());
43   *         }
44   *     }
45   * </pre>
46   *
47   * Be aware that you need to call {@link ReferenceCounted#retain()} on messages that are just passed through if they
48   * are of type {@link ReferenceCounted}. This is needed as the {@link MessageToMessageEncoder} will call
49   * {@link ReferenceCounted#release()} on encoded messages.
50   */
51  public abstract class MessageToMessageEncoder<I> extends ChannelOutboundHandlerAdapter {
52  
53      private final TypeParameterMatcher matcher;
54  
55      /**
56       * Create a new instance which will try to detect the types to match out of the type parameter of the class.
57       */
58      protected MessageToMessageEncoder() {
59          matcher = TypeParameterMatcher.find(this, MessageToMessageEncoder.class, "I");
60      }
61  
62      /**
63       * Create a new instance
64       *
65       * @param outboundMessageType   The type of messages to match and so encode
66       */
67      protected MessageToMessageEncoder(Class<? extends I> outboundMessageType) {
68          matcher = TypeParameterMatcher.get(outboundMessageType);
69      }
70  
71      /**
72       * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next
73       * {@link ChannelOutboundHandler} in the {@link ChannelPipeline}.
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                     // Check if we can use a voidPromise for our extra writes to reduce GC-Pressure
114                     // See https://github.com/netty/netty/issues/2525
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      * Encode from one message to an other. This method will be called for each written message that can be handled
135      * by this encoder.
136      *
137      * @param ctx           the {@link ChannelHandlerContext} which this {@link MessageToMessageEncoder} belongs to
138      * @param msg           the message to encode to an other one
139      * @param out           the {@link List} into which the encoded msg should be added
140      *                      needs to do some kind of aggregation
141      * @throws Exception    is thrown if an error occurs
142      */
143     protected abstract void encode(ChannelHandlerContext ctx, I msg, List<Object> out) throws Exception;
144 }