/*
 * Copyright (c) 2008, PRODYNA AG, Germany. All rights reserved. Created 10.01.2008
 */

package classcastexceptiontest.jndi;

import java.io.InputStream;
import java.util.Hashtable;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

/**
 * JndiLookupUtil
 * 
 * @author Andreas Heizenreder (PRODYNA AG)
 * @version $Id: JndiLookupUtil.java,v 1.1 2008/08/22 15:27:08 aheizenreder Exp $
 */
public class JndiLookupUtil {

    private static Logger logger = Logger.getLogger(JndiLookupUtil.class);

    @SuppressWarnings("unchecked")
    public static <T> T getEJB(T bean, String jndiProviderUrl, String jndiPath)
            throws NamingException {
        T ejb = null;
        try {
            InitialContext initialContext = getInitialContext(jndiProviderUrl);
            ejb = (T) initialContext.lookup(jndiPath);
        } catch (NamingException e) {
            logger.error("The ejb can not be get from the JNDI. name: [" + jndiPath + "]", e);
            throw e;
        }
        logger.debug("got EJB from naming context " + ejb);
        return ejb;
    }

    /**
     * Constructs the InitialContext for the JNDI lookup.
     * 
     * @param jndiProviderUrl
     *            TODO
     * 
     * @return
     * @throws NamingException
     */
    private static InitialContext getInitialContext(String jndiProviderUrl) throws NamingException {
        InitialContext jndiCtx = null;
        // Initial context environment for the JBoss JNDI
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
        env.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
        // The JNDI Port might be different on your JBOSS. Have a look in the startup output
        env.put(Context.PROVIDER_URL, jndiProviderUrl);

        // JNDI Context
        try {
            jndiCtx = new InitialContext(env);
        } catch (NamingException e) {
            logger.error("The initialContext could not be created");
            throw e;
        }

        return jndiCtx;
    }

    public static String readJndiProviderUrlProperty(String propertyName) throws Exception {
        String jndiProviderUrl = null;

        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        InputStream propertiesIs = classLoader
                .getResourceAsStream("classcastexceptiontest.properties");
        if (propertiesIs != null) {
            Properties properties = new Properties();
            properties.load(propertiesIs);

            jndiProviderUrl = properties.getProperty(propertyName);
        } else {
            logger.debug("Resource classcastexcepitontest.properties not found");
        }
        return jndiProviderUrl;
    }
}