FileDocCategorySizeDatePackage
ActiveInboundResourceAdapter.javaAPI DocGlassfish v2 API24299Fri May 04 22:34:22 BST 2007com.sun.enterprise.connectors

ActiveInboundResourceAdapter

public class ActiveInboundResourceAdapter extends ActiveOutboundResourceAdapter
This class represents a live inbound resource adapter, i.e. A resource adapter is considered active after start() and before stop() is called.
author
Binod P G, Sivakumar Thyagarajan

Fields Summary
protected javax.resource.spi.ResourceAdapter
resourceadapter_
private Hashtable
factories_
protected String
moduleName_
static Logger
_logger
private com.sun.enterprise.util.i18n.StringManager
localStrings
private javax.resource.spi.BootstrapContext
bootStrapContextImpl
Constructors Summary
public ActiveInboundResourceAdapter(javax.resource.spi.ResourceAdapter ra, ConnectorDescriptor desc, String moduleName, ClassLoader jcl)
Creates an active inbound resource adapter. Sets all RA java bean properties and issues a start.

param
ra ResourceAdapter java bean.
param
desc ConnectorDescriptor object.
param
moduleName Resource adapter module name.
param
jcl ClassLoader instance.
throws
ConnectorRuntimeException If there is a failure in loading or starting the resource adapter.


                                                                   
     
                  
                
        super(desc,moduleName,jcl);
        this.resourceadapter_ = ra;
        this.factories_       = new Hashtable<String, MessageEndpointFactoryInfo>();
        this.moduleName_      = moduleName;
        try {
                loadRAConfiguration();
                ConnectorRegistry registry = ConnectorRegistry.getInstance();
                String poolId = null;
                ResourceAdapterConfig raConfig = 
                              registry.getResourceAdapterConfig(moduleName_);
                if (raConfig != null) {
                    poolId = raConfig.getThreadPoolIds();
                }
                this.bootStrapContextImpl = new BootstrapContextImpl(poolId);
                
                if (this.moduleName_.equals(ConnectorRuntime.DEFAULT_JMS_ADAPTER)) {
                    java.security.AccessController.doPrivileged
                        (new java.security.PrivilegedExceptionAction() {
                        public java.lang.Object run() throws
                                  ResourceAdapterInternalException {
                            resourceadapter_.start(bootStrapContextImpl);
                            return null;
                        }
                    });
                } else {
                    resourceadapter_.start(bootStrapContextImpl);
                }

                setupMonitoring();
                
        } catch(ResourceAdapterInternalException ex) {
                _logger.log(Level.SEVERE,"rardeployment.start_failed",ex);
            String i18nMsg = localStrings.getString(
                "rardeployment.start_failed", ex.getMessage());
                ConnectorRuntimeException cre = 
                    new ConnectorRuntimeException( i18nMsg );
                cre.initCause( ex );	    
                throw cre;
        } catch(PrivilegedActionException pex) {
                _logger.log(Level.SEVERE,"rardeployment.start_failed",pex.getException());
            String i18nMsg = localStrings.getString(
                "rardeployment.start_failed", pex.getException().getMessage());
                ConnectorRuntimeException cre = 
                    new ConnectorRuntimeException( i18nMsg );
                cre.initCause( pex.getException() );	    
                throw cre;
        } catch (Throwable t) {
            _logger.log(Level.SEVERE,"rardeployment.start_failed",t);
	    t.printStackTrace(); 
            String i18nMsg = localStrings.getString(
                "rardeployment.start_failed", t.getMessage() );
        		ConnectorRuntimeException cre = 
        		    new ConnectorRuntimeException( i18nMsg );
	     if (t.getCause() != null) {	
		/* Put the correct cause of the exception
 	 	 * Fixes issue : 6543333
		 */
       	        cre.initCause( t.getCause());	    
  	     } else {
		cre.initCause(t);
	     } 
       	     throw cre;
        }
    
Methods Summary
public voidaddAdminObject(java.lang.String appName, java.lang.String connectorName, java.lang.String jndiName, java.lang.String adminObjectType, java.util.Properties props)
Creates an admin object.

param
appName Name of application, in case of embedded rar.
param
connectorName Module name of the resource adapter.
param
jndiName JNDI name to be registered.
param
adminObjectType Interface name of the admin object.
param
props Properties object containing name/value pairs of properties.

        if (props == null) {
            // empty properties
            props = new Properties();
        }

        ConnectorRegistry registry = null;
        try{
            registry = ConnectorRegistry.getInstance();
        }catch(Exception e) {
        }
        ConnectorDescriptor desc = registry.getDescriptor(connectorName);
        AdminObject aoDesc =
            desc.getAdminObjectByType(adminObjectType);

        AdministeredObjectResource aor = new AdministeredObjectResource(
                                                 jndiName);
        aor.initialize(aoDesc);
        aor.setResourceAdapter(connectorName);

        Object[] envProps = aoDesc.getConfigProperties().toArray();
        
        //Add default config properties to aor
        //Override them if same config properties are provided by the user 
        for (int i = 0; i < envProps.length; i++) {
            EnvironmentProperty envProp = (EnvironmentProperty) envProps[i];
            String name = envProp.getName();
            String userValue = (String)props.remove(name);
            if (userValue != null)    
                aor.addConfigProperty(new EnvironmentProperty(
                              name, userValue, userValue, envProp.getType()));
            else
                aor.addConfigProperty(envProp);
        }
        
        //Add non-default config properties provided by the user to aor
        Iterator iter = props.keySet().iterator();
        while(iter.hasNext()){
            String name = (String) iter.next();
            String userValue = props.getProperty(name);
            if(userValue != null)
                aor.addConfigProperty(new EnvironmentProperty(
                        name, userValue, userValue));
            
        }

        // bind to JNDI namespace
	try{

            Reference ref = aor.createAdminObjectReference();
            NamingManager nm = Switch.getSwitch().getNamingManager();
            nm.publishObject(jndiName, ref, true);

        } catch (NamingException ex) {
	    String i18nMsg = localStrings.getString(
	        "aira.cannot_bind_admin_obj");
            throw new ConnectorRuntimeException( i18nMsg );
        }
    
public voidaddEndpointFactoryInfo(java.lang.String id, com.sun.enterprise.connectors.inflow.MessageEndpointFactoryInfo info)
Adds endpoint factory information.

param
id Unique identifier of the endpoint factory.
param
info MessageEndpointFactoryInfo object.

        factories_.put(id, info);
    
public javax.resource.spi.ManagedConnectionFactorycreateManagedConnectionFactory(ConnectorConnectionPool pool, java.lang.ClassLoader jcl)
Creates an instance of ManagedConnectionFactory object using the connection pool properties. Also set the ResourceAdapterAssociation

param
pool ConnectorConnectionPool properties.
param
jcl ClassLoader

        ManagedConnectionFactory mcf = null;
        mcf = super.createManagedConnectionFactory(pool,jcl);

        if (mcf instanceof ResourceAdapterAssociation) {
           try{
               ((ResourceAdapterAssociation) mcf).setResourceAdapter(
                           this.resourceadapter_);
           }catch(ResourceException ex) {
               _logger.log(Level.SEVERE,"rardeployment.assoc_failed",ex);
           }
        }

        return mcf;
    
public voiddestroy()
Destroys default pools and resources. Stops the Resource adapter java bean.

        if(isServer() && (connectionDefs_ != null) && 
                             (connectionDefs_.length != 0)) {
            destroyAllConnectorResources();
            //deactivateEndpoints as well!
            Iterator<MessageEndpointFactoryInfo> iter = getAllEndpointFactories().iterator();
            while (iter.hasNext()) {
                MessageEndpointFactoryInfo element = iter.next(); 
                try {
                    this.resourceadapter_.endpointDeactivation(
                        element.getEndpointFactory(),element.getActivationSpec());
                } catch (RuntimeException e) {
                    _logger.warning(e.getMessage());
                    _logger.log(Level.FINE, "Error during endpointDeactivation ", e);
                }
            }
        }
    	try {
            _logger.fine("Calling Resource Adapter stop" + 
                            this.getModuleName());
            resourceadapter_.stop();
            _logger.fine("Resource Adapter stop call of " + 
                            this.getModuleName() + "returned successfully");
            _logger.log(Level.FINE, "rar_stop_call_successful");
    	} catch (Throwable t) {
               _logger.log(Level.SEVERE,"rardeployment.stop_warning",t);
    	}
    
public java.util.CollectiongetAllEndpointFactories()
Retrieves the information about all endpoint factories.

return
a Collection of MessageEndpointFactory objects.

        return factories_.values();
    
public java.util.SetgetAllEndpointFactoryInfo()

        Hashtable infos = (Hashtable<String, MessageEndpointFactoryInfo>) factories_.clone();
        return infos.entrySet();
    
public javax.resource.spi.BootstrapContextgetBootStrapContext()

        return this.bootStrapContextImpl;
    
public com.sun.enterprise.connectors.inflow.MessageEndpointFactoryInfogetEndpointFactoryInfo(java.lang.String id)
Returns information about endpoint factory.

param
id Id of the endpoint factory.
return
MessageEndpointFactoryIndo object.

        return factories_.get(id);
    
public javax.resource.spi.ResourceAdaptergetResourceAdapter()
Retrieves the resource adapter java bean.

return
ResourceAdapter

        return this.resourceadapter_;
    
private com.sun.enterprise.admin.monitor.registry.MonitoringLevelgetWorkStatsMonitoringLevel()

        Config cfg = null;
        MonitoringLevel off = MonitoringLevel.OFF;
        MonitoringLevel l = null;
        try {
            cfg = ServerBeansFactory.getConfigBean(
                            ApplicationServer.getServerContext().getConfigContext());
            String lvl = null;
            lvl  = cfg.getMonitoringService().getModuleMonitoringLevels().getConnectorService();
            l = MonitoringLevel.instance( lvl );
            if (l == null ) {
                //dont bother to throw an exception
                return off;
            }
            return l;
        } catch (Exception e) {
            return off;
        }
    
private voidhackMergedProps(java.util.Set mergedProps)
This is a HACK to remove the connection URL in the case of PE LOCAL/EMBEDDED before setting the properties to the RA. If this was not done, MQ RA incorrectly assumed that the passed in connection URL is one additional URL, apart from the default URL derived from brokerhost:brokerport and reported a PE connection url limitation.


        String brokerType = null;

        for (Iterator iter = mergedProps.iterator(); iter.hasNext();) {
            EnvironmentProperty element = (EnvironmentProperty) iter.next();
            if (element.getName().equals(ActiveJmsResourceAdapter.BROKERTYPE)) {
                     brokerType = element.getValue();
            }
        }
	boolean cluster = false;
	try {
		cluster = JmsRaUtil.isClustered();
	} catch (Exception e) {
		e.printStackTrace();
	}
	// hack is required only for nonclustered nonremote brokers.
	if (!cluster) {
        if (brokerType.equals(ActiveJmsResourceAdapter.LOCAL)
                || brokerType.equals(ActiveJmsResourceAdapter.EMBEDDED)
		|| brokerType.equals(ActiveJmsResourceAdapter.DIRECT)) 
        {              
		for (Iterator iter = mergedProps.iterator(); iter.hasNext();) {
                EnvironmentProperty element = (EnvironmentProperty) iter.next();
                if (element.getName().equals(ActiveJmsResourceAdapter.CONNECTION_URL)) {
                    iter.remove();
                }
          }
    	}
	}
    
protected voidloadRAConfiguration()
Loads RA javabean. This method is protected, so that any system resource adapter can have specific configuration done during the loading.

throws
ConnectorRuntimeException if there is a failure.

	try {
            ElementProperty[] raConfigProps = null;
            Set mergedProps = null;
            ConnectorRegistry registry = ConnectorRegistry.getInstance();
            ResourceAdapterConfig raConfig = 
                    registry.getResourceAdapterConfig(moduleName_);
            if(raConfig != null) {
                raConfigProps = raConfig.getElementProperty();
            }
            if(raConfigProps != null) {
                mergedProps = ConnectorDDTransformUtils.mergeProps(
                        raConfigProps,getDescriptor().getConfigProperties());
            } else {
                mergedProps = ConnectorDDTransformUtils.mergeProps(
                                  new ElementProperty[]{},
                                  getDescriptor().getConfigProperties());
            }

            //HACK !
            if (this.moduleName_.equals(ConnectorRuntime.DEFAULT_JMS_ADAPTER)) {
                    if (ConnectorRuntime.getRuntime().isServer()) {
                        hackMergedProps(mergedProps);
                    }
            }
            logMergedProperties(mergedProps);
            SetMethodAction setMethodAction = new SetMethodAction
                                (this.resourceadapter_, mergedProps);
            setMethodAction.run();
        } catch(Exception e) {
            String i18nMsg = localStrings.getString(
                "ccp_adm.wrong_params_for_create", e.getMessage() );
            ConnectorRuntimeException cre =
                new ConnectorRuntimeException( i18nMsg );
            cre.initCause( e );
            throw cre;
        }
    
private voidlogMergedProperties(java.util.Set mergedProps)

			_logger.fine("Passing in the following properties " +
					"before calling RA.start of " + this.moduleName_);
            StringBuffer b = new StringBuffer();
            
			for (Iterator iter = mergedProps.iterator(); iter.hasNext();) {
				EnvironmentProperty element = (EnvironmentProperty) iter.next();
                b.append( "\nName: " + element.getName() 
						+ " Value: " + element.getValue() );
			}
            _logger.fine(b.toString());
	
private voidobtainServerXMLvalue()


    
private voidregisterWorkStats()

        if (getWorkStatsMonitoringLevel() != MonitoringLevel.OFF) {
            
            ((MonitorableWorkManager)this.getBootStrapContext().getWorkManager())
                                                .setMonitoringEnabled(true);
            
            AccessController.doPrivileged( new PrivilegedAction() {
                public Object run() {
                    try {
                        
                        ServerContext ctxt = ApplicationServer.getServerContext();
                        MonitoringRegistry monRegistry = ctxt.getMonitoringRegistry();
                        String moduleName = ActiveInboundResourceAdapter.this.getModuleName();
                        //@todo :: after MBeans are modified
                        //Dont register system RARs as of now until MBean changes are complete.
                        if (ResourcesUtil.createInstance().belongToSystemRar(moduleName)) {
                            if (!ConnectorAdminServiceUtils.isJMSRA(moduleName)) {
                                return null;
                            }
                        }
                        
                        ConnectorWorkMgmtStatsImpl workstatsimpl =
                            new ConnectorWorkMgmtStatsImpl(ActiveInboundResourceAdapter.this);
                        monRegistry.registerConnectorWorkMgmtStats(
                                   workstatsimpl, 
                                   ConnectorAdminServiceUtils.getApplicationName(moduleName),
                                   ConnectorAdminServiceUtils.getConnectorModuleName(moduleName),
                                   ConnectorAdminServiceUtils.isJMSRA(moduleName),
                                   null);
                    } catch( Exception mre ) {
                        _logger.log( Level.INFO, "poolmon.cannot_reg",
                        mre.getMessage() );
                    }
                
                return null;
                }
            });
            if ( _logger.isLoggable( Level.FINE ) ) {
                _logger.fine("Enabled work monitoring at IBRA creation for "
                                + this.getModuleName());
            }
        }
    
public voidremoveEndpointFactoryInfo(java.lang.String id)
Removes information about an endpoint factory

param
id Unique identifier of the endpoint factory to be removed.

        factories_.remove(id);
    
public voidsetup()
Does the necessary initial setup. Creates the default pool and resource.

throws
ConnectorRuntimeException If there is a failure

        if(connectionDefs_ == null || connectionDefs_.length == 0) {
            return;
        }
        obtainServerXMLvalue();
        ResourcesUtil resUtil = ResourcesUtil.createInstance();

        if(isServer() && !resUtil.belongToSystemRar(moduleName_)) {
            createAllConnectorResources();
        }
    
private voidsetupMonitoring()

        //if monitoring enabled - register workstatsimpl for
        //this inbound resource adapter and endpointfactory stats
        //for inbound-resource-adapter&message-listener-type
        registerWorkStats();
    
private voidunRegisterWorkStats()

        if ( getWorkStatsMonitoringLevel() != MonitoringLevel.OFF ) {
            AccessController.doPrivileged( new PrivilegedAction() {
                public Object run() {
                    try {
                        ServerContext ctxt = ApplicationServer.getServerContext();
                        MonitoringRegistry monRegistry = ctxt.getMonitoringRegistry();
                        String moduleName = ActiveInboundResourceAdapter.this.getModuleName();
                        monRegistry.unregisterConnectorWorkMgmtStats(
                                        ConnectorAdminServiceUtils.getApplicationName(moduleName), 
                                        ConnectorAdminServiceUtils.getConnectorModuleName(moduleName),
                                        ConnectorAdminServiceUtils.isJMSRA(moduleName));
                    } catch( Exception mre) {
                       _logger.log( Level.INFO, "poolmon.cannot_unreg", 
                           mre.getMessage() );
                    }
                    return null;
                }
            });
       }
    
private voidunSetupMonitoring()

        //if monitoring enabled - register workstatsimpl for
        //this inbound resource adapter and endpointfactory stats
        //for inbound-resource-adapter&message-listener-type
        unRegisterWorkStats();
    
private voidwritePoolResourceToServerXML()