/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.server;

import com.sun.appserv.server.util.ASClassLoaderUtil;
import com.sun.enterprise.config.serverbeans.*;
import com.sun.enterprise.config.*;
import com.sun.logging.LogDomains;
import com.sun.enterprise.admin.event.ResourceDeployEvent;
import com.sun.enterprise.deployment.runtime.connector.SunConnector;
import com.sun.enterprise.deployment.ConnectorDescriptor;
import com.sun.enterprise.deployment.ConnectionDefDescriptor;
import com.sun.enterprise.deployment.EnvironmentProperty;
import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.runtime.connector.ResourceAdapter;

import com.sun.enterprise.server.ApplicationLifecycle;
import com.sun.enterprise.instance.AppsManager;
import com.sun.enterprise.instance.EjbModulesManager;
import com.sun.enterprise.instance.InstanceFactory;
import com.sun.enterprise.instance.InstanceEnvironment;
import com.sun.enterprise.loader.EJBClassPathUtils;

import com.sun.enterprise.connectors.ConnectorRegistry;
import com.sun.enterprise.connectors.ConnectorRuntime;
import com.sun.enterprise.connectors.ConnectorConstants;
import com.sun.enterprise.connectors.ConnectorRuntimeException;
import com.sun.enterprise.connectors.DeferredResourceConfig;
import com.sun.enterprise.connectors.util.ConnectionPoolObjectsUtils;
import com.sun.enterprise.util.RelativePathResolver;
import com.sun.enterprise.util.Utility;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.Set;
import java.util.Iterator;
import java.lang.Integer;
import java.util.ArrayList;
import java.lang.reflect.Method;
import javax.resource.spi.ManagedConnectionFactory;


/**
  *
  * @author    Srikanth P, Sivakumar Thyagarajan, Aditya Gore
  * @version
 */

public class ResourcesUtil {
    static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
    static int NO_OF_ALL_CONNECTOR_RESOURCE_TYPE = 4;
    static int NO_OF_CONNECTOR_RESOURCE_TYPE = 3;
    static int NO_OF_JDBC_RESOURCE_TYPE = 2;

    private static ServerContext sc_ = null;
    private static Resources res = null;
    private static Domain dom = null;
    private static ConfigContext configContext_ =null;
    private static ResourcesUtil instance_=null;
    private ConnectorConnectionPool[] standAloneRarConnectorConnectionPools = 
                         null;
    private ConnectorConnectionPool[] embeddedRarConnectorConnectionPools =
                         null;
    private boolean filteredConnectorConnectionPool = false;
    private ConnectorResource[] standAloneRarConnectorResources = null;
    private ConnectorResource[] embeddedRarConnectorResources = null;
    private boolean filteredConnectorResources = false;
    private AdminObjectResource[] standAloneRarAdminObjectResources = null;
    private AdminObjectResource[] embeddedRarAdminObjectResources = null;
    private boolean filteredAdminObjectResources = false;
    private static Applications apps = null;
    private static ConnectorModule[] connectorModules = null;
    private static J2eeApplication[] j2eeApps = null;
    private boolean reinitConfigContext=true;
    
    private static final String JNDI_METHOD = "getJndiName";
    private static final String NAME_METHOD = "getName";   

    public static ResourcesUtil getInstance(ServerContext sc) 
                throws ConfigException {
        if(instance_ == null) {
            sc_ = sc;
            configContext_ = sc.getConfigContext();
            dom = ServerBeansFactory.getDomainBean(configContext_);
            res = dom.getResources();
            apps = dom.getApplications();
            connectorModules = apps.getConnectorModule();
            j2eeApps = apps.getJ2eeApplication();
	    if (isDAS()) {
	        if (_logger.isLoggable(Level.FINE)) {
		    _logger.fine("Creating DASResourcesUtil. We are in DAS");
		}
	        instance_ = new DASResourcesUtil();
	    } else {
                instance_ = new ResourcesUtil();
	    }

        }
        return instance_;
    }

    public static ResourcesUtil getInstance() {
       return instance_;
    }

    protected ResourcesUtil() {
    }

    public ConfigBean[][] getConnectorResources() throws ConfigException{

        ConfigBean configBeanArray[][] = 
                        new ConfigBean[NO_OF_ALL_CONNECTOR_RESOURCE_TYPE][];       

        // connector connection pool
        ConnectorConnectionPool[] ccp = res.getConnectorConnectionPool();
        configBeanArray[0] = getReferencedBeans(ccp, NAME_METHOD);

        // connector resource
        ConnectorResource[] cr = res.getConnectorResource();
        configBeanArray[1] = getReferencedConnectorResourceBeans(cr, JNDI_METHOD);

        // admin object resource
        AdminObjectResource[] ar = res.getAdminObjectResource();
        configBeanArray[2] = getReferencedBeans(ar, JNDI_METHOD);

        // resource adapter config
        ResourceAdapterConfig[] rac = res.getResourceAdapterConfig();
        configBeanArray[3] = getReferencedBeans(rac, NAME_METHOD);       

        return configBeanArray;
    }
    public ConfigBean[][] getConnectorResources(boolean onlystandAloneRars) 
                                throws ConfigException{

        ConfigBean configBeanArray[][] =
                        new ConfigBean[NO_OF_CONNECTOR_RESOURCE_TYPE][];
        configBeanArray[0] = getFilteredConnectorConnectionPools(
                                      onlystandAloneRars);
        configBeanArray[1] = getFilteredConnectorResources(
                                               onlystandAloneRars);
        configBeanArray[2] = getFilteredAdminObjectResources(
                                               onlystandAloneRars);
/*
        if(onlystandAloneRars) {
            configBeanArray[3] = getResourceAdapterConfigProps();    
        }
*/
        return configBeanArray;
    }

    public ConfigBean[][] getStandAloneNonSystemRarConnectorResources()
                           throws ConfigException {

        boolean onlystandAloneRars = true;
        ConfigBean configBeanArray[][] =
                        new ConfigBean[NO_OF_CONNECTOR_RESOURCE_TYPE][];
        ConfigBean[] ccp = getFilteredConnectorConnectionPools(
                                      onlystandAloneRars);
        
        configBeanArray[0] = getNonSystemRarPools(ccp);
        ConfigBean[] connectorResource = getFilteredConnectorResources(
                                               onlystandAloneRars);
        configBeanArray[1] = getNonSystemRarResources(
                                configBeanArray[0],connectorResource);
        ConfigBean[] adminObjectRes = getFilteredAdminObjectResources(
                                               onlystandAloneRars);

        configBeanArray[2] = getNonSystemRarAdminObjects(adminObjectRes);

        return configBeanArray;
    }

    private ConfigBean[] getNonSystemRarPools(ConfigBean[] ccp) {

        if(ccp == null || ccp.length == 0 ) {
            return null;
        }
        int noOfPools = 0;
        String rarName = null;
        Vector indexes = new Vector();
        for(int i=0;i<ccp.length;++i) {
            rarName = ((ConnectorConnectionPool)ccp[i]).getResourceAdapterName();
            if(rarName != null && !belongToSystemRar(rarName)) {
                noOfPools++;
                indexes.add(new Integer(i));
            }
        }
        ConfigBean configBeanArray[] = null;
        if(noOfPools != 0) {
            configBeanArray = new ConfigBean[noOfPools];
        }
        int location = 0;
        for(int i=0;i<indexes.size();++i) {
            location = ((Integer)(indexes.elementAt(i))).intValue();
            configBeanArray[i] = ccp[location];
        }
        return configBeanArray;
    }

    private ConfigBean[] getNonSystemRarAdminObjects(
                          ConfigBean[] adminObjectRes) 
    {
        if(adminObjectRes == null || adminObjectRes.length == 0 ) {
            return null;
        }
        int noOfRes = 0;
        String rarName = null;
        Vector indexes = new Vector();
        for(int i=0;i<adminObjectRes.length;++i) {
            rarName = ((AdminObjectResource)adminObjectRes[i]).getResAdapter();
            if(rarName != null && !belongToSystemRar(rarName)) {
                noOfRes++;
                indexes.add(new Integer(i));
            }
        }
        ConfigBean configBeanArray[] = null;
        if(noOfRes != 0) {
            configBeanArray = new ConfigBean[noOfRes];
        }
        int location = 0;
        for(int i=0;i<indexes.size();++i) {
            location = ((Integer)(indexes.elementAt(i))).intValue();
            configBeanArray[i] = adminObjectRes[location];
        }
        return configBeanArray;
    }
    private ConfigBean[] getNonSystemRarResources(
         ConfigBean[] ccp,ConfigBean[] connectorResource) 
    {
        if(ccp == null || ccp.length == 0  || 
                 connectorResource == null || connectorResource.length == 0) {
            return null;
        }
        int noOfRes = 0;
        String poolName = null;
        String connectionPoolName = null;
        Vector indexes = new Vector();
        for(int i=0;i<connectorResource.length;++i) {
            poolName = ((ConnectorResource)connectorResource[i]).getPoolName();
            for(int j=0;poolName != null && j<ccp.length;++j) {
                connectionPoolName = ((ConnectorConnectionPool)ccp[j]).getName();
                if(poolName.equals(connectionPoolName)) {
                    noOfRes++;
                    indexes.add(new Integer(i));
                }
            }
        }
        ConfigBean configBeanArray[] = null;
        if(noOfRes != 0) {
            configBeanArray = new ConfigBean[noOfRes];
        }
        int location = 0;
        for(int i=0;i<indexes.size();++i) {
            location = ((Integer)(indexes.elementAt(i))).intValue();
            configBeanArray[i] = connectorResource[location];
        }
        return configBeanArray;
    }
    public ConfigBean[] getResourceAdapterConfigs() throws ConfigException {
        reinitialize();
        ResourceAdapterConfig[] raConfigBeans = res.getResourceAdapterConfig();            
        return raConfigBeans;        
    }

    public ConfigBean[] getResourceAdapterConfigs(String rarName) 
                               throws ConfigException 
    {
        reinitialize();
        ResourceAdapterConfig[] raConfigBeans = res.getResourceAdapterConfig();    
        if(raConfigBeans == null) {
            return null;
        }
        Vector tmpVector = new Vector();
        for(int i=0;raConfigBeans != null && i<raConfigBeans.length;++i) {
            if(raConfigBeans[i].getResourceAdapterName().equals(rarName)){
                tmpVector.add(raConfigBeans[i]);
            }
        }
        return convertToConfigBeans(tmpVector);
    }

    public ConfigBean[] getEmbeddedRarResourceAdapterConfigs(String appName) 
                               throws ConfigException 
    {
        reinitialize();
        
        Applications apps = dom.getApplications();
        J2eeApplication j2eeApp = apps.getJ2eeApplicationByName(appName);
        if(j2eeApp == null || !j2eeApp.isEnabled()) {
            return null;
        }
        
        ResourceAdapterConfig[] raConfigBeans = res.getResourceAdapterConfig();
        
        if(raConfigBeans == null) {
            return null;
        }
        String appNameToken = null;
        Vector tmpVector = new Vector();
        for(int i=0;i<raConfigBeans.length;++i) {
            appNameToken = 
                  getAppNameToken(raConfigBeans[i].getResourceAdapterName());
            if(appNameToken != null && appName.equals(appNameToken)) {
                tmpVector.add(raConfigBeans[i]);
            }
        }
        return convertToConfigBeans(tmpVector);
    }

    private String getAppNameToken(String rarName) {
        if(rarName == null) {
            return null;
        }
      
        int index = rarName.indexOf(
                     ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER);
        if(index != -1) {
                return rarName.substring(0,index);
        } else {
            return null;
        }
    }

    public ConfigBean[][] getConnectorResources(String rarName) 
                       throws ConfigException 
    {

        ConfigBean configBeanArray[][] =
                        new ConfigBean[NO_OF_CONNECTOR_RESOURCE_TYPE][];
        configBeanArray[0] = getEnabledConnectorConnectionPools(
                                      rarName);
        configBeanArray[1] = getEnabledConnectorResources(
                                               rarName);
        configBeanArray[2] = getEnabledAdminObjectResources(
                                               rarName);
        return configBeanArray;

    }

    public ConfigBean[][] getAllConnectorResources(String rarName)
                       throws ConfigException
    {

        ConfigBean configBeanArray[][] =
                        new ConfigBean[NO_OF_ALL_CONNECTOR_RESOURCE_TYPE][];
        configBeanArray[0] = getEnabledConnectorConnectionPools(
                                      rarName);
        configBeanArray[1] = getEnabledConnectorResources(
                                               rarName);
        configBeanArray[2] = getEnabledAdminObjectResources(
                                               rarName);
        configBeanArray[3] = getResourceAdapterConfigs(rarName);

        return configBeanArray;

    }

    public void setConfigContext(ConfigContext ctx) {
        configContext_ = ctx;
    }

    public ConfigContext getConfigContext() {
        return configContext_;
    }

    public void setReinitConfigContext(boolean reinitConfigContext) {
        this.reinitConfigContext = reinitConfigContext;
    }

    public boolean isReinitConfigContext() {
        return this.reinitConfigContext;
    }
    public void reinitialize() {
        try {
            if(reinitConfigContext) {
                configContext_ = 
                   ApplicationServer.getServerContext().getConfigContext();
            } 
            dom = ServerBeansFactory.getDomainBean(configContext_);
            res = dom.getResources();
            apps = dom.getApplications();
        } catch (ConfigException ce) {
        }
    } 

    public boolean poolBelongsToSystemRar(String poolName) {
        DeferredResourceConfig poolConfig = 
                       getDeferredConnectorPoolConfigs(poolName);
        if(poolConfig != null && 
                 belongToSystemRar(poolConfig.getRarName())) {
            return true;
        } else {
            poolConfig = getDeferredJdbcPoolConfigs(poolName);
            if(poolConfig != null) {
                return belongToSystemRar(poolConfig.getRarName());
            }
        }
        return false;
    }

    public boolean resourceBelongsToSystemRar(String resourceName) {
        DeferredResourceConfig resourceConfig = 
                       getDeferredConnectorResourceConfigs(resourceName);
        if(resourceConfig != null && 
                belongToSystemRar(resourceConfig.getRarName())) {
            return true;  
        } else {
            resourceConfig = 
                       getDeferredJdbcResourceConfigs(resourceName);
            if(resourceConfig != null) {
                return belongToSystemRar(resourceConfig.getRarName());
            }
        }
        return false;
    }

    public boolean adminObjectBelongsToSystemRar(String adminObject) {
        DeferredResourceConfig adminObjectConfig = 
                       getDeferredAdminObjectConfigs(adminObject);
        if(adminObjectConfig != null) {
            return belongToSystemRar(adminObjectConfig.getRarName());
        } 
        return false;
    }
    protected DeferredResourceConfig getDeferredConnectorResourceConfigs(
                  String resourceName) 
    {

        if(resourceName == null) {
            return null;
        }
        
        ConfigBean[] resourcesToload = new ConfigBean[2];
        reinitialize();

        try {
            if(!isReferenced(resourceName)){
                return null;
            }
        } catch (ConfigException e) {
            _logger.log(Level.WARNING, e.getMessage());
            _logger.log(Level.FINE, "Error while finding resource references " , e);
        }
        
        
        ConnectorResource connectorResource = 
                     res.getConnectorResourceByJndiName(resourceName);
        if(connectorResource == null || !connectorResource.isEnabled()) {
            return null;
        }
        String poolName = connectorResource.getPoolName();
        ConnectorConnectionPool ccPool = 
                       res.getConnectorConnectionPoolByName(poolName);
        if(ccPool == null) {
            return null;
        }
        String rarName = ccPool.getResourceAdapterName();
        if(rarName != null && belongToSystemRar(rarName)) {
            resourcesToload[0] = ccPool;
            resourcesToload[1] = connectorResource;
            ResourceAdapterConfig[] resourceAdapterConfig = 
                                        new ResourceAdapterConfig[1];
            resourceAdapterConfig[0] = 
                         res.getResourceAdapterConfigByResourceAdapterName(
                          rarName);
            DeferredResourceConfig resourceConfig = 
                            new DeferredResourceConfig(rarName,null,ccPool,
                            connectorResource,null,null,
                            resourceAdapterConfig);
            resourceConfig.setResourcesToLoad(resourcesToload); 
            return resourceConfig;
        } 
        return null;
    }

    protected DeferredResourceConfig getDeferredConnectorPoolConfigs(
                  String poolName) 
    {

        ConfigBean[] resourcesToload = new ConfigBean[1];
        if(poolName == null) {
            return null;
        }
        
        
        reinitialize();

        ConnectorConnectionPool ccPool = 
                res.getConnectorConnectionPoolByName(poolName);
        if(ccPool == null) {
            return null;
        }
        
        String rarName = ccPool.getResourceAdapterName();
        
        if(rarName != null && belongToSystemRar(rarName)) {
            resourcesToload[0] = ccPool;
            ResourceAdapterConfig[] resourceAdapterConfig = 
                      new ResourceAdapterConfig[1];
            resourceAdapterConfig[0] = 
                   res.getResourceAdapterConfigByResourceAdapterName(
                   rarName);
            DeferredResourceConfig resourceConfig = 
                 new DeferredResourceConfig(rarName,null,ccPool,
                 null,null,null,resourceAdapterConfig);
            resourceConfig.setResourcesToLoad(resourcesToload); 
            return resourceConfig;
        } 
        return null;
    }
    protected DeferredResourceConfig getDeferredAdminObjectConfigs(
                  String resourceName) 
    {

        if(resourceName == null) {
            return null;
        }
        ConfigBean[] resourcesToload = new ConfigBean[1];
        reinitialize();
        
        try {
            if(!isReferenced(resourceName)){
                return null;
            }
        } catch (ConfigException e) {
            _logger.log(Level.WARNING, e.getMessage());
            _logger.log(Level.FINE, "Error while finding resource references " , e);
        }
        
        AdminObjectResource adminObjectResource = 
                      res.getAdminObjectResourceByJndiName(resourceName);
        if(adminObjectResource == null || !adminObjectResource.isEnabled()) {
            return null;
        }
        String rarName = adminObjectResource.getResAdapter();
        if(rarName != null && belongToSystemRar(rarName)) {
            resourcesToload[0] = adminObjectResource;
            ResourceAdapterConfig[] resourceAdapterConfig = 
                                        new ResourceAdapterConfig[1];
            resourceAdapterConfig[0] = 
                   res.getResourceAdapterConfigByResourceAdapterName(rarName);
            DeferredResourceConfig resourceConfig = 
                         new DeferredResourceConfig(rarName,adminObjectResource,
                         null,null,null,null,resourceAdapterConfig);
            resourceConfig.setResourcesToLoad(resourcesToload); 
            return resourceConfig;
        }
        return null;
    }

    protected DeferredResourceConfig getDeferredJdbcResourceConfigs(
                  String resourceName) 
    {

        ConfigBean[] resourcesToload = new ConfigBean[2];
        if(resourceName == null) {
            return null;
        }
        reinitialize();
        
        try {
            //__pm does not have a domain.xml entry and hence will not
            //be referenced
            if(!(resourceName.endsWith("__pm"))){
                if(!isReferenced(resourceName)){
                    return null;
                }
            }
        } catch (ConfigException e) {
            _logger.log(Level.WARNING, e.getMessage());
            _logger.log(Level.FINE, "Error while finding resource references " , e);
        }
        
        JdbcResource jdbcResource = res.getJdbcResourceByJndiName(resourceName);
        if(jdbcResource == null || !jdbcResource.isEnabled()) {
            String cmpResourceName = 
                        getCorrespondingCmpResourceName(resourceName);
            jdbcResource =res.getJdbcResourceByJndiName(cmpResourceName);
            if(jdbcResource == null) {
                return null;
            }
        }
        JdbcConnectionPool jdbcPool = 
                res.getJdbcConnectionPoolByName(jdbcResource.getPoolName());
        if(jdbcPool == null) {
            return null;
        } 
        String rarName = getRAForJdbcConnectionPool(jdbcPool);
        if(rarName != null && belongToSystemRar(rarName)) {
            resourcesToload[0] = jdbcPool;
            resourcesToload[1] = jdbcResource;
            DeferredResourceConfig resourceConfig = 
                            new DeferredResourceConfig(rarName,null,null,
                            null,jdbcPool,jdbcResource,null);
            resourceConfig.setResourcesToLoad(resourcesToload); 
            return resourceConfig;
        } 
        return null;
    }

    protected DeferredResourceConfig getDeferredJdbcPoolConfigs(
                  String poolName) 
    {
	
        ConfigBean[] resourcesToload = new ConfigBean[1];
        if(poolName == null) {
            return null;
        }
        reinitialize();

        JdbcConnectionPool jdbcPool = 
                res.getJdbcConnectionPoolByName(poolName);
        if(jdbcPool == null) {
            return null;
        }
        String rarName = getRAForJdbcConnectionPool(jdbcPool);
        
        if(rarName != null && belongToSystemRar(rarName)) {
                    resourcesToload[0] = jdbcPool;
                    DeferredResourceConfig resourceConfig = 
                            new DeferredResourceConfig(rarName,null,null,
                            null,jdbcPool,null,null);
                    resourceConfig.setResourcesToLoad(resourcesToload); 
                    return resourceConfig;
        } 
        return null;
    }

    public DeferredResourceConfig getDeferredResourceConfig(String resourceName)
    {
        DeferredResourceConfig resConfig = getDeferredConnectorResourceConfigs(
                                              resourceName);
        if(resConfig != null) {
            return resConfig;
        }
 
        resConfig = getDeferredJdbcResourceConfigs(
                                              resourceName);
        
        if(resConfig != null) {
            return resConfig;
        }
       
        resConfig = getDeferredAdminObjectConfigs(
                                              resourceName);
        
        if(resConfig != null) {
            return resConfig;
        }
        return null;
    }

    public DeferredResourceConfig getDeferredPoolConfig(String poolName)
    {

        DeferredResourceConfig resConfig = getDeferredConnectorPoolConfigs(
                                              poolName);
        if(resConfig != null) {
            return resConfig;
        }

        if(poolName == null){
            return null;
        }
         
        resConfig = getDeferredJdbcPoolConfigs(poolName);
        
        if(resConfig != null) {
            return resConfig;
        }
       
        return null;
    }
    
    protected String getCorrespondingCmpResourceName(String resourceName) {

        int index = resourceName.lastIndexOf("__pm");
        if(index != -1) {
            return resourceName.substring(0,index);
        }
        return null;
    }

    private ConfigBean[] getEnabledConnectorConnectionPools(String rarName) throws ConfigException {

        reinitialize();
        ConnectorConnectionPool[] connectorConnectionPools = 
                     res.getConnectorConnectionPool(); 
        int size = connectorConnectionPools.length;
        if(size == 0) {
            return null;
        }

        Vector tmpVector = new Vector();
        for(int i=0;connectorConnectionPools != null && i<connectorConnectionPools.length;++i) {
            if(connectorConnectionPools[i].getResourceAdapterName().equals(rarName) 
                      && isEnabled(connectorConnectionPools[i])){
                tmpVector.add(connectorConnectionPools[i]);
            }
        }
        return convertToConfigBeans(tmpVector);
    } 


    private ConfigBean[] getEnabledConnectorResources(String rarName) throws ConfigException {

        reinitialize();
        ConnectorResource[] connectorResources = 
                     res.getConnectorResource(); 
        int size = connectorResources.length;
        if(size == 0) {
            return null;
        }

        Vector tmpVector = new Vector();
        for(int i=0;connectorResources != null && i<connectorResources.length;++i) {
            if(belongToRar(rarName,connectorResources[i]) 
                    && isEnabled(connectorResources[i])
                    && isReferenced(connectorResources[i].getJndiName())){
                tmpVector.add(connectorResources[i]);
            }
        }
        return convertToConfigBeans(tmpVector);
    } 
    
    public ConfigBean[] getEnabledAdminObjectResources(String rarName) throws ConfigException {

        reinitialize();
        AdminObjectResource[] aor = 
                     res.getAdminObjectResource(); 
        int size = aor.length;
        if(size == 0) {
            return null;
        }

        Vector tmpVector = new Vector();
        for(int i=0;aor != null && i<aor.length;++i) {
            if(belongToRar(rarName,aor[i]) && isEnabled(aor[i])
                    && isReferenced(aor[i].getJndiName())){
                tmpVector.add(aor[i]);
            }
        }
        return convertToConfigBeans(tmpVector);
    } 

    private ConfigBean[] convertToConfigBeans(Vector vector) {
        int size = vector.size();
        if(size == 0) {
            return null;
        }
        ConfigBean[] retConfigBeans = new ConfigBean[size]; 
        for(int i=0;i<size;++i) {
            retConfigBeans[i] = (ConfigBean)vector.get(i);
        }
        return retConfigBeans;
    }
    
    private ConfigBean[] getFilteredAdminObjectResources(boolean onlystandAloneRars) 
        throws ConfigException 
    {
        if( filteredAdminObjectResources) {
            if(onlystandAloneRars) {
                return standAloneRarAdminObjectResources;
            } else {
                return embeddedRarAdminObjectResources;

            }
        }
        filteredAdminObjectResources=true;
        int noOfAdminObjectResources = res.sizeAdminObjectResource();
        if(noOfAdminObjectResources == 0) {
            return null;
        }

        Vector standAloneRarAdminObjectResourcesVector = new Vector();
        Vector embeddedRarAdminObjectResourcesVector = new Vector();
        for(int i=0; i< noOfAdminObjectResources; ++i) {
            AdminObjectResource adminObjectResource = res.getAdminObjectResource(i);            

            // skips the admin resource if it is not referenced by the server
            if(adminObjectResource == null || !isEnabled(adminObjectResource)
                    || !isReferenced(adminObjectResource.getJndiName())) {
                continue;
            }
            String resourceAdapterName = adminObjectResource.getResAdapter();
            if(belongToStandAloneRarAdminObjectResources(resourceAdapterName) || 
                                          belongToSystemRar(resourceAdapterName)) {
                standAloneRarAdminObjectResourcesVector.add(adminObjectResource);
            } else if(belongToEmbeddedRarAdminObjectResources(resourceAdapterName)){
                embeddedRarAdminObjectResourcesVector.add(adminObjectResource);
            } else {
                _logger.log(Level.WARNING,"loading.wrong_adminobject_entry",
                                              resourceAdapterName);
            }
        }

        if(standAloneRarAdminObjectResourcesVector.size() != 0) {
            standAloneRarAdminObjectResources = new AdminObjectResource[
                       standAloneRarAdminObjectResourcesVector.size()];
            for(int i=0;i<standAloneRarAdminObjectResourcesVector.size();++i) {
                standAloneRarAdminObjectResources[i] = (AdminObjectResource)
                            standAloneRarAdminObjectResourcesVector.elementAt(i);
            }
        }
        if(embeddedRarAdminObjectResourcesVector.size() != 0) {
            embeddedRarAdminObjectResources = new AdminObjectResource[
                      embeddedRarAdminObjectResourcesVector.size()];
            for(int i=0;i<embeddedRarAdminObjectResourcesVector.size();++i) {
                embeddedRarAdminObjectResources[i] = (AdminObjectResource)
                         embeddedRarAdminObjectResourcesVector.elementAt(i);
            }
        }
        if(onlystandAloneRars) {
            return standAloneRarAdminObjectResources;
        } else {
            return embeddedRarAdminObjectResources;
        }
    }
  
    private ConfigBean[] getFilteredConnectorResources(
                            boolean onlystandAloneRars) throws ConfigException {
        if( filteredConnectorResources) {
            if(onlystandAloneRars) {
                return standAloneRarConnectorResources;
            } else {
                return embeddedRarConnectorResources;

            }
        }

        filteredConnectorResources = true;
        int noOfConnectorResources = res.sizeConnectorResource();

        if(noOfConnectorResources == 0) {
            return null;
        }

        Vector standAloneRarConnectorResourcesVector = new Vector();
        Vector embeddedRarConnectorResourcesVector  = new Vector();
        for(int i=0; i< noOfConnectorResources; ++i) {
            ConnectorResource ccResource = res.getConnectorResource(i);
            // skips if the connector resource is not referenced by server
            if(ccResource == null || !isEnabled(ccResource) 
                    || !isReferenced(ccResource.getJndiName())) {
                continue;
            }
            String poolName = ccResource.getPoolName();
            if(belongToStandAloneRarConnectorResources(poolName)) {
                standAloneRarConnectorResourcesVector.add(ccResource);
            } else if(belongToEmbeddedRarConnectorResources(poolName)){
                embeddedRarConnectorResourcesVector.add(ccResource);
            } else {
                _logger.log(Level.WARNING,"loading.wrong_resources_entry",poolName);
            }
        }
        if(standAloneRarConnectorResourcesVector.size() != 0) {
            standAloneRarConnectorResources = new ConnectorResource[
                      standAloneRarConnectorResourcesVector.size()];
            for(int i=0;i<standAloneRarConnectorResourcesVector.size();++i) {
                standAloneRarConnectorResources[i] = (ConnectorResource)
                      standAloneRarConnectorResourcesVector.elementAt(i);
            }
        }
        if(embeddedRarConnectorResourcesVector.size() != 0) {
            embeddedRarConnectorResources = new ConnectorResource[
                      embeddedRarConnectorResourcesVector.size()];
            for(int i=0;i<embeddedRarConnectorResourcesVector.size();++i) {
                embeddedRarConnectorResources[i] = (ConnectorResource)
                         embeddedRarConnectorResourcesVector.elementAt(i);
            }
        }
        if(onlystandAloneRars) {
            return standAloneRarConnectorResources;
        } else {
            return embeddedRarConnectorResources;
        }

    }
    
    private ConfigBean[] getFilteredConnectorConnectionPools(
                        boolean onlystandAloneRars) throws ConfigException {
        if( filteredConnectorConnectionPool ) {
            if(onlystandAloneRars) {
                return standAloneRarConnectorConnectionPools;
            } else {
                return embeddedRarConnectorConnectionPools;
            }
        }

        filteredConnectorConnectionPool = true;
        int noOfConnectorConnectionPools = res.sizeConnectorConnectionPool();

        if(noOfConnectorConnectionPools == 0) {
            return null;
        }

        Vector standAloneRarPoolsVector = new Vector();
        Vector embeddedRarPoolsVector  = new Vector();
        for(int i=0; i< noOfConnectorConnectionPools; ++i) {
            ConnectorConnectionPool ccPool = res.getConnectorConnectionPool(i);
            // skips the pool if not referenced by the server
            if(ccPool == null || !isEnabled(ccPool)) {
                continue;
            }
            String resourceAdapterName = ccPool.getResourceAdapterName();
            if(belongToStandAloneRarConnectionPools(resourceAdapterName) || 
                           belongToSystemRar(resourceAdapterName)) {
                standAloneRarPoolsVector.add(ccPool);
            } else if(belongToEmbeddedRarConnectionPools(
                                               resourceAdapterName)) {
                embeddedRarPoolsVector.add(ccPool);
            } else {
                _logger.log(Level.WARNING,"loading.wrong_connectorpool_entry",
                                 resourceAdapterName);
            }
        }
        if(standAloneRarPoolsVector.size() != 0) {
            standAloneRarConnectorConnectionPools =
                new ConnectorConnectionPool[standAloneRarPoolsVector.size()];
            for(int i=0;i<standAloneRarPoolsVector.size();++i) {
                standAloneRarConnectorConnectionPools[i] =
                 (ConnectorConnectionPool)standAloneRarPoolsVector.elementAt(i);
            }
        }
        if(embeddedRarPoolsVector.size() != 0) {
            embeddedRarConnectorConnectionPools =
                new ConnectorConnectionPool[embeddedRarPoolsVector.size()];
            for(int i=0;i<embeddedRarPoolsVector.size();++i) {
                embeddedRarConnectorConnectionPools[i] =
                  (ConnectorConnectionPool)embeddedRarPoolsVector.elementAt(i);
            }
        }
        if(onlystandAloneRars) {
            return standAloneRarConnectorConnectionPools;
        } else {
            return embeddedRarConnectorConnectionPools;
        }
    }

    private boolean belongToStandAloneRarAdminObjectResources(
                                        String resourceAdapterName) {
        if(connectorModules == null || connectorModules.length == 0) {
            return false;
        }
        for(int i=0; i<connectorModules.length;++i) {
            if(resourceAdapterName.equals(connectorModules[i].getName())) {
                return true;
            }
        }
        return false;
    }


    private boolean belongToEmbeddedRarAdminObjectResources(String resourceAdapterName) {
        if(j2eeApps == null || j2eeApps.length==0) {
            return false;
        }
        for(int i=0; i<j2eeApps.length;++i) {
            int index = resourceAdapterName.indexOf(
                     ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER);
            if(index != -1) {
                String appName = resourceAdapterName.substring(0,index);
                if(appName.equals(j2eeApps[i].getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean belongToStandAloneRarConnectorResources(String poolName) {
        if(standAloneRarConnectorConnectionPools==null || 
                        standAloneRarConnectorConnectionPools.length==0) {
            return false;
        }
        for (int i=0; i<standAloneRarConnectorConnectionPools.length;i++) {
            if(poolName.equals(
                    standAloneRarConnectorConnectionPools[i].getName())){
                return true;
            }
        }
        return false;
    }
    private boolean belongToEmbeddedRarConnectorResources(String poolName) {
        if(embeddedRarConnectorConnectionPools == null ||
                            embeddedRarConnectorConnectionPools.length==0) {
            return false;
        }
        for (int i=0; i<embeddedRarConnectorConnectionPools.length;i++) {
            if(poolName.equals(
                    embeddedRarConnectorConnectionPools[i].getName())){
                return true;
            }
        }
        return false;
    }

    private boolean belongToStandAloneRarConnectionPools(
                    String resourceAdapterName) {
        if(connectorModules == null || connectorModules.length == 0) {
            return false;
        }
        for(int i=0; i<connectorModules.length;++i) {
            if(resourceAdapterName.equals(connectorModules[i].getName())) {
                return true;
            }
        }
        return false;
    }

    public boolean belongToSystemRar(String resourceAdapterName) {

        for(int i=0;i<ConnectorRuntime.systemRarNames.length;++i) {
            if(resourceAdapterName.equals(ConnectorRuntime.systemRarNames[i])) {
                return true;
            }
        }
        return false;
    }
                    

    private boolean belongToEmbeddedRarConnectionPools(
                    String resourceAdapterName) {
        if(j2eeApps == null || j2eeApps.length==0) {
            return false;
        }
        for(int i=0; i<j2eeApps.length;++i) {
            int index = resourceAdapterName.indexOf(
                     ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER);
            if(index != -1) {
                String appName = resourceAdapterName.substring(0,index);
                if(appName.equals(j2eeApps[i].getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean belongToStandAloneRar(String resourceAdapterName){
    	return belongToStandAloneRarConnectionPools(resourceAdapterName);
    }

    public Object[] getConnectorResourcesJndiNames(String poolName) {

        Vector jndiNamesVector = new Vector();
        reinitialize();
        ConnectorResource[] connectorResource = res.getConnectorResource();
        if (connectorResource == null || connectorResource.length == 0) {
            return null;
        }

        for(int i=0; i<connectorResource.length; ++ i) {
            if(connectorResource[i].getPoolName().equals(poolName)) {
                jndiNamesVector.add(connectorResource[i].getJndiName());
            }

        }
        return jndiNamesVector.toArray();
    }

    public Object[] getConnectorConnectionPoolNames(String moduleName) {
        reinitialize();
        Vector poolNamesVector = new Vector();
        ConnectorConnectionPool[] connectorConnectionPool= 
                res.getConnectorConnectionPool();
        if (connectorConnectionPool== null 
               || connectorConnectionPool.length == 0) {
          return null;
        }

        for(int i=0; i<connectorConnectionPool.length; ++ i) {
            if(connectorConnectionPool[i].getResourceAdapterName().equals(
                            moduleName)) {
              poolNamesVector.add(connectorConnectionPool[i].getName());
            }
        }
        return poolNamesVector.toArray();
    }

    public ConnectorConnectionPool[] getConnectorConnectionPools() {
        reinitialize();
        ConnectorConnectionPool[] connectorConnectionPool = null;
        connectorConnectionPool = res.getConnectorConnectionPool();
        if (connectorConnectionPool.length == 0) {
            return null;
        } else {
            return connectorConnectionPool;
        }
    }

    public JdbcConnectionPool[] getJdbcConnectionPools() {
        reinitialize();
        JdbcConnectionPool[] jdbcConnectionPool = res.getJdbcConnectionPool();
        if(jdbcConnectionPool == null) return null;
        if (jdbcConnectionPool.length == 0) {
            return null;
        } else {
            return jdbcConnectionPool;
        }
    }

    public String[] getdbUserPasswordOfJdbcConnectionPool(
                  JdbcConnectionPool jdbcConnectionPool) {

        String[] userPassword = new String[2];
        userPassword[0]=null;
        userPassword[1]=null;
        ElementProperty[] elementProperty = 
                 jdbcConnectionPool.getElementProperty();
        if(elementProperty==null || elementProperty.length == 0) {
            return userPassword;
        }

        for (int i=0; i<elementProperty.length;i++) {
	    String prop = elementProperty[i].getName().toUpperCase();
            if ("USERNAME".equals( prop ) || "USER".equals( prop ) ) {
                userPassword[0]=elementProperty[i].getValue();
            } else if("PASSWORD".equals( prop ) ) {
                userPassword[1]=elementProperty[i].getValue();
            }
        } 
        return userPassword;
    }
 
    public String[] getdbUserPasswordOfConnectorConnectionPool(
                  ConnectorConnectionPool connectorConnectionPool) {

        String[] userPassword = new String[2];
        userPassword[0]=null;
        userPassword[1]=null;
        ElementProperty[] elementProperty =
                 connectorConnectionPool.getElementProperty();
        if(elementProperty != null && elementProperty.length != 0) {
            boolean foundUserPassword = false;
            for (int i=0; i<elementProperty.length;i++) {
	        String prop = elementProperty[i].getName().toUpperCase();

                if( "USERNAME".equals( prop ) || "USER".equals( prop ) ) {
                    userPassword[0]=elementProperty[i].getValue();
                    foundUserPassword = true;
                } else if("PASSWORD".equals( prop ) ) {
                    userPassword[1]=elementProperty[i].getValue();
                    foundUserPassword = true;
                }
            }
            if(foundUserPassword == true) {
                return userPassword;
            }
        } 

	String poolName = connectorConnectionPool.getName();
        String rarName = connectorConnectionPool.getResourceAdapterName();
        String connectionDefName = 
                 connectorConnectionPool.getConnectionDefinitionName();
        ConnectorRegistry connectorRegistry = 
                    ConnectorRegistry.getInstance();
        ConnectorDescriptor connectorDescriptor = 
                    connectorRegistry.getDescriptor(rarName);
        ConnectionDefDescriptor cdd = 
                    connectorDescriptor.getConnectionDefinitionByCFType(
                    connectionDefName);  
        Set configProps = cdd.getConfigProperties();
        for(Iterator iter = configProps.iterator(); iter.hasNext();) {
            EnvironmentProperty envProp= (EnvironmentProperty)iter.next();
	    String prop = envProp.getName().toUpperCase();
	    
            if("USER".equals( prop ) || "USERNAME".equals( prop )) {
	            
                    userPassword[0]=envProp.getValue();
            } else if( "PASSWORD".equals(prop) ) {
                    userPassword[1]=envProp.getValue();
            }

        }

	if ( userPassword[0] != null && ! "".equals(userPassword[0].trim()) ) {
            return userPassword;
	}

	//else read the default username and password from the ra.xml
	ManagedConnectionFactory mcf = 
	    connectorRegistry.getManagedConnectionFactory( poolName );
	userPassword[0] = ConnectionPoolObjectsUtils.getValueFromMCF(
	    "UserName", poolName, mcf);
	userPassword[1] = ConnectionPoolObjectsUtils.getValueFromMCF(
	    "Password", poolName, mcf);

	return userPassword;    
    }

    public void deleteConnectorResources(String poolname) 
                   throws ConfigException{
        ConnectorResource[] connectorResource = res.getConnectorResource();
        if (connectorResource == null || connectorResource.length == 0) {
            return;
        }

        for(int i=0; i<connectorResource.length; ++ i) {
            if(connectorResource[i].getPoolName().equals(poolname)) {
                res.removeConnectorResource(connectorResource[i]);
                configContext_.flush();
            }
        }
    }

    public void deleteConnectorConnectionPool(String moduleName) 
                 throws ConfigException{

        ConnectorConnectionPool[] connectorConnectionPool = 
                 res.getConnectorConnectionPool(); 

        if (connectorConnectionPool == null 
                 || connectorConnectionPool.length == 0) {
            return ;
        }
        for(int i=0; i<connectorConnectionPool.length;++i) {
            if(connectorConnectionPool[i].getResourceAdapterName().equals(
                       moduleName)){
                res.removeConnectorConnectionPool(connectorConnectionPool[i]);
                configContext_.flush();
            }
        }
    }

    public String getResourceType(ConfigBean cb) {
        if(cb instanceof ConnectorConnectionPool) {
           return ResourceDeployEvent.RES_TYPE_CCP;
        } else if(cb instanceof ConnectorResource) {
           return ResourceDeployEvent.RES_TYPE_CR;
        } else if(cb instanceof AdminObjectResource) {
           return ResourceDeployEvent.RES_TYPE_AOR;
        } else if(cb instanceof ResourceAdapterConfig) {
           return ResourceDeployEvent.RES_TYPE_RAC;
        } else if (cb instanceof JdbcConnectionPool) {
	   return ResourceDeployEvent.RES_TYPE_JCP;
        } else if (cb instanceof JdbcResource) {
	   return ResourceDeployEvent.RES_TYPE_JDBC;
        }
        return null;

    }

    public ResourceDeployer getResourceDeployer(String type)
                           throws Exception {

        ResourceDeployerFactory factory = new ResourceDeployerFactory();
        return factory.getResourceDeployer(type);
    }

 
    public void writeSunConnector(ConnectorDescriptor connectorDescriptor,
                String rarName, String poolName) throws ConfigException{

        configContext_ = sc_.getConfigContext();
        dom = ServerBeansFactory.getDomainBean(configContext_);
        res = dom.getResources();
       
        ConnectorConnectionPool connectorConnectionPool = getConnectionPoolObj(
                   connectorDescriptor);
        connectorConnectionPool.setName(poolName);
        connectorConnectionPool.setResourceAdapterName(rarName);

        ConnectorConnectionPool existingPool = 
                   res.getConnectorConnectionPoolByName(poolName);
        if(existingPool != null) {
            res.removeConnectorConnectionPool(existingPool);
            configContext_.flush();
        }
        res.addConnectorConnectionPool(connectorConnectionPool);
        
        configContext_.flush();

        String jndiName = (String)connectorDescriptor.getSunDescriptor().
                  getResourceAdapter().getValue(ResourceAdapter.JNDI_NAME);

        ConnectorResource connectorResource = getConnectorResource(
                  poolName,jndiName);
        ConnectorResource existingConnectorResource = 
                  res.getConnectorResourceByJndiName(jndiName);
        if(existingConnectorResource != null) {
            res.removeConnectorResource(existingConnectorResource);
            configContext_.flush();
        }
        res.addConnectorResource(connectorResource);
        configContext_.flush();
    }

    private ConnectorResource getConnectorResource(String poolName,
                    String jndiName) {

        ConnectorResource connectorResource = new ConnectorResource();

        connectorResource.setJndiName(jndiName);
        connectorResource.setPoolName(poolName);
        return connectorResource;

    }

    private ConnectorConnectionPool getConnectionPoolObj(
                ConnectorDescriptor connectorDescriptor) {
        String connectiondefName = connectorDescriptor.
                getOutboundResourceAdapter().getConnectionFactoryIntf();
        SunConnector sunConnector = connectorDescriptor.getSunDescriptor();
        ResourceAdapter sunRAXML =   sunConnector.getResourceAdapter();
        ConnectorConnectionPool connectorConnectionPool = 
                new ConnectorConnectionPool();
        connectorConnectionPool.setConnectionDefinitionName(connectiondefName);
        connectorConnectionPool.setSteadyPoolSize(
                (String)sunRAXML.getValue(ResourceAdapter.STEADY_POOL_SIZE));
        connectorConnectionPool.setMaxPoolSize(
                (String)sunRAXML.getValue(ResourceAdapter.MAX_POOL_SIZE));
        connectorConnectionPool.setMaxWaitTimeInMillis(
           (String)sunRAXML.getValue(ResourceAdapter.MAX_WAIT_TIME_IN_MILLIS));
        connectorConnectionPool.setPoolResizeQuantity("2");
        connectorConnectionPool.setIdleTimeoutInSeconds(
           (String)sunRAXML.getValue(ResourceAdapter.IDLE_TIMEOUT_IN_SECONDS));
        connectorConnectionPool.setFailAllConnections(false);
        return connectorConnectionPool;
    }

    public String getLocation(String moduleName) {

        if(moduleName == null) {
            return null;
        }
        reinitialize();
        String location  = null;
        ConnectorModule connectorModule = 
              dom.getApplications().getConnectorModuleByName(moduleName);
        if(connectorModule != null) {
            location = connectorModule.getLocation();
        }
        return location;

    }

    public ConfigBean[][] getJdbcResources() throws ConfigException{

        ConfigBean configBeanArray[][] = 
                        new ConfigBean[NO_OF_JDBC_RESOURCE_TYPE][];        
        // returns only the associated jdbc connection pools
        JdbcConnectionPool[] jcp = res.getJdbcConnectionPool();
        configBeanArray[0] = getReferencedBeans(jcp, NAME_METHOD);

        // returns only the associated jdbc resources
        JdbcResource[] jr = res.getJdbcResource();
        configBeanArray[1] = getReferencedJdbcResourceBeans(jr, JNDI_METHOD);       

        return configBeanArray;
    }  

    /**
     * Returns true if the given resource is referenced by this server. 
     *
     * @param   resourceName   the name of the resource
     *
     * @return  true if the named resource is used/referred by this server
     *
     * @throws  ConfigException  if an error while parsing domain.xml
     */
    protected boolean isReferenced(String resourceName) throws ConfigException {
        if (_logger.isLoggable(Level.FINE)) {
            _logger.fine("isReferenced :: " + resourceName + " - " 
                            + ServerHelper.serverReferencesResource(
                                  configContext_, sc_.getInstanceName(), 
                                  resourceName));
        }
        
        return ServerHelper.serverReferencesResource(configContext_, 
            sc_.getInstanceName(), resourceName);
    }
    
    /**
     * Returns an array of beans that are associated to this server instance.
     *
     * @param   beans       array of config beans representing the resources
     * @param   methodName  name of the method name to invoke to get the 
     *                      resource name. Example, getJndiName, getName, etc.
     *
     * @return  an array of beans that are associated to this server instance
     */
    private ConfigBean[] getReferencedBeans(ConfigBean[] beans, 
            String methodName) {

        ArrayList  list = new ArrayList();

        for (int i=0; i<beans.length; i++) {

            try {
                String name = null;

                if (methodName != null) {
                    Class c = beans[i].getClass();
                    Method m = c.getDeclaredMethod(methodName, (java.lang.Class[])null);
                    name = (String) m.invoke(beans[i], (java.lang.Object[])null);
                }

                if (isReferenced(name)) {
                    list.add(beans[i]);
                }
            } catch (Exception e) {
                _logger.log(Level.WARNING, "isReferenced.unexpectedException", e);
            }
        }
        // returns an array of beans referenced by this server
        ConfigBean[] refList = new ConfigBean[list.size()];

        return ( (ConfigBean[]) list.toArray(refList) );
    }   

    public boolean isEnabled(ConnectorResource cr) throws ConfigException {
        reinitialize();
        if(cr == null ) {
            return false;
        } else {
            //Since AS 8.1 PE/SE/EE resources must be referenced and their references
            //must be enabled as well.
            _logger.fine("ResourcesUtil ::  isEnabled " + cr);
            boolean resRef = isReferenced(cr.getJndiName());
            _logger.fine("ResourcesUtil :: is Referenced" + resRef);
            boolean isResRefEnabled = isResourceReferenceEnabled(cr.getJndiName());
            _logger.fine("isResRefEnabled " +  isResRefEnabled);
            if (! (cr.isEnabled() && resRef && isResRefEnabled )) return false;
        }
        
        String poolName = cr.getPoolName();
        ConnectorConnectionPool ccp = res.getConnectorConnectionPoolByName(poolName);
        if (ccp == null) {
            return false;
        }
        String raName = ccp.getResourceAdapterName();
        ConnectorModule module = dom.getApplications().getConnectorModuleByName(raName);
        if(module != null) {
            return module.isEnabled();
        } else if(belongToSystemRar(raName)) {
            return true; 
        } else {
            return belongToEmbeddedRarAndEnabled(raName);
        }
    }

    public boolean isEnabled(AdminObjectResource aot) throws ConfigException {
        reinitialize();
        if(aot == null) {
            return false;
        } else {
            //Since AS 8.1 PE/SE/EE resources must be referenced and their references
            //must be enabled as well.
            boolean resRef = isReferenced(aot.getJndiName());
            boolean isResRefEnabled = isResourceReferenceEnabled(aot.getJndiName());
            if (! (aot.isEnabled() && resRef && isResRefEnabled )) return false;
        }
        
        String raName = aot.getResAdapter();
        ConnectorModule module = dom.getApplications().getConnectorModuleByName(raName);
        if(module != null) {
            return module.isEnabled();
        } else if(belongToSystemRar(raName)){
            return true; 
        } else {
            return belongToEmbeddedRarAndEnabled(raName);
        }
    }

    public boolean isEnabled(ConnectorConnectionPool ccp) {
        if(ccp == null) {
            return false;
        }
        reinitialize();
        String raName = ccp.getResourceAdapterName();
        ConnectorModule module = dom.getApplications().getConnectorModuleByName(raName);
        if(module != null) {
            return module.isEnabled();
        } else if(belongToSystemRar(raName)) {
            return true; 
        } else {
            return belongToEmbeddedRarAndEnabled(raName);
        }
    }
    
    public boolean belongToRar(String rarName,ConnectorConnectionPool ccp) {
        if(ccp == null || rarName== null) {
            return false;
        }
        if(ccp.getResourceAdapterName().equals(rarName)) {
            return true;
        } else {
            return false;
        }
    }
    public boolean belongToRar(String rarName,ConnectorResource cr) {
        if(cr == null || rarName== null) {
            return false;
        }
        reinitialize();
        String poolName = cr.getPoolName();
        ConnectorConnectionPool ccp = res.getConnectorConnectionPoolByName(poolName);
        if (ccp == null) {
            return false;
        }
        if(ccp.getResourceAdapterName().equals(rarName)) {
            return true;
        } else {
            return false;
        }
    }

    public boolean belongToRar(String rarName,AdminObjectResource aor) {
        if(aor == null || rarName== null) {
            return false;
        }
        if(aor.getResAdapter().equals(rarName)) {
            return true;
        } else { 
            return false;
        }
    }
    private boolean belongToEmbeddedRarAndEnabled(
                    String resourceAdapterName) {
        reinitialize();
        Applications apps = dom.getApplications();
        J2eeApplication[] j2eeApps = apps.getJ2eeApplication();
        if(j2eeApps == null || j2eeApps.length==0) {
            return false;
        }
        for(int i=0; i<j2eeApps.length;++i) {
            int index = resourceAdapterName.indexOf(
                     ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER);
            if(index != -1) {
                String appName = resourceAdapterName.substring(0,index);
                if(appName.equals(j2eeApps[i].getName()) && j2eeApps[i].isEnabled()) {
                    return true;
                }
            }
        }
        return false;
    }

    public String[] listConnectorModuleNames() {

        reinitialize();
        Applications apps = dom.getApplications();
        ConnectorModule[] connectorModules = null; 
        String[] connectorModuleNames = null;
        if(apps != null) {
            connectorModules = apps.getConnectorModule();
        }
        if(connectorModules != null) {
            connectorModuleNames = new String[connectorModules.length];
            for(int i=0;connectorModules != null && i<connectorModules.length;
                                ++i){
                connectorModuleNames[i] = connectorModules[i].getName();
            }
        }
        return connectorModuleNames;
    }

    public boolean belongToEmbeddedRar(
                    String resourceAdapterName) {
        reinitialize();
        J2eeApplication[] j2eeApps = null;
        j2eeApps = apps.getJ2eeApplication();
        if(j2eeApps == null || j2eeApps.length==0) {
            return false;
        }
        for(int i=0; i<j2eeApps.length;++i) {
            int index = resourceAdapterName.indexOf(
                     ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER);
            if(index != -1) {
                String appName = resourceAdapterName.substring(0,index);
                if(appName.equals(j2eeApps[i].getName())) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
      * This method takes in an admin JdbcConnectionPool and returns the RA
      * that it belongs to.
      *
      * @param pool - The pool to check
      * @return The name of the JDBC RA that provides this pool's datasource
      *
      */

    public String getRAForJdbcConnectionPool( JdbcConnectionPool pool ) {
        String dsRAName = ConnectorConstants.JDBCDATASOURCE_RA_NAME;

        if ( pool.getResType() == null ) {
             return dsRAName;
        }

        //check if its XA
        if ( "javax.sql.XADataSource".equals( pool.getResType() ) ) {
            if ( pool.getDatasourceClassname() == null ) {
                return dsRAName;
            }
            try {
                Class dsClass=Utility.loadClass(pool.getDatasourceClassname());
                if (javax.sql.XADataSource.class.isAssignableFrom(dsClass)) {
                     return ConnectorConstants.JDBCXA_RA_NAME;
                }
            } catch( ClassNotFoundException cnfe) {
                return dsRAName;
            }
         }

         //check if its CP
         if ("javax.sql.ConnectionPoolDataSource".equals(pool.getResType())) {
             if ( pool.getDatasourceClassname() == null ) {
                 return dsRAName;
             }
             try {
                 Class dsClass=Utility.loadClass(pool.getDatasourceClassname());
                 if(javax.sql.ConnectionPoolDataSource.class.isAssignableFrom(
                                           dsClass) ) {
                     return 
                       ConnectorConstants.JDBCCONNECTIONPOOLDATASOURCE_RA_NAME;
                 }
             } catch( ClassNotFoundException cnfe) {
                 return dsRAName;
             }
         }
         //default to __ds
         return dsRAName;
     }
   
    public ConnectorResource[] getAllJmsResources() {
        reinitialize();
        ConnectorResource[] cr = res.getConnectorResource();
        
        Vector vector = new Vector();
        for(int i=0;cr != null && i<cr.length;++i) {
            if(belongToRar(ConnectorConstants.DEFAULT_JMS_ADAPTER,cr[i])) {
                vector.add(cr[i]);
            }
        }
        return (ConnectorResource[]) vector.toArray();
    }
    
    /**
     * Gets the shutdown-timeout attribute from domain.xml
     * via the connector server config bean. 
     * @return
     */
    public int getShutdownTimeout() throws ConnectorRuntimeException {
        try {
            ConnectorService connectorServiceElement = ServerBeansFactory
            .getConnectorServiceBean(ApplicationServer.getServerContext().
                    getConfigContext());
            int shutdownTimeout;
            if (connectorServiceElement == null) {
                //Connector service element is not specified in
                //domain.xml and hence going with the default time-out
                shutdownTimeout = 
                    ConnectorConstants.DEFAULT_RESOURCE_ADAPTER_SHUTDOWN_TIMEOUT; 
                _logger.log(Level.FINE, "Shutdown timeout set to " 
                        +  shutdownTimeout
                        + "through default");
               return shutdownTimeout;  
            } else {
                shutdownTimeout = (new Integer(connectorServiceElement.
                        getShutdownTimeoutInSeconds())).intValue();
                _logger.log(Level.FINE, "Shutdown timeout set to " 
                        + shutdownTimeout + " from domain.xml");
                return shutdownTimeout;
            }
        } catch (Exception e) {
            ConnectorRuntimeException crex = new ConnectorRuntimeException(e.getMessage());
            crex.initCause(e);
            throw crex;
        }
    }

     /**
      * Returns an array of beans that are associated to this server instance.
      *
      * @param   beans       array of config beans representing the Jdbc resources
      * @param   methodName  name of the method name to invoke to get the
      *                      resource name. Example, getJndiName, getName, etc.
      *
      * @return  an array of beans that are associated to this server instance
      */
     private ConfigBean[] getReferencedJdbcResourceBeans(JdbcResource[] beans,
             String methodName) {

        ArrayList  list = new ArrayList();

        for (int i=0; i<beans.length; i++) {

            try {
                String name = null;

                if (methodName != null) {
                    Class c = beans[i].getClass();
                    Method m = c.getDeclaredMethod(methodName, (java.lang.Class[])null);
                    name = (String) m.invoke(beans[i], (java.lang.Object[])null);
                }

                if (isReferenced(name)) {
                    list.add(beans[i]);
                }
            } catch (Exception e) {
                _logger.log(Level.WARNING, "isReferenced.unexpectedException", e);
            }
        }
        // returns an array of beans referenced by this server
        JdbcResource[] refList = new JdbcResource[list.size()];

        return ( (JdbcResource[]) list.toArray(refList) );
    }
    
     /**
      * Returns an array of beans that are associated to this server instance.
      *
      * @param   beans       array of config beans representing the Connector resources
      * @param   methodName  name of the method name to invoke to get the
      *                      resource name. Example, getJndiName, getName, etc.
      *
      * @return  an array of beans that are associated to this server instance
      */
     private ConfigBean[] getReferencedConnectorResourceBeans(ConnectorResource[] beans,
             String methodName) {

        ArrayList  list = new ArrayList();

        for (int i=0; i<beans.length; i++) {

            try {
                String name = null;

                if (methodName != null) {
                    Class c = beans[i].getClass();
                    Method m = c.getDeclaredMethod(methodName, (java.lang.Class[])null);
                    name = (String) m.invoke(beans[i], (java.lang.Object[])null);
                }

                if (isReferenced(name)) {
                    list.add(beans[i]);
                }
            } catch (Exception e) {
                _logger.log(Level.WARNING, "isReferenced.unexpectedException", e);
            }
        }
        // returns an array of beans referenced by this server
        ConnectorResource[] refList = new ConnectorResource[list.size()];

        return ( (ConnectorResource[]) list.toArray(refList) );
    }


    public static boolean isDAS() {
        try {
	    return ServerHelper.isDAS( com.sun.enterprise.admin.server.core.AdminService.getAdminService().getAdminContext().getAdminConfigContext(), sc_.getInstanceName() );
	} catch( ConfigException ce ) {
	    //better be more restrictive by returning false
	    return false;
	}
    }

    
    /**
     * Determines if a connector connection pool is referred in a 
     * server-instance via resource-refs
     * 
     * @param poolName
     * @return boolean true if pool is referred in this server instance, false 
     * otherwise
     * @throws ConfigException
     */
    public boolean isPoolReferredInServerInstance(String poolName) 
                                        throws ConfigException {
        reinitialize();
        ConnectorResource[] connRes = res.getConnectorResource();
        
        for (int i = 0; i < connRes.length; i++) {
            _logger.fine("poolname " + connRes[i].getPoolName() 
                            + "resource " + connRes[i].getJndiName());
            
            if ((connRes[i].getPoolName().equalsIgnoreCase(poolName))){
                _logger.fine("Connector resource "  + connRes[i].getJndiName() + 
                                "refers " + poolName + "in this server instance");
                return true;
            }
        }
        
        _logger.fine("No JDBC resource refers " + poolName 
                        + "in this server instance");
        return false;
    }

    /**
     * Determines if a JDBC connection pool is referred in a 
     * server-instance via resource-refs
     * 
     * @param jdbcPoolName
     * @return boolean true if pool is referred in this server instance, false 
     * otherwise
     * @throws ConfigException
     */
    public boolean isJdbcPoolReferredInServerInstance(String jdbcPoolName) 
                                        throws ConfigException {
        reinitialize();
        JdbcResource[] jdbcRes = res.getJdbcResource();
        
        for (int i = 0; i < jdbcRes.length; i++) {
            _logger.fine("poolname " + jdbcRes[i].getPoolName() 
                            + "resource " + jdbcRes[i].getJndiName() 
                            + " referred " + isReferenced(jdbcRes[i].getJndiName()));
            //Have to check isReferenced here!
            if ((jdbcRes[i].getPoolName().equalsIgnoreCase(jdbcPoolName)) 
                            && isReferenced(jdbcRes[i].getJndiName())){
                _logger.fine("JDBC resource "  + jdbcRes[i].getJndiName() + 
                            "refers " + jdbcPoolName + "in this server instance");
                return true;
            }
        }
        _logger.fine("No JDBC resource refers " + jdbcPoolName + 
                        "in this server instance");
        return false;
    }

    /**
     * Gets the list of applications deployed.
     * @param none
     * @return Application[] of deloyed applications. 
     */
    
    public Application[] getDeployedApplications() throws ConfigException{
        reinitialize();
        
        _logger.log(Level.FINE, "in ResourcesUtil.getApplicationNames()");
        
        // Get list of deployed "Applications" 
        Applications apps = dom.getApplications();
        // From Applications, get the J2ee Applications and ejb modules
        J2eeApplication[] j2ee_apps = apps.getJ2eeApplication();
        EjbModule[] ejb_modules = apps.getEjbModule();
        
        // This array would contain the deployment descriptors of all the
        // ejbmodules and aplications.
        ArrayList deployedAppsDescriptorList = new ArrayList();        
        
        if ((j2ee_apps.length + ejb_modules.length) == 0)
        	return (new Application[] {});
        
        // Get the respective Managers to retrieve Deployment descriptors
        AppsManager appsManager = getAppsManager();
        EjbModulesManager ejbModulesManager = getEjbModulesManager();

        // Get Deployment desc for J2EE apps. 
        for (int i=0; i<j2ee_apps.length; i++){
        	String appName = j2ee_apps[i].getName();
        	// Check if the application is referenced by the server instance on 
        	// which recovery is happening.  
        	if (!(ServerHelper.serverReferencesApplication(configContext_, sc_.getInstanceName(), appName) ))
        		continue; 
        	
        	try{
        	Application appDescriptor = 
        		appsManager.getAppDescriptor(appName,
                                            ASClassLoaderUtil.getSharedClassLoader());
        	deployedAppsDescriptorList.add(appDescriptor);
        	} catch (Exception e){
        		_logger.log(Level.WARNING, "Exception while getting " +
        				"Application DD from AppsManager" + e.getMessage()); 
        	}         
        }
        
        // Get deployment desc for EJB modules.
        for (int i=0; i<ejb_modules.length; i++){
        	String modName = ejb_modules[i].getName();
        	
        	if (!(ServerHelper.serverReferencesApplication(configContext_, sc_.getInstanceName(), modName) ))
        		continue; 
        	
        	try{
        	Application appDescriptor = 
        		ejbModulesManager.getDescriptor(modName,
                                                ASClassLoaderUtil.getSharedClassLoader());
        	deployedAppsDescriptorList.add(appDescriptor);
        	} catch (Exception e){
        		_logger.log(Level.WARNING, "Exception while getting " +
        				"Application DD from EjbModuleManager" + e.getMessage()); 
        	}
        }
        
        return (Application[])(deployedAppsDescriptorList.toArray(new Application[] {}));
        
        }
        
    public ConnectorDescriptor getConnectorDescriptorFromUri(String appName, String raLoc)
    throws ConfigException{
    	AppsManager am = getAppsManager();
        Application app = am.getAppDescriptor(appName,
                                               ASClassLoaderUtil.getSharedClassLoader());
        return app.getRarDescriptorByUri(raLoc);
    }
    
    
    private AppsManager getAppsManager() throws ConfigException{
    	InstanceEnvironment iEnv = sc_.getInstanceEnvironment();
    	return InstanceFactory.createAppsManager(iEnv, false);
    }
    
    private EjbModulesManager getEjbModulesManager() throws ConfigException{
    	InstanceEnvironment iEnv = sc_.getInstanceEnvironment();
    	return InstanceFactory.createEjbModuleManager(iEnv, false);
    }
    
    
    /**
     * Gets the deployment location for a J2EE application.
     * @param rarName
     * @return
     */
    public String getApplicationDeployLocation(String appName) {
        reinitialize();
        J2eeApplication app = dom.getApplications().getJ2eeApplicationByName(appName);
        return RelativePathResolver.resolvePath(app.getLocation());
    }

    protected Resources getResourcesServerBean() {
        return this.res;
    }
    

    /**
     * Checks if a resource reference is enabled
     * @since SJSAS 8.1 PE/SE/EE
     */
    private boolean isResourceReferenceEnabled(String resourceName) 
                        throws ConfigException {
        ResourceRef ref = ServerHelper.getServerByName( configContext_, 
                        sc_.getInstanceName()).getResourceRefByRef(resourceName);
        //@todo ref would be null only when call from deployers?
        if (ref == null) {
            _logger.fine("ResourcesUtil :: isResourceReferenceEnabled null ref");
            return true;
        }
        _logger.fine("ResourcesUtil :: isResourceReferenceEnabled ref enabled ?" + ref.isEnabled());
        return ref.isEnabled();
    }

    public boolean isEnabled(ConfigBean res) throws ConfigException{
        //If no config context use application server's server config context
        return isEnabled(ApplicationServer.getServerContext().getConfigContext(), res);
    }

    /**
     * Checks if a Resource is enabled.
     * 
     * Since 8.1 PE/SE/EE, A resource [except resource adapter configs, connector and 
     * JDBC connection pools which are global and hence enabled always] is enabled 
     * only when the resource is enabled and there exists a resource ref to this 
     * resource in this server instance and that resource ref is enabled.
     * 
     * Before a resource is loaded or deployed, it is checked to see if it is
     * enabled.
     * 
     * @since 8.1 PE/SE/EE
     */
    public boolean isEnabled(ConfigContext config, ConfigBean res) 
                throws ConfigException{
        _logger.fine("ResourcesUtil :: isEnabled");
        if (res instanceof ResourceAdapterConfig || 
                        res instanceof ConnectorConnectionPool || 
                        res instanceof JdbcConnectionPool) {
            boolean enabled = (res!=null && res.isEnabled());
            _logger.fine("ResourcesUtil :: isEnabled " + res + 
                            " is pool/config - enabled :" + enabled);
            return enabled;
        }
        
        Server server = ServerBeansFactory.getServerBean(config);
        //using ServerTags, otherwise have to resort to reflection or multiple instanceof/casts
        ResourceRef resRef = server.getResourceRefByRef(res.getAttributeValue(ServerTags.JNDI_NAME));

        boolean enabled = ((res != null && res.isEnabled()) && 
                    (resRef != null && resRef.isEnabled()));
        _logger.fine("ResourcesUtil :: isEnabled " + res + 
                        " is resource - enabled :" + enabled);
        return enabled;
    }

    
    public com.sun.enterprise.config.serverbeans.JdbcConnectionPool 
        getJdbcConnectionPoolByName( String poolName ) {
        reinitialize();
	return res.getJdbcConnectionPoolByName( poolName );
    }
     
    public com.sun.enterprise.config.serverbeans.ConnectorConnectionPool 
        getConnectorConnectionPoolByName( String poolName ) 
    {
        reinitialize();
	return res.getConnectorConnectionPoolByName( poolName );
    }
    
    public com.sun.enterprise.config.serverbeans.JdbcConnectionPool
           getJDBCPoolForResource(String resourceName) throws ConfigException {
        JdbcResource jr = res.getJdbcResourceByJndiName(resourceName);
        if (isEnabled(jr)) {
            return this.getJdbcConnectionPoolByName(jr.getPoolName());
        }
        return null;
    }

} 
