/*
 * ConnectionController.java
 *
 * Created on 2007/02/01, 16:58
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.itscool.commons.connection;

import java.net.URL;
import org.itscool.commons.bean.BeanFactory;

/**
 *
 * @author kano
 */
public class ConnectionController {
    public static synchronized void init(){
        ConnectionManager mgr = null;
        try{
            ClassLoader parent = Thread.currentThread().getContextClassLoader();
            URL diconfigUrl = parent.getResource("di-config.xml");
            
            String configFwName;
            //System.out.println("di-config.xml path use = " + diconfigUrl.getPath());
            if(diconfigUrl == null ){
                String err = "di-config.xml path is null.";
                throw new ConnectionPoolInitializerException(err);
            }else{
                configFwName = diconfigUrl.getPath();
            }
            BeanFactory factory = BeanFactory.getInstance();
            factory.create(configFwName);
            mgr = (ConnectionManager) factory.createInstance("ConnectionManager");
            mgr.init();
        }catch(Exception e){
            if( mgr != null ){
                mgr.destroy();
            }
            throw new ConnectionPoolInitializerException(e.getMessage());
        }
    }
    
    public static void executeOnCommit(String sql){
        Transaction transaction = null;
        try{
            transaction = TransactionUtil.getTransaction();
            transaction.execute(sql.toString());
            if( transaction.getTranStatus() == Transaction.PLEASE_COMMIT ){
                transaction.commit();
            }else if( transaction.getTranStatus() == transaction.PLEASE_ROLLBACK){
                transaction.rollback();
            }
        }catch(TransactionException e){
            throw e;
        }finally{
            if( transaction != null && 
                transaction.getTranStatus() != Transaction.NON_PROCESS ){
                TransactionUtil.rollbackTransaction();
            }
            TransactionUtil.returnTransaction();
        }
    }
    
    public static synchronized void destory(){
        BeanFactory factory = BeanFactory.getInstance();
        if( factory == null )return;
        ConnectionManager mgr = (ConnectionManager) factory.createInstance("ConnectionManager");
        if( mgr == null ) return;
        mgr.destroy();
    }
    
}
