/* 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.jndi.url.java;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.spi.ObjectFactory;

import org.jfox.jndi.ContextImpl;
import org.jfox.jndi.JNDIProperties;

/**
 * performed when use Reference with it's RefAddr is StringRefAddr,type is URL, content is "java://.."
 *
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class javaURLContextFactory implements ObjectFactory {
    public Object getObjectInstance(Object obj,
                                    Name name,
                                    Context nameCtx,
                                    Hashtable environment)
            throws Exception {

        if(obj == null) obj = JNDIProperties.PROVIDER_URL + "/";
        if(obj instanceof String) {
            String url = (String) obj;

            int index = url.indexOf('/', url.indexOf("://") + 4); // 去除后面的路径

            String provider = url.substring(0, index);

            if(provider.indexOf(':', provider.indexOf(":") + 2) < 0) { // 没有 port
                provider += ":" + JNDIProperties.DEFAULT_PORT;
            }

            Hashtable env = (Hashtable) environment.clone();
            env.put(Context.PROVIDER_URL, provider);
            ContextImpl context = new ContextImpl("/", env);
            return context;
        }
        else {
            return null;
        }
    }

}
