/*
 * NodeInitializer.java
 *
 * Created on 15 marzo 2004, 23.08
 */

package qms.io.http;
import qms.group.*;
import qms.queue.*;
import qms.util.*;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContext;
import java.net.*;
import java.io.*;
/**
 * Inizializza il "nodo locale"
 * @author  Enrico

 */

public class NodeInitializer implements ServletContextListener {
    
    // Servlet lifecycle events work like Swing events.
    // Any listener interested in observing the servlet context lifecycle
    // should implement the ServletContextListener interface.
    
    // The ServletContextEvent class passed to those methods has only a getServletContext()
    // method that returns the context being initialized or destroyed.
    
    public void contextInitialized(ServletContextEvent e) {
        
        // Called when a Web application is first ready to process requests
        // (i.e. on Web server startup and when a context is added or reloaded).
        // Requests will not be handled until this method returns.
        
        // For example, here might be some database connections established
        // and added to the servlet context attributes.
        
        /*
        Connection con = // create connection
        e.getServletContext().setAttribute("con", con);
         */
        ServletContext ctx = e.getServletContext();        
        try {
            URL url = ctx.getResource("/");       
            String name = url.getPath();            
            
            LocalNodeConfigurator.configurateLocalNode(name);
            ctx.log("Initialized local node:"+name);                        
        } catch (Throwable t) {
            try {
                LocalNodeConfigurator.configurateLocalNode("error");
            } catch (IOException io) { io.printStackTrace(System.out); }
        }
    }
    
    public void contextDestroyed(ServletContextEvent e) {
        
        // Called when a Web application is about to be shut down
        // (i.e. on Web server shutdown or when a context is removed or reloaded).
        // Request handling will be stopped before this method is called.
        
        // For example, the database connections might be closed here.
        
        /*
        Connection con = (Connection) e.getServletContext().getAttribute("con");
        try { con.close(); } catch (SQLException ignored) { } // close connection
         */
        Controller.getLocalInstance().stop();
        Logger.close();
    }
}
