By Michael N. Lipp

JGrapes Logo

View GitHub Project



Web Console

Console Echo

Console Echo is a slightly more complicated application that uses two components. One component is the InputStreamMonitor from the framework, the other is EchoUntilQuit, which implements the application logic of this example.


The two components are created and connected to a channel in the main method.

    public static void main(String[] args) throws InterruptedException {
        Channel mainChannel = new NamedChannel("main");
        EchoUntilQuit app = new EchoUntilQuit(mainChannel);
        app.attach(new InputStreamMonitor(mainChannel, System.in));

Attaching the InputStreamMonitor to the EchoUntilQuit component establishes the composition relationship. The components’ connection to their associated channel is established by passing the channel as argument to the respective component’s constructor.

The “application logic” is provided by the handler method of EchoUntilQuit.

public class EchoUntilQuit extends Component {

    public EchoUntilQuit(Channel channel) {

    public void onInput(Input<ByteBuffer> event) {
        String data = Charset.defaultCharset().decode(event.data()).toString();
        if (data.trim().equals("QUIT")) {
            fire (new Stop());

Input events are created by the InputStreamMonitor in response to text entered in the console and are fired on the channel that the InputStreamMonitor is connected to. EchoUnitQuit’s handler is invoked for all these events. The handler retrieves the data, which is contained in the event as a buffer from the Java NIO package and writes it to the console. Then the handler checks if the line entered was “QUIT”. If this is the case, it fires a Stop event on the application’s channel.

The Stop event is processed by a handler method of InputStreamMonitor and causes the component to stop listening for data from the console. This puts the application in a state where all events are processed and there are no more components that can generate events. This is the state that the invocation of Components.awaitExhaustion() (in the main method above) waits for. As this state is reached now, the main method continues and the application terminates.