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.channel;
17  
18  import io.netty.util.Attribute;
19  import io.netty.util.AttributeKey;
20  
21  import java.lang.annotation.Documented;
22  import java.lang.annotation.ElementType;
23  import java.lang.annotation.Inherited;
24  import java.lang.annotation.Retention;
25  import java.lang.annotation.RetentionPolicy;
26  import java.lang.annotation.Target;
27  
28  /**
29   * Handles an I/O event or intercepts an I/O operation, and forwards it to its next handler in
30   * its {@link ChannelPipeline}.
31   *
32   * <h3>Sub-types</h3>
33   * <p>
34   * {@link ChannelHandler} itself does not provide many methods, but you usually have to implement one of its subtypes:
35   * <ul>
36   * <li>{@link ChannelInboundHandler} to handle inbound I/O events, and</li>
37   * <li>{@link ChannelOutboundHandler} to handle outbound I/O operations.</li>
38   * </ul>
39   * </p>
40   * <p>
41   * Alternatively, the following adapter classes are provided for your convenience:
42   * <ul>
43   * <li>{@link ChannelInboundHandlerAdapter} to handle inbound I/O events,</li>
44   * <li>{@link ChannelOutboundHandlerAdapter} to handle outbound I/O operations, and</li>
45   * <li>{@link ChannelDuplexHandler} to handle both inbound and outbound events</li>
46   * </ul>
47   * </p>
48   * <p>
49   * For more information, please refer to the documentation of each subtype.
50   * </p>
51   *
52   * <h3>The context object</h3>
53   * <p>
54   * A {@link ChannelHandler} is provided with a {@link ChannelHandlerContext}
55   * object.  A {@link ChannelHandler} is supposed to interact with the
56   * {@link ChannelPipeline} it belongs to via a context object.  Using the
57   * context object, the {@link ChannelHandler} can pass events upstream or
58   * downstream, modify the pipeline dynamically, or store the information
59   * (using {@link AttributeKey}s) which is specific to the handler.
60   *
61   * <h3>State management</h3>
62   *
63   * A {@link ChannelHandler} often needs to store some stateful information.
64   * The simplest and recommended approach is to use member variables:
65   * <pre>
66   * public interface Message {
67   *     // your methods here
68   * }
69   *
70   * public class DataServerHandler extends {@link SimpleChannelInboundHandler}&lt;Message&gt; {
71   *
72   *     <b>private boolean loggedIn;</b>
73   *
74   *     {@code @Override}
75   *     public void channelRead0({@link ChannelHandlerContext} ctx, Message message) {
76   *         {@link Channel} ch = e.getChannel();
77   *         if (message instanceof LoginMessage) {
78   *             authenticate((LoginMessage) message);
79   *             <b>loggedIn = true;</b>
80   *         } else (message instanceof GetDataMessage) {
81   *             if (<b>loggedIn</b>) {
82   *                 ch.write(fetchSecret((GetDataMessage) message));
83   *             } else {
84   *                 fail();
85   *             }
86   *         }
87   *     }
88   *     ...
89   * }
90   * </pre>
91   * Because the handler instance has a state variable which is dedicated to
92   * one connection, you have to create a new handler instance for each new
93   * channel to avoid a race condition where a unauthenticated client can get
94   * the confidential information:
95   * <pre>
96   * // Create a new handler instance per channel.
97   * // See {@link ChannelInitializer#initChannel(Channel)}.
98   * public class DataServerInitializer extends {@link ChannelInitializer}&lt;{@link Channel}&gt; {
99   *     {@code @Override}
100  *     public void initChannel({@link Channel} channel) {
101  *         channel.pipeline().addLast("handler", <b>new DataServerHandler()</b>);
102  *     }
103  * }
104  *
105  * </pre>
106  *
107  * <h4>Using {@link AttributeKey}s</h4>
108  *
109  * Although it's recommended to use member variables to store the state of a
110  * handler, for some reason you might not want to create many handler instances.
111  * In such a case, you can use {@link AttributeKey}s which is provided by
112  * {@link ChannelHandlerContext}:
113  * <pre>
114  * public interface Message {
115  *     // your methods here
116  * }
117  *
118  * {@code @Sharable}
119  * public class DataServerHandler extends {@link SimpleChannelInboundHandler}&lt;Message&gt; {
120  *     private final {@link AttributeKey}&lt;{@link Boolean}&gt; auth =
121  *           {@link AttributeKey#valueOf(String) AttributeKey.valueOf("auth")};
122  *
123  *     {@code @Override}
124  *     public void channelRead({@link ChannelHandlerContext} ctx, Message message) {
125  *         {@link Attribute}&lt;{@link Boolean}&gt; attr = ctx.attr(auth);
126  *         {@link Channel} ch = ctx.channel();
127  *         if (message instanceof LoginMessage) {
128  *             authenticate((LoginMessage) o);
129  *             <b>attr.set(true)</b>;
130  *         } else (message instanceof GetDataMessage) {
131  *             if (<b>Boolean.TRUE.equals(attr.get())</b>) {
132  *                 ch.write(fetchSecret((GetDataMessage) o));
133  *             } else {
134  *                 fail();
135  *             }
136  *         }
137  *     }
138  *     ...
139  * }
140  * </pre>
141  * Now that the state of the handler is attached to the {@link ChannelHandlerContext}, you can add the
142  * same handler instance to different pipelines:
143  * <pre>
144  * public class DataServerInitializer extends {@link ChannelInitializer}&lt;{@link Channel}&gt; {
145  *
146  *     private static final DataServerHandler <b>SHARED</b> = new DataServerHandler();
147  *
148  *     {@code @Override}
149  *     public void initChannel({@link Channel} channel) {
150  *         channel.pipeline().addLast("handler", <b>SHARED</b>);
151  *     }
152  * }
153  * </pre>
154  *
155  *
156  * <h4>The {@code @Sharable} annotation</h4>
157  * <p>
158  * In the example above which used an {@link AttributeKey},
159  * you might have noticed the {@code @Sharable} annotation.
160  * <p>
161  * If a {@link ChannelHandler} is annotated with the {@code @Sharable}
162  * annotation, it means you can create an instance of the handler just once and
163  * add it to one or more {@link ChannelPipeline}s multiple times without
164  * a race condition.
165  * <p>
166  * If this annotation is not specified, you have to create a new handler
167  * instance every time you add it to a pipeline because it has unshared state
168  * such as member variables.
169  * <p>
170  * This annotation is provided for documentation purpose, just like
171  * <a href="http://www.javaconcurrencyinpractice.com/annotations/doc/">the JCIP annotations</a>.
172  *
173  * <h3>Additional resources worth reading</h3>
174  * <p>
175  * Please refer to the {@link ChannelHandler}, and
176  * {@link ChannelPipeline} to find out more about inbound and outbound operations,
177  * what fundamental differences they have, how they flow in a  pipeline,  and how to handle
178  * the operation in your application.
179  */
180 public interface ChannelHandler {
181 
182     /**
183      * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events.
184      */
185     void handlerAdded(ChannelHandlerContext ctx) throws Exception;
186 
187     /**
188      * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events
189      * anymore.
190      */
191     void handlerRemoved(ChannelHandlerContext ctx) throws Exception;
192 
193     /**
194      * Gets called if a {@link Throwable} was thrown.
195      *
196      * @deprecated is part of {@link ChannelInboundHandler}
197      */
198     @Deprecated
199     void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception;
200 
201     /**
202      * Indicates that the same instance of the annotated {@link ChannelHandler}
203      * can be added to one or more {@link ChannelPipeline}s multiple times
204      * without a race condition.
205      * <p>
206      * If this annotation is not specified, you have to create a new handler
207      * instance every time you add it to a pipeline because it has unshared
208      * state such as member variables.
209      * <p>
210      * This annotation is provided for documentation purpose, just like
211      * <a href="http://www.javaconcurrencyinpractice.com/annotations/doc/">the JCIP annotations</a>.
212      */
213     @Inherited
214     @Documented
215     @Target(ElementType.TYPE)
216     @Retention(RetentionPolicy.RUNTIME)
217     @interface Sharable {
218         // no value
219     }
220 }