/* $Id: MessageBroker.java,v 1.2 2007/11/05 09:50:54 nito Exp $
 *
 * Copyright (c)ARGO 21, Corporation. 2005, 2006.  All rights reserved.
 * 
 * This file is part of Nautica Workflow Core.
 * 
 *  Nautica Workflow Core 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
 *  (at your option) any later version.
 * 
 *  Nautica Workflow Core 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 Nautica Workflow Core; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *  
 */
package jp.co.argo21.nautica.workflow.engine;

import java.io.File;
import java.util.Hashtable;
import java.util.Map;

import javax.jms.QueueConnectionFactory;

import org.apache.log4j.Logger;

import jp.co.argo21.nautica.workflow.jms.WorkflowMQ;
import jp.co.argo21.nautica.workflow.jms.WorkflowMessageAdapter;
import jp.co.argo21.nautica.workflow.omg.WorkflowException;
import jp.co.argo21.nautica.workflow.util.StringManager;

/**
 * ActiveMQを利用したメッセージ管理機構。
 *
 * @author  nito(Argo 21, Corp.)
 * @version $Revision: 1.2 $
 * @since   Nautica Workflow 1.0
 */
public class MessageBroker
{
	/** エンジンログ */
	private static Logger eLog = LogManager.getEngineLogger();
	
	/** MessageBrokerのシングルトンインスタンス */
	private static MessageBroker broker;
	
	/** MQ接続ファクトリー */
	private static QueueConnectionFactory factory;
	
	/** メッセージキュー管理マップ */
	private Map<String, WorkflowMQ> queues;
	
	public static void initializeConnectionFactory(QueueConnectionFactory f)
	{
		if (factory == null) {
			factory = f;
		}
	}

	/**
	 * MessageBrokerの初期化を行う。
	 *
	 * @throws Exception 任意の例外
	 */
	static void create() throws WorkflowException
	{
		if (broker != null) {
			// Message queue already initialized.
			String msg = StringManager.get("E0054");
			eLog.error(msg);
			throw new WorkflowException(msg);
		}
		String path = getConfigPath();
		
		try {
			broker = new MessageBroker(path);
		} catch (Exception ex) {
			// Message queue configuration failed.
			String msg = StringManager.get("E0055");
			eLog.error(msg, ex);
			throw new WorkflowException(msg, ex);
		}
	}
	
	/**
	 * 設定ファイルのパスを取得する。
	 *
	 * @return パス名
	 * @throws WorkflowException 取得中に例外が起こった場合
	 */
	private static String getConfigPath()
	throws WorkflowException
	{
		String home = SystemChecker.getProperty(WorkflowEngineConstants.NAUTICA_HOME);
		String conf = SystemChecker.getProperty(WorkflowEngineConstants.NAUTICA_MQ_CONFIG);
		String separator = SystemChecker.getProperty("file.separator");
		String path = home
		                   + separator + "config"
						   + separator + conf;
		File confFile = new File(path);
	
		if (! confFile.exists()) {
			String msg = StringManager.get("E0057")
			    + "(ConfigPath=" + path + ")";
			eLog.error(msg);
			throw new WorkflowException(msg);
		}
		if (! confFile.isFile()) {
			String msg = StringManager.get("E0058")
    		    + "(ConfigPath=" + path + ")";
			eLog.error(msg);
			throw new WorkflowException(msg);
		}
		try {
			return confFile.toURI().toString();
		} catch (Exception ex) {
			String msg = StringManager.get("E0059")
			    + "(ConfigPath=" + path + ")";;
			eLog.error(msg, ex);
			throw new WorkflowException(msg, ex);
		}
	}

	/**
	 * MessageBrokerのインスタンスを返す。
	 *
	 * @return MessageBroker
	 */
	static MessageBroker getInstance()
	{
		return broker;
	}
	
	/**
	 * MessageBrokerを生成する。
	 *
	 * @param path パス名
	 */
	private MessageBroker(String path)
	{
		queues = new Hashtable<String, WorkflowMQ>();
	}
	
	/**
	 * メッセージキューを生成する。
	 *
	 * @param queueName キュー名
	 * @param adapter アダプタ
	 * @throws WorkflowException メッセージキュー生成時に例外が起こった場合
	 */
	void generateQueue(String queueName, WorkflowMessageAdapter adapter)
	throws WorkflowException
	{
		if (queues.containsKey(queueName)) {
			// 既に同じ名前のキュ−がある
			String msg = StringManager.get("E0056");
			eLog.error(msg);
			throw new WorkflowException(msg);
		}
		WorkflowMQ queue = new WorkflowMQ(factory, queueName, adapter);
		queues.put(queueName, queue);
		queue.start();
	}
	
	/**
	 * 管理下のキューをシャットダウンし、サービスを停止する。
	 */
	void shutdown()
	{
		for (WorkflowMQ queue : queues.values()) {
			queue.shutdown();
		}
	}
	
	/**
	 * メッセージキューを返す。
	 *
	 * @param queueName キュー名
	 * @return メッセージキュー
	 */
	public WorkflowMQ getWorkflowMQ(String queueName)
	{
		return (WorkflowMQ)queues.get(queueName);
	}
}
