/*
 
Copyright (C) 2008 NTT DATA INTELLILINK CORPORATION
 
This program is free software; you can redistribute it and/or
Modify it under the terms of the GNU General Public License 
as published by the Free Software Foundation, version 2.
 
This program 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 General Public License for more details.
 
*/

package com.clustercontrol.snmptrap.mibloader.util;

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.naming.NamingException;

import org.jnp.interfaces.NamingContext;

import com.clustercontrol.snmptrap.ejb.session.MibLoaderController;
import com.clustercontrol.snmptrap.ejb.session.MibLoaderControllerHome;
import com.clustercontrol.util.LoginManager;

/**
 * EJB Connection Manager Class
 * 
 * @version 2.3.0
 * @since 2.3.0
 */
public class EjbConnectionManager {
    public static final String KEY_EJB_URL = "ejbUrl";
    public static final String VALUE_EJB_URL = "jnp://localhost:1099";
    private static EjbConnectionManager m_instance = null;
    private NamingContext m_ctx = null;

    /**
     * Get ConnectionManager
     * 
     * @return ConnectionManager
     */
    public static EjbConnectionManager getConnectionManager() {
        if (m_instance == null) {
            m_instance = new EjbConnectionManager();
        }
        return m_instance;
    }

    private EjbConnectionManager() {

    }

    /**
     * Get MibLoaderController
     * 
     * @return MibLoaderController
     */
    public synchronized MibLoaderController getMibLoaderController() {
        try {
            m_ctx = LoginManager.getContextManager().getNamingContext();
        } catch (NamingException e) {
            return null;
        }

		Thread cur = Thread.currentThread();
		ClassLoader save = cur.getContextClassLoader();
		
        MibLoaderControllerHome home;
        try {
			cur.setContextClassLoader(MibLoaderControllerHome.class.getClassLoader());
			
			home = (MibLoaderControllerHome)
			m_ctx.lookup(MibLoaderControllerHome.JNDI_NAME);
			
            return home.create();
        } catch (NamingException e) {
        } catch (RemoteException e) {
        } catch (CreateException e) {
        }
		finally{
			cur.setContextClassLoader(save);
		}
        m_ctx = null;
        return null;
    }
}