/* $Id: DataAccessManager.java,v 1.5 2008/01/07 08:27:21 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.sql.Connection;
import java.sql.SQLException;
import java.sql.Timestamp;

import javax.sql.DataSource;

import org.apache.log4j.Logger;

import jp.co.argo21.nautica.workflow.dataaccess.WorkflowDAOFactory;
import jp.co.argo21.nautica.workflow.omg.WorkflowException;
import jp.co.argo21.nautica.workflow.util.StringManager;

/**
 * データアクセス関連の資源を管理する。
 *
 * @author  nito(Argo 21, Corp.)
 * @version $Revision: 1.5 $
 * @since   Nautica Workflow 1.0
 */
public class DataAccessManager
{
	/** スレッドローカルなコネクション */
	private static final ThreadLocal<Connection> connectionHolder = new ThreadLocal<Connection>();
	/** スレッドローカルなタイムスタンプ */
	private static final ThreadLocal<Timestamp> timestampHolder = new ThreadLocal<Timestamp>();

	/** エンジンログ */
	private static Logger eLog = LogManager.getEngineLogger();
	
	/** データソース */
	private static DataSource ds;
	
	/** XA対応データソースかを示すフラグ */
	private static boolean xa;
	
	/** DAOファクトリ */
	private static WorkflowDAOFactory daoFactory;
	
	/**
	 * DataAccessManagerの初期化を行う。
	 *
	 * @throws Exception 任意の例外
	 */
	static void create() throws WorkflowException
	{
		try {
			String daofcn = SystemChecker.getProperty(WorkflowEngineConstants.NAUTICA_DAO_FACTORY);
			daoFactory = (WorkflowDAOFactory)Class.forName(daofcn).newInstance();
		} catch (Exception ex) {
			String msg = StringManager.get("E0071");
			eLog.error(msg, ex);
			throw new WorkflowException(msg, ex);
		}
	}
	
	/**
	 * データソースを返す。
	 *
	 * @return データソース
	 */
	public static DataSource getDataSource()
	{
		return DataAccessManager.ds;
	}

	public static void setDataSource(DataSource ds, boolean xa)
	throws WorkflowException
	{
		if (DataAccessManager.ds == null) {
			DataAccessManager.ds = ds;
			DataAccessManager.xa = xa;
		} else {
			String msg = StringManager.get("E0070");
			eLog.error(msg);
			throw new WorkflowException(msg);
		}
	}

	/**
	 * DAOファクトリを返す。
	 *
	 * @return DAOファクトリ
	 */
	public static WorkflowDAOFactory getDAOFactory()
	{
		return daoFactory;
	}
	
	/**
	 * トランザクションを開始する。
	 *
	 * @param isAutoCommit 自動コミットモードならtrue
	 * @throws SQLException SQL関連例外
	 */
	public static void begin(boolean isAutoCommit)
	throws SQLException
	{
		Connection conn = getConnection();
		conn.setAutoCommit(isAutoCommit);
	}
	
	/**
	 * トランザクションをコミットする。
	 *
	 * @throws SQLException SQL関連例外
	 * @throws WorkflowException ワークフロー関連例外
	 */
	public static void commit()
	throws SQLException, WorkflowException
	{
		//if (DataAccessManager.xa == false) {
			Connection conn = getConnection();
			conn.commit();
		//}
		SystemMessageTransporter.execute();
	}
	
	/**
	 * トランザクションをロールバックする。
	 *
	 * @throws SQLException SQL関連例外
	 */
	public static void rollback()
	throws SQLException
	{
		//if (DataAccessManager.xa == false) {
			Connection conn = getConnection();
			if (conn != null && (! conn.isClosed())) {
				conn.rollback();
			}
		//}
	}

	/**
	 * JDBC接続を取り出す。
	 *
	 * @return JDBC接続
	 * @throws SQLException SQL関連例外
	 */
	public static Connection getConnection()
	throws SQLException
	{
		Connection conn = (Connection)connectionHolder.get();
		
		if (conn == null) {
			conn = ds.getConnection();
			connectionHolder.set(conn);
			long now = System.currentTimeMillis();
			Timestamp ts = new Timestamp(now);
			timestampHolder.set(ts);
		}
		return conn;
	}

	/**
	 * トランザクション内でのアクセス時刻を返す。
	 *
	 * @return アクセス時刻
	 * @throws SQLException SQL関連例外
	 */
	public static Timestamp getAccessTime()
	throws SQLException
	{
		getConnection();
		Timestamp ts = (Timestamp)timestampHolder.get();
		return ts;
	}
	
	/**
	 * JDBC接続を閉じる。
	 *
	 * @throws SQLException SQL関連例外
	 */
	public static void close()
	throws SQLException
	{
		Connection conn = (Connection)connectionHolder.get();
		connectionHolder.set(null);
		timestampHolder.set(null);
		if (conn != null && (! conn.isClosed())) {
			//if (DataAccessManager.xa == false) {
				conn.close();
			//}
		}
	}
}
