/*

Copyright (C) 2009 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 jp.co.intellilink.hinemos.jmx.util;

import jp.co.intellilink.hinemos.jmx.OutputMBeanAttribute;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jboss.jmx.adaptor.rmi.RMIAdaptor;
import org.jnp.interfaces.NamingContext;

/**
 * EJBとのコネクションを管理するクラス<br>
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
public class EjbConnectionManager {
	/** シングルトン用インスタンス。 */
	private static EjbConnectionManager m_instance = null;
	/** コンテキスト。 */
	private NamingContext m_ctx = null;
	// ログ出力
	private static Log log = LogFactory.getLog(OutputMBeanAttribute.class);

	private EjbConnectionManager() {

	}

	/**
	 * 本クラスのインスタンスを返します。<br>
	 * 
	 * @return 唯一のインスタンス
	 */
	public static EjbConnectionManager getConnectionManager() {
		if (m_instance == null) {
			m_instance = new EjbConnectionManager();
		}
		return m_instance;
	}

	/**
	 * RMIAdaptorを取得する。
	 * 
	 * @return RMIAdaptor
	 */
	public synchronized RMIAdaptor getRMIAdaptor() {
		try {
			m_ctx = LoginManager.getContextManager().getNamingContext(
					Config.getConfig("Login.USER"),
					Config.getConfig("Login.PASSWORD"), 
					Config.getConfig("Login.URL"));
		} catch (Exception e) {
			try {
				LoginManager.getContextManager().logout();
			} catch (Exception e1) {
			}
			log.error(Messages.getMsg("JMXTool.ConnectManagerFailed"), e);
			return null;
		}

		RMIAdaptor server;
		try {
			server = (RMIAdaptor)m_ctx.lookup("jmx/invoker/RMIAdaptor");
			return server;
		} catch (Exception e) {
			try {
				LoginManager.getContextManager().logout();
			} catch (Exception e1) {
			}
			log.error(Messages.getMsg("JMXTool.ConnectManagerFailed"), e);
		}
		m_ctx = null;
		return null;
	}
}