1 /*
2 * JBoss, Home of Professional Open Source
3 *
4 * Copyright 2013 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.conduits;
20
21 import org.xnio.ChannelListener;
22 import org.xnio.ChannelListeners;
23 import org.xnio.IoUtils;
24 import org.xnio.channels.CloseListenerSettable;
25 import org.xnio.channels.SuspendableWriteChannel;
26 import org.xnio.channels.WriteListenerSettable;
27
28 /**
29 * A conduit write-ready handler.
30 *
31 * @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
32 */
33 public interface WriteReadyHandler extends TerminateHandler {
34 /**
35 * Signify that writes are ready.
36 */
37 void writeReady();
38
39 /**
40 * A write ready handler which calls channel listener(s).
41 *
42 * @param <C> the channel type
43 */
44 class ChannelListenerHandler<C extends SuspendableWriteChannel & WriteListenerSettable<C> & CloseListenerSettable<C>> implements WriteReadyHandler {
45 private final C channel;
46
47 /**
48 * Construct a new instance.
49 *
50 * @param channel the channel
51 */
52 public ChannelListenerHandler(final C channel) {
53 this.channel = channel;
54 }
55
56 public void forceTermination() {
57 IoUtils.safeClose(channel);
58 }
59
60 public void writeReady() {
61 final ChannelListener<? super C> writeListener = channel.getWriteListener();
62 if (writeListener == null) {
63 channel.suspendWrites();
64 } else {
65 ChannelListeners.invokeChannelListener(channel, writeListener);
66 }
67 }
68
69 public void terminated() {
70 ChannelListeners.invokeChannelListener(channel, channel.getCloseListener());
71 }
72 }
73
74 /**
75 * A runnable task which invokes the {@link WriteReadyHandler#writeReady()} method of the given handler.
76 */
77 class ReadyTask implements Runnable {
78
79 private final WriteReadyHandler handler;
80
81 /**
82 * Construct a new instance.
83 *
84 * @param handler the handler to invoke
85 */
86 public ReadyTask(final WriteReadyHandler handler) {
87 this.handler = handler;
88 }
89
90 public void run() {
91 handler.writeReady();
92 }
93 }
94 }
95