package org.apache.slide.transaction;

import javax.transaction.TransactionManager;
import javax.naming.Context;
import javax.naming.InitialContext;

import org.apache.slide.common.SlideException;
import org.apache.slide.util.conf.*;


/**
 * @author ggongaware@itensil.com
 * @version $Revision: 1.0 $
 */
public class TransactionManagerConfig {


	public TransactionManager getTransactionManager(Configuration definition) 
			throws SlideException {

		TransactionManager tm = null;
		Configuration tmConf = null;
		try {
			tmConf = definition.getConfiguration("transaction-manager");
		} catch (ConfigurationException ce) {}		    
		if (tmConf != null) {
		    String value = tmConf.getValue();
			String type = tmConf.getAttribute("type", "classname");
			if (type.equalsIgnoreCase("classname")) {
				try {
					Class tmClass = Class.forName(value, true,
	                        Thread.currentThread().getContextClassLoader());                
	                tm = (TransactionManager)tmClass.newInstance();
				} catch (Exception ex) {
					throw new SlideException(
							"Transaction manager class error: " +
							ex.getMessage());
				}
			} else if (type.equalsIgnoreCase("jndi")) {
				try {
					Context initCtx = new InitialContext();
					Context envCtx = (Context) initCtx.lookup("java:comp/env");
					tm = (TransactionManager)envCtx.lookup(value);
				} catch (Exception ex) {
					throw new SlideException(
							"Transaction manager JNDI error: " +
							ex.getMessage());
				}
			}						
		}
		if (tm == null) {
			tm = new SlideTransactionManager();
		}		
		return tm;
	}
}

