/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.deployment.web;

import java.io.IOException;

import org.jfox.jndi.enc.EnterpriseContextFactory;
import org.mortbay.http.HttpException;
import org.mortbay.http.HttpRequest;
import org.mortbay.http.HttpResponse;
import org.mortbay.jetty.servlet.WebApplicationContext;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class JettyWebApplicationContext extends WebApplicationContext {
    private static WebEnterpriseContextContainer encFactory = WebEnterpriseContextContainer.getInstance();

    public JettyWebApplicationContext() {
    }

    public JettyWebApplicationContext(String s) {
        super(s);
    }

    /**
     * before handle, set the current thread's web-context
     *
     * @param s
     * @param s1
     * @param httpRequest
     * @param httpResponse
     * @return
     * @throws HttpException
     * @throws IOException
     */
    public boolean handle(String s, String s1, HttpRequest httpRequest, HttpResponse httpResponse) throws HttpException, IOException {

        // and get the EnterpriseContext
        String contextPath = getContextPath();
        if(contextPath.startsWith("/")) {
            contextPath = contextPath.substring(1);
        }

        EnterpriseContextFactory.EnterpriseType type = EnterpriseContextFactory.enterWeb();
        String old = encFactory.setCurrentEnterpriseContextName(contextPath);
        try {
            return super.handle(s, s1, httpRequest, httpResponse);
        }
        finally {
            encFactory.setCurrentEnterpriseContextName(old);
            EnterpriseContextFactory.enter(type);
        }
    }

    public static void main(String[] args) {

    }
}

