/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vut.msa.servlets;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
import vut.msa.transport.TransportServer;

/**
 *
 * @author starosta
 */
public class TransportServerServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(TransportServerServlet.class);

    private Thread serverThread;
    private static final ScheduledExecutorService worker =
                                    Executors.newSingleThreadScheduledExecutor();

    @Override
    public void init(ServletConfig config) throws ServletException {
        try {
            ServletContext context = config.getServletContext();
            final String path =  context.getRealPath("/") + "backup.keys";

            //serverThread = new Thread(new TransportServer(path));
            //serverThread.sleep(30 * 1000);

            
            worker.schedule(new Runnable() {

                public void run() {
                    try {
                        new TransportServer(path, TransportServer.DEFAULT_PORT);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }, 30, TimeUnit.SECONDS);
            
            log.info("Server thread started.");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void destroy() {
        super.destroy();

        /*
        if (serverThread != null & serverThread.isAlive())
            serverThread.interrupt();
         */
        
        if (worker != null)
            worker.shutdown();
        
        log.info("Server thread stopped.");
    }


}
