sg.atom.managex.api.net.telnet.TelnetServerHandler.java Source code

Java tutorial

Introduction

Here is the source code for sg.atom.managex.api.net.telnet.TelnetServerHandler.java

Source

/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package sg.atom.managex.api.net.telnet;

import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.joda.time.DateTime;
import org.joda.time.Interval;
import sg.atom.utils.datastructure.delta.diff.util.Strings;

/**
 * Handles a server-side channel.
 */
@Sharable
public class TelnetServerHandler extends SimpleChannelInboundHandler<String> {

    HashMap<String, TelnetUser> users = new LinkedHashMap<String, TelnetUser>();
    private static final Logger logger = Logger.getLogger(TelnetServerHandler.class.getName());
    ArrayList<Message> messages = new ArrayList<Message>();

    class Message {

        TelnetUser user;
        String content;
        DateTime time;

        public Message(TelnetUser user, String content, DateTime time) {
            this.user = user;
            this.content = content;
            this.time = time;
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        users.put(ctx.name(), new TelnetUser(ctx.name(), new DateTime()));
        // Send greeting for a new connection.
        ctx.write("Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");

        ctx.write("It is " + new Date() + " now.\r\n");
        ctx.write("There are " + users.values().size() + " here!\r\n");
        for (TelnetUser user : users.values()) {
            ctx.write(user.name + " .\r\n");
        }
        ctx.flush();
    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, String request) throws Exception {

        // Generate and write a response.
        String response;
        boolean close = false;
        if (request.isEmpty()) {
            response = "Please type something.\r\n";
        } else if ("bye".equals(request.toLowerCase())) {
            response = "Have a good day!\r\n";
            close = true;
        } else {
            TelnetUser thisUser = users.get(ctx.name());
            DateTime thisTime = new DateTime();
            addMessage(request, thisUser, thisTime);
            //response = "Did you say '" + request + "'?\r\n";
            response = getMessages(thisUser.lastActive, thisTime);
            thisUser.lastActive = thisTime;
        }

        // We do not need to write a ChannelBuffer here.
        // We know the encoder inserted at TelnetPipelineFactory will do the conversion.
        ChannelFuture future = ctx.write(response);

        // Close the connection after sending 'Have a good day!'
        // if the client has sent 'bye'.
        if (close) {
            future.addListener(ChannelFutureListener.CLOSE);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.log(Level.WARNING, "Unexpected exception from downstream.", cause);
        ctx.close();
    }

    Function<Message, String> toLineFunction = new Function<Message, String>() {
        @Override
        public String apply(Message input) {
            return input.user.name + ":" + input.content + "\r\n";
        }
    };

    private void addMessage(String request, TelnetUser user, DateTime time) {
        messages.add(new Message(user, request, time));
    }

    private String getMessages(DateTime start, DateTime end) {
        final Interval interval = new Interval(start, end);
        ImmutableList<Message> filteredMessages = ImmutableList
                .copyOf(Iterables.filter(messages, new Predicate<Message>() {
                    @Override
                    public boolean apply(Message msg) {
                        return interval.contains(msg.time);
                    }
                }));

        return Strings.join("\r\n", Lists.transform(filteredMessages, toLineFunction));
    }
}