KickJava   Java API By Example, From Geeks To Geeks.

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


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.resource;
25
26 import java.util.*;
27 import java.security.AccessController JavaDoc;
28 import java.security.PrivilegedAction JavaDoc;
29 import java.security.PrivilegedExceptionAction JavaDoc;
30 import java.security.PrivilegedActionException JavaDoc;
31 import java.lang.reflect.Method JavaDoc;
32 import java.security.Principal JavaDoc;
33 import java.util.logging.*;
34 import javax.transaction.*;
35 import javax.transaction.xa.*;
36 import javax.naming.*;
37 import javax.sql.*;
38 import java.sql.SQLException JavaDoc;
39 import com.sun.jms.spi.xa.*;
40 import javax.jms.Session JavaDoc;
41 import javax.jms.JMSException JavaDoc;
42 import javax.resource.spi.ActivationSpec JavaDoc;
43 import javax.resource.spi.ManagedConnectionFactory JavaDoc;
44 import javax.resource.spi.ManagedConnection JavaDoc;
45 import javax.resource.spi.security.PasswordCredential JavaDoc;
46 import javax.resource.ResourceException JavaDoc;
47 import javax.security.auth.Subject JavaDoc;
48 import com.sun.enterprise.*;
49 import com.sun.ejb.*;
50 import com.sun.enterprise.log.Log;
51 import com.sun.enterprise.util.*;
52 import com.sun.enterprise.util.io.FileUtils;
53 import com.sun.enterprise.deployment.*;
54 import com.sun.enterprise.repository.*;
55 import com.sun.logging.*;
56 import com.sun.enterprise.instance.AppsManager;
57 import com.sun.enterprise.jms.IASJmsUtil;
58
59 import com.sun.enterprise.config.ConfigContext;
60 import com.sun.enterprise.config.ConfigException;
61 import com.sun.enterprise.config.serverbeans.TransactionService;
62 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
63 import com.sun.enterprise.config.serverbeans.ElementProperty;
64 import com.sun.enterprise.config.ConfigBean;
65 import com.sun.enterprise.server.ApplicationServer;
66 import com.sun.enterprise.server.ResourcesUtil;
67 import com.sun.enterprise.transaction.XAResourceWrapper;
68
69 import javax.naming.spi.InitialContextFactory JavaDoc;
70 import javax.naming.InitialContext JavaDoc;
71
72 import java.io.File JavaDoc;
73 import com.sun.enterprise.server.Constants;
74 import com.sun.enterprise.server.pluggable.PluggableFeatureFactory;
75
76 import com.sun.enterprise.connectors.ActiveInboundResourceAdapter;
77 import com.sun.enterprise.connectors.ActiveResourceAdapter;
78 import com.sun.enterprise.connectors.ConnectorRegistry;
79 import com.sun.enterprise.connectors.ConnectorRuntime;
80 import com.sun.enterprise.connectors.ConnectorRuntimeException;
81 import com.sun.enterprise.connectors.ResourceAdapterAdminServiceImpl;
82 import com.sun.enterprise.repository.JdbcConnectionPool;
83 import com.sun.enterprise.connectors.ConnectorConnectionPool;
84 import com.sun.enterprise.connectors.ConnectorDescriptorInfo;
85 import com.sun.enterprise.connectors.util.SetMethodAction;
86 import com.sun.enterprise.connectors.ConnectorConstants;
87 import com.sun.enterprise.connectors.system.ActiveJmsResourceAdapter;
88 import com.sun.enterprise.connectors.ConnectorAdminServiceUtils;
89 import com.sun.enterprise.connectors.util.RARUtils;
90
91 import com.sun.enterprise.ManagementObjectManager;
92 import com.sun.enterprise.autotxrecovery.TransactionRecovery;
93
94 import com.sun.jts.CosTransactions.Configuration;
95 import com.sun.jts.CosTransactions.RecoveryManager;
96 import com.sun.jts.CosTransactions.DelegatedRecoveryManager;
97
98 import com.sun.enterprise.instance.InstanceFactory;
99
100 /**
101  * This class handles the installation and configuration
102  * of various resources including JDBC datasources,
103  * resource adapters and connection factories
104  *
105  * @author Tony Ng
106  */

107 public class ResourceInstaller {
108     
109     static public final String JavaDoc CONNECTOR_ADAPTER_DIR =
110     "connector" + File.separator + "adapters";
111     static public final String JavaDoc CONNECTOR_PROPS =
112     "connector" + File.separator + "connector.properties";
113     
114     static final private String JavaDoc OBSOLETE_JDBC_DRIVER_PROP = "jdbc.drivers";
115     static final private String JavaDoc OBSOLETE_JDBC10_PROP = "jdbc.datasources";
116     static final private String JavaDoc OBSOLETE_JDBC20_PROP = "jdbc20.datasources";
117     static final private String JavaDoc SET_ = "set";
118     static final private String JavaDoc SET_CONNECTION_FACTORY = "setConnectionFactory";
119     //GJCINT
120
static final private String JavaDoc SET_CONNECTION_FACTORY_NAME = "setConnectionFactoryName";
121     
122     // static final private boolean debug = true;
123
static final private boolean debug = false;
124     
125     private static LocalStringManagerImpl localStrings =
126     new LocalStringManagerImpl(ResourceInstaller.class);
127     
128     // appName:connectorName -> ConnectorDescriptor
129
private Hashtable connectorDescriptors;
130     
131     private J2EEResourceFactory resFactory;
132     private J2EEResourceCollection resourceInfo;
133
134     //ManagementObjectManager for registering JSR77 types
135
private ManagementObjectManager mgmtObjectMgr;
136
137     
138     // Create logger object per Java SDK 1.4 to log messages
139
// introduced Santanu De, Sun Microsystems, March 2002
140

141     static Logger _logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
142     
143     public ResourceInstaller() {
144         connectorDescriptors = new Hashtable();
145         mgmtObjectMgr = Switch.getSwitch().getManagementObjectManager();
146
147         try {
148             resFactory = ServerConfiguration.getJ2EEResourceFactory();
149             resourceInfo = resFactory.loadDefaultResourceCollection();
150         } catch(J2EEResourceException re) {
151             _logger.log(Level.SEVERE,"J2EE.cannot_load_resources",re);
152             
153         }
154     }
155
156     
157     private void loadAllJdbcResources() {
158         
159         ResourcesUtil resutil = ResourcesUtil.getInstance();
160         try {
161             com.sun.enterprise.config.ConfigBean[][] configBeans =
162                     resutil.getJdbcResources();
163             com.sun.enterprise.config.serverbeans.JdbcResource[] jdbcResources =
164                     (com.sun.enterprise.config.serverbeans.JdbcResource[])configBeans[1];
165             InitialContext JavaDoc ic = new InitialContext JavaDoc();
166             for(int i=0; jdbcResources != null && i < jdbcResources.length; ++i) {
167                 if (jdbcResources[i].isEnabled()) {
168                     try{
169                         ic.lookup(jdbcResources[i].getJndiName());
170                     } catch(Exception JavaDoc ex) {
171                         _logger.log(Level.SEVERE,"error.loading.jdbc.resources.during.recovery",jdbcResources[i].getJndiName());
172                         if (_logger.isLoggable(Level.FINE)) {
173                             _logger.log( Level.FINE, ex.toString(), ex);
174                         }
175                     }
176                 }
177             }
178         } catch(ConfigException ce) {
179             _logger.log(Level.SEVERE,"error.loading.jdbc.resources.during.recovery",ce.getMessage());
180             if (_logger.isLoggable(Level.FINE)) {
181                 _logger.log( Level.FINE, ce.toString(), ce);
182             }
183         } catch(NamingException ne) {
184             _logger.log(Level.SEVERE,"error.loading.jdbc.resources.during.recovery",ne.getMessage());
185             if (_logger.isLoggable(Level.FINE)) {
186                 _logger.log( Level.FINE, ne.toString(), ne);
187             }
188         }
189     }
190
191     private void loadAllConnectorResources() {
192         
193         ResourcesUtil resutil = ResourcesUtil.getInstance();
194         try {
195             com.sun.enterprise.config.ConfigBean[][] configBeans =
196                     resutil.getConnectorResources();
197             com.sun.enterprise.config.serverbeans.ConnectorResource[] connResources =
198                     (com.sun.enterprise.config.serverbeans.ConnectorResource[])configBeans[1];
199             InitialContext JavaDoc ic = new InitialContext JavaDoc();
200             for(int i=0; connResources != null && i < connResources.length; ++i) {
201                 if (connResources[i].isEnabled()) {
202                     try{
203                         ic.lookup(connResources[i].getJndiName());
204                     } catch(NameNotFoundException ne) {
205                         //If you are here then it is most probably an embedded RAR resource
206
//So we need to explicitly load that rar and create the resources
207
try{
208                             com.sun.enterprise.config.serverbeans.ConnectorConnectionPool connConnectionPool =
209                                     resutil.getConnectorConnectionPoolByName(connResources[i].getPoolName());
210                             createActiveResourceAdapter(connConnectionPool.getResourceAdapterName());
211                             (new ConnectorResourceDeployer()).deployResource(connResources[i]);
212                         }catch(Exception JavaDoc ex){
213                             _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery",connResources[i].getJndiName());
214                             if (_logger.isLoggable(Level.FINE)) {
215                                 _logger.log( Level.FINE, ne.toString(), ne);
216                             }
217                             _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery",connResources[i].getJndiName());
218                             if (_logger.isLoggable(Level.FINE)) {
219                                 _logger.log( Level.FINE, ex.toString() , ex);
220                             }
221                         }
222                     } catch(Exception JavaDoc ex) {
223                         _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery",connResources[i].getJndiName());
224                         if (_logger.isLoggable(Level.FINE)) {
225                             _logger.log( Level.FINE, ex.toString() , ex);
226                         }
227                     }
228                 }
229             }
230         } catch(ConfigException ce) {
231             _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery",ce.getMessage());
232             if (_logger.isLoggable(Level.FINE)) {
233                 _logger.log( Level.FINE, ce.toString() , ce);
234             }
235         } catch(NamingException ne) {
236             _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery",ne.getMessage());
237             if (_logger.isLoggable(Level.FINE)) {
238                 _logger.log( Level.FINE, ne.toString(), ne);
239             }
240         }
241     }
242
243     private void loadAllJmsResources() {
244         
245         try {
246             ResourcesUtil resutil = ResourcesUtil.getInstance();
247             com.sun.enterprise.config.serverbeans.ConnectorResource[] jmsResources =
248                     resutil.getAllJmsResources();
249             InitialContext JavaDoc ic = new InitialContext JavaDoc();
250             for(int i=0; jmsResources != null && i < jmsResources.length; ++i) {
251                 if(jmsResources[i].isEnabled()){
252                     try{
253                         ic.lookup(jmsResources[i].getJndiName());
254                     } catch(Exception JavaDoc ex) {
255                         _logger.log(Level.SEVERE,"error.loading.jms.resources.during.recovery",jmsResources[i]);
256                         if (_logger.isLoggable(Level.FINE)) {
257                             _logger.log( Level.FINE, ex.toString(), ex );
258                         }
259                     }
260                 }
261             }
262         } catch(NamingException ne) {
263             _logger.log(Level.SEVERE,"error.loading.jms.resources.during.recovery",ne);
264             if (_logger.isLoggable(Level.FINE)) {
265                 _logger.log( Level.FINE, ne.toString(), ne );
266             }
267         }
268         
269     }
270
271     public boolean recoverIncompleteTx(boolean delegated, String JavaDoc logPath) throws Exception JavaDoc {
272         boolean result = false;
273             Vector jdbcConnList = new Vector();
274             Vector jmsConnList = new Vector();
275             Vector connectorConnList = new Vector();
276         try {
277             if(_logger.isLoggable(Level.FINE)) {
278                 _logger.log(Level.FINE, "Performing recovery of incomplete Tx...");
279             }
280
281             Vector xaresList = new Vector();
282             Context ic =
283             Switch.getSwitch().getNamingManager().getInitialContext();
284             
285             recoverJdbcXAResources(xaresList, jdbcConnList);
286             recoverExternalJndiResourceJMSXAResources(ic,xaresList,jmsConnList);
287             recoverConnectorXAResources(xaresList, connectorConnList);
288             recoverInboundTransactions(xaresList);
289             
290             int size = xaresList.size();
291             XAResource[] xaresArray = new XAResource[size];
292             for (int i=0; i<size; i++) {
293                 xaresArray[i] = (XAResource) xaresList.elementAt(i);
294             }
295             String JavaDoc msg = localStrings.getLocalString
296             ("xaresource.recovering", "Recovering {0} XA resources...",
297             new Object JavaDoc[] {String.valueOf(size)});
298
299             _logger.log(Level.FINE,msg);
300             if (!delegated) {
301                 RecoveryManager.recoverIncompleteTx(xaresArray);
302                 result = true;
303             }
304             else
305                 result = DelegatedRecoveryManager.delegated_recover(logPath, xaresArray);
306             
307             return result;
308         } finally {
309             try {
310                 closeJdbcXAResources(jdbcConnList);
311                 closeConnectorXAResources(connectorConnList);
312                 closeJMSXAResources(jmsConnList);
313             } catch (Exception JavaDoc ex1) {
314                 _logger.log(Level.WARNING,"xaresource.recover_error",ex1);
315             }
316         }
317     }
318
319     public void recoverXAResources() {
320         try {
321             ConfigContext ctx =
322                   ApplicationServer.getServerContext().getConfigContext();
323             TransactionService txnService = null;
324             txnService =
325                ServerBeansFactory.getTransactionServiceBean(ctx);
326             PluggableFeatureFactory pff = ApplicationServer.getServerContext().
327                     getPluggableFeatureFactory();
328             TransactionRecovery transactionRecoveryService =
329                     pff.getTransactionRecoveryService();
330             //transactionRecoveryService.start(context) ;
331
RecoveryManager.registerTransactionRecoveryService(transactionRecoveryService);
332             if (!txnService.isAutomaticRecovery()) {
333                 return;
334             }
335             if(_logger.isLoggable(Level.FINE)) {
336                 _logger.log(Level.FINE,"ejbserver.recovery",
337                             "Perform recovery of XAResources...");
338             }
339
340             Vector xaresList = new Vector();
341             Vector jdbcConnList = new Vector();
342             Vector jmsConnList = new Vector();
343             Vector connectorConnList = new Vector();
344             Context ic =
345             Switch.getSwitch().getNamingManager().getInitialContext();
346             
347             recoverJdbcXAResources(xaresList, jdbcConnList);
348             recoverExternalJndiResourceJMSXAResources(ic,xaresList,jmsConnList);
349             recoverConnectorXAResources(xaresList, connectorConnList);
350             recoverInboundTransactions(xaresList);
351             
352             int size = xaresList.size();
353             XAResource[] xaresArray = new XAResource[size];
354             for (int i=0; i<size; i++) {
355                 xaresArray[i] = (XAResource) xaresList.elementAt(i);
356             }
357             J2EETransactionManager tm =
358             Switch.getSwitch().getTransactionManager();
359             String JavaDoc msg = localStrings.getLocalString
360             ("xaresource.recovering", "Recovering {0} XA resources...",
361             new Object JavaDoc[] {String.valueOf(size)});
362
363             _logger.log(Level.FINE,msg);
364             tm.recover(xaresArray);
365             
366             closeJdbcXAResources(jdbcConnList);
367             closeConnectorXAResources(connectorConnList);
368             closeJMSXAResources(jmsConnList);
369         } catch (Exception JavaDoc ex) {
370             _logger.log(Level.SEVERE,"xaresource.recover_error",ex);
371         }
372     }
373     
374     
375     private void recoverJdbcXAResources( Vector xaresList, Vector connList) {
376         
377         ResourcesUtil resourceUtil = ResourcesUtil.getInstance();
378     com.sun.enterprise.config.ConfigBean[] jdbcres = null;
379
380     try {
381         jdbcres = resourceUtil.getJdbcResources()[1];
382     } catch( ConfigException ce ) {
383         _logger.log(Level.WARNING, ce.getMessage() );
384         return;
385     }
386         
387     if ( jdbcres == null || jdbcres.length == 0 ) {
388         return;
389     }
390         
391     Set jdbcPools = new HashSet();
392     
393     for (int i = 0; i < jdbcres.length; i++ ) {
394         try {
395             if ( resourceUtil.isEnabled( jdbcres[i]) ) {
396                 com.sun.enterprise.config.serverbeans.JdbcConnectionPool
397                     pool = resourceUtil.getJdbcConnectionPoolByName(
398                         ((com.sun.enterprise.config.serverbeans.JdbcResource)
399                         jdbcres[i]).getPoolName() );
400                 if ( pool != null &&
401                     "javax.sql.XADataSource".equals(pool.getResType() ) ) {
402                     jdbcPools.add( pool );
403                 }
404                 logFine( "ResourceInstaller:: recoverJdbcXAResources :: "
405                     + "adding : " + ((com.sun.enterprise.config.serverbeans.JdbcResource)
406                         jdbcres[i]).getPoolName() );
407             }
408         } catch( ConfigException ce ) {
409             _logger.log(Level.WARNING, ce.getMessage() );
410         }
411     }
412     
413         loadAllJdbcResources();
414         // Read from the transaction-service , if the replacement of
415
// Vendor XAResource class with our version required.
416
// If yes, put the mapping in the xaresourcewrappers properties.
417
Properties xaresourcewrappers = new Properties();
418         try {
419             ConfigContext ctx =
420                  ApplicationServer.getServerContext().getConfigContext();
421             TransactionService txs =
422                  ServerBeansFactory.getTransactionServiceBean(ctx);
423             xaresourcewrappers.put(
424                 "oracle.jdbc.xa.client.OracleXADataSource",
425                 "com.sun.enterprise.transaction.OracleXAResource");
426             
427             ElementProperty[] eprops = txs.getElementProperty();
428             for(int i=0;i<eprops.length;i++){
429                 String JavaDoc name = eprops[i].getName();
430                 String JavaDoc value = eprops[i].getValue();
431                 if(name.equals("oracle-xa-recovery-workaround")) {
432                     if("false".equals(value)){
433                         xaresourcewrappers.remove(
434                            "oracle.jdbc.xa.client.OracleXADataSource");
435                     }
436                 } else if(name.equals("sybase-xa-recovery-workaround")) {
437                     if(value.equals("true")) {
438                         xaresourcewrappers.put(
439                             "com.sybase.jdbc2.jdbc.SybXADataSource",
440                             "com.sun.enterprise.transaction.SybaseXAResource");
441                     }
442                 }
443             }
444         }catch(ConfigException cex){
445             _logger.log(Level.INFO,"jdbc.config_error",cex);
446             
447         }
448
449         ConnectorRuntime crt = ConnectorRuntime.getRuntime();
450
451         //for(int i=0; i<jdbcConnectionPools.length; ++i) {
452
Iterator iter = jdbcPools.iterator();
453     while( iter.hasNext() ) {
454         com.sun.enterprise.config.serverbeans.JdbcConnectionPool
455             jdbcConnectionPool = (com.sun.enterprise.config.serverbeans.JdbcConnectionPool)
456         iter.next();
457             if(jdbcConnectionPool.getResType()==null
458                 || jdbcConnectionPool.getName()==null
459                 || !jdbcConnectionPool.getResType().equals(
460                           "javax.sql.XADataSource")) {
461                 continue;
462             }
463             String JavaDoc poolName = jdbcConnectionPool.getName();
464             try {
465                 
466                 String JavaDoc[] dbUserPassword =
467                       resourceUtil.getdbUserPasswordOfJdbcConnectionPool(
468                       jdbcConnectionPool);
469                 String JavaDoc dbUser = dbUserPassword[0];
470                 String JavaDoc dbPassword = dbUserPassword[1];
471                 ManagedConnectionFactory JavaDoc fac =
472                       crt.obtainManagedConnectionFactory(poolName);
473                 Subject JavaDoc subject = new Subject JavaDoc();
474                 PasswordCredential JavaDoc pc = new PasswordCredential JavaDoc(
475                       dbUser, dbPassword.toCharArray());
476                 pc.setManagedConnectionFactory(fac);
477                 Principal JavaDoc prin = new ResourcePrincipal(dbUser, dbPassword);
478                 subject.getPrincipals().add(prin);
479                 subject.getPrivateCredentials().add(pc);
480                 ManagedConnection JavaDoc mc = fac.createManagedConnection(subject, null);
481                 connList.addElement(mc);
482                 try {
483                     XAResource xares = mc.getXAResource();
484                     if (xares != null) {
485
486                 // See if a wrapper class for the vendor XADataSource is
487
// specified if yes, replace the XAResouce class of database
488
// vendor with our own version
489

490
491                         String JavaDoc clName =
492                              jdbcConnectionPool.getDatasourceClassname();
493                         String JavaDoc wrapperclass = (String JavaDoc)xaresourcewrappers.get(
494                              clName);
495                         if(wrapperclass!=null){
496                             XAResourceWrapper xaresWrapper = null;
497                             try{
498                                xaresWrapper = (XAResourceWrapper)Class.forName(
499                                    wrapperclass).newInstance();
500                             }catch(Exception JavaDoc ex){
501                                throw ex;
502                             }
503                             xaresWrapper.init(mc,subject);
504                             xaresList.addElement(xaresWrapper);
505                         }else{
506                             xaresList.addElement(xares);
507                         }
508                     }
509                 } catch (ResourceException JavaDoc ex) {
510                     // ignored. Not at XA_TRANSACTION level
511
}
512             } catch (Exception JavaDoc ex) {
513                 _logger.log(Level.WARNING,"datasource.xadatasource_error",
514                              poolName);
515                 _logger.log(Level.FINE,"datasource.xadatasource_error_excp",ex);
516
517             }
518         }
519     }
520     
521     private void recoverConnectorXAResources(Vector xaresList,Vector connList){
522
523         ResourcesUtil resourceUtil = ResourcesUtil.getInstance();
524     
525     com.sun.enterprise.config.ConfigBean[] connRes = null;
526     
527     try {
528         connRes = resourceUtil.getConnectorResources()[1];
529     } catch( ConfigException ce ) {
530         _logger.log(Level.WARNING, ce.getMessage() ) ;
531         return;
532     }
533         
534         if(connRes == null || connRes.length == 0 ) {
535             return;
536         }
537         Set connPools = new HashSet();
538     for (int i = 0 ; i < connRes.length; i++) {
539         try {
540             if ( resourceUtil.isEnabled( connRes[i]) ) {
541                 com.sun.enterprise.config.serverbeans.ConnectorConnectionPool pool =
542                     resourceUtil.getConnectorConnectionPoolByName(
543                         ((com.sun.enterprise.config.serverbeans.ConnectorResource)
544                     connRes[i]).getPoolName() );
545                 if ( pool != null &&
546                  ConnectorConstants.XA_TRANSACTION_TX_SUPPORT_STRING.equals(
547                      getTransactionSupport(pool)) ) {
548                     connPools.add( pool );
549                     logFine( "ResourceInstaller:: recoverConnectorXAResources :: "
550                         + "adding : " +
551                     (((com.sun.enterprise.config.serverbeans.ConnectorResource)
552                         (connRes)[i])).getPoolName() );
553                 }
554             }
555         } catch( ConfigException ce ) {
556             _logger.warning( ce.getMessage() );
557         }
558     }
559     loadAllConnectorResources();
560
561     Iterator iter = connPools.iterator();
562     
563         ConnectorRuntime crt = ConnectorRuntime.getRuntime();
564         //for(int i = 0; i<connectorConnectionPools.length;++i) {
565
while( iter.hasNext() ) {
566         com.sun.enterprise.config.serverbeans.ConnectorConnectionPool
567             connPool = (com.sun.enterprise.config.serverbeans.ConnectorConnectionPool)
568             iter.next();
569             String JavaDoc poolName = connPool.getName();
570             try {
571                 String JavaDoc[] dbUserPassword =
572                        resourceUtil.getdbUserPasswordOfConnectorConnectionPool(
573                        connPool);
574         if ( dbUserPassword == null ) {
575             continue;
576         }
577                 String JavaDoc dbUser = dbUserPassword[0];
578                 String JavaDoc dbPassword = dbUserPassword[1];
579                 ManagedConnectionFactory JavaDoc mcf =
580                        crt.obtainManagedConnectionFactory(poolName);
581                 Subject JavaDoc subject = new Subject JavaDoc();
582                 
583                 //If username or password of the connector connection pool
584
//is null a warning is logged and recovery continues with
585
//empty String username or password as the case may be,
586
//because some databases allow null[as in empty string]
587
//username [pointbase interprets this as "root"]/password.
588
if(dbPassword==null) {
589                     dbPassword = "";
590                     _logger.log(Level.WARNING,
591                         "datasource.xadatasource_nullpassword_error",poolName);
592                 }
593                 
594         if(dbUser == null){
595                     dbUser = "";
596                     _logger.log(Level.WARNING,
597                        "datasource.xadatasource_nulluser_error",poolName);
598         }
599                 
600                 PasswordCredential JavaDoc pc = new PasswordCredential JavaDoc(
601                        dbUser, dbPassword.toCharArray());
602                 pc.setManagedConnectionFactory(mcf);
603                 Principal JavaDoc prin = new ResourcePrincipal(dbUser, dbPassword);
604                 subject.getPrincipals().add(prin);
605                 subject.getPrivateCredentials().add(pc);
606                 ManagedConnection JavaDoc mc = mcf.createManagedConnection(subject, null);
607                 connList.addElement(mc);
608                 try {
609                     XAResource xares = mc.getXAResource();
610                     if (xares != null) {
611 // connList.addElement(mc);
612
xaresList.addElement(xares);
613                     }
614                 } catch (ResourceException JavaDoc ex) {
615                     // ignored. Not at XA_TRANSACTION level
616
}
617             } catch (Exception JavaDoc ex) {
618                 _logger.log(Level.WARNING,"datasource.xadatasource_error",
619                         poolName);
620                 _logger.log(Level.FINE,"datasource.xadatasource_error_excp",ex);
621             }
622         }
623     }
624     private void recoverExternalJndiResourceJMSXAResources(Context ic, Vector xaresList, Vector connList) {
625         Set res = resourceInfo.getResourcesByType
626         (J2EEResource.EXTERNAL_JNDI_RESOURCE);
627         
628         recoverJMSXAResources(ic, xaresList, connList, res);
629     }
630     
631     private void recoverJMSResourceJMSXAResources(Context ic, Vector xaresList, Vector connList) {
632         loadAllJmsResources();
633         Set res = resourceInfo.getResourcesByType
634         (J2EEResource.JMS_CNX_FACTORY);
635         recoverJMSXAResources(ic, xaresList, connList, res);
636         
637         String JavaDoc jndiName = null;
638         JMSXAConnectionFactory obj;
639         try {
640             jndiName = IASJmsUtil.MDB_CONTAINER_QUEUE_XACF;
641             obj = (JMSXAConnectionFactory)ic.lookup(jndiName);
642             recoverJMSXAResource(xaresList, connList, obj, true);
643         }
644         catch (Exception JavaDoc ex) {
645             _logger.log(Level.SEVERE,"datasource.xadatasource_error",jndiName);
646             _logger.log(Level.SEVERE,"datasource.xadatasource_error_excp",ex);
647         }
648         try {
649             jndiName = IASJmsUtil.MDB_CONTAINER_TOPIC_XACF;
650             obj = (JMSXAConnectionFactory)ic.lookup(jndiName);
651             recoverJMSXAResource(xaresList, connList, obj, false);
652         }
653         catch (Exception JavaDoc ex) {
654             _logger.log(Level.SEVERE,"datasource.xadatasource_error",jndiName);
655             _logger.log(Level.SEVERE,"datasource.xadatasource_error_excp",ex);
656         }
657     }
658     
659     private void recoverJMSXAResources(Context ic,
660     Vector xaresList, Vector connList, Set jmsRes) {
661         for(Iterator iter = jmsRes.iterator(); iter.hasNext();) {
662             J2EEResource next = (J2EEResource)iter.next();
663             if (next instanceof ExternalJndiResource) {
664                 if (!((ExternalJndiResource)next).isJMSConnectionFactory()) {
665                     continue;
666                 }
667             }
668             
669             String JavaDoc jndiName = next.getName();
670             try {
671                 JMSXAConnectionFactory obj;
672                 boolean isQueue;
673                 if (next instanceof ExternalJndiResource) {
674                     Object JavaDoc objext = ic.lookup(jndiName);
675                     if (!(objext instanceof javax.jms.ConnectionFactory JavaDoc)) {
676                         throw new NamingException(localStrings.getLocalString("recovery.unexpected_objtype",
677                         "Unexpected object type "+objext.getClass().getName()+" for "+ jndiName,
678                         new Object JavaDoc[]{objext.getClass().getName(), jndiName}));
679                     }
680                     obj = (JMSXAConnectionFactory)IASJmsUtil.wrapJMSConnectionFactoryObject(objext);
681                     isQueue = (objext instanceof javax.jms.QueueConnectionFactory JavaDoc);
682                 }
683                 else {
684                     obj = (JMSXAConnectionFactory)ic.lookup(IASJmsUtil.getXAConnectionFactoryName(jndiName));
685                     isQueue = (obj instanceof JMSXAQueueConnectionFactory);
686                 }
687                 recoverJMSXAResource(xaresList, connList, obj, isQueue);
688             } catch (Exception JavaDoc ex) {
689                 _logger.log(Level.SEVERE,"datasource.xadatasource_error",jndiName);
690                 _logger.log(Level.SEVERE,"datasource.xadatasource_error_excp",ex);
691             }
692         }
693     }
694     
695     private void recoverJMSXAResource(Vector xaresList, Vector connList,
696     JMSXAConnectionFactory obj, boolean isQueue ) throws Exception JavaDoc {
697         if (isQueue) {
698             JMSXAQueueConnectionFactory fac =
699             (JMSXAQueueConnectionFactory) obj;
700             JMSXAQueueConnection con = fac.createXAQueueConnection();
701             connList.addElement(con);
702             XAResource xares = con.createXAQueueSession
703             (true, Session.AUTO_ACKNOWLEDGE).getXAResource();
704             xaresList.addElement(xares);
705         } else {
706             // XATopicConnectionFactory
707
JMSXATopicConnectionFactory fac =
708             (JMSXATopicConnectionFactory) obj;
709             JMSXATopicConnection con = fac.createXATopicConnection();
710             connList.addElement(con);
711             XAResource xares = con.createXATopicSession
712             (true, Session.AUTO_ACKNOWLEDGE).getXAResource();
713             xaresList.addElement(xares);
714         }
715     }
716     
717      private void recoverInboundTransactions(Vector xaresList) throws ConfigException{
718         try{
719             _logger.log(Level.INFO, "Recovery of Inbound Transactions started.");
720         ResourcesUtil resutil = ResourcesUtil.getInstance();
721         // Get list of application deployment desc from all deployed apps and ejb-modules.
722
Application[] applications = resutil.getDeployedApplications();
723         
724         if (applications.length == 0){
725             _logger.log(Level.FINE, "No applications deployed.");
726             return;
727         }
728         // List of CMT enabled MDB descriptors on the application server instance.
729
ArrayList xaEnabledMDBList = new ArrayList();
730             
731         for (int i=0; i<applications.length; i++){
732         Vector ejbDescVec = applications[i].getEjbDescriptors();
733             for (int j=0; j<ejbDescVec.size(); j++){
734                 EjbDescriptor desc = (EjbDescriptor)ejbDescVec.elementAt(j);
735                 // If EjbDescriptor is an instance of a CMT enabled MDB descriptor,
736
// add it to the list of xaEnabledMDBList.
737
if ( desc instanceof EjbMessageBeanDescriptor &&
738                         desc.getTransactionType().
739                             equals(EjbDescriptor.CONTAINER_TRANSACTION_TYPE)){
740                     xaEnabledMDBList.add(desc);
741                     _logger.log(Level.FINE, "Found a CMT MDB: "
742                             + desc.getEjbClassName());
743                 }
744             }
745         }
746         
747         if (xaEnabledMDBList.size() == 0) {
748             _logger.log(Level.FINE, "Found no CMT MDBs in all applications");
749             return;
750         }
751         
752         ConnectorRuntime cr = ConnectorRuntime.getRuntime();
753         ConnectorRegistry creg = ConnectorRegistry.getInstance();
754         ClassLoader JavaDoc cl = ConnectorClassLoader.getInstance();
755
756         
757         // for each RA (key in the hashtable) get the list (value) of MDB Descriptors
758
Hashtable mappings = createRAEjbMapping(xaEnabledMDBList);
759         // To iterate through the keys(ramid), get the key Set from Hashtable.
760
Set raMidSet = mappings.keySet();
761         
762         Iterator iter = raMidSet.iterator();
763         
764         //For each RA
765
while (iter.hasNext()){
766             
767             String JavaDoc raMid = (String JavaDoc)iter.next();
768                 ArrayList respectiveDesc = (ArrayList)mappings.get(raMid);
769                 
770                 try{
771                     createActiveResourceAdapter(raMid);
772                 } catch(Exception JavaDoc ex) {
773                     _logger.log(Level.SEVERE,"error.loading.connector.resources.during.recovery", raMid);
774                     if (_logger.isLoggable(Level.FINE)) {
775                         _logger.log( Level.FINE, ex.toString() , ex);
776                     }
777                 }
778                 
779                 ActiveInboundResourceAdapter activeInboundRA = (ActiveInboundResourceAdapter) creg
780                         .getActiveResourceAdapter(raMid);
781                 
782                 assert activeInboundRA instanceof ActiveInboundResourceAdapter;
783                 
784                 boolean isSystemJmsRA = false;
785                 if (activeInboundRA instanceof ActiveJmsResourceAdapter) {
786                     isSystemJmsRA = true;
787                 }
788                 
789                 javax.resource.spi.ResourceAdapter JavaDoc resourceAdapter = activeInboundRA
790                         .getResourceAdapter();
791                 // activationSpecList represents the ActivationSpec[] that would be
792
// sent to the getXAResources() method.
793
ArrayList activationSpecList = new ArrayList();
794             
795             try{
796             for (int i=0; i<respectiveDesc.size(); i++){
797                 try{
798                 // Get a MessageBeanDescriptor from respectiveDesc ArrayList
799
EjbMessageBeanDescriptor descriptor =
800                     (EjbMessageBeanDescriptor)respectiveDesc.get(i);
801                         // A descriptor using 1.3 System JMS RA style properties needs
802
// to be updated J2EE 1.4 style props.
803
if (isSystemJmsRA) {
804                              //XXX: Find out the pool descriptor corres to MDB and update
805
//MDBRuntimeInfo with that.
806
((ActiveJmsResourceAdapter) activeInboundRA)
807                                                             .updateMDBRuntimeInfo(descriptor, null);
808                         }
809                     
810                 // Get the ActivationConfig Properties from the MDB Descriptor
811
Set activationConfigProps =
812                     RARUtils.getMergedActivationConfigProperties(descriptor);
813                 // get message listener type
814
String JavaDoc msgListenerType = descriptor.getMessageListenerType();
815                 
816                 // start resource adapter and get ActivationSpec class for
817
// the given message listener type from the ConnectorRuntime
818

819                         ActivationSpec JavaDoc aspec = (ActivationSpec JavaDoc) (Class.forName(
820                                                        cr.getActivationSpecClass(raMid,
821                                                        msgListenerType), false,
822                                                        resourceAdapter.getClass().getClassLoader()).newInstance());
823                         aspec.setResourceAdapter(resourceAdapter);
824                 
825                 // Populate ActivationSpec class with ActivationConfig properties
826
SetMethodAction sma =
827                     new SetMethodAction(aspec,activationConfigProps);
828                 sma.run();
829                 activationSpecList.add(aspec);
830                 } catch (Exception JavaDoc e){
831                     _logger.log(Level.WARNING, "Error creating ActivationSpec \n"+e.getMessage());
832                                 if(_logger.isLoggable(Level.FINE)){
833                                     _logger.log(Level.FINE, e.toString(), e);
834                                 }
835                 }
836             }
837                     
838             // Get XA resources from RA.
839

840             ActivationSpec JavaDoc[] activationSpecArray = (ActivationSpec JavaDoc[])activationSpecList.toArray(new ActivationSpec JavaDoc[] {});
841             XAResource[] xar = resourceAdapter.getXAResources(activationSpecArray);
842             
843             // Add the resources to the xaresList which is used by the RecoveryManager
844
for(int p=0; p<xar.length; p++){
845                 xaresList.addElement(xar[p]);
846             
847             }
848             // Catch UnsupportedOperationException if a RA does not support XA
849
// which is fine.
850
} catch (UnsupportedOperationException JavaDoc uoex){
851                 _logger.log(Level.FINE, uoex.getMessage());
852                 // otherwise catch the unexpected exception
853
} catch (Exception JavaDoc e) {
854                 _logger.log(Level.SEVERE, e.getMessage());
855             } finally {
856                 continue;
857             }
858         }
859     } catch (Exception JavaDoc e){
860         _logger.log(Level.SEVERE, e.getMessage());
861     } finally {
862         return;
863     }
864     
865     }
866
867      private void createActiveResourceAdapter(String JavaDoc rarModuleName) throws ConfigException, ConnectorRuntimeException {
868          
869          ConnectorRuntime cr = ConnectorRuntime.getRuntime();
870          ResourcesUtil resutil = ResourcesUtil.getInstance();
871          ConnectorRegistry creg = ConnectorRegistry.getInstance();
872          
873          if(creg.isRegistered(rarModuleName))
874              return;
875          
876          // If RA is embedded RA, find location of exploded rar.
877
if (ConnectorAdminServiceUtils.isEmbeddedConnectorModule(rarModuleName)) {
878              String JavaDoc appName = ConnectorAdminServiceUtils .getApplicationName(rarModuleName);
879              String JavaDoc rarFileName = ConnectorAdminServiceUtils
880                      .getConnectorModuleName(rarModuleName)+".rar";
881              ConnectorDescriptor cd = resutil.getConnectorDescriptorFromUri(appName, rarFileName);
882              String JavaDoc loc = resutil.getApplicationDeployLocation(appName);
883              loc = loc + File.separator + FileUtils.makeFriendlyFilename(rarFileName);
884              
885              // start RA
886
cr.createActiveResourceAdapter(cd,rarModuleName, loc, false);
887              
888              // else if RA is not embedded, it is already present in the
889
// ConnectorRegistry. Start it straight away.
890
} else {
891              cr.createActiveResourceAdapter(resutil.getLocation(rarModuleName), rarModuleName, false);
892          }
893      }
894
895       private Hashtable createRAEjbMapping(ArrayList list){
896         
897         Hashtable ht = new Hashtable();
898
899             
900         for (int i=0; i<list.size(); i++){
901                 ArrayList ejbmdbd = new ArrayList();
902             String JavaDoc ramid =
903                 ((EjbMessageBeanDescriptor)list.get(i)).getResourceAdapterMid();
904                 if ((ramid == null) || (ramid.equalsIgnoreCase(""))) {
905                     ramid = ConnectorConstants.DEFAULT_JMS_ADAPTER;
906                 }
907                 
908             // If Hashtable contains the RAMid key, get the list of MDB descriptors
909
// and add the current MDB Descriptor (list[i]) to the list and put the
910
// pair back into hashtable.
911
// Otherwise, add the RAMid and the current MDB Descriptor to the hashtable
912
if (ht.containsKey(ramid)){
913                 ejbmdbd = (ArrayList)ht.get(ramid);
914                 ht.remove(ramid);
915             }
916             
917             ejbmdbd.add(list.get(i));
918             ht.put(ramid, ejbmdbd);
919         }
920         return ht;
921             
922     }
923
924    private void closeJdbcXAResources(Vector connList) {
925         int size = connList.size();
926         for (int i=0; i<size; i++) {
927             try {
928                 ManagedConnection JavaDoc con = (ManagedConnection JavaDoc) connList.elementAt(i);
929                 con.destroy();
930             } catch (ResourceException JavaDoc ex) {
931                 _logger.log(Level.FINE,"JDBC Resources cannot be closed",ex);
932             }
933         }
934     }
935     
936     private void closeJMSXAResources(Vector connList) {
937         int size = connList.size();
938         for (int i=0; i<size; i++) {
939             try {
940                 Object JavaDoc obj = connList.elementAt(i);
941                 ((JMSXAConnection) obj).close();
942             } catch (JMSException JavaDoc ex) {
943                 
944                 // Since closing error has been advised to be ignored
945
// so we are not logging the message as an exception
946
// but treating the same as a debug message
947
// Santanu De, Sun Microsystems, 2002.
948

949                 _logger.log(Level.FINE,"JMS Resources cannot be closed",ex);
950                 
951             }
952         }
953     }
954     
955     private void closeConnectorXAResources(Vector connList) {
956         int size = connList.size();
957         for (int i=0; i<size; i++) {
958             try {
959                 Object JavaDoc obj = connList.elementAt(i);
960                 ((ManagedConnection JavaDoc) obj).destroy();
961             } catch (ResourceException JavaDoc ex) {
962                 // Since closing error has been advised to be ignored
963
// so we are not logging the message as an exception
964
// but treating the same as a debug message
965
// Santanu De, Sun Microsystems, 2002.
966

967                 _logger.log(Level.FINE,"Connector Resources cannot be closed",ex);
968                 
969             }
970         }
971     }
972
973     /**
974      * Create a name for the internal data source for PM use
975      * based on the user-specified JNDI name.
976      */

977     public static String JavaDoc getPMJndiName(String JavaDoc userJndiName) {
978         return userJndiName + ConnectorConstants.PM_JNDI_SUFFIX;
979     }
980     
981     public String JavaDoc getSystemModuleLocation(String JavaDoc moduleName) {
982         String JavaDoc j2eeModuleDirName = System.getProperty(Constants.INSTALL_ROOT) +
983         File.separator + "lib" +
984         File.separator + "install" +
985         File.separator + "applications" +
986         File.separator + moduleName;
987         
988         return j2eeModuleDirName;
989     }
990    
991     public void installPersistenceManagerResources() throws Exception JavaDoc {
992         logFine("***** Installing PersistenceManagerResources *****");
993         Set pmfDatasources = resourceInfo.getResourcesByType
994         (J2EEResource.PMF_RESOURCE);
995         
996         for(Iterator iter = pmfDatasources.iterator(); iter.hasNext();) {
997             logFine("***** In for loop PersistenceManagerResources *****");
998             PMFResource next = (PMFResource) iter.next();
999             installPersistenceManagerResource(next);
1000            
1001        } // end for
1002

1003        logFine("End of for loop PersistenceManagerResources *****");
1004        
1005    } // end installPersistenceManagerResources
1006

1007    public void installPersistenceManagerResource(PMFResource pmfRes)
1008        throws Exception JavaDoc
1009    {
1010        String JavaDoc jndiName = null;
1011        try {
1012            jndiName = pmfRes.getName();
1013            logFine("***** installPersistenceManagerResources jndiName *****" + jndiName);
1014            
1015            String JavaDoc factory = pmfRes.getFactoryClass();
1016            logFine("**** PersistenceManagerSettings - factory " + factory);
1017            Class JavaDoc pmfImplClass = Class.forName(factory);
1018            Object JavaDoc pmfImpl = pmfImplClass.newInstance();
1019            
1020            String JavaDoc ds_jndi = pmfRes.getJdbcResourceJndiName();
1021            if (ds_jndi != null && ds_jndi.length() > 0) {
1022                String JavaDoc ds_jndi_pm = ResourceInstaller.getPMJndiName(ds_jndi);
1023                logFine("**** PersistenceManagerSettings - ds_jndi " + ds_jndi_pm);
1024                DataSource pmDataSource = null;
1025                try {
1026                    javax.naming.Context JavaDoc ctx = new javax.naming.InitialContext JavaDoc();
1027                    pmDataSource = (DataSource)ctx.lookup(ds_jndi_pm);
1028                    
1029                    //ASSUMPTION
1030
//factory must have the following method specified in JDO
1031
// public void setConnectionFactory(Object);
1032
//GJCINT - changing to setConnectionFactoryName
1033
Method JavaDoc connFacMethod = pmfImplClass.getMethod(
1034                    SET_CONNECTION_FACTORY_NAME,
1035                    new Class JavaDoc[] { String JavaDoc.class });
1036                    //connFacMethod.invoke(pmfImpl, new Object[] { pmDataSource });
1037
connFacMethod.invoke(pmfImpl, new Object JavaDoc[] { ds_jndi_pm });
1038                    
1039                } catch ( Exception JavaDoc ex ) {
1040                    _logger.log(Level.SEVERE,"jndi.persistence_manager_config",ds_jndi_pm);
1041                    _logger.log(Level.FINE,"jndi.persistence_manager_config_excp",ex);
1042            throw ex;
1043                }
1044            }
1045            
1046            Set propSet = pmfRes.getProperties();
1047            Iterator propIter = propSet.iterator();
1048            while (propIter.hasNext()) {
1049                ResourceProperty prop = (ResourceProperty)propIter.next();
1050                String JavaDoc name = prop.getName();
1051                String JavaDoc value = (String JavaDoc)prop.getValue();
1052                logFine("**** PersistenceManager propSettings - " + name + " " + value);
1053                String JavaDoc methodName = SET_ + name.substring(0, 1).toUpperCase() +
1054                name.substring(1);
1055                //ASSUMPTION
1056
//set property in pmf have a mutator with String as arg
1057
Method JavaDoc method = pmfImplClass.getMethod(methodName,
1058                new Class JavaDoc[] { String JavaDoc.class });
1059                //ASSUMPTION
1060
method.invoke(pmfImpl, new Object JavaDoc[] { value });
1061            }
1062            
1063            NamingManager nm = Switch.getSwitch().getNamingManager();
1064            nm.publishObject(jndiName, pmfImpl, true);
1065            
1066            logFine("***** After publishing PersistenceManagerResources *****" );
1067        } catch (Exception JavaDoc ex) {
1068            _logger.log(Level.SEVERE,"poolmgr.datasource_error",jndiName);
1069            _logger.log(Level.FINE,"poolmgr.datasource_error_excp",ex);
1070            throw ex;
1071        }
1072    } // end installPersistenceManagerResource
1073

1074    /**
1075     * Installs the given custom resource. It publishes the resource as a
1076     * javax.naming.Reference with the naming manager (jndi). This method gets
1077     * called during server initialization and custom resource deployer to
1078     * handle custom resource events.
1079     *
1080     * @param custonRes custom resource
1081     */

1082    public void installCustomResource(CustomResource customRes) {
1083        
1084        NamingManager nm = Switch.getSwitch().getNamingManager();
1085        String JavaDoc bindName = null;
1086        
1087        try {
1088            bindName = customRes.getName();
1089            
1090            if (debug) {
1091                _logger.log(Level.FINE,"***** installCustomResources jndiName *****"
1092                + bindName);
1093            }
1094            
1095            // bind a Reference to the object factory
1096
Reference ref = new Reference(customRes.getResType(),
1097            customRes.getFactoryClass(),
1098            null);
1099            
1100            // add resource properties as StringRefAddrs
1101
for (Iterator props=customRes.getProperties().iterator();
1102            props.hasNext(); ) {
1103                
1104                ResourceProperty prop = (ResourceProperty) props.next();
1105                
1106                ref.add(new StringRefAddr(prop.getName(),
1107                (String JavaDoc) prop.getValue()));
1108            }
1109            
1110            // publish the reference
1111
nm.publishObject(bindName, ref, true);
1112        } catch (Exception JavaDoc ex) {
1113            _logger.log(Level.SEVERE,"customrsrc.create_ref_error",bindName);
1114            _logger.log(Level.SEVERE,"customrsrc.create_ref_error_excp",ex);
1115        }
1116    }
1117    
1118    /**
1119     * Installs all iAS 7.0 custom resource object factories. This method gets
1120     * called during server initialization.
1121     */

1122    public void installCustomResources() {
1123        
1124        Set customResSet =
1125        resourceInfo.getResourcesByType(J2EEResource.CUSTOM_RESOURCE);
1126        
1127        for (Iterator iter = customResSet.iterator(); iter.hasNext();) {
1128            
1129            CustomResource next = (CustomResource) iter.next();
1130            installCustomResource(next);
1131        }
1132    }
1133    
1134    /**
1135     * load and create an object instance
1136     */

1137    public static Object JavaDoc loadObject(String JavaDoc className) {
1138        Object JavaDoc obj = null;
1139        Class JavaDoc c;
1140        
1141        try {
1142            obj = Class.forName(className).newInstance();
1143        } catch (Exception JavaDoc cnf) {
1144            try {
1145                c = ClassLoader.getSystemClassLoader().loadClass(className);
1146                obj = c.newInstance();
1147            } catch (Exception JavaDoc ex) {
1148                _logger.log(Level.SEVERE,"classloader.load_class_fail",className);
1149                _logger.log(Level.SEVERE,"classloader.load_class_fail_excp",ex.getMessage());
1150                
1151            }
1152        }
1153        
1154        return obj;
1155    }
1156    
1157    /**
1158     * Installs the given external jndi resource. This method gets called
1159     * during server initialization and from external jndi resource
1160     * deployer to handle resource events.
1161     *
1162     * @param extJndiRes external jndi resource
1163     */

1164    public void installExternalJndiResource(ExternalJndiResource extJndiRes) {
1165        
1166        NamingManager nm = Switch.getSwitch().getNamingManager();
1167        
1168        String JavaDoc bindName = null;
1169        
1170        try {
1171            bindName = extJndiRes.getName();
1172            
1173            // create the external JNDI factory, its initial context and
1174
// pass them as references.
1175
String JavaDoc factoryClass = extJndiRes.getFactoryClass();
1176            String JavaDoc jndiLookupName = extJndiRes.getJndiLookupName();
1177            
1178            if (debug) {
1179                _logger.log(Level.FINE,"installExternalJndiResources jndiName "
1180                + bindName + " factoryClass " + factoryClass
1181                + " jndiLookupName = " + jndiLookupName);
1182            }
1183            
1184            
1185            Object JavaDoc factory = loadObject(factoryClass);
1186            if (factory == null) {
1187                _logger.log(Level.WARNING,"jndi.factory_load_error",factoryClass);
1188                return;
1189                
1190            } else if (! (factory instanceof javax.naming.spi.InitialContextFactory JavaDoc)) {
1191                _logger.log(Level.WARNING,"jndi.factory_class_unexpected",factoryClass);
1192                return;
1193            }
1194            
1195            // Get properties to create the initial naming context
1196
// for the target JNDI factory
1197
Hashtable env = new Hashtable();
1198            for (Iterator props = extJndiRes.getProperties().iterator();
1199            props.hasNext(); ) {
1200                
1201                ResourceProperty prop = (ResourceProperty) props.next();
1202                env.put(prop.getName(), prop.getValue());
1203            }
1204            
1205            Context context = null;
1206            try {
1207                context =
1208                ((InitialContextFactory JavaDoc)factory).getInitialContext(env);
1209                
1210            } catch (NamingException ne) {
1211                _logger.log(Level.SEVERE,"jndi.initial_context_error",factoryClass);
1212                _logger.log(Level.SEVERE,"jndi.initial_context_error_excp",ne.getMessage());
1213            }
1214            
1215            if (context == null) {
1216                _logger.log(Level.SEVERE,"jndi.factory_create_error",factoryClass);
1217                return;
1218            }
1219            
1220            // Bind a Reference to the proxy object factory; set the
1221
// initial context factory.
1222
//JndiProxyObjectFactory.setInitialContext(bindName, context);
1223

1224            Reference ref = new Reference(extJndiRes.getResType(),
1225            "com.sun.enterprise.resource.JndiProxyObjectFactory",
1226            null);
1227            
1228            // unique JNDI name within server runtime
1229
ref.add(new StringRefAddr("jndiName", bindName));
1230            
1231            // target JNDI name
1232
ref.add(new StringRefAddr("jndiLookupName", jndiLookupName));
1233            
1234            // target JNDI factory class
1235
ref.add(new StringRefAddr("jndiFactoryClass", factoryClass));
1236            
1237            // add Context info as a reference address
1238
ref.add(new ProxyRefAddr(bindName, env));
1239            
1240            // Publish the reference
1241
nm.publishObject(bindName, ref, true);
1242            
1243        } catch (Exception JavaDoc ex) {
1244            _logger.log(Level.SEVERE,"customrsrc.create_ref_error",bindName);
1245            _logger.log(Level.SEVERE,"customrsrc.create_ref_error_excp",ex);
1246            
1247        }
1248    }
1249    
1250    /**
1251     * Installs all iAS 7.0 external JNDI resource proxy resources. This method
1252     * gets called during server initialization.
1253     */

1254    public void installExternalJndiResources() {
1255        
1256        // all available external jndi resources
1257
Set extResSet = resourceInfo.getResourcesByType(
1258        J2EEResource.EXTERNAL_JNDI_RESOURCE);
1259        
1260        for (Iterator iter=extResSet.iterator(); iter.hasNext();) {
1261            
1262            ExternalJndiResource next = (ExternalJndiResource) iter.next();
1263            
1264            // install the resource
1265
installExternalJndiResource(next);
1266        }
1267    }
1268    
1269    /**
1270     * Un-installs the external jndi resource.
1271     *
1272     * @param resource external jndi resource
1273     */

1274    public void uninstallExternalJndiResource(J2EEResource resource) {
1275        
1276        // remove from the collection
1277
resourceInfo.removeResource(resource);
1278        
1279        // removes the jndi context from the factory cache
1280
JndiProxyObjectFactory.removeInitialContext( resource.getName() );
1281        
1282        // removes the resource from jndi naming
1283
NamingManager nm = Switch.getSwitch().getNamingManager();
1284        try {
1285            nm.unpublishObject( resource.getName() );
1286            //START OF IASRI 4660565
1287
if (((ExternalJndiResource)resource).isJMSConnectionFactory()) {
1288                nm.unpublishObject(IASJmsUtil.getXAConnectionFactoryName(resource.getName()));
1289            }
1290            //END OF IASRI 4660565
1291
} catch (javax.naming.NamingException JavaDoc e) {
1292            _logger.log(Level.FINE,
1293            "Error while unpublishing resource: " + resource.getName(), e);
1294        }
1295    }
1296    
1297    /**
1298     * Installs the given mail resource. This method gets called during server
1299     * initialization and from mail resource deployer to handle resource events.
1300     *
1301     * @param mailRes mail resource
1302     */

1303    public void installMailResource(MailResource mailRes) {
1304        
1305        NamingManager nm = Switch.getSwitch().getNamingManager();
1306        String JavaDoc bindName = null;
1307        
1308        try {
1309            bindName = mailRes.getName();
1310            
1311            MailConfiguration config = new MailConfiguration(mailRes);
1312            
1313            // Publish the objet
1314
nm.publishObject(bindName, config, true);
1315        } catch (Exception JavaDoc ex) {
1316            _logger.log(Level.SEVERE, "mailrsrc.create_obj_error", bindName);
1317            _logger.log(Level.SEVERE, "mailrsrc.create_obj_error_excp", ex);
1318        }
1319    }
1320    
1321    /**
1322     * Installs all iAS 7.0 mail resources. This method gets called during
1323     * server initialization.
1324     */

1325    public void installMailResources() {
1326        
1327        // all available mail resources
1328
Set mailResSet = resourceInfo.getResourcesByType(
1329        J2EEResource.MAIL_RESOURCE);
1330        
1331        for (Iterator iter = mailResSet.iterator(); iter.hasNext();) {
1332            MailResource next = (MailResource)iter.next();
1333            
1334            // install the resource
1335
installMailResource(next);
1336        }
1337    }
1338    
1339    public void addResource(J2EEResource resource)throws PoolingException{
1340        try{
1341            resourceInfo.addResource(resource);
1342            resFactory.storeDefaultResourceCollection(resourceInfo);
1343        } catch (Exception JavaDoc ex) {
1344            _logger.log(Level.SEVERE,"J2EE.add_resource_error",ex);
1345            throw new PoolingException(ex.toString());
1346        }
1347    }
1348    
1349    
1350    
1351    public void removeResource(J2EEResource resource)throws PoolingException{
1352        try{
1353            resourceInfo.removeResource(resource);
1354            resFactory.storeDefaultResourceCollection(resourceInfo);
1355        } catch (Exception JavaDoc ex) {
1356            _logger.log(Level.WARNING,"J2EE.remove_resource_error",ex);
1357            throw new PoolingException(ex.toString());
1358        }
1359    }
1360
1361    public ConnectorDescriptor
1362        getDescriptorByConnectorName(String JavaDoc appName, String JavaDoc connectorName) {
1363
1364    return null;
1365
1366    }
1367
1368    private void logFine( String JavaDoc msg ) {
1369        if (_logger.isLoggable(Level.FINE)) {
1370        _logger.fine( msg );
1371    }
1372    }
1373
1374    private String JavaDoc getTransactionSupport(
1375        com.sun.enterprise.config.serverbeans.ConnectorConnectionPool pool)
1376   {
1377
1378    String JavaDoc txSupport = pool.getTransactionSupport();
1379
1380        if ( txSupport != null ) {
1381        return txSupport;
1382    }
1383        
1384        try {
1385    
1386        txSupport = ConnectorRuntime.getRuntime().getConnectorDescriptor(
1387            pool.getResourceAdapterName() ).getOutboundResourceAdapter().
1388        getTransSupport() ;
1389    } catch( ConnectorRuntimeException cre ) {
1390        _logger.log(Level.WARNING, cre.getMessage() );
1391        txSupport = ConnectorConstants.NO_TRANSACTION_TX_SUPPORT_STRING;
1392    }
1393
1394        return txSupport;
1395    }
1396}
1397
Popular Tags