/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
package com.sun.web.server;

import java.util.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.text.MessageFormat;
import com.sun.enterprise.*;
import com.sun.enterprise.log.Log;
import com.sun.enterprise.deployment.JndiNameEnvironment;
import com.sun.enterprise.InjectionException;
import org.apache.catalina.*;

//START OF IASRI 4660742
import java.util.logging.*;
import com.sun.logging.*;
import java.util.logging.Logger;
//END OF IASRI 4660742

/**
 * This class implements the Tomcat ContainerListener interface and
 * handles Context and Session related events.
 * @author Tony Ng
 */
public final class WebContainerListener 
    implements ContainerListener {

    // START OF IASRI 4660742
    static Logger _logger=LogDomains.getLogger(LogDomains.WEB_LOGGER);
    // END OF IASRI 4660742

    static private HashSet beforeEvents = new HashSet();
    static private HashSet afterEvents = new HashSet();

    static {
        // preInvoke events
        beforeEvents.add("beforeContextInitialized");
        beforeEvents.add("beforeContextDestroyed");
        beforeEvents.add("beforeContextAttributeAdded");
        beforeEvents.add("beforeContextAttributeRemoved");
        beforeEvents.add("beforeContextAttributeReplaced");
        beforeEvents.add("beforeRequestInitialized");
        beforeEvents.add("beforeRequestDestroyed");
        beforeEvents.add("beforeSessionCreated");
        beforeEvents.add("beforeSessionDestroyed");
        beforeEvents.add("beforeSessionAttributeAdded");
        beforeEvents.add("beforeSessionAttributeRemoved");
        beforeEvents.add("beforeSessionAttributeReplaced");
        beforeEvents.add("beforeFilterInitialized");

        // postInvoke events
        afterEvents.add("afterContextInitialized");
        afterEvents.add("afterContextDestroyed");
        afterEvents.add("afterContextAttributeAdded");
        afterEvents.add("afterContextAttributeRemoved");
        afterEvents.add("afterContextAttributeReplaced");
        afterEvents.add("afterRequestInitialized");
        afterEvents.add("afterRequestDestroyed");
        afterEvents.add("afterSessionCreated");
        afterEvents.add("afterSessionDestroyed");
        afterEvents.add("afterSessionAttributeAdded");
        afterEvents.add("afterSessionAttributeRemoved");
        afterEvents.add("afterSessionAttributeReplaced");
        afterEvents.add("afterFilterInitialized");
    }

    private InvocationManager im;
    private InjectionManager injectionMgr;


    public WebContainerListener() {
        injectionMgr = Switch.getSwitch().getInjectionManager();
    }

    public void containerEvent(ContainerEvent event) {
        if(_logger.isLoggable(Level.FINEST)) {
	    _logger.log(Level.FINEST,"**** ContainerEvent: " +
                        event.getType() + "," +
                        event.getContainer() + "," +
                        event.getData());
        }

        String type = event.getType();

        try {
            if ("afterListenerInstantiated".equals(type)
                    || "beforeFilterInitialized".equals(type)) {
                preInvoke((Context) event.getContainer());
                injectInstance(event);
                postInvoke((Context) event.getContainer());
            }

            if (beforeEvents.contains(type)) {
                preInvoke((Context) event.getContainer());
            } else if (afterEvents.contains(type)) {
                postInvoke((Context) event.getContainer());
            }
        } catch (Exception ex) {
            String msg = _logger.getResourceBundle().getString(
                "web_server.excep_handle_event");
            msg = MessageFormat.format(msg, new Object[] { type });
            throw new RuntimeException(msg, ex);
        }

    }

    private void preInvoke(Context ctx) {
        // set context class loader for use by RMIClassLoader
        final ClassLoader cl = ctx.getLoader().getClassLoader();
        AccessController.doPrivileged
            (new PrivilegedAction() {
                public Object run() {
                    Thread.currentThread().setContextClassLoader(cl);
                    return null;
                }
            });
        ComponentInvocation inv = new ComponentInvocation();
        inv.instance = null;
        inv.container = ctx;

        if (im == null) {
            im = Switch.getSwitch().getInvocationManager();
        }
        im.preInvoke(inv);
    }

    private void postInvoke(Context ctx) {
        ComponentInvocation inv = new ComponentInvocation();
        inv.instance = null;
        inv.container = ctx;
        if (im == null) {
            im = Switch.getSwitch().getInvocationManager();
        }
        im.postInvoke(inv);
    }


    /*
     * Injects all injectable resources into the servlet context listener
     * or filter instance associated with the given ContainerEvent.
     *
     * @param event The ContainerEvent to process
     */
    private void injectInstance(ContainerEvent event)
            throws InjectionException {

        JndiNameEnvironment desc = (JndiNameEnvironment) 
            Switch.getSwitch().getDescriptorFor(
                                    (Context) event.getContainer());
        if( desc != null ) {
            injectionMgr.injectInstance(event.getData(), desc);
        }
    }
}
