KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > connectors > system > ActiveJmsResourceAdapter


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.system;
25
26 import com.sun.enterprise.deployment.ConnectorDescriptor;
27 import com.sun.enterprise.deployment.EjbMessageBeanDescriptor;
28 import com.sun.enterprise.deployment.runtime.BeanPoolDescriptor;
29 import com.sun.enterprise.deployment.EnvironmentProperty;
30
31 import com.sun.enterprise.connectors.*;
32 import com.sun.enterprise.connectors.inflow.*;
33 import com.sun.enterprise.connectors.util.JmsRaUtil;
34 import com.sun.logging.LogDomains;
35 import com.sun.enterprise.config.ConfigBean;
36 import com.sun.enterprise.config.ConfigContext;
37 import com.sun.enterprise.config.ConfigException;
38 import com.sun.enterprise.server.ApplicationServer;
39 import com.sun.enterprise.server.ResourcesUtil;
40
41 import com.sun.enterprise.server.ServerContext;
42 import com.sun.enterprise.config.serverbeans.ClusterHelper;
43 import com.sun.enterprise.config.serverbeans.JavaConfig;
44 import com.sun.enterprise.config.serverbeans.JdbcConnectionPool;
45 import com.sun.enterprise.config.serverbeans.JmsAvailability;
46 import com.sun.enterprise.config.serverbeans.Resources;
47 import com.sun.enterprise.config.serverbeans.ServerBeansFactory;
48 import com.sun.enterprise.config.serverbeans.ConnectorResource;
49 import com.sun.enterprise.config.serverbeans.AdminObjectResource;
50 import com.sun.enterprise.config.serverbeans.ConnectorConnectionPool;
51 import com.sun.enterprise.config.serverbeans.ElementProperty;
52 import com.sun.enterprise.config.serverbeans.AvailabilityService;
53 import com.sun.enterprise.config.serverbeans.JmsService;
54 import com.sun.enterprise.config.serverbeans.JmsHost;
55 import com.sun.enterprise.config.serverbeans.AdminService;
56 import com.sun.enterprise.config.serverbeans.JmxConnector;
57 import com.sun.enterprise.config.serverbeans.ServerHelper;
58 import com.sun.enterprise.instance.ServerManager;
59 import com.sun.enterprise.jms.IASJmsUtil;
60 import com.sun.enterprise.jms.JmsProviderLifecycle;
61 import com.sun.enterprise.util.SystemPropertyConstants;
62 import com.sun.enterprise.util.i18n.StringManager;
63
64 import java.rmi.Naming JavaDoc;
65 import java.util.ArrayList JavaDoc;
66 import java.util.HashSet JavaDoc;
67 import java.util.List JavaDoc;
68 import java.util.Properties JavaDoc;
69 import java.util.Set JavaDoc;
70 import java.util.Iterator JavaDoc;
71 import java.util.StringTokenizer JavaDoc;
72 import java.io.BufferedWriter JavaDoc;
73 import java.io.File JavaDoc;
74 import java.io.FileWriter JavaDoc;
75 import java.io.IOException JavaDoc;
76 import java.lang.reflect.Method JavaDoc;
77 import java.util.logging.Level JavaDoc;
78 import java.util.logging.Logger JavaDoc;
79 import javax.resource.spi.ManagedConnectionFactory JavaDoc;
80 import javax.resource.spi.ResourceAdapter JavaDoc;
81
82 /**
83  * Represents an active JMS resource adapter. This does
84  * additional configuration to ManagedConnectionFactory
85  * and ResourceAdapter java beans.
86  *
87  * XXX: For code management reasons, think about splitting this
88  * to a preHawk and postHawk RA (with postHawk RA extending preHawk RA).
89  *
90  * @author Binod P.G, Sivakumar Thyagarajan
91  */

92 public class ActiveJmsResourceAdapter extends ActiveInboundResourceAdapter {
93
94     static Logger JavaDoc logger = LogDomains.getLogger(LogDomains.RSR_LOGGER);
95
96     private final String JavaDoc SETTER = "setProperty";
97     private static final String JavaDoc SEPARATOR = "#";
98     private static final String JavaDoc MQ_PASS_FILE_PREFIX = "asmq";
99     private static final String JavaDoc MQ_PASS_FILE_KEY = "imq.imqcmd.password=";
100
101     //RA Javabean properties.
102
public static final String JavaDoc CONNECTION_URL = "ConnectionURL";
103     private final String JavaDoc RECONNECTENABLED = "ReconnectEnabled";
104     private final String JavaDoc RECONNECTINTERVAL = "ReconnectInterval";
105     private final String JavaDoc RECONNECTATTEMPTS = "ReconnectAttempts";
106     private static final String JavaDoc GROUPNAME = "GroupName";
107     private static final String JavaDoc CLUSTERCONTAINER = "InClusteredContainer";
108     
109     //Lifecycle RA JavaBean properties
110
public static final String JavaDoc BROKERTYPE="BrokerType";
111     private static final String JavaDoc BROKERINSTANCENAME="BrokerInstanceName";
112     private static final String JavaDoc BROKERBINDADDRESS="BrokerBindAddress";
113     private static final String JavaDoc BROKERPORT="BrokerPort";
114     private static final String JavaDoc BROKERARGS="BrokerArgs";
115     private static final String JavaDoc BROKERHOMEDIR="BrokerHomeDir";
116     private static final String JavaDoc BROKERVARDIR="BrokerVarDir";
117     private static final String JavaDoc BROKERJAVADIR="BrokerJavaDir";
118     private static final String JavaDoc BROKERSTARTTIMEOUT="BrokerStartTimeOut";
119     private static final String JavaDoc ADMINUSERNAME="AdminUserName";
120     private static final String JavaDoc ADMINPASSWORD="AdminPassword";
121     private static final String JavaDoc ADMINPASSFILE="AdminPassFile";
122
123     private static final String JavaDoc MASTERBROKER="MasterBroker";
124     
125     //JMX properties
126
private static final String JavaDoc JMXSERVICEURL="JMXServiceURL";
127     private static final String JavaDoc JMXSERVICEURLLIST="JMXServiceURLList";
128     private static final String JavaDoc JMXCONNECTORENV="JMXConnectorEnv";
129     private static final String JavaDoc USEJNDIRMISERVICEURL="useJNDIRMIServiceURL";
130     private static final String JavaDoc RMIREGISTRYPORT="RmiRegistryPort";
131     private static final String JavaDoc USEEXTERNALRMIREGISTRY="startRMIRegistry";
132     private static final String JavaDoc SSLJMXCONNECTOR="SslJMXConnector";
133     
134     //Availability properties
135
private static final String JavaDoc HAREQUIRED = "HARequired";
136     private static final String JavaDoc CLUSTERID = "ClusterId";
137     private static final String JavaDoc BROKERID = "BrokerId";
138     private static final String JavaDoc PINGINTERVAL = "PingInterval";
139     private static final String JavaDoc DBTYPE = "DBType";
140     private static final String JavaDoc DBTYPE_HADB="hadb";
141     private static final String JavaDoc BROKERENABLEHA = "BrokerEnableHA";
142     
143     private static final String JavaDoc DB_HADB_PROPS = "DBProps";
144     //properties within DB_PROPS
145
private static final String JavaDoc DB_HADB_USER = "hadb.user";
146     private static final String JavaDoc DB_HADB_PASSWORD = "hadb.password";
147     private static final String JavaDoc DB_HADB_DRIVERCLASS = "hadb.driverClass";
148     private static final String JavaDoc DS_HADB_PROPS = "DSProps";
149     //properties within DS_PROPS
150
private static final String JavaDoc DS_HADB_SERVERLIST = "hadb.serverList";
151     
152     //Not used now.
153
private final String JavaDoc CONTAINER = "InAppClientContainer";
154
155     //Activation config properties of MQ resource adapter.
156
public static String JavaDoc DESTINATION = "Destination";
157     public static String JavaDoc DESTINATION_TYPE = "DestinationType";
158     private static String JavaDoc SUBSCRIPTION_NAME = "SubscriptionName";
159     private static String JavaDoc CLIENT_ID = "ClientID";
160     public static String JavaDoc PHYSICAL_DESTINATION = "Name";
161     private static String JavaDoc MAXPOOLSIZE = "EndpointPoolMaxSize";
162     private static String JavaDoc MINPOOLSIZE = "EndpointPoolSteadySize";
163     private static String JavaDoc RESIZECOUNT = "EndpointPoolResizeCount";
164     private static String JavaDoc RESIZETIMEOUT = "EndpointPoolResizeTimeout";
165     private static String JavaDoc REDELIVERYCOUNT = "EndpointExceptionRedeliveryAttempts";
166     public static String JavaDoc ADDRESSLIST = "AddressList";
167     private static String JavaDoc ADRLIST_BEHAVIOUR = "AddressListBehavior";
168     private static String JavaDoc ADRLIST_ITERATIONS = "AddressListIterations";
169     private static final String JavaDoc MDBIDENTIFIER = "MdbName";
170
171     //MCF properties
172
private static final String JavaDoc MCFADDRESSLIST = "MessageServiceAddressList";
173
174     private StringManager sm =
175         StringManager.getManager(ActiveJmsResourceAdapter.class);
176
177     MQAddressList urlList = null;
178
179     //Properties in domain.xml for HADB JDBC connection pool (for HA)
180
private static final String JavaDoc DUSERNAME = "User";
181     private static final String JavaDoc DPASSWORD = "Password";
182     private static final String JavaDoc DSERVERLIST = "ServerList";
183     private static final String JavaDoc HADB_CONNECTION_URL_PREFIX = "jdbc:sun:hadb:";
184     
185     //Lifecycle properties
186
public static final String JavaDoc EMBEDDED="EMBEDDED";
187     public static final String JavaDoc LOCAL="LOCAL";
188     public static final String JavaDoc REMOTE="REMOTE";
189
190     private final String JavaDoc DEFAULT_STORE_POOL_JNDI_NAME = "jdbc/hastore";
191
192     // Both the properties below are hacks. These will be changed later on.
193
private static String JavaDoc MQRmiPort =
194         System.getProperty("com.sun.enterprise.connectors.system.MQRmiPort");
195     private static final String JavaDoc DASRMIPORT = "31099";
196
197     private Properties JavaDoc dbProps = null;
198     private Properties JavaDoc dsProps = null;
199     private String JavaDoc brokerInstanceName = null;
200         
201     private File JavaDoc mqPassFile = null;
202         
203     /**
204      * Constructor for an active Jms Adapter.
205      *
206      * @param ra ResourceAdapter Javabean.
207      * @param desc Deployment descriptor object
208      * @param moduleName Name of the resource adapter.
209      * @parm jcl Class Loader.
210      * @throw ConnectorRuntimeException in case of an exception.
211      */

212     public ActiveJmsResourceAdapter(
213             ResourceAdapter JavaDoc ra, ConnectorDescriptor desc, String JavaDoc moduleName,
214             ClassLoader JavaDoc jcl) throws ConnectorRuntimeException {
215         super(ra,desc,moduleName,jcl);
216         
217         //Now that the RA has been started, delete the temp passfile
218
if (mqPassFile != null) {
219             mqPassFile.delete();
220         }
221     }
222
223     /**
224      * Loads RA configuration for MQ Resource adapter.
225      *
226      * @throw ConnectorRuntimeException in case of an exception.
227      */

228     protected void loadRAConfiguration() throws ConnectorRuntimeException{
229         if (ConnectorRuntime.getRuntime().getEnviron()
230                                        == ConnectorRuntime.SERVER) {
231             // Check whether MQ has started up or not.
232
try {
233                 if (!JmsProviderLifecycle.shouldUseMQRAForLifecycleControl()) {
234                     JmsProviderLifecycle.checkProviderStartup();
235                 } else {
236                     setLifecycleProperties();
237                 }
238             } catch (Exception JavaDoc e) {
239                 ConnectorRuntimeException cre = new ConnectorRuntimeException
240                                                         (e.getMessage());
241                 throw (ConnectorRuntimeException) cre.initCause(e);
242             }
243             
244             setMdbContainerProperties();
245             setJmsServiceProperties(null);
246             setClusterRABeanProperties();
247             setAvailabilityProperties();
248         } else {
249             setAppClientRABeanProperties();
250         }
251         super.loadRAConfiguration();
252         postRAConfiguration();
253     }
254
255     /*
256      * Set Availability related properties
257      * If EE: If JMS availability true set availability properties
258      * If shared hadb : get HADB CCP information and set accordingly
259      * If not shared : read configured pool information and set.
260      */

261     private void setAvailabilityProperties() throws ConnectorRuntimeException {
262         try {
263             ConfigContext ctx = ApplicationServer.getServerContext().getConfigContext();
264             AvailabilityService as = ServerBeansFactory.getConfigBean(ctx).getAvailabilityService();
265             if (as == null) {
266                 logFine("Availability Service is null. Not setting HA attributes");
267                 return;
268             }
269             
270             //Only if JMS availability is true
271
if (isJMSAvailabilityOn(as)) {
272                 ConnectorDescriptor cd = getDescriptor();
273                 //Set HARequired as true - irrespective of whether it is REMOTE or
274
//LOCAL
275
EnvironmentProperty envProp1 = new EnvironmentProperty (
276                                             HAREQUIRED , "true","HA Required",
277                                            "java.lang.String");
278                 setProperty(cd, envProp1);
279                 
280                 JmsService jmsService = ServerBeansFactory.getConfigBean(ctx).
281                                                                 getJmsService();
282                 if (isClustered()) {
283                     if (jmsService.getType().equals(REMOTE)) {
284                         //If REMOTE, the broker cluster instances already have
285
//been configured with the right properties.
286
return;
287                     } else {
288                         //LOCAL/EMBEDDED instances in a cluster.
289
String JavaDoc clusterName = getMQClusterName();
290                         EnvironmentProperty envProp2 = new EnvironmentProperty (
291                                     CLUSTERID , clusterName,"Cluster Id",
292                                     "java.lang.String");
293                         setProperty(cd, envProp2);
294                         
295                         if(brokerInstanceName == null) {
296                             brokerInstanceName = getBrokerInstanceName(jmsService);
297                         }
298                         EnvironmentProperty envProp3 = new EnvironmentProperty (
299                                     BROKERID , brokerInstanceName,"Broker Id",
300                                     "java.lang.String");
301                         setProperty(cd, envProp3);
302                         
303                         
304                         EnvironmentProperty envProp4 = new EnvironmentProperty (
305                                         DBTYPE , DBTYPE_HADB,"DBType",
306                                         "java.lang.String");
307                         setProperty(cd, envProp4);
308
309                         /*
310                          * The broker has a property to control whether
311                          * it starts in HA mode or not and that's represented on
312                          * the RA by BrokerEnableHA.
313                          * On the MQ Client connection side it is HARequired -
314                          * this does not control the broker, it just is a client
315                          * side requirement.
316                          * So for AS EE, if BrokerType is LOCAL or EMBEDDED,
317                          * and AS HA is enabled for JMS then both these must be
318                          * set to true.
319                          */

320                         EnvironmentProperty envProp5 = new EnvironmentProperty (
321                                         BROKERENABLEHA , "true",
322                                         "BrokerEnableHA flag","java.lang.Boolean");
323                         setProperty(cd, envProp5);
324                         
325                         //get pool name
326
String JavaDoc poolJNDIName = as.getJmsAvailability().getMqStorePoolName();
327                         //If no MQ store pool name is specified, use default poolname
328
//XXX: default pool name is jdbc/hastore but asadmin
329
//configure-ha-cluster creates a resource called
330
//"jdbc/<asclustername>-hastore" which needs to be used.
331
if (poolJNDIName == null || poolJNDIName =="" ) {
332                             //get Web container's HA store's pool name
333
poolJNDIName = as.getWebContainerAvailability().
334                                                 getHttpSessionStorePoolName();
335                             logFine("HTTP Session store pool jndi name " +
336                                     "is " + poolJNDIName);
337                         }
338                         //XXX: request HADB team mq-store-pool name to be
339
//populated as part of configure-ha-cluster
340

341                         JdbcConnectionPool jdbcConPool = getJDBCConnectionPoolInfo(
342                                                             poolJNDIName);
343                         //DBProps: compute values from pool object
344
String JavaDoc userName = getPropertyFromPool(jdbcConPool, DUSERNAME);
345                         logFine("HA username is " + userName);
346                         
347                         String JavaDoc password = getPropertyFromPool(jdbcConPool, DPASSWORD);
348                         logFine("HA Password is " + password);
349                         
350                         String JavaDoc driverClass = jdbcConPool.getDatasourceClassname();
351                         logFine("HA driverclass" + driverClass);
352                         
353                         dbProps = new Properties JavaDoc();
354                         dbProps.setProperty(DB_HADB_USER, userName);
355                         dbProps.setProperty(DB_HADB_PASSWORD, password);
356                         dbProps.setProperty(DB_HADB_DRIVERCLASS, driverClass);
357                         
358                         //DSProps: compute values from pool object
359
String JavaDoc serverList = getPropertyFromPool(jdbcConPool, DSERVERLIST);
360                         logFine("HADB server list is " + serverList);
361                         dsProps = new Properties JavaDoc();
362
363                         if (serverList != null) {
364                             dsProps.setProperty(DS_HADB_SERVERLIST, serverList);
365                         } else {
366                             logger.warning("ajra.incorrect_hadb_server_list");
367                         }
368                         
369                         //set all other properties in dsProps as well.
370
Properties JavaDoc p = getDSPropertiesFromThePool(jdbcConPool);
371                         Iterator JavaDoc iterator = p.keySet().iterator();
372                         while (iterator.hasNext()) {
373                             String JavaDoc key = (String JavaDoc) iterator.next();
374                             String JavaDoc val = (String JavaDoc)p.get(key);
375                             dsProps.setProperty(key, val);
376                         }
377                     }
378                 } else {
379                     //ignore. Not clustered.
380
logFine("Instance not clustered. Not setting HA " +
381                     "attributes");
382                 }
383             }
384         } catch (ConfigException e) {
385             ConnectorRuntimeException crex = new ConnectorRuntimeException(
386                             e.getMessage());
387             throw (ConnectorRuntimeException)crex.initCause(e);
388         }
389     }
390     
391     /*
392      * Gets all the other [apart from serverlist] DataSource properties from
393      * the HADB JDBC connection pool.
394      */

395     private Properties JavaDoc getDSPropertiesFromThePool(JdbcConnectionPool jdbcConPool) {
396         Properties JavaDoc p = new Properties JavaDoc();
397         ElementProperty[] elemProp = jdbcConPool.getElementProperty();
398         Set JavaDoc<String JavaDoc> excludeList = new HashSet JavaDoc<String JavaDoc>();
399         excludeList.add(DUSERNAME);
400         excludeList.add(DPASSWORD);
401         excludeList.add(DSERVERLIST);
402         
403         for(ElementProperty e: elemProp) {
404             String JavaDoc propName = e.getAttributeValue("name");
405             if (!excludeList.contains(propName)) {
406                 p.setProperty(propName, e.getAttributeValue("value"));
407             }
408         }
409         logFine("Additional DataSource properties from pool "
410                         + jdbcConPool.getName() + " are " + p);
411         return p;
412     }
413
414     /**
415      * Method to perform any post RA configuration action by derivative subclasses.
416      * For example, this method is used by <code>ActiveJMSResourceAdapter</code>
417      * to set unsupported javabean property types on its RA JavaBean runtime
418      * instance.
419      * @throws ConnectorRuntimeException
420      */

421     protected void postRAConfiguration() throws ConnectorRuntimeException {
422         //Set all non-supported javabean property types in the JavaBean
423
try {
424             if (dbProps != null) {
425                 Method JavaDoc[] mthds = this.resourceadapter_.getClass().getMethods();
426                 for (int i = 0; i < mthds.length; i++) {
427                     if(mthds[i].getName().equalsIgnoreCase("set" + DB_HADB_PROPS)) {
428                         logFine("Setting property:" + DB_HADB_PROPS
429                                         + "=" + dbProps.toString());
430                         mthds[i].invoke(this.resourceadapter_,
431                                         new Object JavaDoc[]{dbProps});
432                     } else if(mthds[i].getName().equalsIgnoreCase("set" + DS_HADB_PROPS)) {
433                         logFine("Setting property:" + DS_HADB_PROPS
434                                         + "=" + dsProps.toString());
435                         mthds[i].invoke(this.resourceadapter_, new Object JavaDoc[]{dsProps});
436                     }
437                 }
438             }
439         } catch (Exception JavaDoc e) {
440             ConnectorRuntimeException crex = new ConnectorRuntimeException(
441                             e.getMessage());
442             throw (ConnectorRuntimeException)crex.initCause(e);
443         }
444     }
445     
446     private String JavaDoc getPropertyFromPool(JdbcConnectionPool jdbcConPool,
447                     String JavaDoc poolPropertyName) {
448         String JavaDoc poolPropertyValue = null;
449         if(jdbcConPool == null) {
450             return null;
451         }
452         ElementProperty[] props = jdbcConPool.getElementProperty();
453         for (int i = 0; i < props.length; i++) {
454             String JavaDoc name = props[i].getAttributeValue("name");
455             String JavaDoc value = props[i].getAttributeValue("value");
456             if (name.equalsIgnoreCase(poolPropertyName)) {
457             //if (name.equalsIgnoreCase("username")) {
458
poolPropertyValue = value;
459             }
460         }
461         logFine("ActiveJMSResourceAdapter :: got property " + poolPropertyName
462                         + "="+ poolPropertyValue);
463         return poolPropertyValue;
464     }
465
466     private JdbcConnectionPool getJDBCConnectionPoolInfo(String JavaDoc poolJndiName)
467                                                         throws ConfigException {
468         return ResourcesUtil.getInstance().getJDBCPoolForResource(poolJndiName);
469     }
470
471     private boolean isJMSAvailabilityOn(AvailabilityService as) {
472         //need to check for global availability like EJB
473
JmsAvailability ja = as.getJmsAvailability();
474         boolean jmsAvailability = ja.isAvailabilityEnabled();
475         logFine("JMS availability :: " + jmsAvailability);
476         return jmsAvailability;
477     }
478
479     /**
480      * Set MQ4.0 RA lifecycle properties
481      */

482     private void setLifecycleProperties() throws
483                                       ConfigException, ConnectorRuntimeException {
484         ConfigContext ctx = ApplicationServer.getServerContext().getConfigContext();
485     
486
487         //If PE:
488
//EMBEDDED/LOCAL goto jms-service, get defaultjmshost info and set
489
//accordingly
490
//if EE:
491
//EMBEDDED/LOCAL get this instance and cluster name, search for a
492
//jms-host wth this this name in jms-service gets its proeprties
493
//and set
494
//@siva As of now use default JMS host. As soon as changes for modifying EE
495
//cluster to LOCAL is brought in, change this to use system properties
496
//for EE to get port, host, adminusername, adminpassword.
497
JmsService jmsService = ServerBeansFactory.getJmsServiceBean(ctx);
498         String JavaDoc defaultJmsHost = jmsService.getDefaultJmsHost();
499         logFine("Default JMS Host :: " + defaultJmsHost);
500         
501         JmsHost jmsHost = null;
502         if (defaultJmsHost == null || defaultJmsHost.equals("")) {
503             jmsHost = ServerBeansFactory.getJmsHostBean(ctx);
504         } else {
505             jmsHost = jmsService.getJmsHostByName(defaultJmsHost);
506         }
507         
508         if (jmsHost != null && jmsHost.isEnabled()) {
509             JavaConfig javaConfig = ServerBeansFactory.getJavaConfigBean(ctx);
510             String JavaDoc java_home = javaConfig.getJavaHome();
511             
512             //Get broker type from JMS Service.
513
String JavaDoc brokerType = jmsService.getType();
514             String JavaDoc brokerPort = jmsHost.getPort();
515             String JavaDoc adminUserName = jmsHost.getAdminUserName();
516             String JavaDoc adminPassword = jmsHost.getAdminPassword();
517
518             createMQVarDirectoryIfNecessary();
519             String JavaDoc brokerVarDir = getMQVarDir();
520
521             String JavaDoc tmpString = jmsService.getStartArgs();
522             if (tmpString == null) {
523                 tmpString = "";
524             }
525             
526             String JavaDoc brokerArgs = tmpString;
527             
528
529             //XXX: Extract the information from the optional properties.
530
ElementProperty[] jmsProperties =
531                 jmsService.getElementProperty();
532             
533             String JavaDoc brokerHomeDir = getBrokerHomeDir();
534             if (brokerInstanceName == null) {
535                 brokerInstanceName = getBrokerInstanceName(jmsService);
536             }
537             
538             long brokerTimeOut = getBrokerTimeOut(jmsService);
539
540             //Need to set the following properties
541
//BrokerType, BrokerInstanceName, BrokerPort,
542
//BrokerArgs, BrokerHomeDir, BrokerVarDir, BrokerStartTimeout
543
//adminUserName, adminPassword
544
ConnectorDescriptor cd = getDescriptor();
545             EnvironmentProperty envProp1 = new EnvironmentProperty (
546                     BROKERTYPE, brokerType, "Broker Type", "java.lang.String");
547             setProperty(cd, envProp1);
548             EnvironmentProperty envProp2 = new EnvironmentProperty (
549                     BROKERINSTANCENAME, brokerInstanceName ,
550                     "Broker Instance Name", "java.lang.String");
551             setProperty(cd, envProp2);
552             EnvironmentProperty envProp3 = new EnvironmentProperty (
553                     BROKERPORT , brokerPort ,
554                     "Broker Port", "java.lang.String");
555             setProperty(cd, envProp3);
556             EnvironmentProperty envProp4 = new EnvironmentProperty (
557                     BROKERARGS , brokerArgs ,
558                     "Broker Args", "java.lang.String");
559             setProperty(cd, envProp4);
560             EnvironmentProperty envProp5 = new EnvironmentProperty (
561                     BROKERHOMEDIR , brokerHomeDir ,
562                     "Broker Home Dir", "java.lang.String");
563             setProperty(cd, envProp5);
564             EnvironmentProperty envProp6 = new EnvironmentProperty (
565                     BROKERJAVADIR , java_home ,
566                     "Broker Java Dir", "java.lang.String");
567                     setProperty(cd, envProp6);
568             EnvironmentProperty envProp7 = new EnvironmentProperty (
569                     BROKERVARDIR , brokerVarDir ,
570                     "Broker Var Dir", "java.lang.String");
571             setProperty(cd, envProp7);
572             EnvironmentProperty envProp8 = new EnvironmentProperty (
573                     BROKERSTARTTIMEOUT , "" + brokerTimeOut ,
574                     "Broker Start Timeout", "java.lang.String");
575             setProperty(cd, envProp8);
576             EnvironmentProperty envProp9 = new EnvironmentProperty (
577                     ADMINUSERNAME , adminUserName,
578                     "Broker admin username", "java.lang.String");
579             setProperty(cd, envProp9);
580             EnvironmentProperty envProp10 = new EnvironmentProperty (
581                     ADMINPASSWORD , adminPassword ,
582                     "Broker admin password", "java.lang.String");
583             setProperty(cd, envProp10);
584             
585             //set adminpassfile
586
if (!jmsService.getType().equals(REMOTE)) {
587                 //For LOCAL and EMBEDDED, we pass in the admin pass file path
588
//containing the MQ admin password to enable authenticated
589
//startup of the broker.
590
String JavaDoc adminPassFilePath = getAdminPassFilePath(adminPassword);
591                 if (adminPassFilePath != null) {
592                     EnvironmentProperty envProp11 = new EnvironmentProperty (
593                             ADMINPASSFILE , adminPassFilePath ,
594                             "Broker admin password", "java.lang.String");
595                     setProperty(cd, envProp11);
596                 }
597             }
598         }
599         //Optional
600
//BrokerBindAddress, RmiRegistryPort
601
}
602     
603     private String JavaDoc getAdminPassFilePath(String JavaDoc adminPassword) {
604         try {
605             mqPassFile = File.createTempFile(MQ_PASS_FILE_PREFIX,null);
606             BufferedWriter JavaDoc out = new BufferedWriter JavaDoc(new FileWriter JavaDoc(mqPassFile));
607             out.write(MQ_PASS_FILE_KEY + adminPassword);
608             out.newLine();
609             out.flush();
610             out.close();
611             return mqPassFile.getCanonicalPath();
612         } catch (IOException JavaDoc e) {
613             logger.log(Level.WARNING, "IOException while creating MQ admin pass file" + e.getMessage());
614         }
615         return null;
616     }
617
618     private long getBrokerTimeOut(JmsService jmsService) {
619         //@@remove
620
long defaultTimeout = 30 * 1000; //30 seconds
621
long timeout = defaultTimeout;
622     
623         String JavaDoc specifiedTimeOut = jmsService.getInitTimeoutInSeconds();
624         if (specifiedTimeOut != null)
625             timeout = Integer.parseInt(specifiedTimeOut) * 1000;
626         return timeout;
627     }
628
629     public static String JavaDoc getBrokerInstanceName(JmsService js)
630                       throws ConfigException, ConnectorRuntimeException {
631         String JavaDoc asInstance = ApplicationServer.getServerContext().getInstanceName();
632         String JavaDoc domainName = null;
633         if (isClustered()) {
634             domainName = ClusterHelper.getClusterForInstance(
635                             ApplicationServer.getServerContext().getConfigContext(),
636                             asInstance).getName();
637         } else {
638             domainName = ServerManager.instance().getDomainName();
639         }
640         String JavaDoc s = IASJmsUtil.getBrokerInstanceName(domainName, asInstance, js);
641         logFine("IASJMSUtil gave broker Instancename as " + s);
642         String JavaDoc converted = convertStringToValidMQIdentifier(s);
643         logFine("converted instance name " + converted);
644         return converted;
645     }
646
647     private void createMQVarDirectoryIfNecessary(){
648         String JavaDoc asInstanceRoot = ApplicationServer.getServerContext().
649                                    getInstanceEnvironment().getInstancesRoot();
650         String JavaDoc mqInstanceDir = asInstanceRoot + java.io.File.separator
651                                                   + IASJmsUtil.MQ_DIR_NAME;
652          // If the directory doesnt exist, create it.
653
// It is necessary for windows.
654
java.io.File JavaDoc instanceDir = new java.io.File JavaDoc(mqInstanceDir);
655          if (!(instanceDir.exists() && instanceDir.isDirectory())) {
656              instanceDir.mkdirs();
657          }
658     }
659     
660     private String JavaDoc getMQVarDir(){
661         String JavaDoc asInstanceRoot = ApplicationServer.getServerContext().
662                                   getInstanceEnvironment().getInstancesRoot();
663         String JavaDoc mqInstanceDir = asInstanceRoot + java.io.File.separator
664                                                  + IASJmsUtil.MQ_DIR_NAME;
665         return mqInstanceDir;
666     }
667     
668     private String JavaDoc getBrokerHomeDir() {
669         // If the property was not specified, then look for the
670
// imqRoot as defined by the com.sun.aas.imqRoot property
671
String JavaDoc brokerHomeDir = java.lang.System.getProperty(SystemPropertyConstants.IMQ_BIN_PROPERTY);
672         logFine("broker home dir from system property " + brokerHomeDir);
673         
674         // Finally if all else fails (though this should never happen)
675
// look for IMQ relative to the installation directory
676
//@todo reget brokerHomeDir
677
if (brokerHomeDir == null) {
678             String JavaDoc IMQ_INSTALL_SUBDIR = java.io.File.separator +
679                 ".." + java.io.File.separator + ".." +
680                 java.io.File.separator + "imq" ;
681                 //java.io.File.separator + "bin"; hack until MQ RA changes
682
//XXX: This doesn't work in clustered instances.
683
brokerHomeDir = ApplicationServer.getServerContext().getInstallRoot()
684                                 + IMQ_INSTALL_SUBDIR;
685         } else {
686             //hack until MQ RA changes
687
brokerHomeDir = brokerHomeDir + java.io.File.separator + ".." ;
688         }
689         
690         logFine("Broker Home Directory :: " + brokerHomeDir);
691         logFine("broker home dir finally" + brokerHomeDir);
692         return brokerHomeDir;
693         
694     }
695     
696     ////@Siva: provide an API to read JMX information from RA and return it.
697
//private
698

699     
700
701     /**
702      * Sets the SE/EE specific MQ-RA bean properties
703      * @throws ConnectorRuntimeException
704      */

705     private void setClusterRABeanProperties() throws ConnectorRuntimeException {
706         ConnectorDescriptor cd = super.getDescriptor();
707         try {
708             if (isClustered()) {
709                 String JavaDoc val = getGroupName();
710                 EnvironmentProperty envProp = new EnvironmentProperty (
711                     GROUPNAME, val, "Group Name", "java.lang.String");
712                 setProperty(cd, envProp);
713                 EnvironmentProperty envProp1 = new EnvironmentProperty (
714                     CLUSTERCONTAINER, "true", "Cluster container flag",
715                     "java.lang.Boolean");
716                 setProperty(cd, envProp1);
717                 logFine("CLUSTERED instance - setting groupname as" + val);
718             } else {
719                 logFine("Instance not Clustered and hence not setting " +
720                         "groupname");
721             }
722         } catch (ConfigException e) {
723             ConnectorRuntimeException crex = new ConnectorRuntimeException(e.getMessage());
724             throw (ConnectorRuntimeException)crex.initCause(e);
725         }
726     }
727     
728
729     /**
730      * Sets the SE/EE specific MQ-RA bean properties
731      * @throws ConnectorRuntimeException
732      */

733     private void setAppClientRABeanProperties() throws ConnectorRuntimeException {
734         logFine("In Appclient container!!!");
735         ConnectorDescriptor cd = super.getDescriptor();
736         EnvironmentProperty envProp1 = new EnvironmentProperty (
737                         BROKERTYPE, REMOTE, "Broker Type", "java.lang.String");
738                 setProperty(cd, envProp1);
739         
740         EnvironmentProperty envProp2 = new EnvironmentProperty (
741             GROUPNAME, "", "Group Name", "java.lang.String");
742         cd.removeConfigProperty(envProp2);
743         EnvironmentProperty envProp3 = new EnvironmentProperty (
744             CLUSTERCONTAINER, "false", "Cluster flag", "java.lang.Boolean");
745         setProperty(cd, envProp3);
746     }
747     
748     
749     private static boolean isClustered() throws ConnectorRuntimeException {
750         return JmsRaUtil.isClustered();
751     }
752     
753     private String JavaDoc getGroupName() throws ConfigException{
754         return getDomainName() + SEPARATOR + getClusterName();
755     }
756     
757     private String JavaDoc getClusterName() throws ConfigException {
758         return ClusterHelper.getClusterForInstance(
759                         ApplicationServer.getServerContext().getConfigContext(),
760                         ApplicationServer.getServerContext().getInstanceName()).getName();
761     }
762     
763     /*
764      * Generates an Name for the MQ Cluster associated with the
765      * application server cluster.
766      */

767     private String JavaDoc getMQClusterName() throws ConfigException {
768         return convertStringToValidMQIdentifier(getClusterName()) + "_MQCluster";
769     }
770     
771     //All Names passed into MQ needs to be valid Java Identifiers
772
//so as of now replacing all characters that are not valid
773
//java identifier components with '_'
774
private static String JavaDoc convertStringToValidMQIdentifier(String JavaDoc s) {
775         if (s == null) return "";
776         
777         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
778         for(int i = 0; i < s.length(); i++) {
779             if(Character.isLetterOrDigit(s.charAt(i))){
780                             //|| s.charAt(i) == '_'){
781
buf.append(s.charAt(i));
782             }
783         }
784         return buf.toString();
785     }
786     
787     private String JavaDoc getDomainName() throws ConfigException {
788         ConfigContext ctxt = ApplicationServer.getServerContext().getConfigContext();
789         //computing hashcode, since the application root string could
790
//be potentially large
791
/*
792         String domainName = "" + ServerBeansFactory.getDomainBean(ctxt).
793                             getApplicationRoot().hashCode();
794         return domainName;
795         */

796         // FIX LATER
797
return "";
798     }
799
800     /**
801      * Recreates the ResourceAdapter using new values from JmsSerice.
802      *
803      * @param js JmsService element of the domain.xml
804      * @throws ConnectorRuntimeException in case of any backend error.
805      */

806     public void reloadRA(JmsService js) throws ConnectorRuntimeException {
807         setMdbContainerProperties();
808         setJmsServiceProperties(js);
809      
810         super.loadRAConfiguration();
811     rebindDescriptor();
812     }
813
814     /**
815      * Adds the JmsHost to the MQAddressList of the resource adapter.
816      *
817      * @param host JmsHost element in the domain.xml
818      * @throws ConnectorRuntimeException in case of any backend error.
819      */

820     public void addJmsHost(JmsHost host) throws ConnectorRuntimeException {
821         urlList.addMQUrl(host);
822         setAddressList();
823     }
824
825     /**
826      * Removes the JmsHost from the MQAddressList of the resource adapter.
827      *
828      * @param host JmsHost element in the domain.xml
829      * @throws ConnectorRuntimeException in case of any backend error.
830      */

831     public void deleteJmsHost(JmsHost host) throws ConnectorRuntimeException {
832         urlList.removeMQUrl(host);
833         setAddressList();
834     }
835
836     /**
837      * Updates the JmsHost information in the MQAddressList of the resource adapter.
838      *
839      * @param host JmsHost element in the domain.xml
840      * @throws ConnectorRuntimeException in case of any backend error.
841      */

842     public void updateJmsHost(JmsHost host) throws ConnectorRuntimeException {
843         urlList.updateMQUrl(host);
844         setAddressList();
845     }
846     
847     private void setMdbContainerProperties() throws ConnectorRuntimeException {
848         JmsRaUtil raUtil = new JmsRaUtil(null);
849                        
850         ConnectorDescriptor cd = super.getDescriptor();
851         raUtil.setMdbContainerProperties();
852
853         String JavaDoc val = ""+MdbContainerProps.getReconnectEnabled();
854         EnvironmentProperty envProp2 = new EnvironmentProperty (
855             RECONNECTENABLED, val, val, "java.lang.Boolean");
856         setProperty(cd, envProp2);
857
858         val = ""+MdbContainerProps.getReconnectDelay();
859         EnvironmentProperty envProp3 = new EnvironmentProperty (
860             RECONNECTINTERVAL, val, val, "java.lang.Integer");
861         setProperty(cd, envProp3);
862
863         val = ""+MdbContainerProps.getReconnectMaxRetries();
864         EnvironmentProperty envProp4 = new EnvironmentProperty (
865             RECONNECTATTEMPTS, val, val, "java.lang.Integer");
866         setProperty(cd, envProp4);
867
868     // The above properties will be set in ConnectorDescriptor and
869
// will be bound in JNDI. This will be available to appclient
870
// and standalone client.
871
}
872
873     private void setAddressList() throws ConnectorRuntimeException {
874         //@Siva: Enhance setting AddressList. [Ignore this machines jms-host while
875
//constructing addresslist]
876
try {
877             ConfigContext ctx = ApplicationServer.getServerContext().getConfigContext();
878             JmsService jmsService = ServerBeansFactory.getJmsServiceBean(ctx);
879             setConnectionURL(jmsService, urlList);
880         } catch (ConfigException e) {
881             e.printStackTrace();
882         }
883         super.loadRAConfiguration();
884     }
885
886     //This is a MQ workaround. In PE, when the broker type is
887
//EMBEDDED or LOCAL, do not set the addresslist, else
888
//MQ RA assumes that there are two URLs and fails (EE limitation).
889
private void setConnectionURL(JmsService jmsService, MQAddressList urlList) {
890         ConnectorDescriptor cd = super.getDescriptor();
891         String JavaDoc val = urlList.toString();
892         if (val != null) {
893             logger.info("JMS Service Connection URL is :" + val);
894             EnvironmentProperty envProp1 = new EnvironmentProperty (
895                CONNECTION_URL, val, val, "java.lang.String");
896             setProperty(cd, envProp1);
897         }
898     }
899
900     private void setJmsServiceProperties(JmsService service) throws
901                                          ConnectorRuntimeException {
902         JmsRaUtil jmsraUtil = new JmsRaUtil(service);
903         
904         urlList = jmsraUtil.getUrlList();
905
906         ConnectorDescriptor cd = super.getDescriptor();
907         setConnectionURL(service, urlList);
908
909         String JavaDoc val = ""+jmsraUtil.getReconnectEnabled();
910         EnvironmentProperty envProp2 = new EnvironmentProperty (
911             RECONNECTENABLED, val, val, "java.lang.Boolean");
912         setProperty(cd, envProp2);
913
914         //convert to milliseconds
915
int newval = (new Integer JavaDoc(jmsraUtil.getReconnectInterval())).intValue() * 1000;
916         val = "" + newval;
917         EnvironmentProperty envProp3 = new EnvironmentProperty (
918             RECONNECTINTERVAL, val, val, "java.lang.Integer");
919         setProperty(cd, envProp3);
920
921         val = ""+jmsraUtil.getReconnectAttempts();
922         EnvironmentProperty envProp4 = new EnvironmentProperty (
923             RECONNECTATTEMPTS, val, val, "java.lang.Integer");
924         setProperty(cd, envProp4);
925
926         val = ""+jmsraUtil.getAddressListBehaviour();
927         EnvironmentProperty envProp5 = new EnvironmentProperty (
928             ADRLIST_BEHAVIOUR, val, val, "java.lang.String");
929         setProperty(cd, envProp5);
930
931         val = ""+jmsraUtil.getAddressListIterations();
932         EnvironmentProperty envProp6 = new EnvironmentProperty (
933             ADRLIST_ITERATIONS, val, val, "java.lang.Integer");
934         setProperty(cd, envProp6);
935         
936         boolean useExternal = shouldUseExternalRmiRegistry(jmsraUtil);
937         val = (new Boolean JavaDoc(useExternal)).toString();
938         EnvironmentProperty envProp7 = new EnvironmentProperty (
939             USEEXTERNALRMIREGISTRY, val, val, "java.lang.Boolean");
940         setProperty(cd, envProp7);
941
942         //If MQ RA needs to use AS RMI Registry Port, then set
943
//the RMI registry port, else MQ RA uses its default RMI
944
//Registry port [as of now 1099]
945
if (!useExternal) {
946             String JavaDoc configuredRmiRegistryPort = getRmiRegistryPort();
947             val = configuredRmiRegistryPort;
948             if (val != null) {
949                 EnvironmentProperty envProp8 = new EnvironmentProperty (
950                     RMIREGISTRYPORT, val, val, "java.lang.Integer");
951                 setProperty(cd, envProp8);
952             } else {
953                 logger.log(Level.WARNING, "Invalid RMI registry port");
954             }
955         }
956     }
957
958     /*
959      * Checks if AS RMI registry is started and available for use.
960      */

961     private boolean shouldUseExternalRmiRegistry (JmsRaUtil jmsraUtil) {
962         boolean useExternalRmiRegistry = ( !isASRmiRegistryPortAvailable(jmsraUtil) );
963         //System.out.println("useExternalRMIRegisterty :: " + useExternalRmiRegistry);
964
return useExternalRmiRegistry;
965     }
966
967     /**
968      * Get the AS RMI registry port for MQ RA to use.
969      */

970     private String JavaDoc getRmiRegistryPort() {
971         String JavaDoc val = null;
972         if (MQRmiPort != null && !MQRmiPort.trim().equals("")){
973             return MQRmiPort;
974         } else {
975             String JavaDoc configuredPort = null;
976             try {
977                 configuredPort = getConfiguredRmiRegistryPort();
978             } catch (ConfigException ex) {
979                 logger.log(Level.WARNING, ex.getMessage());
980                 logger.log(Level.FINE, "Exception while getting configured rmi " +
981                                                  "registry port", ex);
982             }
983             if (configuredPort != null) {
984                 return configuredPort;
985             }
986             
987             //Finally if DAS and configured port doesn't work, return DAS'
988
//RMI registry port as a fallback option.
989
if (ResourcesUtil.isDAS()) {
990                     return DASRMIPORT;
991             }
992         }
993         return val;
994     }
995     
996     private String JavaDoc getConfiguredRmiRegistryHost() throws ConfigException {
997         return getJmxConnector().getAddress();
998     }
999
1000    private String JavaDoc getConfiguredRmiRegistryPort() throws ConfigException {
1001        return getJmxConnector().getPort();
1002    }
1003    
1004    private JmxConnector getJmxConnector() throws ConfigException{
1005        AdminService as = ServerBeansFactory.getConfigBean(
1006                        ApplicationServer.getServerContext().getConfigContext()).getAdminService();
1007        return as.getJmxConnectorByName(as.getSystemJmxConnectorName());
1008    }
1009    
1010    private boolean isASRmiRegistryPortAvailable(JmsRaUtil jmsraUtil) {
1011        logFine("isASRmiRegistryPortAvailable - JMSService Type:" + jmsraUtil.getJMSServiceType());
1012
1013        //If JMSServiceType is REMOTE, then we need not ask the MQ RA to use the
1014
//AS RMI Registry. So the check below is not necessary.
1015
if (jmsraUtil.getJMSServiceType().equals(REMOTE)) {
1016            return false;
1017        }
1018        
1019        String JavaDoc name = null;
1020        try {
1021           //Attempt to connect to the RMI registry
1022
name = "rmi://"+getConfiguredRmiRegistryHost() + ":" + getConfiguredRmiRegistryPort();
1023            if (logger.isLoggable(Level.FINE)) {
1024                logger.fine("Attempting to list " + name);
1025            }
1026            String JavaDoc[] ss = Naming.list(name);
1027            if (logger.isLoggable(Level.FINE)) {
1028                logger.fine("List on " + name + " succeeded");
1029            }
1030            //return configured port only if RMI registry is available
1031
return true;
1032        } catch (Exception JavaDoc e) {
1033            logger.fine(e.getMessage() + " " + name);
1034            return false;
1035        }
1036    }
1037    
1038    private void setProperty(ConnectorDescriptor cd, EnvironmentProperty envProp){
1039        cd.removeConfigProperty(envProp);
1040        cd.addConfigProperty(envProp);
1041    }
1042
1043
1044    private void rebindDescriptor() throws ConnectorRuntimeException {
1045        try {
1046            String JavaDoc descriptorJNDIName = ConnectorAdminServiceUtils.getReservePrefixedJNDINameForDescriptor(super.getModuleName());
1047        com.sun.enterprise.Switch.getSwitch().getNamingManager().
1048        publishObject( descriptorJNDIName, super.getDescriptor(), true);
1049    } catch (javax.naming.NamingException JavaDoc ne) {
1050        ConnectorRuntimeException cre = new ConnectorRuntimeException (ne.getMessage());
1051        throw (ConnectorRuntimeException) cre.initCause(ne);
1052    }
1053    }
1054
1055
1056    /**
1057     * Creates ManagedConnection Factory instance. For any property that is
1058     * for supporting AS7 imq properties, resource adapter has a set method
1059     * setProperty(String,String). All AS7 properties starts with "imq".
1060     * MQ Adapter supports this only for backward compatibility.
1061     *
1062     * @param cpr <code>ConnectorConnectionPool</code> object
1063     * @parm loader Class Loader.
1064     * @throw ConnectorRuntimeException in case of an exception.
1065     */

1066    public ManagedConnectionFactory JavaDoc createManagedConnectionFactory
1067               (com.sun.enterprise.connectors.ConnectorConnectionPool cpr,
1068                                                       ClassLoader JavaDoc loader) {
1069        ManagedConnectionFactory JavaDoc mcf =
1070            super.createManagedConnectionFactory(cpr, loader);
1071        if ( mcf != null ) {
1072            Set JavaDoc s = cpr.getConnectorDescriptorInfo().getMCFConfigProperties();
1073            Iterator JavaDoc it = s.iterator();
1074            while (it.hasNext()) {
1075                EnvironmentProperty prop = (EnvironmentProperty) it.next();
1076                String JavaDoc propName = prop.getName();
1077           
1078                propName.substring(1);
1079                // If the property has started with imq, then it should go to
1080
// setProperty(String,String) method.
1081
if (propName.startsWith("imq") && prop.getValue() != "") {
1082                    try {
1083                        Method JavaDoc meth = mcf.getClass().getMethod
1084                        (SETTER, new Class JavaDoc[] {java.lang.String JavaDoc.class,
1085                                               java.lang.String JavaDoc.class});
1086                        meth.invoke(mcf, new Object JavaDoc[] {prop.getName(),
1087                                                        prop.getValueObject()});
1088                    } catch (NoSuchMethodException JavaDoc ex) {
1089                        logger.log(Level.WARNING, "no.such.method",
1090                        new Object JavaDoc[] {SETTER, mcf.getClass().getName()});
1091                    } catch (Exception JavaDoc ex) {
1092                        logger.log(Level.SEVERE, "error.execute.method",
1093                        new Object JavaDoc[] {SETTER, mcf.getClass().getName()});
1094                    }
1095            }
1096            }
1097                
1098        }
1099        return mcf;
1100    }
1101
1102    /**
1103     * This is the most appropriate time (??) to update the runtime
1104     * info of a 1.3 MDB into 1.4 MDB. <p>
1105     *
1106     * Assumptions : <p>
1107     * 0. Assume it is a 1.3 MDB if no RA mid is specified.
1108     * 1. Use the default system JMS resource adapter. <p>
1109     * 2. The ActivationSpec of the default JMS RA will provide the
1110     * setDestination, setDestinationType, setSubscriptionName methods.
1111     * 3. The jndi-name of the 1.3 MDB is the value for the Destination
1112     * property for the ActivationSpec.
1113     * 4. The ActivationSpec provides setter methods for the properties
1114     * defined in the CF that corresponds to the mdb-connection-factory
1115     * JNDI name.
1116     *
1117     */

1118    public void updateMDBRuntimeInfo(EjbMessageBeanDescriptor descriptor_,
1119           BeanPoolDescriptor poolDescriptor) throws ConnectorRuntimeException{
1120
1121        String JavaDoc jndiName = descriptor_.getJndiName();
1122        
1123        //handling of MDB 1.3 runtime deployment descriptor
1124
//if no RA-mid is specified, assume it is a 1.3 DD
1125
if (jndiName == null) { //something's wrong in DD
1126
logger.log (Level.SEVERE, "Missing Destination JNDI Name");
1127        String JavaDoc msg = sm.getString("ajra.error_in_dd");
1128            throw new RuntimeException JavaDoc(msg);
1129        }
1130        
1131        String JavaDoc resourceAdapterMid = ConnectorRuntime.DEFAULT_JMS_ADAPTER;
1132        
1133        descriptor_.setResourceAdapterMid(resourceAdapterMid);
1134
1135
1136        String JavaDoc destName = getPhysicalDestinationFromConfiguration(jndiName);
1137        
1138        //1.3 jndi-name ==> 1.4 setDestination
1139
descriptor_.putRuntimeActivationConfigProperty(
1140                new EnvironmentProperty(DESTINATION,
1141                        destName, null));
1142    
1143        
1144        //1.3 (standard) destination-type == 1.4 setDestinationType
1145
//XXX Do we really need this???
1146
if (descriptor_.getDestinationType() != null &&
1147                !"".equals(descriptor_.getDestinationType())) {
1148            descriptor_.putRuntimeActivationConfigProperty(
1149                    new EnvironmentProperty(DESTINATION_TYPE,
1150                            descriptor_.getDestinationType(), null));
1151        } else {
1152            /*
1153             * If destination type is not provided by the MDB component
1154             * [typically used by EJB3.0 styled MDBs which create MDBs without
1155             * a destination type activation-config property] and the MDB is for
1156             * the default JMS RA, attempt to infer the destination type by trying
1157             * to find out if there has been any JMS destination resource already
1158             * defined for default JMS RA. This is a best attempt guess and if there
1159             * are no JMS destination resources/admin-objects defined, AS would pass
1160             * the properties as defined by the MDB.
1161             */

1162            ConfigBean[] cb;
1163            try {
1164                cb = ResourcesUtil.getInstance().getEnabledAdminObjectResources(
1165                        ConnectorConstants.DEFAULT_JMS_ADAPTER);
1166                for (int i = 0; i < cb.length; i++) {
1167                    AdminObjectResource aor = (AdminObjectResource) cb[i];
1168                    if (aor.getJndiName().equals(jndiName)) {
1169                        descriptor_.putRuntimeActivationConfigProperty(
1170                                new EnvironmentProperty(DESTINATION_TYPE,
1171                                        aor.getResType(), null));
1172                        logger.log(Level.INFO, "endpoint.determine.destinationtype", new
1173                                Object JavaDoc[]{aor.getResType() , aor.getJndiName() , descriptor_.getName()});
1174                    }
1175                }
1176            } catch (ConfigException e) {
1177                
1178            }
1179        }
1180        
1181        
1182        //1.3 durable-subscription-name == 1.4 setSubscriptionName
1183
descriptor_.putRuntimeActivationConfigProperty(
1184                new EnvironmentProperty(SUBSCRIPTION_NAME,
1185                        descriptor_.getDurableSubscriptionName(), null));
1186
1187        String JavaDoc mdbCF = null;
1188    try {
1189        mdbCF = descriptor_.getIASEjbExtraDescriptors().
1190                    getMdbConnectionFactory().getJndiName();
1191    } catch(NullPointerException JavaDoc ne ) {
1192        // Dont process connection factory.
1193
}
1194
1195        if (mdbCF != null && mdbCF != "") {
1196        setValuesFromConfiguration(mdbCF, descriptor_);
1197        }
1198
1199        // a null object is passes as a PoolDescriptor during recovery.
1200
// See com/sun/enterprise/resource/ResourceInstaller
1201

1202        if (poolDescriptor != null) {
1203        descriptor_.putRuntimeActivationConfigProperty
1204            (new EnvironmentProperty (MAXPOOLSIZE, ""+
1205                 poolDescriptor.getMaxPoolSize(),"", "java.lang.Integer" ));
1206        descriptor_.putRuntimeActivationConfigProperty
1207            (new EnvironmentProperty (MINPOOLSIZE,""+
1208                 poolDescriptor.getSteadyPoolSize(),"", "java.lang.Integer"));
1209        descriptor_.putRuntimeActivationConfigProperty
1210            (new EnvironmentProperty (RESIZECOUNT,""+
1211                 poolDescriptor.getPoolResizeQuantity(),"", "java.lang.Integer"));
1212        descriptor_.putRuntimeActivationConfigProperty
1213            (new EnvironmentProperty (RESIZETIMEOUT,""+
1214                 poolDescriptor.getPoolIdleTimeoutInSeconds(),"", "java.lang.Integer"));
1215        descriptor_.putRuntimeActivationConfigProperty
1216            (new EnvironmentProperty (REDELIVERYCOUNT,""+
1217                 MdbContainerProps.getMaxRuntimeExceptions(),"", "java.lang.Integer"));
1218        }
1219        
1220        //Set SE/EE specific MQ-RA ActivationSpec properties
1221
try {
1222            boolean clustered = isClustered();
1223            logFine("Are we in a Clustered contained ? " + clustered);
1224            if (clustered) {
1225                setClusterActivationSpecProperties(descriptor_);
1226                logFine("Creating physical destination " + destName);
1227                logFine("Destination is Queue? " + descriptor_.hasQueueDest());
1228                if (descriptor_.hasQueueDest()) {
1229                    autoCreatePhysicalDest(destName, true);
1230                } else {
1231                    autoCreatePhysicalDest(destName, false);
1232                }
1233            }
1234        } catch (ConfigException e) {
1235            ConnectorRuntimeException crex = new ConnectorRuntimeException(e.getMessage());
1236            throw (ConnectorRuntimeException)crex.initCause(e);
1237        }
1238    }
1239
1240    void autoCreatePhysicalDest(String JavaDoc destName, boolean isQueue)
1241                                throws ConnectorRuntimeException{
1242        MQAdministrator mqAdmin = new MQAdministrator();
1243        mqAdmin.createPhysicalDestination(destName, isQueue);
1244    }
1245
1246    /**
1247     * Set SE/EE specific MQ-RA ActivationSpec properties
1248     * @param descriptor_
1249     * @throws ConfigException
1250     */

1251    private void setClusterActivationSpecProperties(EjbMessageBeanDescriptor
1252                    descriptor_) throws ConfigException {
1253        //Set MDB Identifier in a clustered instance.
1254
descriptor_.putRuntimeActivationConfigProperty(new
1255                        EnvironmentProperty(MDBIDENTIFIER,""+
1256                        getMDBIdentifier(descriptor_),"MDB Identifier",
1257                        "java.lang.String"));
1258        logFine("CLUSTERED instance - setting MDB identifier as" +
1259                        getMDBIdentifier(descriptor_));
1260        
1261    }
1262
1263    /**
1264     * Gets the MDBIdentifier for the message bean endpoint
1265     * @param descriptor_
1266     * @return
1267     * @throws ConfigException
1268     */

1269    private String JavaDoc getMDBIdentifier(EjbMessageBeanDescriptor descriptor_) throws ConfigException {
1270        return getDomainName() + SEPARATOR + getClusterName() + SEPARATOR + descriptor_.getUniqueId() ;
1271    }
1272
1273    private String JavaDoc getPhysicalDestinationFromConfiguration(String JavaDoc logicalDest)
1274                                throws ConnectorRuntimeException{
1275    ElementProperty ep = null;
1276        try {
1277            ServerContext sc = ApplicationServer.getServerContext();
1278            ConfigContext ctx = sc.getConfigContext();
1279            Resources rbeans =
1280                           ServerBeansFactory.getDomainBean(ctx).getResources();
1281            AdminObjectResource res = (AdminObjectResource)
1282                   rbeans.getAdminObjectResourceByJndiName(logicalDest);
1283        if (res == null) {
1284            String JavaDoc msg = sm.getString("ajra.err_getting_dest", logicalDest );
1285        throw new ConnectorRuntimeException(msg);
1286        }
1287                 
1288        ep = res.getElementPropertyByName(PHYSICAL_DESTINATION);
1289        } catch(ConfigException ce) {
1290        String JavaDoc msg = sm.getString("ajra.err_getting_dest", logicalDest);
1291        ConnectorRuntimeException cre = new ConnectorRuntimeException( msg );
1292        cre.initCause( ce );
1293            throw cre;
1294        }
1295
1296        if (ep == null) {
1297       String JavaDoc msg = sm.getString("ajra.cannot_find_phy_dest", ep);
1298           throw new ConnectorRuntimeException(msg);
1299        }
1300
1301        return ep.getValue();
1302    }
1303
1304
1305    private void setValuesFromConfiguration(String JavaDoc cfName, EjbMessageBeanDescriptor
1306                                     descriptor_) throws ConnectorRuntimeException{
1307    ElementProperty[] ep = null;
1308        try {
1309            ServerContext sc = ApplicationServer.getServerContext();
1310            ConfigContext ctx = sc.getConfigContext();
1311            Resources rbeans = ServerBeansFactory.getDomainBean(ctx).getResources();
1312            ConnectorResource res = (ConnectorResource)
1313                             rbeans.getConnectorResourceByJndiName(cfName);
1314        if (res == null) {
1315            String JavaDoc msg = sm.getString("ajra.mdb_cf_not_created", cfName);
1316        throw new ConnectorRuntimeException(msg);
1317        }
1318
1319        ConnectorConnectionPool ccp = (ConnectorConnectionPool)
1320            rbeans.getConnectorConnectionPoolByName(res.getPoolName());
1321                 
1322        ep = ccp.getElementProperty();
1323        } catch(ConfigException ce) {
1324        String JavaDoc msg = sm.getString("ajra.mdb_cf_not_created", cfName);
1325        ConnectorRuntimeException cre = new ConnectorRuntimeException( msg );
1326        ce.initCause( ce );
1327            throw cre;
1328        }
1329
1330        if (ep == null) {
1331        String JavaDoc msg = sm.getString("ajra.cannot_find_phy_dest");
1332            throw new ConnectorRuntimeException( msg );
1333        }
1334
1335    for (int i=0; i < ep.length; i++) {
1336        ElementProperty prop = ep[i];
1337        String JavaDoc name = prop.getName();
1338        if (name.equals(MCFADDRESSLIST)) {
1339            name = ADDRESSLIST;
1340        }
1341        String JavaDoc val = prop.getValue();
1342        if (val == null || val.equals("")) {
1343        continue;
1344        }
1345            descriptor_.putRuntimeActivationConfigProperty(
1346                new EnvironmentProperty(name, val, null));
1347    }
1348
1349    }
1350    
1351    private static void logFine(String JavaDoc s) {
1352        if (logger.isLoggable(Level.FINE)){
1353            logger.fine(s);
1354        }
1355    }
1356}
1357
Popular Tags