/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */

package org.jfox.jdbc.xa;

import java.util.Hashtable;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.Reference;
import javax.naming.spi.ObjectFactory;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class XADataSourceObjectFactory implements ObjectFactory {

    public synchronized Object getObjectInstance(Object obj, Name name, Context nameCtx, Hashtable environment) throws Exception {
        Reference ref = (Reference) obj;
        if(ref.getClassName().equals(TxDataSource.class.getName())) {
            String dsName = (String) ref.get("dsName").getContent();
            String dbUrl = (String) ref.get("dbURL").getContent();
            String user = (String) ref.get("user").getContent();
            String password = (String) ref.get("password").getContent();

            if((dsName != null) && XADataSourceManager.existsDataSource(dsName)) {
                return XADataSourceManager.getDataSource(dsName);
            }
            else {
                TxDataSource txds = XADataSourceManager.newDataSource(dbUrl, user, password);
                txds.init();
                if(dsName != null && !dsName.equals("")) {
                    XADataSourceManager.registerDataSource(dsName, txds);
                }
                return txds;
            }
        }
        else {
            return null;
        }
    }

    public static void main(String[] args) {

    }
}