KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > connectors > ActiveInboundResourceAdapter


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

23
24 package com.sun.enterprise.connectors;
25
26 import com.sun.enterprise.deployment.*;
27 import com.sun.enterprise.admin.monitor.registry.MonitoringLevel;
28 import com.sun.enterprise.connectors.system.ActiveJmsResourceAdapter;
29 import com.sun.enterprise.connectors.util.*;
30 import com.sun.enterprise.connectors.work.monitor.ConnectorWorkMgmtStatsImpl;
31 import com.sun.enterprise.connectors.work.monitor.MonitorableWorkManager;
32 import com.sun.enterprise.NamingManager;
33 import com.sun.enterprise.Switch;
34 import com.sun.enterprise.connectors.inflow.MessageEndpointFactoryInfo;
35 import com.sun.enterprise.config.serverbeans.*;
36 import com.sun.enterprise.server.*;
37 import com.sun.enterprise.util.i18n.StringManager;
38 import com.sun.logging.LogDomains;
39
40 import java.security.AccessController JavaDoc;
41 import java.security.PrivilegedAction JavaDoc;
42 import java.security.PrivilegedActionException JavaDoc;
43 import java.util.Collection JavaDoc;
44 import java.util.Hashtable JavaDoc;
45 import java.util.Set JavaDoc;
46 import java.util.Properties JavaDoc;
47 import java.util.Iterator JavaDoc;
48 import java.util.logging.*;
49
50 import javax.resource.spi.ResourceAdapter JavaDoc;
51 import javax.resource.spi.BootstrapContext JavaDoc;
52 import javax.resource.spi.ManagedConnectionFactory JavaDoc;
53 import javax.resource.spi.ResourceAdapterAssociation JavaDoc;
54 import javax.resource.spi.ResourceAdapterInternalException JavaDoc;
55 import javax.naming.Reference JavaDoc;
56 import javax.naming.NamingException JavaDoc;
57 import javax.resource.ResourceException JavaDoc;
58
59 import com.sun.enterprise.admin.monitor.registry.MonitoringRegistry;
60
61 /**
62  * This class represents a live inbound resource adapter, i.e.
63
64  * A resource adapter is considered active after start()
65  * and before stop() is called.
66  *
67  * @author Binod P G, Sivakumar Thyagarajan
68  */

69
70 public class ActiveInboundResourceAdapter extends
71                                 ActiveOutboundResourceAdapter {
72     
73     protected ResourceAdapter resourceadapter_; //runtime instance
74

75     //beanID -> endpoint factory and its activation spec
76
private Hashtable JavaDoc factories_;
77
78     protected String JavaDoc moduleName_;
79     static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
80
81     private StringManager localStrings =
82         StringManager.getManager( ActiveInboundResourceAdapter.class );
83
84     private BootstrapContext JavaDoc bootStrapContextImpl;
85
86     /**
87      * Creates an active inbound resource adapter. Sets all RA java bean
88      * properties and issues a start.
89      *
90      * @param ra <code>ResourceAdapter<code> java bean.
91      * @param desc <code>ConnectorDescriptor</code> object.
92      * @param moduleName Resource adapter module name.
93      * @param jcl <code>ClassLoader</code> instance.
94      * @throws ConnectorRuntimeException If there is a failure in loading
95      * or starting the resource adapter.
96      */

97     public ActiveInboundResourceAdapter(
98             ResourceAdapter ra, ConnectorDescriptor desc, String JavaDoc moduleName,
99             ClassLoader JavaDoc jcl) throws ConnectorRuntimeException {
100         super(desc,moduleName,jcl,false);
101         this.resourceadapter_ = ra;
102         this.factories_ = new Hashtable JavaDoc();
103         this.moduleName_ = moduleName;
104         try {
105                 loadRAConfiguration();
106                 ConnectorRegistry registry = ConnectorRegistry.getInstance();
107                 String JavaDoc poolId = null;
108                 ResourceAdapterConfig raConfig =
109                               registry.getResourceAdapterConfig(moduleName_);
110                 if (raConfig != null) {
111                     poolId = raConfig.getThreadPoolIds();
112                 }
113                 this.bootStrapContextImpl = new BootstrapContextImpl(poolId);
114                 
115                 if (this.moduleName_.equals(ConnectorRuntime.DEFAULT_JMS_ADAPTER)) {
116                     java.security.AccessController.doPrivileged
117                         (new java.security.PrivilegedExceptionAction JavaDoc() {
118                         public java.lang.Object JavaDoc run() throws
119                                   ResourceAdapterInternalException JavaDoc {
120                             resourceadapter_.start(bootStrapContextImpl);
121                             return null;
122                         }
123                     });
124                 } else {
125                     resourceadapter_.start(bootStrapContextImpl);
126                 }
127
128                 setupMonitoring();
129                 
130         } catch(ResourceAdapterInternalException JavaDoc ex) {
131                 _logger.log(Level.SEVERE,"rardeployment.start_failed",ex);
132             String JavaDoc i18nMsg = localStrings.getString(
133                 "rardeployment.start_failed", ex.getMessage());
134                 ConnectorRuntimeException cre =
135                     new ConnectorRuntimeException( i18nMsg );
136                 cre.initCause( ex );
137                 throw cre;
138         } catch(PrivilegedActionException JavaDoc pex) {
139                 _logger.log(Level.SEVERE,"rardeployment.start_failed",pex.getException());
140             String JavaDoc i18nMsg = localStrings.getString(
141                 "rardeployment.start_failed", pex.getException().getMessage());
142                 ConnectorRuntimeException cre =
143                     new ConnectorRuntimeException( i18nMsg );
144                 cre.initCause( pex.getException() );
145                 throw cre;
146         } catch (Throwable JavaDoc t) {
147                 _logger.log(Level.SEVERE,"rardeployment.start_failed",t);
148             String JavaDoc i18nMsg = localStrings.getString(
149                 "rardeployment.start_failed", t.getMessage() );
150                 ConnectorRuntimeException cre =
151                     new ConnectorRuntimeException( i18nMsg );
152                     cre.initCause( t );
153                 throw cre;
154         }
155     }
156
157     private void setupMonitoring() {
158         //if monitoring enabled - register workstatsimpl for
159
//this inbound resource adapter and endpointfactory stats
160
//for inbound-resource-adapter&message-listener-type
161
registerWorkStats();
162     }
163
164     private void unSetupMonitoring() {
165         //if monitoring enabled - register workstatsimpl for
166
//this inbound resource adapter and endpointfactory stats
167
//for inbound-resource-adapter&message-listener-type
168
unRegisterWorkStats();
169     }
170     
171
172
173     private void unRegisterWorkStats() {
174         if ( getWorkStatsMonitoringLevel() != MonitoringLevel.OFF ) {
175             AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
176                 public Object JavaDoc run() {
177                     try {
178                         ServerContext ctxt = ApplicationServer.getServerContext();
179                         MonitoringRegistry monRegistry = ctxt.getMonitoringRegistry();
180                         String JavaDoc moduleName = ActiveInboundResourceAdapter.this.getModuleName();
181                         monRegistry.unregisterConnectorWorkMgmtStats(
182                                         ConnectorAdminServiceUtils.getApplicationName(moduleName),
183                                         ConnectorAdminServiceUtils.getConnectorModuleName(moduleName),
184                                         ConnectorAdminServiceUtils.isJMSRA(moduleName));
185                     } catch( Exception JavaDoc mre) {
186                        _logger.log( Level.INFO, "poolmon.cannot_unreg",
187                            mre.getMessage() );
188                     }
189                     return null;
190                 }
191             });
192        }
193     }
194
195     private void registerWorkStats() {
196         if (getWorkStatsMonitoringLevel() != MonitoringLevel.OFF) {
197             
198             final ConnectorWorkMgmtStatsImpl workStatsImpl
199                             = new ConnectorWorkMgmtStatsImpl(this);
200
201             ((MonitorableWorkManager)this.getBootStrapContext().getWorkManager())
202                                                 .setMonitoringEnabled(true);
203             
204             AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
205                 public Object JavaDoc run() {
206                     try {
207                         
208                         ServerContext ctxt = ApplicationServer.getServerContext();
209                         MonitoringRegistry monRegistry = ctxt.getMonitoringRegistry();
210                         String JavaDoc moduleName = ActiveInboundResourceAdapter.this.getModuleName();
211                         //@todo :: after MBeans are modified
212
//Dont register system RARs as of now until MBean changes are complete.
213
if (ResourcesUtil.getInstance().belongToSystemRar(moduleName)) {
214                             if (!ConnectorAdminServiceUtils.isJMSRA(moduleName)) {
215                                 return null;
216                             }
217                         }
218                         
219                         ConnectorWorkMgmtStatsImpl workstatsimpl =
220                             new ConnectorWorkMgmtStatsImpl(ActiveInboundResourceAdapter.this);
221                         monRegistry.registerConnectorWorkMgmtStats(
222                                    workstatsimpl,
223                                    ConnectorAdminServiceUtils.getApplicationName(moduleName),
224                                    ConnectorAdminServiceUtils.getConnectorModuleName(moduleName),
225                                    ConnectorAdminServiceUtils.isJMSRA(moduleName),
226                                    null);
227                     } catch( Exception JavaDoc mre ) {
228                         _logger.log( Level.INFO, "poolmon.cannot_reg",
229                         mre.getMessage() );
230                     }
231                 
232                 return null;
233                 }
234             });
235             if ( _logger.isLoggable( Level.FINE ) ) {
236                 _logger.fine("Enabled work monitoring at IBRA creation for "
237                                 + this.getModuleName());
238             }
239         }
240     }
241
242     /*
243      * Gets the current monitoring level for Jdbc pools
244      */

245     private MonitoringLevel getWorkStatsMonitoringLevel() {
246         Config cfg = null;
247         MonitoringLevel off = MonitoringLevel.OFF;
248         MonitoringLevel l = null;
249         try {
250             cfg = ServerBeansFactory.getConfigBean(
251                             ApplicationServer.getServerContext().getConfigContext());
252             String JavaDoc lvl = null;
253             lvl = cfg.getMonitoringService().getModuleMonitoringLevels().getConnectorService();
254             l = MonitoringLevel.instance( lvl );
255             if (l == null ) {
256                 //dont bother to throw an exception
257
return off;
258             }
259             return l;
260         } catch (Exception JavaDoc e) {
261             return off;
262         }
263     }
264     
265
266     /**
267      * Retrieves the resource adapter java bean.
268      *
269      * @return <code>ResourceAdapter</code>
270      */

271     public ResourceAdapter getResourceAdapter() {
272         return this.resourceadapter_;
273     }
274
275     /**
276      * Does the necessary initial setup. Creates the default pool and
277      * resource.
278      *
279      * @throws ConnectorRuntimeException If there is a failure
280      */

281     public void setup() throws ConnectorRuntimeException {
282         if(connectionDefs_ == null || connectionDefs_.length == 0) {
283             return;
284         }
285         obtainServerXMLvalue();
286         ResourcesUtil resUtil = ResourcesUtil.getInstance();
287
288         if(isServer() && !resUtil.belongToSystemRar(moduleName_)) {
289             createAllConnectorResources();
290         }
291     }
292
293     private void obtainServerXMLvalue(){
294
295     }
296
297     /**
298      * Destroys default pools and resources. Stops the Resource adapter
299      * java bean.
300      */

301     public void destroy() {
302         if(isServer() && (connectionDefs_ != null) &&
303                              (connectionDefs_.length != 0)) {
304             destroyAllConnectorResources();
305             //deactivateEndpoints as well!
306
Iterator JavaDoc iter = getAllEndpointFactoryInfo().iterator();
307             while (iter.hasNext()) {
308                 MessageEndpointFactoryInfo element =
309                     (MessageEndpointFactoryInfo) iter.next();
310                 try {
311                     this.resourceadapter_.endpointDeactivation(
312                         element.getEndpointFactory(),element.getActivationSpec());
313                 } catch (RuntimeException JavaDoc e) {
314                     _logger.warning(e.getMessage());
315                     _logger.log(Level.FINE, "Error during endpointDeactivation ", e);
316                 }
317             }
318         }
319         try {
320             _logger.fine("Calling Resource Adapter stop" +
321                             this.getModuleName());
322             resourceadapter_.stop();
323             _logger.fine("Resource Adapter stop call of " +
324                             this.getModuleName() + "returned successfully");
325             _logger.log(Level.FINE, "rar_stop_call_successful");
326         } catch (Throwable JavaDoc t) {
327                _logger.log(Level.SEVERE,"rardeployment.stop_warning",t);
328         }
329     }
330
331     /**
332      * Creates an instance of <code>ManagedConnectionFactory</code>
333      * object using the connection pool properties. Also set the
334      * <code>ResourceAdapterAssociation</code>
335      *
336      * @param pool <code>ConnectorConnectionPool</code> properties.
337      * @param jcl <code>ClassLoader</code>
338      */

339     public ManagedConnectionFactory JavaDoc createManagedConnectionFactory (
340                     ConnectorConnectionPool pool, ClassLoader JavaDoc jcl) {
341         ManagedConnectionFactory JavaDoc mcf = null;
342         mcf = super.createManagedConnectionFactory(pool,jcl);
343
344         if (mcf instanceof ResourceAdapterAssociation JavaDoc) {
345            try{
346                ((ResourceAdapterAssociation JavaDoc) mcf).setResourceAdapter(
347                            this.resourceadapter_);
348            }catch(ResourceException JavaDoc ex) {
349                _logger.log(Level.SEVERE,"rardeployment.assoc_failed",ex);
350            }
351         }
352
353         return mcf;
354     }
355
356     private void writePoolResourceToServerXML() {
357     }
358
359     /**
360      * Returns information about endpoint factory.
361      *
362      * @param id Id of the endpoint factory.
363      * @return <code>MessageEndpointFactoryIndo</code> object.
364      */

365     public MessageEndpointFactoryInfo getEndpointFactoryInfo(String JavaDoc id) {
366         return (MessageEndpointFactoryInfo) factories_.get(id);
367     }
368
369     /*
370      * @return A set of Map.Entry that has the bean ID as the key
371      * and the MessageEndpointFactoryInfo as value
372      * A shallow copy only to avoid concurrency issues.
373      */

374     public Set JavaDoc getAllEndpointFactoryInfo() {
375         Hashtable JavaDoc infos = (Hashtable JavaDoc) factories_.clone();
376         return infos.entrySet();
377     }
378
379     /**
380      * Adds endpoint factory information.
381      *
382      * @param id Unique identifier of the endpoint factory.
383      * @param info <code>MessageEndpointFactoryInfo</code> object.
384      */

385     public void addEndpointFactoryInfo(
386         String JavaDoc id, MessageEndpointFactoryInfo info) {
387         factories_.put(id, info);
388     }
389
390     /**
391      * Removes information about an endpoint factory
392      *
393      * @param id Unique identifier of the endpoint factory to be
394      * removed.
395      */

396     public void removeEndpointFactoryInfo(String JavaDoc id) {
397         factories_.remove(id);
398     }
399
400     /**
401      * Retrieves the information about all endpoint factories.
402      *
403      * @return a <code>Collection</code> of <code>MessageEndpointFactory</code>
404      * objects.
405      */

406     public Collection JavaDoc getAllEndpointFactories() {
407         return factories_.values();
408     }
409
410     /**
411      * Creates an admin object.
412      *
413      * @param appName Name of application, in case of embedded rar.
414      * @param connectorName Module name of the resource adapter.
415      * @param jndiName JNDI name to be registered.
416      * @param adminObjectType Interface name of the admin object.
417      * @param props <code>Properties</code> object containing name/value
418      * pairs of properties.
419      */

420     public void addAdminObject (
421             String JavaDoc appName,
422             String JavaDoc connectorName,
423             String JavaDoc jndiName,
424             String JavaDoc adminObjectType,
425             Properties JavaDoc props)
426         throws ConnectorRuntimeException {
427         if (props == null) {
428             // empty properties
429
props = new Properties JavaDoc();
430         }
431
432         ConnectorRegistry registry = null;
433         try{
434             registry = ConnectorRegistry.getInstance();
435         }catch(Exception JavaDoc e) {
436         }
437         ConnectorDescriptor desc = registry.getDescriptor(connectorName);
438         AdminObject aoDesc =
439             desc.getAdminObjectByType(adminObjectType);
440
441         AdministeredObjectResource aor = new AdministeredObjectResource(
442                                                  jndiName);
443         aor.initialize(aoDesc);
444         aor.setResourceAdapter(connectorName);
445
446         Object JavaDoc[] envProps = aoDesc.getConfigProperties().toArray();
447         
448         //Add default config properties to aor
449
//Override them if same config properties are provided by the user
450
for (int i = 0; i < envProps.length; i++) {
451             EnvironmentProperty envProp = (EnvironmentProperty) envProps[i];
452             String JavaDoc name = envProp.getName();
453             String JavaDoc userValue = (String JavaDoc)props.remove(name);
454             if (userValue != null)
455                 aor.addConfigProperty(new EnvironmentProperty(
456                               name, userValue, userValue, envProp.getType()));
457             else
458                 aor.addConfigProperty(envProp);
459         }
460         
461         //Add non-default config properties provided by the user to aor
462
Iterator JavaDoc iter = props.keySet().iterator();
463         while(iter.hasNext()){
464             String JavaDoc name = (String JavaDoc) iter.next();
465             String JavaDoc userValue = props.getProperty(name);
466             if(userValue != null)
467                 aor.addConfigProperty(new EnvironmentProperty(
468                         name, userValue, userValue));
469             
470         }
471
472         // bind to JNDI namespace
473
try{
474
475             Reference JavaDoc ref = aor.createAdminObjectReference();
476             NamingManager nm = Switch.getSwitch().getNamingManager();
477             nm.publishObject(jndiName, ref, true);
478
479         } catch (NamingException JavaDoc ex) {
480         String JavaDoc i18nMsg = localStrings.getString(
481             "aira.cannot_bind_admin_obj");
482             throw new ConnectorRuntimeException( i18nMsg );
483         }
484     }
485
486     /**
487      * Loads RA javabean. This method is protected, so that any system
488      * resource adapter can have specific configuration done during the
489      * loading.
490      *
491      * @throws ConnectorRuntimeException if there is a failure.
492      */

493     protected void loadRAConfiguration() throws ConnectorRuntimeException {
494     try {
495             ElementProperty[] raConfigProps = null;
496             Set JavaDoc mergedProps = null;
497             ConnectorRegistry registry = ConnectorRegistry.getInstance();
498             ResourceAdapterConfig raConfig =
499                     registry.getResourceAdapterConfig(moduleName_);
500             if(raConfig != null) {
501                 raConfigProps = raConfig.getElementProperty();
502             }
503             if(raConfigProps != null) {
504                 mergedProps = ConnectorDDTransformUtils.mergeProps(
505                         raConfigProps,getDescriptor().getConfigProperties());
506             } else {
507                 mergedProps = ConnectorDDTransformUtils.mergeProps(
508                                   new ElementProperty[]{},
509                                   getDescriptor().getConfigProperties());
510             }
511             
512             //HACK !
513
if (this.moduleName_.equals(ConnectorRuntime.DEFAULT_JMS_ADAPTER)) {
514             if (ConnectorRuntime.getRuntime().isServer()) {
515                         hackMergedProps(mergedProps);
516             }
517             }
518             
519             logMergedProperties(mergedProps);
520             SetMethodAction setMethodAction = new SetMethodAction
521                                 (this.resourceadapter_, mergedProps);
522             setMethodAction.run();
523     } catch(Exception JavaDoc e) {
524         String JavaDoc i18nMsg = localStrings.getString(
525             "ccp_adm.wrong_params_for_create", e.getMessage() );
526         ConnectorRuntimeException cre =
527                 new ConnectorRuntimeException( i18nMsg );
528             cre.initCause( e );
529         throw cre;
530     }
531
532     }
533
534     /**
535      * This is a HACK to remove the connection URL
536      * in the case of PE LOCAL/EMBEDDED before setting the properties
537      * to the RA. If this was not done, MQ RA incorrectly assumed
538      * that the passed in connection URL is one additional
539      * URL, apart from the default URL derived from brokerhost:brokerport
540      * and reported a PE connection url limitation.
541      *
542      */

543     private void hackMergedProps(Set JavaDoc mergedProps) {
544         
545         String JavaDoc brokerType = null;
546         
547         for (Iterator JavaDoc iter = mergedProps.iterator(); iter.hasNext();) {
548             EnvironmentProperty element = (EnvironmentProperty) iter.next();
549             if (element.getName().equals(ActiveJmsResourceAdapter.BROKERTYPE)) {
550                      brokerType = element.getValue();
551             }
552         }
553         
554         if (brokerType.equals(ActiveJmsResourceAdapter.LOCAL)
555                 || brokerType.equals(ActiveJmsResourceAdapter.EMBEDDED)) {
556               for (Iterator JavaDoc iter = mergedProps.iterator(); iter.hasNext();) {
557                 EnvironmentProperty element = (EnvironmentProperty) iter.next();
558                 if (element.getName().equals(ActiveJmsResourceAdapter.CONNECTION_URL)) {
559                     iter.remove();
560                 }
561              }
562         }
563     }
564     
565
566     private void logMergedProperties(Set JavaDoc mergedProps) {
567             _logger.fine("Passing in the following properties " +
568                     "before calling RA.start of " + this.moduleName_);
569             StringBuffer JavaDoc b = new StringBuffer JavaDoc();
570             
571             for (Iterator JavaDoc iter = mergedProps.iterator(); iter.hasNext();) {
572                 EnvironmentProperty element = (EnvironmentProperty) iter.next();
573                 b.append( "\nName: " + element.getName()
574                         + " Value: " + element.getValue() );
575             }
576             _logger.fine(b.toString());
577     }
578
579     public BootstrapContext JavaDoc getBootStrapContext(){
580         return this.bootStrapContextImpl;
581     }
582
583 }
584
Popular Tags