KickJava   Java API By Example, From Geeks To Geeks.

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


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 java.util.logging.*;
27 import java.util.*;
28 import java.security.*;
29 import javax.resource.*;
30 import javax.security.auth.*;
31 import javax.resource.spi.security.*;
32 import javax.naming.*;
33 import javax.resource.spi.*;
34 import com.sun.enterprise.*;
35 import com.sun.enterprise.server.*;
36 import com.sun.enterprise.config.serverbeans.*;
37 import com.sun.enterprise.config.ConfigBean;
38 import com.sun.enterprise.config.ConfigException;
39 import com.sun.enterprise.config.ConfigContext;
40 import com.sun.enterprise.deployment.*;
41 import com.sun.enterprise.resource.*;
42 import com.sun.enterprise.connectors.util.*;
43 import com.sun.enterprise.util.i18n.StringManager;
44 import com.sun.enterprise.resource.UnpooledConnectionEventListener;
45 import com.sun.enterprise.util.RelativePathResolver;
46 import java.sql.Connection JavaDoc;
47 import java.sql.SQLException JavaDoc;
48 import com.sun.enterprise.Switch;
49 import com.sun.enterprise.PoolManager;
50 import com.sun.enterprise.connectors.util.ConnectionPoolReconfigHelper.ReconfigAction;
51 import com.sun.enterprise.connectors.authentication.RuntimeSecurityMap;
52 import com.sun.enterprise.connectors.authentication.ConnectorSecurityMap;
53 import com.sun.enterprise.naming.NamingManagerImpl;
54
55
56 /**
57  * This is connector connection pool admin service. It performs the
58  * functionality of creation,deletion,recreation, testing of the pools.
59  * @author Srikanth P and Aditya Gore
60  */

61
62
63 public class ConnectorConnectionPoolAdminServiceImpl extends
64                    ConnectorServiceImpl implements ConnectorAdminService {
65     
66     private static StringManager localStrings =
67         StringManager.getManager( ConnectorConnectionPoolAdminServiceImpl.class);
68
69     /**
70      * Default constructor
71      */

72
73     public ConnectorConnectionPoolAdminServiceImpl() {
74         super();
75         initialize();
76     }
77
78      
79     /** Creates connector connection pool in the connector container.
80      * @param ccp ConnectorConnectionPool instance to be bound to JNDI. This
81      * object contains the pool properties.
82      * @param connectionDefinitionName Connection definition name against which
83      * connection pool is being created
84      * @param rarName Name of the resource adapter
85      * @param props Properties of MCF which are present in domain.xml
86      * These properties override the ones present in ra.xml
87      * @param securityMaps Array fo security maps.
88      * @throws ConnectorRuntimeException When creation of pool fails.
89      */

90
91     public void createConnectorConnectionPool(ConnectorConnectionPool ccp,
92                           String JavaDoc connectionDefinitionName , String JavaDoc rarName,
93                           ElementProperty[] props, SecurityMap[] securityMaps)
94                           throws ConnectorRuntimeException
95     {
96
97         if( (ccp == null) || (connectionDefinitionName == null)
98                           || (rarName == null)) {
99             _logger.log(Level.FINE,"Wrong parameters for pool creation ");
100         String JavaDoc i18nMsg = localStrings.getString(
101             "ccp_adm.wrong_params_for_create");
102             throw new ConnectorRuntimeException( i18nMsg );
103         }
104         ConnectorDescriptor connectorDescriptor =
105                                 _registry.getDescriptor(rarName);
106         if(connectorDescriptor == null) {
107             ifSystemRarLoad(rarName);
108             connectorDescriptor = _registry.getDescriptor(rarName);
109         }
110         if (connectorDescriptor == null) {
111         String JavaDoc i18nMsg = localStrings.getString(
112             "ccp_adm.no_conn_pool_obj");
113             ConnectorRuntimeException cre = new ConnectorRuntimeException(
114                             i18nMsg );
115             _logger.log(Level.SEVERE,
116               "rardeployment.connector_descriptor_notfound_registry",rarName);
117             _logger.log(Level.SEVERE,"",cre);
118             throw cre;
119         }
120         Set connectionDefs =
121           connectorDescriptor.getOutboundResourceAdapter().getConnectionDefs();
122         ConnectionDefDescriptor cdd = null;
123         Iterator it = connectionDefs.iterator();
124         while(it.hasNext()) {
125           cdd = (ConnectionDefDescriptor)it.next();
126           if(connectionDefinitionName.equals(cdd.getConnectionFactoryIntf()))
127               break;
128
129         }
130         ConnectorDescriptorInfo cdi = new ConnectorDescriptorInfo();
131
132         cdi.setRarName(rarName);
133         cdi.setResourceAdapterClassName(
134                     connectorDescriptor.getResourceAdapterClass());
135         cdi.setConnectionDefinitionName(cdd.getConnectionFactoryIntf());
136         cdi.setManagedConnectionFactoryClass(
137                     cdd.getManagedConnectionFactoryImpl());
138         cdi.setConnectionFactoryClass(cdd.getConnectionFactoryImpl());
139         cdi.setConnectionFactoryInterface(cdd.getConnectionFactoryIntf());
140         cdi.setConnectionClass(cdd.getConnectionImpl());
141         cdi.setConnectionInterface(cdd.getConnectionIntf());
142         Set mergedProps = ConnectorDDTransformUtils.mergeProps(props,
143                       cdd.getConfigProperties());
144         cdi.setMCFConfigProperties(mergedProps);
145         cdi.setResourceAdapterConfigProperties(
146                     connectorDescriptor.getConfigProperties());
147         ccp.setSecurityMaps(SecurityMapUtils.getConnectorSecurityMaps(securityMaps));
148         createConnectorConnectionPool(ccp , cdi);
149     }
150
151     /** Creates connector connection pool in the connector container.
152      * @param ccp ConnectorConnectionPool instance to be bound to JNDI. This
153      * object contains the pool properties.
154      * @param cdd ConnectorDescriptor obejct which abstracts the ra.xml
155      * @param rarName Name of the resource adapter
156      * @throws ConnectorRuntimeException When creation of pool fails.
157      */

158
159     public void createConnectorConnectionPool(ConnectorConnectionPool ccp,
160                     ConnectionDefDescriptor cdd, String JavaDoc rarName)
161                     throws ConnectorRuntimeException
162     {
163
164         if( (ccp == null) || (cdd == null) || (rarName == null)) {
165
166             _logger.log(Level.FINE,"Wrong parameters for pool creation ");
167         String JavaDoc i18nMsg = localStrings.getString(
168             "ccp_adm.wrong_params_for_create");
169             throw new ConnectorRuntimeException( i18nMsg );
170         }
171         ConnectorDescriptorInfo cdi = new ConnectorDescriptorInfo();
172
173         ConnectorDescriptor connectorDescriptor = _registry.getDescriptor(
174                                                           rarName);
175         if(connectorDescriptor == null) {
176             ifSystemRarLoad(rarName);
177             connectorDescriptor = _registry.getDescriptor(rarName);
178         }
179
180         if (connectorDescriptor == null) {
181         String JavaDoc i18nMsg = localStrings.getString(
182             "ccp_adm.no_conn_pool_obj");
183             ConnectorRuntimeException cre = new
184             ConnectorRuntimeException(i18nMsg);
185             _logger.log(Level.SEVERE,
186                   "rardeployment.connector_descriptor_notfound_registry",
187                   rarName);
188             _logger.log(Level.SEVERE,"",cre);
189             throw cre;
190         }
191         cdi.setRarName(rarName);
192         cdi.setResourceAdapterClassName(
193                           connectorDescriptor.getResourceAdapterClass());
194         cdi.setConnectionDefinitionName(cdd.getConnectionFactoryIntf());
195     cdi.setManagedConnectionFactoryClass(
196                           cdd.getManagedConnectionFactoryImpl());
197     cdi.setConnectionFactoryClass(cdd.getConnectionFactoryImpl());
198     cdi.setConnectionFactoryInterface(cdd.getConnectionFactoryIntf());
199     cdi.setConnectionClass(cdd.getConnectionImpl());
200     cdi.setConnectionInterface(cdd.getConnectionIntf());
201     cdi.setMCFConfigProperties(cdd.getConfigProperties());
202     cdi.setResourceAdapterConfigProperties(
203                           connectorDescriptor.getConfigProperties());
204         createConnectorConnectionPool(ccp , cdi);
205     }
206
207     /** Creates connector connection pool in the connector container.
208      * @param ccp ConnectorConnectionPool instance to be bound to JNDI. This
209      * object contains the pool properties.
210      * @param connectorDescInfo ConnectorDescriptorInfo object which
211      * abstracts the connection definition values
212      * present in ra.xml
213      * @throws ConnectorRuntimeException When creation of pool fails.
214      */

215
216     private void createConnectorConnectionPool(
217                        ConnectorConnectionPool connectorPoolObj ,
218                        ConnectorDescriptorInfo connectorDescInfo )
219                        throws ConnectorRuntimeException
220     {
221
222     connectorPoolObj.setConnectorDescriptorInfo( connectorDescInfo );
223         createConnectorConnectionPool( connectorPoolObj );
224     }
225
226     /** Creates connector connection pool in the connector container.
227      * @param ccp ConnectorConnectionPool instance to be bound to JNDI. This
228      * object contains the pool properties.
229      * @throws ConnectorRuntimeException When creation of pool fails.
230      */

231     public void createConnectorConnectionPool(
232             ConnectorConnectionPool connectorPoolObj )
233             throws ConnectorRuntimeException
234     {
235
236         String JavaDoc poolName = connectorPoolObj.getName();
237         if( connectorPoolObj == null || poolName == null) {
238             _logger.log(Level.FINE,"Wrong parameters for pool creation ");
239         String JavaDoc i18nMsg = localStrings.getString(
240             "ccp_adm.wrong_params_for_create");
241             throw new ConnectorRuntimeException( i18nMsg );
242         }
243         String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
244                     getReservePrefixedJNDINameForPool(poolName);
245         try {
246             Switch.getSwitch().getNamingManager().publishObject(
247                           jndiNameForPool,(Object JavaDoc)connectorPoolObj,true);
248             ManagedConnectionFactory mcf =
249                           obtainManagedConnectionFactory(poolName);
250             if(mcf == null) {
251             InitialContext ic = new InitialContext();
252                 ic.unbind(jndiNameForPool);
253             String JavaDoc i18nMsg = localStrings.getString(
254                 "ccp_adm.failed_to_create_mcf");
255         ConnectorRuntimeException cre = new
256             ConnectorRuntimeException( i18nMsg );
257                 _logger.log(Level.SEVERE,"rardeployment.mcf_creation_failure",
258                            poolName);
259                 _logger.log(Level.SEVERE,"",cre);
260         throw cre;
261             }
262
263         } catch(NamingException ex) {
264        
265         String JavaDoc i18nMsg = localStrings.getString(
266             "ccp_adm.failed_to_publish_in_jndi");
267             ConnectorRuntimeException cre = new
268             ConnectorRuntimeException( i18nMsg );
269             cre.initCause(ex);
270             _logger.log(Level.SEVERE,"rardeployment.pool_jndi_bind_failure",
271                          poolName);
272             _logger.log(Level.SEVERE,"",cre);
273             throw cre;
274         } catch(NullPointerException JavaDoc ex) {
275             try {
276             InitialContext ic = new InitialContext();
277                 ic.unbind(jndiNameForPool);
278             } catch(NamingException ne) {
279                 _logger.log(Level.FINE,
280                      "Failed to unbind connection pool object ",poolName);
281             }
282         
283         String JavaDoc i18nMsg = localStrings.getString(
284             "ccp_adm.failed_to_register_mcf");
285             ConnectorRuntimeException cre = new
286             ConnectorRuntimeException( i18nMsg );
287             cre.initCause(ex);
288             _logger.log(Level.SEVERE,"rardeployment.mcf_registration_failure",
289                                      poolName);
290             _logger.log(Level.SEVERE,"",cre);
291             throw cre;
292         }
293     }
294
295     /** Creates connector connection pool in the connector container.
296      * cannot be used for 1.5 rar cases
297      * @param ccp ConnectorConnectionPool instance to be bound to JNDI. This
298      * object contains the pool properties.
299      * @param security unused
300      * @param configProperties MCF config properties
301      * @throws ConnectorRuntimeException When creation of pool fails.
302      */

303
304     public void createConnectorConnectionPool(
305                 ConnectorConnectionPool connectorPoolObj, String JavaDoc security,
306                 Set configProperties) throws ConnectorRuntimeException
307     {
308         if( connectorPoolObj == null || configProperties == null) {
309              _logger.log(Level.FINE,"Wrong parameters for pool creation ");
310         String JavaDoc i18nMsg = localStrings.getString(
311             "ccp_adm.wrong_params_for_create");
312             throw new ConnectorRuntimeException( i18nMsg );
313         }
314         String JavaDoc poolName = connectorPoolObj.getName();
315         String JavaDoc moduleName =
316                     connectorPoolObj.getConnectorDescriptorInfo().getRarName();
317         String JavaDoc connectionDefinitionName =
318                     connectorPoolObj.getConnectorDescriptorInfo().
319                     getConnectionDefinitionName();
320
321         ConnectorDescriptor connectorDescriptor =
322                     _registry.getDescriptor(moduleName);
323         if(connectorDescriptor == null) {
324             ifSystemRarLoad(moduleName);
325             connectorDescriptor = _registry.getDescriptor(moduleName);
326         }
327
328         if(connectorDescriptor == null) {
329         String JavaDoc i18nMsg = localStrings.getString(
330             "ccp_adm.null_connector_desc");
331             ConnectorRuntimeException cre = new
332             ConnectorRuntimeException( i18nMsg );
333              _logger.log(Level.SEVERE,"rardeployment.null_mcf_in_registry",
334                     moduleName);
335              _logger.log(Level.SEVERE,"", cre);
336             throw cre;
337         }
338
339         Set connectionDefs =
340           connectorDescriptor.getOutboundResourceAdapter().getConnectionDefs();
341
342         Iterator iterator = connectionDefs.iterator();
343
344         ConnectionDefDescriptor connectionDefDescriptor = null;
345
346         while(iterator.hasNext()){
347               connectionDefDescriptor =
348                        (ConnectionDefDescriptor) iterator.next();
349               if(connectionDefinitionName.equals(
350                        connectionDefDescriptor.getConnectionFactoryIntf()))
351                  break;
352         }
353
354         ConnectorDescriptorInfo connectorDescInfo =
355                  ConnectorDDTransformUtils.getConnectorDescriptorInfo(
356                  connectionDefDescriptor);
357         connectorDescInfo.setMCFConfigProperties(configProperties);
358         connectorDescInfo.setRarName(moduleName);
359         connectorDescInfo.setResourceAdapterClassName(
360                      connectorDescriptor.getResourceAdapterClass());
361
362         createConnectorConnectionPool(connectorPoolObj,connectorDescInfo);
363     }
364
365     /** Deletes connector Connection pool
366      * @param poolName Name of the pool to delete
367      * @throws ConnectorRuntimeException if pool deletion operation fails
368      */

369
370     public void deleteConnectorConnectionPool(String JavaDoc poolName)
371                                  throws ConnectorRuntimeException
372     {
373         deleteConnectorConnectionPool(poolName,false);
374     }
375
376     /** Deletes connector Connection pool. Here check in made whether resources
377      * pertaining to pool are present in domain.xml.
378      * @param poolName Name of the pool to delete
379      * @param cascade If true all the resources associed with that are also
380      * deleted from connector container
381      * If false and if some resources pertaining to pool
382      * are present deletion operation fails . If no resources
383      * are present pool is deleted.
384      * @throws ConnectorRuntimeException if pool deletion operation fails
385      */

386
387     public void deleteConnectorConnectionPool(String JavaDoc poolName,boolean cascade)
388                                  throws ConnectorRuntimeException
389     {
390
391         if(poolName==null){
392             _logger.log( Level.WARNING,"Deletion of pool : poolName null.");
393         String JavaDoc i18nMsg = localStrings.getString(
394             "ccp_adm.null_pool_name");
395             throw new ConnectorRuntimeException( i18nMsg );
396         }
397  
398         boolean errorOccured=false;
399         ResourcesUtil resUtil = ResourcesUtil.getInstance();
400         Object JavaDoc[] connectorResourcesJndiNames =
401                         resUtil.getConnectorResourcesJndiNames(poolName);
402         if(cascade==true && connectorResourcesJndiNames != null) {
403            for(int i=0;i<connectorResourcesJndiNames.length;++i) {
404                try {
405                    _runtime.deleteConnectorResource(
406                               (String JavaDoc)connectorResourcesJndiNames[i]);
407                } catch(ConnectorRuntimeException cre) {
408                  errorOccured=true;
409                }
410            }
411
412         } else if(connectorResourcesJndiNames != null &&
413                       connectorResourcesJndiNames.length != 0) {
414
415            // FIXME: ResourcesUtil class needs to change so that
416
// it is reference friendly.
417
// Refer to bug 5004451
418
/*
419         String i18nMsg = localStrings.getString(
420             "ccp_adm.connector_res_exist");
421             ConnectorRuntimeException cre = new
422             ConnectorRuntimeException( i18nMsg );
423            _logger.log(Level.SEVERE,"rardeployment.resources_exist",
424                                      poolName);
425            _logger.log(Level.SEVERE,"",cre);
426             throw cre;
427             */

428         }
429         killPool(poolName);
430         boolean result = _registry.removeManagedConnectionFactory(poolName);
431         if(result == false && !resUtil.poolBelongsToSystemRar(poolName)) {
432             _logger.log( Level.FINE,
433                            "rardeployment.mcf_removal_failure",poolName);
434             return;
435         }
436         try {
437             String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
438                 getReservePrefixedJNDINameForPool( poolName );
439             InitialContext ic = new InitialContext();
440             ic.unbind(jndiNameForPool);
441         } catch(NamingException ne) {
442             if(resUtil.poolBelongsToSystemRar(poolName)) {
443                 return;
444             }
445             _logger.log(Level.SEVERE,
446                    "rardeployment.connectionpool_removal_from_jndi_error",
447                    poolName);
448         String JavaDoc i18nMsg = localStrings.getString(
449             "ccp_adm.failed_to_remove_from_jndi");
450         ConnectorRuntimeException cre = new
451             ConnectorRuntimeException( i18nMsg );
452             cre.initCause(ne);
453             _logger.log(Level.SEVERE,"",cre);
454         throw cre;
455         }
456         if(errorOccured==true && !resUtil.poolBelongsToSystemRar(poolName)) {
457         String JavaDoc i18nMsg = localStrings.getString(
458             "ccp_adm.failed_to_delete_conn_res" );
459         ConnectorRuntimeException cre = new
460             ConnectorRuntimeException( i18nMsg );
461             _logger.log(Level.SEVERE,
462                 "rardeployment.all_resources_removal_error", poolName);
463             _logger.log(Level.SEVERE,"",cre);
464             throw cre;
465         }
466     }
467
468     /** unloads and kills the connector Connection pool without checking for
469      * resources in domain.xml.
470      * @param poolName Name of the pool to delete
471      * @throws ConnectorRuntimeException if pool unload or kill operation fails
472      */

473
474     private void unloadAndKillPool(String JavaDoc poolName)
475                        throws ConnectorRuntimeException
476     {
477
478         killPool(poolName);
479         boolean result = _registry.removeManagedConnectionFactory(poolName);
480         if(result == false) {
481             _logger.log( Level.SEVERE,
482                            "rardeployment.mcf_removal_failure",poolName);
483         String JavaDoc i18nMsg = localStrings.getString(
484             "ccp_adm.wrong_params_for_create");
485             ConnectorRuntimeException cre = new
486             ConnectorRuntimeException( i18nMsg );
487             _logger.log( Level.FINE,"",cre);
488             throw cre;
489         }
490         try {
491             String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
492                     getReservePrefixedJNDINameForPool(poolName);
493             InitialContext ic = new InitialContext();
494             ic.unbind(jndiNameForPool);
495         } catch(NamingException ne) {
496         String JavaDoc i18nMsg = localStrings.getString(
497             "ccp_adm.failed_to_remove_from_jndi");
498         ConnectorRuntimeException cre = new
499             ConnectorRuntimeException( i18nMsg );
500             cre.initCause(ne);
501             _logger.log(Level.SEVERE,
502                    "rardeployment.connectionpool_removal_from_jndi_error",
503                    poolName);
504             _logger.log(Level.FINE,"",cre);
505             throw cre;
506         }
507  
508     }
509
510     /**
511      * asadmin test-connection-pool
512      * This method is used to provide backend functionality for the
513      * test-connection-pool asadmin command. Briefly the design is as
514      * follows:<br>
515      * 1. obtainManagedConnection for the poolname<br>
516      * 2. lookup ConnectorDescriptorInfo from InitialContext using poolname<br>
517      * 3. from cdi get username and password<br>
518      * 4. create ResourcePrincipal using default username and password<br>
519      * 5. create a Subject from this (doPriveleged)<br>
520      * 6. createManagedConnection using above subject<br>
521      * 7. getConnection from the ManagedConnection with above subject<br>
522      *
523      * @return true if the connection pool is healthy. false otherwise
524      * @throws ResourceException if pool is not usable
525      */

526     public boolean testConnectionPool( String JavaDoc poolName )
527             throws ResourceException {
528         dump(poolName);
529     Object JavaDoc con = null;
530     DASResourcesUtil dasResUtil = null;
531     try {
532         //Since ping works only in DAS right now, we know for sure that
533
//the ResourcesUtil that we are using is definitely DASResourcesUtil
534
dasResUtil = (DASResourcesUtil) ResourcesUtil.getInstance();
535             dasResUtil.setGetConnectionFromConnectorRuntime( true );
536
537         //Create the ManagedConnection
538
con = getUnpooledConnection( poolName, null, false );
539         
540     } catch( Exception JavaDoc re ) {
541         //Since we have an exception, the pool is not good
542
_logger.log(Level.WARNING, re.getMessage() );
543             ResourceException e = new ResourceException( re.getMessage());
544         e.initCause( re );
545         throw e;
546     } finally {
547         try {
548             //destroy the MC
549
dasResUtil.setGetConnectionFromConnectorRuntime( false );
550         ((ManagedConnection)con).destroy();
551
552         } catch( Throwable JavaDoc e ) {
553             //ignore
554
}
555     }
556         
557     //We did not get a ResourceException, so pool must be OK
558
return true;
559     }
560     
561     /*
562      * Returns a ResourcePrincipal object populated with a pool's
563      * default USERNAME and PASSWORD
564      *
565      * @throws NamingException if poolname lookup fails
566      */

567     private ResourcePrincipal getDefaultResourcePrincipal( String JavaDoc poolName,
568         ManagedConnectionFactory mcf ) throws NamingException {
569         // All this to get the default user name and principal
570
ConnectorConnectionPool connectorConnectionPool = null;
571         try {
572             String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
573                 getReservePrefixedJNDINameForPool( poolName );
574             InitialContext ic = new InitialContext();
575             connectorConnectionPool =
576                     (ConnectorConnectionPool) ic.lookup(jndiNameForPool);
577     } catch (NamingException ne ) {
578         throw ne;
579     }
580     
581         ConnectorDescriptorInfo cdi = connectorConnectionPool.
582             getConnectorDescriptorInfo();
583         
584         Set mcfConfigProperties = cdi.getMCFConfigProperties();
585         Iterator mcfConfPropsIter = mcfConfigProperties.iterator();
586         String JavaDoc userName = null;
587         String JavaDoc password = null;
588         while( mcfConfPropsIter.hasNext() ) {
589             EnvironmentProperty prop =
590             (EnvironmentProperty)mcfConfPropsIter.next();
591             
592             if ( prop.getName().toUpperCase().equals("USERNAME") ||
593                  prop.getName().toUpperCase().equals("USER") ) {
594                 userName = prop.getValue();
595             } else if ( prop.getName().toUpperCase().equals("PASSWORD") ) {
596                 password = prop.getValue();
597                 try{
598                     password = RelativePathResolver.getRealPasswordFromAlias(password);
599                 }catch(Exception JavaDoc e){
600                     _logger.log(Level.WARNING,"unable_to_get_password_from_alias",e);
601                 }
602             }
603         }
604
605         // To avoid using "", "" as the default username password, try to get
606
// the username and password from MCF, to use in subject. MQ adapter
607
// cannot use "","" as the username/password.
608

609         if (userName == null || userName.trim().equals("")) {
610             userName = ConnectionPoolObjectsUtils.getValueFromMCF("UserName", poolName, mcf);
611             password = ConnectionPoolObjectsUtils.getValueFromMCF("Password", poolName, mcf);
612         }
613         //Now return the ResourcePrincipal
614
return new ResourcePrincipal( userName, password );
615     }
616
617     /**
618      * Dynamic reconfig
619      * Reconfigure a connection pool.
620      * This method compares the passed connector connection pool with the one
621      * in memory. If the pools are unequal and the MCF properties are changed
622      * a pool recreate is required. However if the pools are unequal and the
623      * MCF properties are not changed a recreate is not required
624      *
625      * @param ccp - the Updated connector connection pool object that admin
626      * hands over
627      * @return true - if a pool restart is required, false otherwise
628      * @throws ConnectorRuntimeException
629      */

630     public boolean reconfigureConnectorConnectionPool( ConnectorConnectionPool
631             ccp ) throws ConnectorRuntimeException
632     {
633         return reconfigureConnectorConnectionPool( ccp, new HashSet());
634     }
635
636     /**
637      * Rebinds the connection pool with matchning flag set.
638      *
639      * @param matching Either true or false.
640      * @throws ConnectorRuntimeException , if a Naming error occurs.
641      */

642     public void switchOnMatching(String JavaDoc poolName) throws ConnectorRuntimeException {
643         try {
644             ConnectorConnectionPool origCcp =
645             getOriginalConnectorConnectionPool( poolName );
646             origCcp.setMatchConnections(true);
647
648             //now rebind the object in jndi
649
String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
650                 getReservePrefixedJNDINameForPool( poolName );
651             
652             InitialContext ic = new InitialContext();
653             ic.unbind( jndiNameForPool );
654             Switch.getSwitch().getNamingManager().publishObject(
655             jndiNameForPool, (Object JavaDoc)origCcp, true );
656         } catch (NamingException e) {
657             ConnectorRuntimeException ex =
658             new ConnectorRuntimeException( e.getMessage());
659             throw (ConnectorRuntimeException) ex.initCause(e);
660         }
661
662     }
663
664     /**
665      * Reconfigure a connection pool.
666      * This method compares the passed connector connection pool with the one
667      * in memory. If the pools are unequal and the MCF properties are changed
668      * a pool recreate is required. However if the pools are unequal and the
669      * MCF properties are not changed a recreate is not required
670      *
671      * @param ccp - the Updated connector connection pool object that admin
672      * hands over
673      * @param excludedProps - A set of excluded property names that we want
674      * to be excluded in the comparison check while
675      * comparing MCF properties
676      * @return true - if a pool restart is required, false otherwise
677      * @throws ConnectorRuntimeException
678      */

679     public boolean reconfigureConnectorConnectionPool( ConnectorConnectionPool
680             ccp, Set excludedProps ) throws ConnectorRuntimeException
681     {
682         //see if the new ConnectorConnectionPool is different from
683
//the original one and update relevant properties
684
String JavaDoc poolName = ccp.getName();
685         ConnectorConnectionPool origCcp = null;
686     try {
687             origCcp = getOriginalConnectorConnectionPool( poolName );
688     } catch( NamingException ne) {
689         throw new ConnectorRuntimeException( ne.getMessage() );
690     }
691     
692     logFine("origCcp :\n" + ((origCcp != null) ? origCcp.toString() : "null"));
693     logFine("ccp :\n" + ((ccp != null) ? ccp.toString(): "null"));
694
695     ReconfigAction action = ConnectionPoolReconfigHelper.compare( origCcp, ccp,
696         excludedProps );
697     
698     if ( action == ReconfigAction.UPDATE_MCF_AND_ATTRIBUTES ) {
699         logFine( "@@@@ action == " + action);
700         updateMCFAndPoolAttributes( ccp );
701     } else if ( action == ReconfigAction.RECREATE_POOL ) {
702         logFine( "@@@@ action == " + action);
703         return true;
704     }
705
706     return false;
707     }
708     
709     /*
710      * Create a ConnectorConnectionPool from information in memory
711      */

712     private ConnectorConnectionPool getOriginalConnectorConnectionPool(
713             String JavaDoc poolName ) throws NamingException
714     {
715             
716     ConnectorConnectionPool ccpOrig = null;
717     
718         String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
719             getReservePrefixedJNDINameForPool( poolName );
720         InitialContext ic = new InitialContext();
721         try {
722             ccpOrig = (ConnectorConnectionPool) ic.lookup( jndiNameForPool );
723         } catch(NamingException ne) {
724             if(checkAndLoadPoolResource(poolName)) {
725                 ccpOrig = (ConnectorConnectionPool)ic.lookup( jndiNameForPool );
726             } else {
727                 throw ne;
728             }
729
730         }
731     
732         return ccpOrig;
733     }
734
735     private void updateMCFAndPoolAttributes( ConnectorConnectionPool
736             ccp ) throws ConnectorRuntimeException
737     {
738         String JavaDoc poolName = ccp.getName();
739         try {
740             ConnectorConnectionPool origCcp =
741             getOriginalConnectorConnectionPool( poolName );
742             
743             //update properties
744
origCcp.setSteadyPoolSize(ccp.getSteadyPoolSize());
745             origCcp.setMaxPoolSize(ccp.getMaxPoolSize());
746             origCcp.setMaxWaitTimeInMillis(ccp.getMaxWaitTimeInMillis());
747             origCcp.setPoolResizeQuantity(ccp.getPoolResizeQuantity());
748             origCcp.setIdleTimeoutInSeconds(ccp.getIdleTimeoutInSeconds());
749             origCcp.setFailAllConnections(ccp.isFailAllConnections());
750             
751         //lazyEnlist, lazyAssoc and assocWithThread not required since they result
752
//in a pool restart anyways, so they wouldn't have changed if we
753
//came here
754
origCcp.setMatchConnections( ccp.matchConnections() );
755             origCcp.setNonComponent( ccp.isNonComponent() );
756             origCcp.setNonTransactional( ccp.isNonTransactional() );
757
758             //now rebind the object in jndi
759
String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
760                 getReservePrefixedJNDINameForPool( poolName );
761             InitialContext ic = new InitialContext();
762             ic.unbind( jndiNameForPool );
763             Switch.getSwitch().getNamingManager().publishObject(
764             jndiNameForPool, (Object JavaDoc)origCcp, true );
765     
766         } catch( NamingException ne ) {
767             throw new ConnectorRuntimeException( ne.getMessage() ) ;
768         }
769
770     //Check if this pool has been brought into memory
771
//If its already in memory, just call reconfig on it
772

773         PoolManager poolMgr = Switch.getSwitch().getPoolManager();
774         try {
775             poolMgr.reconfigPoolProperties( ccp );
776         } catch( PoolingException pe ) {
777             throw new ConnectorRuntimeException( pe.getMessage() );
778         }
779     //Run setXXX methods on the copy of the MCF that we have
780
//this is done to update the MCF to reflect changes in the
781
//MCF properties for which we don't really need to recreate
782
//the pool
783
ConnectorRegistry registry = ConnectorRegistry.getInstance();
784         ManagedConnectionFactory mcf = registry.getManagedConnectionFactory(
785                     poolName );
786         SetMethodAction sma = new SetMethodAction( mcf,
787             ccp.getConnectorDescriptorInfo().getMCFConfigProperties() );
788         try {
789             sma.run();
790         } catch( Exception JavaDoc e) {
791             _logger.log( Level.WARNING, e.getMessage() );
792             ConnectorRuntimeException cre = new ConnectorRuntimeException(e.getMessage());
793             cre.initCause( e );
794             throw cre;
795         }
796         
797         //update the properties "allow-non-component-callers" and
798
//"non-transactional-connections" in the PoolMetaData
799
PoolMetaData pmd = registry.getPoolMetaData( poolName );
800         pmd.setIsPM( ccp.isNonComponent() );
801         pmd.setIsNonTx( ccp.isNonTransactional() );
802         pmd.setLazyEnlistable( ccp.isLazyConnectionEnlist() );
803         pmd.setAuthCredentialsDefinedInPool(ccp.getAuthCredentialsDefinedInPool());
804         
805         logFine("Pool properties reconfiguration done");
806     }
807    
808     /**
809      * Recreate a connector connection pool. This method essentially does
810      * the following things:
811      * 1. Delete the said connector connection pool<br>
812      * 2. Bind the pool to JNDI<br>
813      * 3. Create an MCF for this pool and register with the connector registry<br>
814      *
815      * @param ccp - the ConnectorConnectionPool to publish
816      */

817     public void recreateConnectorConnectionPool( ConnectorConnectionPool ccp)
818         throws ConnectorRuntimeException
819     {
820         ConnectorRegistry registry = ConnectorRegistry.getInstance();
821         if (registry == null ) {
822             throw new ConnectorRuntimeException(
823             "Cannot get ConnectorRegistry");
824         }
825     String JavaDoc poolName = ccp.getName();
826     //First remove this pool from memory
827
try {
828         unloadAndKillPool( poolName );
829         } catch( ConnectorRuntimeException cre ) {
830        throw cre;
831     }
832     //kill the pool
833
//FIXME: deleteConnectorConnectionPool should do this
834
//PoolManager poolManager = Switch.getSwitch().getPoolManager();
835
//poolManager.killPool( poolName );
836

837     //Now bind the updated pool and
838
//obtain a new managed connection factory for this pool
839
try {
840         String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
841                 getReservePrefixedJNDINameForPool( poolName );
842         Switch.getSwitch().getNamingManager().publishObject(
843         jndiNameForPool, (Object JavaDoc)ccp, true );
844         ManagedConnectionFactory mcf = null;
845         mcf = obtainManagedConnectionFactory( poolName );
846         if (mcf == null ) {
847                 InitialContext ic = new InitialContext();
848             ic.unbind( jndiNameForPool );
849             _logger.log(Level.WARNING,
850                        "rardeployment.mcf_creation_failure", poolName);
851                
852             String JavaDoc i18nMsg = localStrings.getString(
853                 "ccp_adm.failed_to_create_mcf");
854                 throw new ConnectorRuntimeException( i18nMsg );
855         }
856
857     } catch( NamingException ne ) {
858         _logger.log(Level.SEVERE,
859         "rardeployment.pool_jndi_bind_failure", poolName );
860         String JavaDoc i18nMsg = localStrings.getString(
861             "ccp_adm.could_not_recreate_pool");
862             ConnectorRuntimeException crex = new ConnectorRuntimeException( i18nMsg );
863             crex.initCause(ne);
864             throw crex;
865     }
866
867     }
868     /** Returns the MCF instance. If the MCF is already created and
869      * present in connectorRegistry that instance is returned. Otherwise it
870      * is created explicitly and added to ConnectorRegistry.
871      * @param poolName Name of the pool.MCF pertaining to this pool is
872      * created/returned.
873      * @return created/already present MCF instance
874      * @throws ConnectorRuntimeException if creation/retrieval of MCF fails
875      */

876     public ManagedConnectionFactory obtainManagedConnectionFactory(
877            String JavaDoc poolName) throws ConnectorRuntimeException
878     {
879         try {
880             if (_registry.isMCFCreated(poolName)) {
881                 return _registry.getManagedConnectionFactory( poolName );
882             } else {
883                 String JavaDoc jndiNameForPool = ConnectorAdminServiceUtils.
884                     getReservePrefixedJNDINameForPool ( poolName );
885                 InitialContext ic = new InitialContext();
886                 ConnectorConnectionPool connectorConnectionPool =
887                         (ConnectorConnectionPool) ic.lookup(jndiNameForPool);
888                 if(connectorConnectionPool == null) {
889                 String JavaDoc i18nMsg = localStrings.getString(
890                     "ccp_adm.null_pool");
891                      ConnectorRuntimeException cre = new
892                  ConnectorRuntimeException( i18nMsg );
893                     _logger.log(Level.SEVERE,
894                         "rardeployment.connectionpool_object_null",poolName);
895             if (_logger.isLoggable( Level.FINE ) ) {
896                         _logger.log(Level.FINE,"",cre);
897             }
898                     throw cre;
899                 }
900
901                 String JavaDoc rarName = connectorConnectionPool.
902                                   getConnectorDescriptorInfo().getRarName();
903                 ActiveResourceAdapter activeResourceAdapter =
904                                   _registry.getActiveResourceAdapter(rarName);
905                 if(activeResourceAdapter == null) {
906                     ifSystemRarLoad(rarName);
907                     activeResourceAdapter =
908                              _registry.getActiveResourceAdapter(rarName);
909                 }
910                 if( activeResourceAdapter == null) {
911                 String JavaDoc i18nMsg = localStrings.getString(
912                     "ccp_adm.active_ra_not_init");
913                     
914                     ConnectorRuntimeException cre = new
915                 ConnectorRuntimeException( i18nMsg );
916                     _logger.log(Level.SEVERE,
917                       "rardeployment.resourceadapter_not_initialized",rarName);
918             if (_logger.isLoggable( Level.FINE ) ) {
919                         _logger.log(Level.FINE,"",cre);
920             }
921             throw cre;
922                 }
923                 ManagedConnectionFactory mcf =
924                      activeResourceAdapter.createManagedConnectionFactory(
925                                   connectorConnectionPool, null);
926                 if(mcf != null) {
927             ResourcePrincipal prin =
928                 getDefaultResourcePrincipal(poolName,mcf);
929             Subject s = ConnectionPoolObjectsUtils.createSubject(mcf, prin);
930             int txSupport = connectorConnectionPool.getTransactionSupport();
931
932                     boolean isPM = connectorConnectionPool.isNonComponent();
933                     boolean isNonTx = connectorConnectionPool.isNonTransactional();
934                     ConnectorSecurityMap[] securityMaps =
935                         connectorConnectionPool.getSecurityMaps();
936                     RuntimeSecurityMap runtimeSecurityMap =
937                         SecurityMapUtils.processSecurityMaps(securityMaps);
938                     boolean lazyEnlistable = connectorConnectionPool.isLazyConnectionEnlist();
939                     boolean lazyAssoc = connectorConnectionPool.isLazyConnectionAssoc();
940                     if ( isPM || isNonTx ) {
941                         /*
942                         We should not do lazyEnlistment if we are an __pm
943                         resource since we won't have an InvocationContext and
944                         the lazy enlistment depends upon an InvocationContext
945                         For a nonTx resource enlistment (lazy or otherwise)
946                         doesn't come into the picture at all
947                         */

948                         lazyEnlistable = false;
949                     }
950
951                     if ( isPM ) {
952                         //We need to switch off lazy association here because of
953
//the way our Persistence layer behaves. Adding a system
954
//property here to allow other persistence layers to use
955
//lazy association with PM resources
956
String JavaDoc str = System.getProperty(
957                             "com.sun.enterprise.resource.AllowLazyAssociationWithPM");
958                         if ( str != null && str.toUpperCase().trim().equals("TRUE") ) {
959                             lazyAssoc = lazyAssoc & true;
960                         } else {
961                             lazyAssoc = false;
962                         }
963                     }
964
965             PoolMetaData pmd = new PoolMetaData(poolName, mcf, s, txSupport, prin,
966                         isPM, isNonTx, lazyEnlistable, runtimeSecurityMap, lazyAssoc);
967             logFine( pmd.toString() );
968                     _registry.addManagedConnectionFactory(poolName, pmd);
969                 }
970         
971                 
972                 PoolType pt = (connectorConnectionPool.isAssociateWithThread() ?
973                     PoolType.ASSOCIATE_WITH_THREAD_POOL :
974                     PoolType.STANDARD_POOL );
975
976         createAndAddPool( poolName, pt );
977         return mcf;
978             }
979         } catch(NamingException ne) {
980         String JavaDoc i18nMsg = localStrings.getString(
981             "pingpool.name_not_bound");
982             ConnectorRuntimeException cre = new
983             ConnectorRuntimeException( i18nMsg);
984             cre.initCause(ne);
985             _logger.log(Level.FINE,"rardeployment.jndi_lookup_failed",
986                                poolName);
987         if (_logger.isLoggable( Level.FINE ) ) {
988                 _logger.log(Level.FINE,"",cre);
989         }
990             //_logger.log(Level.SEVERE,"",cre);
991
throw cre;
992         }
993         catch(NullPointerException JavaDoc ne) {
994         String JavaDoc i18nMsg = localStrings.getString(
995             "ccp_adm.failed_to_register_mcf");
996             ConnectorRuntimeException cre = new
997             ConnectorRuntimeException( i18nMsg );
998             cre.initCause(ne);
999             _logger.log(Level.SEVERE,"mcf_add_toregistry_failed",poolName);
1000        if (_logger.isLoggable( Level.FINE ) ) {
1001                _logger.log(Level.FINE,"",cre);
1002        }
1003            //_logger.log(Level.SEVERE,"",cre);
1004
throw cre;
1005        }
1006    }
1007
1008    /**
1009     * Kills all the pools pertaining to the rar module.
1010     * @moduleName Rar module Name
1011     */

1012
1013    public void killAllPools(String JavaDoc moduleName) {
1014
1015        ResourcesUtil resUtil = ResourcesUtil.getInstance();
1016        Object JavaDoc[] poolNamesArray = resUtil.getConnectorConnectionPoolNames(
1017                                           moduleName);
1018        String JavaDoc poolName=null;
1019        for(int i=0;poolNamesArray != null && i<poolNamesArray.length;i++) {
1020            poolName = (String JavaDoc)poolNamesArray[i];
1021            killPool(poolName);
1022        }
1023    }
1024
1025    /**
1026     * Kills a specific pool
1027     * @param poolName poolName to kill
1028     */

1029
1030    public void killPool(String JavaDoc poolName) {
1031        Switch.getSwitch().getPoolManager().killPool(poolName);
1032    }
1033
1034       /**
1035         * Gets the properties of the Java bean connection definition class that
1036         * have setter methods defined
1037         *
1038         * @param connectionDefinitionClassName
1039         * The Connection Definition Java bean class for which
1040         * overrideable properties are required.
1041         * @return A Set of properties that have a setter method defined in the
1042         * Connection Definition class
1043         */

1044    public static Set getConnectionDefinitionProperties(String JavaDoc connectionDefinitionClassName) {
1045        return ConnectionDefinitionUtils.getConnectionDefinitionProperties(
1046            connectionDefinitionClassName);
1047    }
1048                                                                                                                                               
1049        /**
1050         * Gets the properties of the Java bean connection definition class that
1051         * have setter methods defined and the default values as provided by the
1052         * Connection Definition java bean developer.
1053         *
1054         * @param connectionDefinitionClassName
1055         * The Connection Definition Java bean class for which
1056         * overrideable properties are required.
1057         * @return Map [property, defaultValue]
1058         */

1059    public static Map getConnectionDefinitionPropertiesAndDefaults(String JavaDoc connectionDefinitionClassName) {
1060        return ConnectionDefinitionUtils
1061            .getConnectionDefinitionPropertiesAndDefaults(
1062            connectionDefinitionClassName);
1063    }
1064
1065    /**
1066     * This method is used to provide backend functionality for the
1067     * ping-connection-pool asadmin command. Briefly the design is as
1068     * follows:<br>
1069     * 1. obtainManagedConnectionFactory for the poolname<br>
1070     * 2. lookup ConnectorDescriptorInfo from InitialContext using poolname<br>
1071     * 3. from cdi get username and password<br>
1072     * 4. create ResourcePrincipal using default username and password<br>
1073     * 5. create a Subject from this (doPriveleged)<br>
1074     * 6. createManagedConnection using above subject<br>
1075     * 7. add a dummy ConnectionEventListener to the mc that simply handles connectionClosed
1076     * 8. getConnection from the ManagedConnection with above subject<br>
1077     *
1078     * @param poolName The poolname from whose MCF to obtain the unpooled mc
1079     * @param prin The ResourcePrincipal to use for authenticating the request if not null.
1080                       If null, the pool's default authentication mechanism is used
1081     * @param returnConnectionHandle If true will return the logical connection handle
1082     * derived from the Managed Connection, else will only return mc
1083     *
1084     * @return an unPooled connection
1085     * @throws ResourceException for various error conditions
1086     */

1087
1088    private Object JavaDoc getUnpooledConnection( String JavaDoc poolName, ResourcePrincipal prin,
1089            boolean returnConnectionHandle)
1090            throws ResourceException
1091    {
1092        //Get the ManagedConnectionFactory for this poolName
1093
ManagedConnectionFactory mcf = null;
1094    boolean needToUndeployPool = false;
1095        com.sun.enterprise.config.serverbeans.JdbcConnectionPool
1096        jdbcPoolToDeploy = null;
1097        com.sun.enterprise.config.serverbeans.ConnectorConnectionPool
1098        ccPoolToDeploy = null;
1099
1100
1101        try {
1102        mcf = obtainManagedConnectionFactory( poolName );
1103        
1104    } catch( ConnectorRuntimeException cre ) {
1105            logFine("getUnpooledConnection :: obtainManagedConnectionFactory " +
1106            "threw exception. SO doing checkAndLoadPoolResource");
1107            if(checkAndLoadPoolResource(poolName)) {
1108                logFine("getUnpooledConnection:: checkAndLoadPoolResource is true");
1109                try {
1110            //deploy the pool resource if not already done
1111
//The pool resource would get loaded in case we are in DAS
1112
//due to the checkAndLoadPoolResource call
1113
//but in EE, if the pool we are trying to access is in a
1114
//remote instance, the pool will not have been created
1115
if ( ! isConnectorConnectionPoolDeployed( poolName ) ) {
1116                        logFine("getUnpooledConnection :: " +
1117                "isConnectorConnectionPoolDeployed is false");
1118                try {
1119                    jdbcPoolToDeploy = getJdbcConnectionPoolServerBean( poolName );
1120                if ( jdbcPoolToDeploy != null ) {
1121                        (new JdbcConnectionPoolDeployer()).deployResource(
1122                        jdbcPoolToDeploy );
1123                                logFine("getUnpooledConnection :: force deployed the " +
1124                        "JdbcConnectionPool : " + poolName);
1125                } else {
1126                    ccPoolToDeploy = getConnectorConnectionPoolServerBean(
1127                    poolName );
1128                    (new ConnectorConnectionPoolDeployer()).deployResource(
1129                    ccPoolToDeploy);
1130                                logFine("getUnpooledConnection :: force deployed the " +
1131                        "ConnectorConnectionPool :" + poolName);
1132                }
1133                needToUndeployPool = true;
1134                } catch(Exception JavaDoc e ) {
1135                    _logger.log( Level.SEVERE,
1136                        "jdbc.could_not_do_actual_deploy for : ", poolName );
1137                    throw new ResourceException( e );
1138                }
1139            }
1140                    logFine("getUnpooledConnection :: " +
1141                "Now calling obtainManagedConnectionFactory again");
1142                mcf = obtainManagedConnectionFactory( poolName );
1143                    logFine("getUnpooledConnection:: " +
1144                "done obtainManagedConnectionFactory again");
1145            } catch( ConnectorRuntimeException creAgain ) {
1146            String JavaDoc l10nMsg = localStrings.getString(
1147                "pingpool.cannot_obtain_mcf");
1148            _logger.log( Level.WARNING, "jdbc.pool_not_reachable",
1149                        l10nMsg );
1150            ResourceException e = new ResourceException( l10nMsg );
1151            e.initCause( creAgain );
1152            throw e;
1153                }
1154            } else {
1155            _logger.log( Level.WARNING, "jdbc.pool_not_reachable",
1156                         cre.getMessage() );
1157        String JavaDoc l10nMsg = localStrings.getString(
1158                "pingpool.cannot_obtain_mcf");
1159                ResourceException e = new ResourceException( l10nMsg );
1160                e.initCause( cre );
1161                throw e;
1162
1163            }
1164    }
1165        
1166    
1167        ResourcePrincipal resourcePrincipal = null;
1168    if (prin == null ) {
1169        try {
1170                resourcePrincipal = getDefaultResourcePrincipal( poolName, mcf);
1171            } catch( NamingException ne) {
1172            _logger.log(Level.WARNING, "jdbc.pool_not_reachable",
1173                            ne.getMessage() );
1174                String JavaDoc l10nMsg = localStrings.getString(
1175                "pingpool.name_not_bound");
1176                ResourceException e = new ResourceException( l10nMsg + poolName );
1177            e.initCause( ne );
1178            throw e;
1179        }
1180    } else {
1181        resourcePrincipal = prin;
1182    }
1183        
1184    final Subject defaultSubject =
1185            ConnectionPoolObjectsUtils.createSubject( mcf, resourcePrincipal);
1186
1187      
1188    if (_logger.isLoggable(Level.FINE)) {
1189        _logger.fine("using subject: " + defaultSubject);
1190        
1191    }
1192        
1193    ManagedConnection mc = null;
1194    //Create the ManagedConnection
1195
mc = mcf.createManagedConnection( defaultSubject, null );
1196
1197    //We are done with the pool for now, so undeploy if we deployed
1198
//it here
1199
if ( needToUndeployPool ) {
1200        if (jdbcPoolToDeploy != null ) {
1201        logFine("getUnpooledConnection :: need to force undeploy pool");
1202                try {
1203                    (new JdbcConnectionPoolDeployer()).undeployResource(
1204                        jdbcPoolToDeploy );
1205                } catch( Exception JavaDoc e ) {
1206                    _logger.fine( "getUnpooledConnection: error undeploying pool");
1207                }
1208            logFine("getUnpooledConnection :: done.. force undeploy of pool");
1209        } else {
1210            try {
1211                    (new ConnectorConnectionPoolDeployer()).undeployResource(
1212                        ccPoolToDeploy );
1213                } catch( Exception JavaDoc e ) {
1214                    _logger.fine( "getUnpooledConnection: error undeploying pool");
1215                }
1216            logFine("getUnpooledConnection :: done.. force undeploy of pool");
1217            }
1218        }
1219
1220    //Add our dummy ConnectionEventListener impl.
1221
//This impl only knows how to handle connectionClosed events
1222
UnpooledConnectionEventListener el = new
1223        UnpooledConnectionEventListener();
1224    mc.addConnectionEventListener( new UnpooledConnectionEventListener() );
1225        return returnConnectionHandle ?
1226        mc.getConnection( defaultSubject, null ) :
1227        mc;
1228    }
1229    
1230    /**
1231     * Get a sql connection from the DataSource specified by the jdbcJndiName.
1232     * This API is intended to be used in the DAS. The motivation for having this
1233     * API is to provide the CMP backend a means of acquiring a connection during
1234     * the codegen phase. If a user is trying to deploy an app on a remote server,
1235     * without this API, a resource reference has to be present both in the DAS
1236     * and the server instance. This makes the deployment more complex for the
1237     * user since a resource needs to be forcibly created in the DAS Too.
1238     * This API will mitigate this need.
1239     *
1240     * @param jndiName the jndi name of the resource being used to get Connection from
1241     * This resource can either be a pmf resource or a jdbc resource
1242     * @param user the user used to authenticate this request
1243     * @param password the password used to authenticate this request
1244     *
1245     * @return a java.sql.Connection
1246     * @throws java.sql.SQLException in case of errors
1247     */

1248    public Connection JavaDoc getConnection(String JavaDoc jndiName, String JavaDoc user, String JavaDoc password)
1249            throws SQLException JavaDoc
1250    {
1251             
1252        DASResourcesUtil dasResUtil = (DASResourcesUtil) ResourcesUtil.getInstance();
1253    dasResUtil.setGetConnectionFromConnectorRuntime( true );
1254    String JavaDoc poolName = getPoolNameFromResourceJndiName( jndiName );
1255        if (_logger.isLoggable(Level.FINE)) {
1256        _logger.fine("ConnectorRuntime.getConnection :: poolName : " + poolName );
1257    }
1258    java.sql.Connection JavaDoc con = null;
1259    try {
1260        //Maintain consitency with the ConnectionManagerImpl change to be checked in later
1261
String JavaDoc passwd = (password == null ) ? "" : password;
1262
1263        //From what we have seen so far, the user cannot be null
1264
//but password can be
1265
//if user is null we will use default authentication
1266
//TODO: Discuss if this is the right thing to do
1267
ResourcePrincipal prin = (user == null) ?
1268            null : new ResourcePrincipal(user, password);
1269        con = (java.sql.Connection JavaDoc) getUnpooledConnection( poolName, prin, true);
1270        if ( con == null ) {
1271            String JavaDoc i18nMsg = localStrings.getString(
1272               "ccp_adm.null_unpooled_connection");
1273        SQLException JavaDoc sqle = new SQLException JavaDoc( i18nMsg );
1274        throw sqle;
1275        }
1276    } catch( ResourceException re ) {
1277        SQLException JavaDoc sqle = new SQLException JavaDoc( re.getMessage() );
1278        sqle.initCause( re );
1279        _logger.log( Level.WARNING, "jdbc.exc_get_conn", re.getMessage());
1280        if (_logger.isLoggable(Level.FINE)) {
1281            _logger.fine( " getConnection in ConnectorRuntime failed : " + re );
1282        }
1283    } finally {
1284        try {
1285            dasResUtil.setGetConnectionFromConnectorRuntime( false );
1286        } catch( Exception JavaDoc e ) {
1287        if (_logger.isLoggable(Level.FINE)) {
1288                _logger.fine("caught exception while setting " +
1289                "getConnectionFromConnectorRuntime to false");
1290        }
1291        }
1292
1293    }
1294
1295    return con;
1296    }
1297
1298    /**
1299     * Get a sql connection from the DataSource specified by the jdbcJndiName.
1300     * This API is intended to be used in the DAS. The motivation for having this
1301     * API is to provide the CMP backend a means of acquiring a connection during
1302     * the codegen phase. If a user is trying to deploy an app on a remote server,
1303     * without this API, a resource reference has to be present both in the DAS
1304     * and the server instance. This makes the deployment more complex for the
1305     * user since a resource needs to be forcibly created in the DAS Too.
1306     * This API will mitigate this need.
1307     *
1308     * @param jndiName the jndi name of the resource being used to get Connection from
1309     * This resource can either be a pmf resource or a jdbc resource
1310     *
1311     * @return a java.sql.Connection
1312     * @throws java.sql.SQLException in case of errors
1313     */

1314    public Connection JavaDoc getConnection(String JavaDoc jndiName)
1315            throws SQLException JavaDoc
1316    {
1317    java.sql.Connection JavaDoc con = null;
1318    DASResourcesUtil dasResUtil = null;
1319    try {
1320        dasResUtil = (DASResourcesUtil) ResourcesUtil.getInstance();
1321        dasResUtil.setGetConnectionFromConnectorRuntime( true );
1322        String JavaDoc poolName = getPoolNameFromResourceJndiName( jndiName );
1323            if (_logger.isLoggable(Level.FINE)) {
1324            _logger.fine("ConnectorRuntime.getConnection :: poolName : "
1325            + poolName );
1326        }
1327        con = (java.sql.Connection JavaDoc) getUnpooledConnection( poolName, null,
1328            true );
1329        if ( con == null ) {
1330            String JavaDoc i18nMsg = localStrings.getString(
1331               "ccp_adm.null_unpooled_connection");
1332        SQLException JavaDoc sqle = new SQLException JavaDoc( i18nMsg );
1333        throw sqle;
1334        }
1335    } catch( ResourceException re ) {
1336        SQLException JavaDoc sqle = new SQLException JavaDoc( re.getMessage() );
1337        sqle.initCause( re );
1338        _logger.log( Level.WARNING, "jdbc.exc_get_conn", re.getMessage());
1339        if (_logger.isLoggable(Level.FINE)) {
1340            _logger.fine( "Exception : " + re );
1341        }
1342        throw sqle;
1343    } finally {
1344        try {
1345            dasResUtil.setGetConnectionFromConnectorRuntime( false );
1346        } catch( Exception JavaDoc e ) {
1347        if (_logger.isLoggable(Level.FINE)) {
1348                _logger.fine("caught exception while setting " +
1349                "getConnectionFromConnectorRuntime to false");
1350        }
1351        }
1352    }
1353
1354    return con;
1355    }
1356   
1357    /**
1358     * Gets the Pool name that this JDBC resource points to. In case of a PMF resource
1359     * gets the pool name of the pool pointed to by jdbc resource being pointed to by
1360     * the PMF resource
1361     *
1362     * @param jndiName the jndi name of the resource being used to get Connection from
1363     * This resource can either be a pmf resource or a jdbc resource
1364     * @return poolName of the pool that this resource directly/indirectly points to
1365     */

1366    private String JavaDoc getPoolNameFromResourceJndiName( String JavaDoc jndiName) {
1367        String JavaDoc poolName = null ;
1368        JdbcResource jdbcRes = null;
1369        DASResourcesUtil resourcesUtil = (DASResourcesUtil)ResourcesUtil.getInstance();
1370    
1371        //check if the jndi name is that of a pmf resource or a jdbc resource
1372
if (resourcesUtil.isPMFResource( jndiName)) {
1373        jdbcRes = resourcesUtil.getJdbcResourceByJndiName(
1374                resourcesUtil.getPMFResourceByJndiName(jndiName ).
1375                getJdbcResourceJndiName());
1376    } else {
1377        jdbcRes = resourcesUtil.getJdbcResourceByJndiName(jndiName);
1378    }
1379
1380    if ( jdbcRes != null ) {
1381            if (_logger.isLoggable(Level.FINE)) {
1382            _logger.fine( "jdbcRes is ---: " + jdbcRes.getJndiName() );
1383            _logger.fine( "poolName is ---: " + jdbcRes.getPoolName() );
1384        }
1385    }
1386    return jdbcRes == null ? null : jdbcRes.getPoolName();
1387    }
1388
1389    /**
1390     * Checks if a conncetor connection pool has been deployed to this server
1391     * instance
1392     * @param poolName
1393     * @return
1394     */

1395    public boolean isConnectorConnectionPoolDeployed(String JavaDoc poolName) {
1396        try {
1397            InitialContext ic = new InitialContext();
1398            String JavaDoc jndiName = ConnectorAdminServiceUtils.
1399                    getReservePrefixedJNDINameForPool( poolName );
1400            ic.lookup(jndiName);
1401            return true;
1402        } catch (NamingException e) {
1403            return false;
1404        }
1405    }
1406    
1407    private void dump(String JavaDoc poolName) {
1408        try {
1409            ConfigContext ctx = com.sun.enterprise.admin.server.core.AdminService.
1410                    getAdminService().getAdminContext().getAdminConfigContext();
1411            Domain dom = ServerBeansFactory.getDomainBean(ctx);
1412            Resources res = dom.getResources();
1413    
1414            ConfigBean dasContextBean = null;
1415    
1416            com.sun.enterprise.config.serverbeans.JdbcConnectionPool
1417                    jdbcPool = res.getJdbcConnectionPoolByName(poolName);
1418    
1419            //Determine whether the pool is JDBC Pool or Connector Connection Pool and dump accordingly
1420
if (jdbcPool != null) {
1421                dasContextBean = (ConfigBean) jdbcPool;
1422            } else {
1423                com.sun.enterprise.config.serverbeans.ConnectorConnectionPool ccPool =
1424                        res.getConnectorConnectionPoolByName(poolName);
1425                if (ccPool != null) {
1426                    dasContextBean = (ConfigBean) ccPool;
1427                }
1428            }
1429    
1430            if (dasContextBean != null) {
1431                StringBuffer JavaDoc str = new StringBuffer JavaDoc();
1432                dasContextBean.dump(str, "\t\t");
1433                _logger.log(Level.INFO, "DAS CONTEXT IS : " + str);
1434            }
1435        } catch (Exception JavaDoc e) {
1436            _logger.log(Level.WARNING, "Exception while dumping pool details ", e.fillInStackTrace());
1437        }
1438    }
1439
1440    private com.sun.enterprise.config.serverbeans.JdbcConnectionPool
1441        getJdbcConnectionPoolServerBean( String JavaDoc poolName )
1442    throws ConfigException
1443    {
1444    if ( poolName == null ) {
1445        throw new ConfigException("null poolname");
1446    }
1447
1448    ConfigContext ctxt = null;
1449
1450    if ( ResourcesUtil.isDAS() ) {
1451        ctxt = com.sun.enterprise.admin.server.core.AdminService.
1452            getAdminService().getAdminContext().getAdminConfigContext();
1453    } else {
1454        ctxt = ApplicationServer.getServerContext().getConfigContext();
1455    }
1456    Domain dom = ServerBeansFactory.getDomainBean( ctxt );
1457    Resources res = dom.getResources();
1458        
1459    return res.getJdbcConnectionPoolByName( poolName );
1460    
1461    }
1462
1463    private com.sun.enterprise.config.serverbeans.ConnectorConnectionPool
1464        getConnectorConnectionPoolServerBean( String JavaDoc poolName )
1465    throws ConfigException
1466    {
1467    if ( poolName == null ) {
1468        throw new ConfigException("null poolname");
1469    }
1470
1471    ConfigContext ctxt = null;
1472
1473    if ( ResourcesUtil.isDAS() ) {
1474        ctxt = com.sun.enterprise.admin.server.core.AdminService.
1475            getAdminService().getAdminContext().getAdminConfigContext();
1476    } else {
1477        ctxt = ApplicationServer.getServerContext().getConfigContext();
1478    }
1479    Domain dom = ServerBeansFactory.getDomainBean( ctxt );
1480    Resources res = dom.getResources();
1481        
1482    return res.getConnectorConnectionPoolByName( poolName );
1483    
1484    }
1485
1486    private void logFine( String JavaDoc msg ) {
1487        if ( msg != null ) {
1488            if (_logger.isLoggable(Level.FINE)) {
1489            _logger.fine( msg );
1490        }
1491        }
1492    }
1493
1494    private void createAndAddPool( String JavaDoc poolName, PoolType pt) throws
1495            ConnectorRuntimeException
1496    {
1497        PoolManager poolMgr = Switch.getSwitch().getPoolManager();
1498        try {
1499        poolMgr.createEmptyConnectionPool( poolName, pt );
1500        } catch( PoolingException pe ) {
1501            String JavaDoc i18nMsg = localStrings.getString(
1502                "ccp_adm.failed_to_create_pool_object");
1503            ConnectorRuntimeException cre =
1504                new ConnectorRuntimeException( i18nMsg );
1505            cre.initCause( pe );
1506            throw cre;
1507        }
1508    }
1509    
1510    private void initialize() {
1511        Switch sw = Switch.getSwitch();
1512    if (sw.getContainerType() == ConnectorConstants.NON_ACC_CLIENT) {
1513            //Invocation from a non-ACC client
1514
try {
1515            if (sw.getPoolManager() == null) {
1516            sw.setPoolManager(new PoolManagerImpl());
1517        }
1518
1519            if (sw.getNamingManager() == null) {
1520            sw.setNamingManager(new NamingManagerImpl());
1521        }
1522        } catch(Exception JavaDoc e) {
1523                _logger.log( Level.WARNING, e.getMessage());
1524        }
1525    }
1526
1527    }
1528}
1529
Popular Tags