package mina;

import java.io.*;
import java.net.*;
import java.nio.charset.*;
import org.apache.mina.core.service.*;
import org.apache.mina.core.session.*;
import org.apache.mina.core.filterchain.*;
import org.apache.mina.filter.codec.*;
import org.apache.mina.filter.codec.textline.*;
import org.apache.mina.filter.logging.*;
import org.apache.mina.transport.socket.nio.*;

public class MinaDemo {
	
	private static final int PORT = 9123;
	
	public static void addEventLog(IoAcceptor acceptor) {
		//Logs all MINA protocol events.
		IoFilter eventLog = new LoggingFilter();
		acceptor.getFilterChain().addLast("logger", eventLog);
	}
	
	public static void addTextCodec(IoAcceptor acceptor) {
		IoFilter codec = new ProtocolCodecFilter(
				new TextLineCodecFactory(Charset.forName("UTF-8")));
		acceptor.getFilterChain().addLast("codec", codec);
	}
	
	public static void configServer(IoAcceptor acceptor) {
		IoSessionConfig config = acceptor.getSessionConfig();
		config.setReadBufferSize(2048);
		config.setIdleTime(IdleStatus.BOTH_IDLE, 10);
	}
	
	public static void main(String[] args) throws IOException {
		IoAcceptor acceptor = new NioSocketAcceptor();
		addEventLog(acceptor);
		addTextCodec(acceptor);
		configServer(acceptor);
		acceptor.setHandler(new TimeServerHandler());
        acceptor.bind(new InetSocketAddress(PORT));
	}
}