1 /*
2 * JBoss, Home of Professional Open Source
3 *
4 * Copyright 2009 Red Hat, Inc. and/or its affiliates.
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 */
18
19 package org.xnio;
20
21 import java.nio.channels.Channel;
22 import java.util.EventListener;
23 import org.jboss.logging.Logger;
24
25 import static org.xnio._private.Messages.listenerMsg;
26
27 /**
28 * A listener for channel events. Possible channel events include: channel readable, channel writable, channel
29 * opened, channel closed, channel bound, channel unbound.
30 *
31 * @param <T> the channel type
32 *
33 * @since 2.0
34 */
35 public interface ChannelListener<T extends Channel> extends EventListener {
36
37 /**
38 * Handle the event on this channel.
39 *
40 * @param channel the channel event
41 */
42 void handleEvent(T channel);
43
44 /**
45 * A setter for a channel listener. The indirection is necessary
46 * because while covariance is supported on return types, contravariance is not supported on parameters.
47 *
48 * @param <T> the channel type
49 *
50 * @since 2.0
51 */
52 interface Setter<T extends Channel> {
53
54 /**
55 * Set the listener, or {@code null} to ignore the associated event type.
56 *
57 * @param listener the new listener
58 */
59 void set(ChannelListener<? super T> listener);
60 }
61
62 /**
63 * A simple implementation of {@link Setter}.
64 *
65 * @param <T> the channel type
66 *
67 * @since 3.0
68 */
69 class SimpleSetter<T extends Channel> implements Setter<T> {
70
71 private ChannelListener<? super T> channelListener;
72
73 /** {@inheritDoc} */
74 public void set(final ChannelListener<? super T> listener) {
75 listenerMsg.logf(SimpleSetter.class.getName(), Logger.Level.TRACE, null, "Setting channel listener to %s", listener);
76 channelListener = listener;
77 }
78
79 /**
80 * Get the channel listener set on this setter.
81 *
82 * @return the channel listener
83 */
84 public ChannelListener<? super T> get() {
85 return channelListener;
86 }
87
88 public String toString() {
89 return "Simple channel listener setter (currently=" + channelListener + ")";
90 }
91 }
92 }
93