/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2008 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * Application Versioning System
 * Copyright (C) 2008 France Telecom R&D
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

// Use the org.ow2.carol.jndi.spi instead of an org.ow2.jonas.* package in
// order to make the transition between MultiOrbInitialContextFactory and
// VirtualJNDIContextFactory transparent for CAROL bundle inclusions.
package org.ow2.carol.jndi.spi;

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.spi.InitialContextFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Context factory that uses {@link VirtualJNDILookup} for JNDI lookups.
 *
 * @author S. Ali Tokmen
 */
public class VirtualJNDIContextFactory implements InitialContextFactory {

    /**
     * Logger.
     */
    private static Log logger = LogFactory.getLog(VirtualJNDIContextFactory.class);

    /**
     * Parent InitialContextFactory environment variable.
     */
    public static final String PARENT_INITIAL_CONTEXT_FACTORY = VirtualJNDIContextFactory.class.getName() + "_PARENT_"
        + Context.INITIAL_CONTEXT_FACTORY;

    /**
     * Creates a context using the parent context factory and maps it with a
     * new {@link VirtualJNDILookup} instance.
     *
     * @param env The possibly null environment specifying information
     *        to be used in the creation of the initial context.
     *
     * @return A non-null initial context object that implements the Context
     *         interface.
     *
     * @throws NamingException If cannot create an initial context.
     */
    @SuppressWarnings("unchecked")
    public Context getInitialContext(final Hashtable<?, ?> env) throws NamingException {
        String parent = System.getProperty(VirtualJNDIContextFactory.PARENT_INITIAL_CONTEXT_FACTORY);
        if (parent == null) {
            throw new IllegalStateException("The parent InitialContextFactory is null!");
        } else {
            // If a Context implementation for the desired protocol is not in
            // the context factory stack, the parent will always call the
            // default factory. Since the default (VirtualJNDIContextFactory)
            // will call back the parent, this might end up in an infinite
            // loop. Check for self in the stack to ensure we never enter that
            // case.
            boolean selfAlreadyInStack = false;
            for (StackTraceElement ste : Thread.currentThread().getStackTrace()) {
                if (this.getClass().getName().equals(ste.getClassName())) {
                    selfAlreadyInStack = true;
                    break;
                }
            }
            Hashtable environment = new Hashtable();
            if (env != null) {
                environment.putAll(env);
            }
            if (selfAlreadyInStack || environment.get(Context.INITIAL_CONTEXT_FACTORY) == null) {
                environment.put(Context.INITIAL_CONTEXT_FACTORY, parent);
            }

            InitialContextFactory parentFactory;
            try {
                Class parentClass = Thread.currentThread().getContextClassLoader().loadClass(parent);
                parentFactory = (InitialContextFactory) parentClass.newInstance();
            } catch (Exception e) {
                throw new NamingException("Cannot load parent initial context (" + parent + "): " + e);
            }
            logger.debug("Getting initial context with parent factory " + parentFactory);
            return new VirtualJNDILookup(parentFactory.getInitialContext(environment));
        }
    }
}
