KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > resource > PoolManagerImpl


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 package com.sun.enterprise.resource;
24
25 import java.util.*;
26 import java.util.concurrent.ConcurrentHashMap JavaDoc;
27 import java.util.logging.*;
28 import java.security.AccessController JavaDoc;
29 import java.security.PrivilegedAction JavaDoc;
30 import java.sql.DriverManager JavaDoc;
31 import java.sql.SQLException JavaDoc;
32 import javax.transaction.*;
33 import javax.transaction.xa.*;
34 import com.sun.logging.*;
35 import com.sun.enterprise.*;
36 import com.sun.enterprise.Switch;
37 import com.sun.enterprise.util.*;
38 import com.sun.enterprise.distributedtx.*;
39 import com.sun.enterprise.deployment.*;
40 import com.sun.enterprise.connectors.ConnectorConnectionPool;
41 import com.sun.enterprise.resource.monitor.ConnectorServiceMonitoringLevelListener;
42 import com.sun.enterprise.resource.monitor.JDBCPoolMonitoringLevelListener;
43 import com.sun.enterprise.resource.monitor.ConnectorPoolMonitoringLevelListener;
44 import com.sun.enterprise.resource.monitor.ConnectorConnectionPoolStatsImpl;
45 import com.sun.enterprise.resource.monitor.JDBCConnectionPoolStatsImpl;
46 import com.sun.enterprise.admin.monitor.registry.MonitoringRegistry;
47 import com.sun.enterprise.admin.monitor.registry.MonitoredObjectType;
48 import com.sun.enterprise.admin.monitor.registry.MonitoringLevel;
49 import com.sun.enterprise.server.ApplicationServer;
50 import com.sun.enterprise.server.ServerContext;
51 import com.sun.enterprise.server.ResourcesUtil;
52 import com.sun.enterprise.connectors.ConnectorRuntime;
53 import com.sun.enterprise.connectors.ConnectorConstants;
54 import com.sun.enterprise.connectors.PoolMetaData;
55 import com.sun.enterprise.connectors.ConnectorRegistry;
56 import com.sun.enterprise.connectors.ConnectorConstants.PoolType;
57 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
58 import com.sun.enterprise.config.serverbeans.Config;
59 import javax.resource.spi.ManagedConnection JavaDoc;
60 import javax.resource.ResourceException JavaDoc;
61 import javax.resource.spi.DissociatableManagedConnection JavaDoc;
62
63
64 /**
65  * @author Tony Ng, Aditya Gore
66  *
67  */

68 public class PoolManagerImpl implements PoolManager {
69
70     static final private boolean debug = false;
71     static final private long DEFAULT_SLEEPTIME = 10;
72     
73     private ConcurrentHashMap JavaDoc poolTable;
74     
75     private static LocalStringManagerImpl localStrings =
76     new LocalStringManagerImpl(PoolManagerImpl.class);
77     
78     private ResourceManager resourceManager;
79     private ResourceManager sysResourceManager;
80     private ResourceManager noTxResourceManager;
81     private LazyEnlistableResourceManagerImpl lazyEnlistableResourceManager;
82     private PoolLifeCycle listener = null;
83
84     // Create logger object per Java SDK 1.4 to log messages
85
// introduced Santanu De, Sun Microsystems, March 2002
86

87     static Logger _logger = null;
88     static{
89         _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
90     }
91
92     MonitoringRegistry monitoringRegistry_;
93
94     public PoolManagerImpl() {
95         this.poolTable = new ConcurrentHashMap JavaDoc();
96
97         resourceManager = new ResourceManagerImpl();
98         sysResourceManager = new SystemResourceManagerImpl();
99         noTxResourceManager = new NoTxResourceManagerImpl();
100         lazyEnlistableResourceManager = new LazyEnlistableResourceManagerImpl();
101
102     }
103     
104     private boolean isTransactionActive(Transaction tran) {
105         return (tran != null);
106     }
107
108     // self management hook
109
public void registerPoolLifeCycleListner(PoolLifeCycle poolListener) {
110         listener = poolListener;
111     }
112
113     public void createEmptyConnectionPool(String JavaDoc poolName,
114         PoolType pt) throws PoolingException
115     {
116         //Create and initialise the connection pool
117
createAndInitPool(poolName, pt);
118         if (listener != null) {
119             try {
120                listener.poolCreated(poolName);
121             } catch (Exception JavaDoc ex) {
122             _logger.log(Level.FINE, "Exception thrown on pool listener");
123             }
124         }
125     }
126     
127     /**
128      * Create and initialize pool if not created already.
129      *
130      * @param poolName Name of the pool to be created
131      */

132     private ResourcePool createAndInitPool(final String JavaDoc poolName, PoolType pt)
133         throws PoolingException
134     {
135         ResourcePool pool = getPool( poolName );
136     if ( pool == null ) {
137             pool = ResourcePoolFactoryImpl.newInstance( poolName, pt );
138         addPool( pool );
139         //--Monitoring
140
//create Stats object for this pool and add it to the stats
141
//registry
142
try {
143             ConnectorRuntime runtime = ConnectorRuntime.getRuntime();
144             if ( runtime.getEnviron() == ConnectorConstants.SERVER ) {
145                 if (isJdbcPool( poolName ) ) {
146                     enableJDBCPoolMonitoring(pool, poolName);
147                 } else {
148                     enableConnectorConnectionPoolMonitoring(pool, poolName);
149                 }
150             }
151         } catch( Exception JavaDoc e) {
152             _logger.log(Level.INFO, "poolmon.cannot_reg");
153             _logger.log(Level.FINE, "Exception while registering " +
154                 "connection pool", e);
155         }
156         //--Monitoring End
157
logFine( "Created connection pool and added it to PoolManager :" + pool);
158     }
159     return pool;
160     }
161     
162     // invoked by DataSource objects to obtain a connection
163
public Object JavaDoc getResource(ResourceSpec spec, ResourceAllocator alloc,
164     ClientSecurityInfo info)
165     throws PoolingException {
166         
167         Transaction tran = null;
168         boolean transactional = alloc.isTransactional();
169         
170         if (transactional) {
171             tran = getResourceManager( spec ).getTransaction();
172         }
173         
174         ResourceHandle handle =
175         getResourceFromPool(spec, alloc, info, tran);
176
177         if( ! handle.supportsLazyAssociation() ) {
178             spec.setLazyAssociatable( false ) ;
179         }
180
181         if (spec.isLazyAssociatable() &&
182                 spec.getConnectionToAssociate() != null) {
183             //If getConnectionToAssociate returns a connection that means
184
//we need to associate a new connection with it
185
try {
186                 Object JavaDoc connection = spec.getConnectionToAssociate();
187                 ManagedConnection JavaDoc dmc
188                     = (ManagedConnection JavaDoc) handle.getResource();
189                 dmc.associateConnection( connection );
190             } catch( ResourceException JavaDoc e ) {
191                 putbackDirectToPool( handle, spec.getConnectionPoolName());
192                 PoolingException pe = new PoolingException(
193                     e.getMessage() );
194                 pe.initCause( e );
195                 throw pe;
196             }
197         }
198         
199         //If the ResourceAdapter does not support lazy enlistment
200
//we cannot either
201
if ( ! handle.supportsLazyEnlistment() ) {
202             spec.setLazyEnlistable( false );
203         }
204         handle.setResourceSpec(spec);
205         
206         try {
207         if( handle.getResourceState().isUnenlisted()) {
208                 //The spec being used here is the spec with the updated
209
//lazy enlistment info
210
//Here's the real place where we care about the correct
211
//resource manager (which in turn depends upon the ResourceSpec)
212
//and that's because if lazy enlistment needs to be done
213
//we need to get the LazyEnlistableResourceManager
214
getResourceManager( spec ).enlistResource(handle);
215         }
216         } catch( Exception JavaDoc e) {
217             //In the rare cases where enlistResource throws exception, we
218
//should return the resource to the pool
219
putbackDirectToPool( handle, spec.getConnectionPoolName());
220             _logger.log(Level.WARNING, "poolmgr.err_enlisting_res_in_getconn");
221             if (_logger.isLoggable(Level.FINE) ) {
222                 _logger.fine("rm.enlistResource threw Exception. Returning resource to pool");
223             }
224             //and rethrow the exception
225
throw new PoolingException( e );
226     
227         }
228     
229         return handle.getUserConnection();
230     }
231    
232     public void registerResource(ResourceHandle handle)
233     throws PoolingException {
234         ResourceManager rm = getResourceManager(handle.getResourceSpec());
235         rm.registerResource(handle);
236     }
237
238     public ResourceHandle getResourceFromPool(ResourceSpec spec,
239                                                 ResourceAllocator alloc,
240                                                 ClientSecurityInfo info,
241                                                 Transaction tran)
242     throws PoolingException {
243         ResourcePool pool = getPool( spec.getConnectionPoolName() );
244         // pool.getResource() has been modified to:
245
// - be able to create new resource if needed
246
// - block the caller until a resource is acquired or
247
// the max-wait-time expires
248
ResourceHandle resource = pool.getResource(spec, alloc, tran);
249         
250         return resource;
251     }
252    
253     
254     private void enableConnectorConnectionPoolMonitoring(ResourcePool pool,
255         final String JavaDoc poolName) {
256         
257         MonitorableResourcePool mrp = null;
258         
259         if ( pool instanceof MonitorableResourcePool ) {
260             mrp = (MonitorableResourcePool)pool;
261         } else {
262             return;
263         }
264         
265         //this is a connector connection pool
266
//check if monitoring level is ON and only then do
267
//registration
268
if (getConnectorPoolMonitoringLevel() != MonitoringLevel.OFF ) {
269             final ConnectorConnectionPoolStatsImpl ccpStatsImpl =
270             new ConnectorConnectionPoolStatsImpl(mrp );
271
272             if (getConnectorPoolMonitoringLevel() == MonitoringLevel.HIGH ) {
273                 setMonitoringEnabledHigh( poolName );
274             }
275             if (getConnectorPoolMonitoringLevel() == MonitoringLevel.LOW ) {
276                 setMonitoringEnabledLow(poolName );
277             }
278
279             AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
280                 public Object JavaDoc run() {
281                     try {
282                         monitoringRegistry_.registerConnectorConnectionPoolStats(
283                 ccpStatsImpl, poolName, null );
284                     } catch( Exception JavaDoc mre ) {
285                         _logger.log( Level.INFO, "poolmon.cannot_reg",
286                 (mre.getMessage() != null ? mre.getMessage() : " ") );
287                         logFine("Error while enabling Connector Pool monitoring for pool "
288                 + poolName + mre);
289                         //reset monitoring state of the pool
290
disableMonitoring( poolName);
291                     }
292                     return null;
293                 }
294             });
295             if (_logger.isLoggable( Level.FINE ) ) {
296                 _logger.fine("Enabled pool monitoring at pool creation for " + poolName );
297             }
298         }
299     }
300
301     private void enableJDBCPoolMonitoring(ResourcePool pool, final String JavaDoc poolName) {
302         MonitorableResourcePool mrp = null;
303
304         if( pool instanceof MonitorableResourcePool ) {
305             mrp = (MonitorableResourcePool) pool;
306         } else {
307             return;
308         }
309         
310         //check if monitoring level is ON and only then
311
//do registration
312
if (getJdbcPoolMonitoringLevel() != MonitoringLevel.OFF) {
313             final JDBCConnectionPoolStatsImpl jdbcStatsImpl =
314                 new JDBCConnectionPoolStatsImpl(mrp );
315             if (getJdbcPoolMonitoringLevel() == MonitoringLevel.HIGH ) {
316                 setMonitoringEnabledHigh( poolName );
317             }
318             if (getJdbcPoolMonitoringLevel() == MonitoringLevel.LOW ) {
319                 setMonitoringEnabledLow(poolName );
320             }
321             AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
322                 public Object JavaDoc run() {
323                     try {
324                         monitoringRegistry_.registerJDBCConnectionPoolStats(
325                 jdbcStatsImpl, poolName, null );
326                     } catch( Exception JavaDoc mre ) {
327                         _logger.log( Level.INFO, "poolmon.cannot_reg",
328                 (mre.getMessage() != null ? mre.getMessage() : " ") );
329                         logFine("Error while enabling JDBC Pool monitoring for pool "
330                 + poolName + mre);
331
332                         //reset monitoring state of the pool
333
disableMonitoring( poolName );
334                     }
335                     return null;
336                 }
337             });
338             
339             if (_logger.isLoggable( Level.FINE ) ) {
340                 _logger.fine("Enabled pool monitoring at pool creation for " + poolName );
341             }
342         }
343     }
344
345     // called by EJB Transaction Manager
346
public void resourceEnlisted(Transaction tran,
347         ResourceHandle res) throws IllegalStateException JavaDoc
348     {
349         
350         String JavaDoc poolName = res.getResourceSpec().getConnectionPoolName();
351         try {
352             J2EETransaction j2eeTran = (J2EETransaction) tran;
353             if (poolName != null && j2eeTran.getResources(poolName) == null) {
354                 addSyncListener(tran);
355             }
356         } catch (ClassCastException JavaDoc e) {
357             addSyncListener(tran);
358         }
359     if ( poolName != null ) {
360         ResourcePool pool = getPool( poolName );
361             if (pool != null) {
362             pool.resourceEnlisted(tran, res);
363         }
364     }
365     }
366
367     private void addSyncListener(Transaction tran) {
368         Synchronization sync = new SynchronizationListener(tran);
369         try {
370             tran.registerSynchronization(sync);
371         } catch (Exception JavaDoc ex) {
372             logFine( "Error adding syncListener : " +
373             (ex.getMessage() != null ? ex.getMessage() : " "));
374         }
375     }
376     
377     // called by EJB Transaction Manager
378
public void transactionCompleted(Transaction tran, int status)
379     throws IllegalStateException JavaDoc {
380         
381     Iterator iter = ((J2EETransaction)tran).getAllParticipatingPools().iterator();
382         while (iter.hasNext()) {
383             ResourcePool pool = getPool((String JavaDoc)iter.next());
384         logFine( "calling transactionCompleted on " + pool.getPoolName() );
385         pool.transactionCompleted( tran, status );
386         }
387
388     }
389     
390     public void resourceClosed(ResourceHandle resource) {
391         ResourceManager rm = getResourceManager(resource.getResourceSpec());
392         rm.delistResource(resource, XAResource.TMSUCCESS);
393         putbackResourceToPool(resource, false);
394     }
395     
396     public void resourceErrorOccurred(ResourceHandle resource) {
397         putbackResourceToPool(resource, true);
398     }
399     
400     public void unregisterResource(ResourceHandle resource,
401     int xaresFlag) {
402         
403         ResourceManager rm = getResourceManager(resource.getResourceSpec());
404         rm.unregisterResource(resource,xaresFlag);
405     }
406     
407     public void putbackResourceToPool(ResourceHandle h,
408     boolean errorOccurred) {
409         
410         // cleanup resource
411
try {
412             ResourceAllocator alloc = h.getResourceAllocator();
413             alloc.cleanup(h);
414         } catch (PoolingException ex) {
415             errorOccurred = true; // destroy resource
416
}
417         
418         // notify pool
419
String JavaDoc poolName = h.getResourceSpec().getConnectionPoolName();
420     if ( poolName != null ) {
421             ResourcePool pool = (ResourcePool) poolTable.get( poolName );
422             if (pool != null) {
423                 if (errorOccurred) {
424                     pool.resourceErrorOccurred(h);
425                 } else {
426                     pool.resourceClosed(h);
427                 }
428             }
429     }
430     }
431     public void emptyResourcePool(ResourceSpec spec) {
432         //ResourcePool pool = (ResourcePool) poolTable.get(spec.getConnectionPoolName());
433
String JavaDoc poolName = spec.getConnectionPoolName();
434     if ( poolName != null ) {
435             ResourcePool pool = (ResourcePool) poolTable.get( poolName );
436             if (pool != null) {
437                 pool.emptyPool();
438             }
439     }
440     }
441
442     public ResourceReferenceDescriptor getResourceReference(String JavaDoc jndiName) {
443         
444         InvocationManager i = Switch.getSwitch().getInvocationManager();
445         if (i == null) return null;
446         
447         ComponentInvocation inv = null;
448         
449         inv = i.getCurrentInvocation();
450         if (inv == null) {
451             return null;
452         }
453         
454         int invType = inv.getInvocationType();
455         Set refs = null;
456         Object JavaDoc container = inv.getContainerContext();
457         JndiNameEnvironment env = (JndiNameEnvironment)
458         Switch.getSwitch().getDescriptorFor(container);
459         // env can be null if it's CMP SQL generation
460
if (env == null) return null;
461         refs = env.getResourceReferenceDescriptors();
462         
463         Iterator iter = refs.iterator();
464         
465         while (iter.hasNext()) {
466             ResourceReferenceDescriptor ref =
467             (ResourceReferenceDescriptor) iter.next();
468             String JavaDoc name = ref.getJndiName();
469             if (jndiName.equals(name)) {
470                 return ref;
471             }
472         }
473         // cannot find corresponding resource reference
474
return null;
475     }
476     
477     private ResourceManager getResourceManager(ResourceSpec spec) {
478         if (spec.isNonTx()) {
479             logFine( "@@@@ Returning noTxResourceManager");
480             return noTxResourceManager;
481         } else if (spec.isPM()) {
482             logFine( "@@@@ Returning sysResourceManager");
483             return sysResourceManager;
484         } else if (spec.isLazyEnlistable() ) {
485             logFine( "@@@@ Returning LazyEnlistableResourceManager");
486             return lazyEnlistableResourceManager;
487         } else {
488             logFine( "@@@@ Returning resourceManager");
489             return resourceManager;
490         }
491     }
492     
493     class SynchronizationListener implements Synchronization {
494         
495         private Transaction tran;
496         
497         SynchronizationListener(Transaction tran) {
498             this.tran = tran;
499         }
500         
501         public void afterCompletion(int status) {
502             try {
503                 transactionCompleted(tran, status);
504             } catch (Exception JavaDoc ex) {
505                 logFine( "Exception in afterCompletion : " +
506             (ex.getMessage() != null ? ex.getMessage() : " " ));
507             }
508         }
509         
510         public void beforeCompletion() {
511             // do nothing
512
}
513         
514     }
515     
516     public void putbackDirectToPool(ResourceHandle h, String JavaDoc poolName ){
517         // notify pool
518
if ( poolName != null ) {
519             ResourcePool pool = (ResourcePool) poolTable.get( poolName );
520             if (pool != null) {
521                 pool.resourceClosed(h);
522             }
523     }
524     }
525
526     /**
527      * Kill the pool with the specified pool name
528      *
529      * @param poolName - The name of the pool to kill
530      */

531     public void killPool( String JavaDoc poolName ) {
532         //empty the pool
533
//and remove from poolTable
534
ResourcePool pool = (ResourcePool) poolTable.get( poolName );
535         if (pool != null ) {
536             pool.cancelResizerTask();
537             pool.emptyPool();
538              logFine("Removing pool " + pool + " from pooltable");
539         synchronized( poolTable ) {
540                 poolTable.remove( poolName );
541         }
542         }
543
544         // self management hook
545
if (listener != null)
546             listener.poolDestroyed(poolName);
547             
548         //--Monitoring
549
try {
550             ConnectorRuntime runtime = ConnectorRuntime.getRuntime();
551             
552             if ( runtime.getEnviron() == ConnectorConstants.SERVER ) {
553                 final String JavaDoc fPoolName = poolName;
554                 if (isJdbcPool( fPoolName )) {
555                     disableJDBCPoolMonitoring(fPoolName);
556                 } else {
557                     disableConnectorConnectionPoolMonitoring(fPoolName);
558                 }
559             }
560         } catch( Exception JavaDoc e) {
561             _logger.log( Level.INFO, "poolmon.cannot_unreg");
562         }
563         //--Monitoring End
564
}
565
566     private void disableConnectorConnectionPoolMonitoring(final String JavaDoc fPoolName) {
567         if (getConnectorPoolMonitoringLevel() != MonitoringLevel.OFF ) {
568             AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
569                 public Object JavaDoc run() {
570                     try {
571                         monitoringRegistry_.unregisterConnectorConnectionPoolStats(
572                             fPoolName );
573                     } catch( Exception JavaDoc mre) {
574                         _logger.log( Level.INFO, "poolmon.cannot_unreg",
575                             mre.getMessage() );
576                     }
577                     return null;
578                 }
579             });
580         }
581     }
582
583     private void disableJDBCPoolMonitoring(final String JavaDoc fPoolName) {
584         //We need to do this iff MonitoringLevel is not OFF
585
//Otherwise, we haven't registered the pool anyways
586
if ( getJdbcPoolMonitoringLevel() != MonitoringLevel.OFF ) {
587              AccessController.doPrivileged( new PrivilegedAction JavaDoc() {
588                  public Object JavaDoc run() {
589                          try {
590                          monitoringRegistry_.unregisterJDBCConnectionPoolStats(
591                              fPoolName );
592                      } catch( Exception JavaDoc mre) {
593                         _logger.log( Level.INFO, "poolmon.cannot_unreg",
594                             mre.getMessage() );
595                      }
596                      return null;
597              }
598              });
599         }
600     }
601
602     /**
603      * Deletgates the task of setting a pool's properties to the actual
604      * pool.
605      * @param ccp - the ConnectorConnectionPool object that holds the new
606      * pool properties
607      */

608     public void reconfigPoolProperties( ConnectorConnectionPool ccp )
609             throws PoolingException
610     {
611         String JavaDoc poolName = ccp.getName();
612         PoolManager poolmgr = Switch.getSwitch().getPoolManager();
613         ResourcePool pool = (ResourcePool) poolmgr.getPoolTable().get( poolName );
614
615         if (pool != null ) {
616             pool.reconfigPoolProperties( ccp );
617         }
618     }
619     
620     /**
621      * Sets/resets the monitoringEnabled flag for each pool
622      *
623      * @param poolName - the pool whose flag is to be set
624      * @param monitoringEnabled - the flag
625      */

626     public void disableMonitoring( String JavaDoc poolName ) {
627         ResourcePool pool = (ResourcePool) poolTable.get( poolName );
628         if (pool != null ) {
629             pool.disableMonitoring();
630         }
631     }
632
633     /**
634      * Sets/resets the monitoringEnabledHigh flag for each pool
635      * This flag indicates that the pool is being monitored at the
636      * "HIGH" monitoring level
637      *
638      * @param poolName - the pool whose flag is to be set
639      * @param monitoringEnabled - the flag
640      */

641     public void setMonitoringEnabledHigh( String JavaDoc poolName ) {
642         ResourcePool pool = (ResourcePool) poolTable.get( poolName );
643         if (pool != null ) {
644             pool.setMonitoringEnabledHigh();
645         }
646     }
647
648     /**
649      * Sets/resets the monitoringEnabledLow flag for each pool
650      * This flag indicates that the pool is being monitored at the
651      * "HIGH" monitoring level
652      *
653      * @param poolName - the pool whose flag is to be set
654      * @param monitoringEnabled - the flag
655      */

656     public void setMonitoringEnabledLow( String JavaDoc poolName ) {
657         ResourcePool pool = (ResourcePool) poolTable.get( poolName );
658         if (pool != null ) {
659             pool.setMonitoringEnabledLow();
660         }
661     }
662
663     /**
664      * Switch on matching in the pool.
665      *
666      * @param poolName Name of the pool
667      */

668     public boolean switchOnMatching(String JavaDoc poolName) {
669         PoolManager poolmgr = Switch.getSwitch().getPoolManager();
670     ResourcePool pool = (ResourcePool) poolmgr.getPoolTable().get( poolName );
671
672     if (pool != null ) {
673         pool.switchOnMatching();
674             return true;
675         } else {
676             return false;
677         }
678     }
679     
680     /*
681      * Checks in the domain.xml via ResourcesUtil to see if this is
682      * a JDBC connection pool
683      * returns true if it is
684      */

685     private boolean isJdbcPool( String JavaDoc poolName ) {
686         com.sun.enterprise.config.serverbeans.JdbcConnectionPool[]
687         pools = ResourcesUtil.getInstance().getJdbcConnectionPools();
688         
689     for( int i = 0 ;i < pools.length; i++ ) {
690         if (poolName.equals( pools[i].getName() ) ) {
691             return true;
692         }
693     }
694
695     return false;
696     }
697
698     public ConcurrentHashMap JavaDoc getPoolTable() {
699         return poolTable;
700     }
701
702     private void addPool(ResourcePool pool){
703         logFine("Adding pool " + pool.getPoolName() + "to pooltable");
704     synchronized( poolTable ) {
705             poolTable.put(pool.getPoolName(), pool);
706     }
707     }
708
709     /**
710      * Initialize monitoring by registering module monitoring level listeners
711      * for Connector-service and JDBC Connector conncetion pools.
712      *
713      * All Connector-Service and the old Connectorconnectionpool related module stats
714      * [namely connector-services' connection pools, Work management] are registered
715      * or unregistered, as the case maybe, in
716      * <code>ConnectorServiceModuleMonitoringLevelListener</code>
717      *
718      * All JMS Service module related stats [as of now only JMS connection
719      * factories] are <i>also</i> registered or unregistered, as the case maybe,
720      * in <code>ConnectorServiceModuleMonitoringLevelListener</code>
721      *
722      * All JDBCConnectionPool related stats are registerd or unregistered,
723      * as the case maybe, in <code>JDBCPoolModuleMonitoringLevelListener</code>
724      *
725      * (In 8.1 PE/SE/EE)
726      * For backward compatability reasons: When the old connector connection pool
727      * or the new JMS-Service module's monitoring level is updated, the
728      * connector-service's module monitoring level listener is updated
729      * and vice-versa.
730      */

731     public void initializeMonitoring() {
732         try {
733             final ConnectorServiceMonitoringLevelListener csMonitoringListener
734                 = new ConnectorServiceMonitoringLevelListener();
735             final JDBCPoolMonitoringLevelListener jdbcMonitoringListener
736                 = new JDBCPoolMonitoringLevelListener();
737             
738             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
739                 public Object JavaDoc run() {
740                     ServerContext ctxt = ApplicationServer.getServerContext();
741                     if (ctxt != null) {
742                         monitoringRegistry_ = ctxt.getMonitoringRegistry();
743                         monitoringRegistry_.registerMonitoringLevelListener(
744                             csMonitoringListener, MonitoredObjectType.CONNECTOR_SERVICE);
745                         monitoringRegistry_.registerMonitoringLevelListener(
746                                         jdbcMonitoringListener,
747                                         MonitoredObjectType.JDBC_CONN_POOL);
748                     }
749                     return null;
750                 }
751             });
752             _logger.log( Level.FINE, "poolmon.init_monitoring_registry");
753         } catch(Exception JavaDoc e) {
754             _logger.log( Level.INFO, "poolmon.error_registering_listener",
755                 e);
756         }
757     
758     }
759    
760     /*
761      * Gets the current monitoring level for Jdbc pools
762      */

763     private MonitoringLevel getJdbcPoolMonitoringLevel() {
764         Config cfg = null;
765     MonitoringLevel off = MonitoringLevel.OFF;
766     MonitoringLevel l = off;
767
768     try {
769             cfg = ServerBeansFactory.getConfigBean(
770             ApplicationServer.getServerContext().getConfigContext());
771         
772             String JavaDoc lvl =
773             cfg.getMonitoringService().getModuleMonitoringLevels().getJdbcConnectionPool();
774         l = MonitoringLevel.instance( lvl );
775         if (l == null ) {
776             //dont bother to throw an exception
777
return off;
778         }
779     } catch (Exception JavaDoc e) {
780         return off;
781     }
782         return l;
783     }
784
785     /*
786      * Gets the current monitoring level for connector pools
787      */

788     private MonitoringLevel getConnectorPoolMonitoringLevel() {
789         Config cfg = null;
790     MonitoringLevel off = MonitoringLevel.OFF;
791     MonitoringLevel l = off;
792
793     try {
794             cfg = ServerBeansFactory.getConfigBean(
795             ApplicationServer.getServerContext().getConfigContext());
796         
797             String JavaDoc lvl =
798             cfg.getMonitoringService().getModuleMonitoringLevels().getConnectorConnectionPool();
799         l = MonitoringLevel.instance( lvl );
800         if (l == null ) {
801             //dont bother to throw an exception
802
return off;
803         }
804     } catch (Exception JavaDoc e) {
805         return off;
806     }
807         return l;
808
809     }
810
811     /**
812      * Kills all the connection pools in the server
813      */

814     
815     public void killAllPools() {
816
817     Iterator pools = poolTable.values().iterator();
818         logFine( "---Killing all pools");
819         while( pools.hasNext() ) {
820         ResourcePool pool = (ResourcePool) pools.next();
821         if ( pool != null ) {
822             String JavaDoc name = pool.getPoolName();
823             try {
824             logFine( "Now killing pool : " + name);
825                 killPool( name );
826         } catch( Exception JavaDoc e ) {
827             logFine( "Error killing pool : " + name + " :: "
828                 + ( e.getMessage() != null ? e.getMessage() : " " ));
829         }
830         }
831     }
832         stopEmbeddedDerby();
833     }
834
835      private void stopEmbeddedDerby(){
836         try{
837             Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
838             DriverManager.getConnection("jdbc:derby:;shutdown=true");
839         }
840         catch(ClassNotFoundException JavaDoc cnfe){
841             _logger.log(Level.FINE, "Derby.Driver.Not.Found", cnfe.fillInStackTrace());
842         }
843         //Embedded derby, when shutdown will throw this exception in all cases.
844
catch(SQLException JavaDoc se){
845              _logger.log(Level.FINE, "Derby.Shutdown.Exception", se.fillInStackTrace());
846         }
847         catch(Exception JavaDoc e){
848              _logger.log(Level.FINE, "Derby.Shutdown.Exception", e.fillInStackTrace());
849         }
850     }
851
852     
853     public void killFreeConnectionsInPools() {
854     Iterator pools = poolTable.values().iterator();
855         logFine("-----Killing all free connections in pools");
856         while( pools.hasNext() ) {
857         ResourcePool pool = (ResourcePool) pools.next();
858         if ( pool != null ) {
859             String JavaDoc name = pool.getPoolName();
860             try {
861             if ( name != null ) {
862                 ResourcePool poolToKill = (ResourcePool)
863                 poolTable.get( name );
864                 if ( poolToKill != null ) {
865                     pool.emptyFreeConnectionsInPool();
866                 }
867                 logFine( "Now killing free connections in pool : " + name);
868             }
869         } catch( Exception JavaDoc e ) {
870             logFine( "Error killing pool : " + name + " :: "
871                 + ( e.getMessage() != null ? e.getMessage() : " " ));
872         }
873         }
874     }
875
876     }
877     
878     private void logFine( String JavaDoc msg ) {
879         if ( _logger.isLoggable(Level.FINE)) {
880         _logger.fine( msg );
881     }
882     }
883
884     public ResourcePool getPool( String JavaDoc name ) {
885         if ( name == null ) {
886             return null;
887         }
888         return (ResourcePool)
889         Switch.getSwitch().getPoolManager().getPoolTable().get( name );
890     
891     }
892
893     public void setSelfManaged( String JavaDoc poolName, boolean flag ) {
894         if ( poolName == null ) {
895             return;
896         }
897         getPool( poolName ).setSelfManaged( flag );
898     }
899
900     /**
901      * This method gets called by the LazyEnlistableConnectionManagerImpl when
902      * a connection needs enlistment, i.e on use of a Statement etc.
903      */

904     public void lazyEnlist( ManagedConnection JavaDoc mc ) throws ResourceException JavaDoc {
905         lazyEnlistableResourceManager.lazyEnlist( mc );
906     }
907     
908     /*
909      * Called by the InvocationManager at methodEnd. This method
910      * will disassociate ManagedConnection instances from Connection
911      * handles if the ResourceAdapter supports that.
912      */

913     public void postInvoke() throws InvocationException
914     {
915         J2EETransactionManager tm = Switch.getSwitch().getTransactionManager();
916         ComponentInvocation invToUse =
917             Switch.getSwitch().getInvocationManager().getCurrentInvocation();
918             
919         if ( invToUse == null ) {
920             return;
921         }
922
923         Object JavaDoc comp = invToUse.getInstance();
924
925         if ( comp == null ) {
926             return;
927         }
928
929         
930         List list = ((J2EETransactionManagerImpl)tm).getExistingResourceList(
931             comp, invToUse );
932         if (list == null ) {
933             //For invocations of asadmin the ComponentInvocation does not
934
//have any resources and hence the existingResourcesList is null
935
return;
936         }
937         ResourceHandle[] handles = (ResourceHandle[])list.toArray(
938             new ResourceHandle[0] );
939         for( ResourceHandle h : handles) {
940             ResourceSpec spec = h.getResourceSpec();
941             if ( spec.isLazyAssociatable() ) {
942                 //In this case we are assured that the managedConnection is
943
//of type DissociatableManagedConnection
944
javax.resource.spi.DissociatableManagedConnection JavaDoc mc =
945                     (javax.resource.spi.DissociatableManagedConnection JavaDoc) h.getResource();
946                 if ( h.isEnlisted() ) {
947                     getResourceManager( spec ).delistResource(
948                         h, XAResource.TMSUCCESS);
949                 }
950                 try {
951                     mc.dissociateConnections();
952                 } catch( ResourceException JavaDoc re ) {
953                     InvocationException ie = new InvocationException(
954                         re.getMessage() );
955                     ie.initCause( re );
956                     throw ie;
957                 } finally {
958                     if ( h.getResourceState().isBusy() ) {
959                         putbackDirectToPool( h, spec.getConnectionPoolName() );
960                     }
961                 }
962                 
963             }
964         }
965         
966     }
967 }
968
969
Popular Tags