KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > mbeans > ApplicationsConfigMBean


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 /*
25  * ApplicationsConfigMBean.java
26  *
27  * Created on April 29, 2003, 5:45 PM
28  * @author sandhyae
29  * <BR> <I>$Source: /cvs/glassfish/admin/mbeans/src/java/com/sun/enterprise/admin/mbeans/ApplicationsConfigMBean.java,v $
30  *
31  */

32
33 package com.sun.enterprise.admin.mbeans;
34
35 import com.sun.enterprise.admin.mbeans.custom.CustomMBeanException;
36 import java.io.File JavaDoc;
37 import java.net.InetAddress JavaDoc;
38 import java.net.UnknownHostException JavaDoc;
39 import java.util.ArrayList JavaDoc;
40 import java.util.Properties JavaDoc;
41 import java.util.StringTokenizer JavaDoc;
42 import java.util.logging.Level JavaDoc;
43 import java.util.logging.Logger JavaDoc;
44 import java.util.Map JavaDoc;
45 import java.util.HashMap JavaDoc;
46 import java.util.Set JavaDoc;
47 import java.util.HashSet JavaDoc;
48 import java.util.Enumeration JavaDoc;
49 import javax.management.MBeanException JavaDoc;
50 import javax.management.MBeanServer JavaDoc;
51 import javax.management.ObjectName JavaDoc;
52 import javax.management.Attribute JavaDoc;
53 import javax.management.AttributeList JavaDoc;
54 import javax.management.MBeanInfo JavaDoc;
55
56 import com.sun.enterprise.instance.InstanceEnvironment;
57 //config
58
import com.sun.enterprise.admin.config.BaseConfigMBean;
59 import com.sun.enterprise.config.ConfigBean;
60 import com.sun.enterprise.config.ConfigContext;
61 import com.sun.enterprise.config.ConfigBeansFactory;
62 import com.sun.enterprise.config.ConfigException;
63 import com.sun.enterprise.config.serverbeans.Server;
64 import com.sun.enterprise.config.serverbeans.ServerXPathHelper;
65 import com.sun.enterprise.config.serverbeans.HttpService;
66 import com.sun.enterprise.config.serverbeans.VirtualServer;
67 import com.sun.enterprise.config.serverbeans.Applications;
68 import com.sun.enterprise.config.serverbeans.J2eeApplication;
69 import com.sun.enterprise.config.serverbeans.WebModule;
70 import com.sun.enterprise.config.serverbeans.EjbModule;
71 import com.sun.enterprise.config.serverbeans.ConnectorModule;
72 import com.sun.enterprise.config.serverbeans.Config;
73 import com.sun.enterprise.config.serverbeans.ServerTags;
74 import com.sun.enterprise.config.serverbeans.PropertyResolver;
75 import com.sun.enterprise.config.serverbeans.LifecycleModule;
76 import com.sun.enterprise.config.serverbeans.ElementProperty;
77 import com.sun.enterprise.admin.common.exception.DeploymentException;
78 import com.sun.enterprise.admin.common.exception.ServerInstanceException;
79 import com.sun.enterprise.admin.common.constant.AdminConstants;
80 import com.sun.enterprise.admin.common.exception.MBeanConfigException;
81 import com.sun.enterprise.admin.event.BaseDeployEvent;
82 import com.sun.enterprise.admin.server.core.AdminService;
83 import com.sun.enterprise.admin.util.HostAndPort;
84 import com.sun.enterprise.admin.common.MBeanServerFactory;
85 //phasing
86
import com.sun.enterprise.deployment.phasing.DeploymentService;
87 import com.sun.enterprise.deployment.phasing.DeploymentServiceUtils;
88 import com.sun.enterprise.deployment.phasing.DeploymentTarget;
89 import com.sun.enterprise.deployment.phasing.DeploymentTargetFactory;
90 //dbe
91
import com.sun.enterprise.deployment.backend.DeployableObjectType;
92 import com.sun.enterprise.deployment.backend.IASDeploymentException;
93 import com.sun.enterprise.deployment.backend.DeploymentRequest;
94 import com.sun.enterprise.deployment.backend.DeploymentCommand;
95 import com.sun.enterprise.deployment.backend.DeploymentStatus;
96 import com.sun.enterprise.deployment.util.DeploymentProperties;
97 import com.sun.enterprise.util.i18n.StringManager;
98 // sub-component-status
99
import com.sun.enterprise.deployment.Application;
100 import com.sun.enterprise.deployment.BundleDescriptor;
101 import com.sun.enterprise.deployment.EjbBundleDescriptor;
102 import com.sun.enterprise.deployment.WebBundleDescriptor;
103 import com.sun.enterprise.deployment.WebComponentDescriptor;
104 import com.sun.enterprise.deployment.ConnectorDescriptor;
105 import com.sun.enterprise.deployment.InboundResourceAdapter;
106 import com.sun.enterprise.deployment.OutboundResourceAdapter;
107 import com.sun.enterprise.deployment.EjbDescriptor;
108 import com.sun.enterprise.deployment.io.DescriptorList;
109 import com.sun.enterprise.deployment.backend.DeploymentUtils;
110 import com.sun.enterprise.instance.InstanceFactory;
111 import com.sun.enterprise.instance.AppsManager;
112 import com.sun.enterprise.instance.EjbModulesManager;
113 import com.sun.enterprise.instance.WebModulesManager;
114 import com.sun.enterprise.instance.ConnectorModulesManager;
115 import com.sun.enterprise.instance.AppclientModulesManager;
116 import java.util.Iterator JavaDoc;
117 import com.sun.enterprise.Switch;
118 import com.sun.enterprise.ManagementObjectManager;
119 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
120 import com.sun.enterprise.deployment.util.XModuleType;
121 import com.sun.enterprise.connectors.ConnectorConstants;
122
123 import com.sun.enterprise.config.serverbeans.ApplicationRef;
124 import com.sun.enterprise.util.StringUtils;
125 import java.util.List JavaDoc;
126 import java.util.ListIterator JavaDoc;
127
128 import com.sun.enterprise.server.Constants;
129 import com.sun.enterprise.admin.mbeanapi.IApplicationsConfigMBean;
130 import com.sun.enterprise.admin.mbeans.custom.BasicCustomMBeanConfigQueries;
131 import com.sun.enterprise.admin.mbeans.custom.BasicCustomMBeanOperations;
132 import com.sun.enterprise.admin.mbeans.custom.CustomMBeanConfigQueries;
133 import com.sun.enterprise.admin.mbeans.custom.CustomMBeanOperationsMBean;
134
135 import com.sun.enterprise.admin.target.TargetType;
136 import com.sun.enterprise.config.serverbeans.ApplicationHelper;
137 import com.sun.enterprise.config.serverbeans.ClusterHelper;
138 import com.sun.enterprise.config.serverbeans.ServerHelper;
139
140 import com.sun.enterprise.util.io.FileUtils;
141
142 /**
143  * The MBean that represents the deployment management interface for iAS SE. In
144  * other words it represents the <strong> deployment interface </strong> .
145  * <p>
146  * The MBeanServer will have one instance of this MBean. This MBean is lazy loaded.
147  * <p>
148  * ObjectName of this MBean is ias:type=Deployment, name=<instance-name>
149  * @author Sandhya E
150  */

151 public class ApplicationsConfigMBean extends BaseConfigMBean
152     implements IApplicationsConfigMBean, CustomMBeanOperationsMBean, CustomMBeanConfigQueries
153 {
154     
155     /** default target name when there is no target in the request object **/
156     public static final String JavaDoc DEFAULT_TARGET = "domain";
157     
158     /** FIXME **/
159     public static final Logger JavaDoc sLogger = Logger.getLogger(AdminConstants.kLoggerName);
160     
161     // Begin EE: 4946914 - Cluster deployment support
162

163     /** Deployment Service object used to invoke operations like deployment, undeployment **/
164     protected DeploymentService deployService = null;
165     
166     /** instance name **/
167     protected String JavaDoc mInstanceName = null;
168     
169     /** context object **/
170     protected ConfigContext m_configContext = null;
171     protected CustomMBeanOperationsMBean cmo = null;
172     protected CustomMBeanConfigQueries cmcq = null;
173     
174     protected static final Object JavaDoc[] emptyParams = new Object JavaDoc[]{};
175     protected static final String JavaDoc[] emptySignature = new String JavaDoc[]{};
176     
177     
178     protected static StringManager localStrings =
179     StringManager.getManager( ApplicationsConfigMBean.class );
180      
181     
182     protected static final String JavaDoc TYPE_APPLICATION = "application";
183     protected static final String JavaDoc TYPE_EJB = "ejb";
184     protected static final String JavaDoc TYPE_WEB = "web";
185     protected static final String JavaDoc TYPE_CONNECTOR = "connector";
186     protected static final String JavaDoc TYPE_APPCLIENT = "appclient";
187     
188     protected static final String JavaDoc JSR88_TYPE_APPLICATION = "ear";
189     protected static final String JavaDoc JSR88_TYPE_EJB = "ejb";
190     protected static final String JavaDoc JSR88_TYPE_WEB = "war";
191     protected static final String JavaDoc JSR88_TYPE_CONNECTOR = "rar";
192     protected static final String JavaDoc JSR88_TYPE_APPCLIENT = "car";
193
194     protected static final String JavaDoc DOMAIN_TARGET = "domain";
195     
196     protected static final DeployableObjectType[] deployableObjectTypes =
197                                                 new DeployableObjectType[] {
198                                                     DeployableObjectType.APP,
199                                                     DeployableObjectType.EJB,
200                                                     DeployableObjectType.WEB,
201                                                     DeployableObjectType.CONN,
202                                                     DeployableObjectType.CAR,
203                                                     DeployableObjectType.LCM,
204                                                     DeployableObjectType.CMB
205                                                 };
206
207     // End EE: 4946914 - Cluster deployment support
208

209     private static final TargetType[] VALID_LIST_TYPES = new TargetType[] {
210         TargetType.CLUSTER, TargetType.SERVER, TargetType.DAS, TargetType.DOMAIN};
211         
212
213     /**
214      * Creates a new instance of ApplicationsConfigMBean
215      * @param instanceName name of this instance
216      * @param configContext context object
217      */

218     public ApplicationsConfigMBean(String JavaDoc instanceName, ConfigContext configContext) throws MBeanConfigException {
219         super();
220         mInstanceName = instanceName;
221         m_configContext = configContext;
222         deployService = DeploymentService.getDeploymentService(configContext);
223         initCustomMBeanHandlers();
224     }
225     
226     public ApplicationsConfigMBean() throws MBeanConfigException {
227         super();
228         initCustomMBeanHandlers();
229     }
230
231     protected void initCustomMBeanHandlers() {
232         cmo = new BasicCustomMBeanOperations();
233         cmcq = new BasicCustomMBeanConfigQueries();
234     }
235     
236     private DeploymentTarget getAndValidateDeploymentTarget(String JavaDoc targetName,
237         String JavaDoc appName, boolean isRegistered) throws IASDeploymentException
238     {
239         return getAndValidateDeploymentTarget(targetName, appName, isRegistered, false);
240     }
241     
242     private DeploymentTarget getAndValidateDeploymentTarget(String JavaDoc targetName,
243         String JavaDoc appName, boolean isRegistered, boolean isDeleting) throws IASDeploymentException
244     {
245         try {
246             final DeploymentTarget target = getTargetFactory().getTarget(
247                 getConfigContext(), getDomainName(), targetName);
248
249             if (isRegistered) {
250                 if (targetName == null) {
251                     //If the targetName passed in was null, we need to set it to its default value.
252
targetName = target.getTarget().getName();
253                 }
254                 if (target.getTarget().getType() == TargetType.DOMAIN && isDeleting) {
255                     // If the target is the domain and the object is being deleted, then we must
256
// ensure that the there are no references to it.
257
if (ApplicationHelper.isApplicationReferenced(getConfigContext(), appName)) {
258                         throw new IASDeploymentException(localStrings.getString("applicationIsReferenced",
259                             appName, ApplicationHelper.getApplicationReferenceesAsString(
260                                 getConfigContext(), appName)));
261                     }
262                 }
263                 else if (target.getTarget().getType() == TargetType.SERVER ||
264                     target.getTarget().getType() == TargetType.DAS) {
265                     // If the application exists, we must ensure that if a standalone server instance is
266
// the target, that it must be the only entity referring to the application and
267
// indeed it must have a reference to the application
268
if (!ServerHelper.serverReferencesApplication(getConfigContext(),
269                         targetName, appName) && isDeleting) {
270                         throw new IASDeploymentException(localStrings.getString("serverApplicationRefDoesNotExist",
271                             targetName, appName));
272                     } else if (!ApplicationHelper.isApplicationReferencedByServerOnly(getConfigContext(),
273                             appName, targetName)) {
274                         throw new IASDeploymentException(localStrings.getString("applicationHasMultipleRefs",
275                             targetName, appName, ApplicationHelper.getApplicationReferenceesAsString(
276                                 getConfigContext(), appName)));
277                     }
278                 } else if (target.getTarget().getType() == TargetType.CLUSTER) {
279                     // If the application exists, we must ensure that if a cluster is
280
// the target, that it must be the only entity referring to the application and
281
// indeed it must have a reference to the application
282
if (!ClusterHelper.clusterReferencesApplication(getConfigContext(),
283                         targetName, appName) && isDeleting) {
284                         throw new IASDeploymentException(localStrings.getString("clusterApplicationRefDoesNotExist",
285                             targetName, appName));
286                     } else if (!ApplicationHelper.isApplicationReferencedByClusterOnly(getConfigContext(),
287                             appName, targetName)) {
288                         throw new IASDeploymentException(localStrings.getString("applicationHasMultipleRefs",
289                             targetName, appName, ApplicationHelper.getApplicationReferenceesAsString(
290                                 getConfigContext(), appName)));
291                      }
292                 }
293             }
294             return target;
295         } catch (IASDeploymentException ex) {
296             throw (ex);
297         } catch (Exception JavaDoc ex) {
298             throw new IASDeploymentException(ex);
299         }
300     }
301     
302     /**
303      * Deploys a component to the given array of targets which can be
304      * domains, clusters, or standalone instances. Since there are restrictions
305      * around how clusters and standalone instance share deployments, the
306      * component bits are deployed only to the first target in the list and then
307      * application references are created for the rest of the targets in the
308      * array specified.
309      *
310      * @return DeploymentStatus
311      * @param props The properties associated with a deployment.
312      * @param targets An array of available targets for deployment.
313      * @throws DeploymentException when an error occurs during association or
314      * deployment of the bits
315      */

316     public DeploymentStatus deploy(Properties JavaDoc props, String JavaDoc [] targets)
317                 throws DeploymentException{
318         DeploymentStatus status = null;
319         props.setProperty(DeploymentProperties.TARGET, targets[0]);
320         status = deploy(props);
321         for(int i = 1; i < targets.length; i++) {
322             try {
323                 associateApplication(props, targets[i]);
324             } catch(MBeanConfigException m) {
325                 DeploymentException e = new DeploymentException(m.getMessage());
326                 e.initCause(m);
327                 throw e;
328             }
329         }
330         return status;
331     }
332     
333     /**
334      * Associates a deployed application with an available target for
335      * deployment. Once an application has been deployed to a cluster, domain,
336      * or server instance, this method will create an application reference
337      * for that target.
338      *
339      * @param props Properties of the application to be referenced. This
340      * includes setting the following properties:
341      * <p>
342      * DeploymentProperties.NAME
343      * DeploymentProperties.ENABLE
344      * DeploymentProperties.VIRTUAL_SERVERS
345      * </p>
346      * @param targetName The name of the target to associate the application.
347      */

348     public void associateApplication(Properties JavaDoc props, String JavaDoc targetName)
349             throws MBeanConfigException {
350         try {
351             final DeploymentTarget target = getTargetFactory().getTarget(
352                     getConfigContext(), getDomainName(), targetName);
353             boolean enabled = new Boolean JavaDoc(props.getProperty(
354                                 DeploymentProperties.ENABLE)).booleanValue();
355             target.addAppReference(
356                     props.getProperty(DeploymentProperties.NAME),
357                     enabled,
358                     props.getProperty(DeploymentProperties.VIRTUAL_SERVERS));
359         } catch(Exception JavaDoc e) {
360             MBeanConfigException m = new MBeanConfigException(e.getMessage());
361             m.initCause(e);
362             throw m;
363         }
364     }
365     
366     /**
367      * Undeploys a component to the given array of targets which can be
368      * domains, clusters, or standalone instances. Since there are restrictions
369      * around how clusters and standalone instances share deployments,
370      * the application references are removed for all the targets except for
371      * the first one in the array. After this, the component bits are undeployed
372      * from the first target in the array.
373      *
374      * @return DeploymentStatus
375      * @param props The properties associated with an undeployment.
376      * @param targets An array of targets for undeploying the application.
377      * @throws DeploymentException when an error occurs during removal of the
378      * application references or physical undeployment of the bits.
379      */

380     public DeploymentStatus undeploy(Properties JavaDoc props, String JavaDoc [] targets)
381                 throws DeploymentException{
382         DeploymentStatus status = null;
383         props.setProperty(DeploymentProperties.TARGET, targets[0]);
384         for(int i = 1; i < targets.length; i++) {
385             try {
386                 disassociateApplication(props, targets[i]);
387             } catch (MBeanConfigException m) {
388                 DeploymentException e = new DeploymentException(m.getMessage());
389                 e.initCause(m);
390                 throw e;
391             }
392         }
393         status = undeploy(props);
394         return status;
395     }
396     
397     /**
398      * Removes the application reference from the specified target on which
399      * that application reference exists.
400      *
401      * @param props The properties of the application. The following property
402      * must be set for the application to be disassociated:
403      * <p>
404      * DeploymentProperties.NAME
405      * </p>
406      * @param targetName The name of the target that the application must be
407      * removed from.
408      */

409     public void disassociateApplication(Properties JavaDoc props, String JavaDoc targetName)
410             throws MBeanConfigException {
411         try {
412             final DeploymentTarget target = getTargetFactory().getTarget(
413                     getConfigContext(), getDomainName(), targetName);
414             target.removeAppReference(
415                     props.getProperty(DeploymentProperties.NAME));
416         } catch(Exception JavaDoc e) {
417             MBeanConfigException m = new MBeanConfigException(e.getMessage());
418             m.initCause(e);
419             throw m;
420         }
421     }
422
423     /**
424      * Return application/module type
425      * @param String stand-alone application or stand-alone module name
426      * @param Integer Integer representation of application or module type
427      * as jsr88 module type
428      * pl. refer to javax.enterprise.deploy.shared.ModuleType
429      * Note that we cannot return ModuleType directory to
430      * the client since it is not Serializable
431      */

432      public Integer JavaDoc getModuleType(String JavaDoc standAloneModuleName)
433         throws ServerInstanceException {
434
435         sLogger.log(Level.FINE, "getModuleType - begin" +
436                 " standAloneModuleName = " + standAloneModuleName);
437
438         // initialization
439
J2EEModule j2eeModule = new J2EEModule(standAloneModuleName);
440
441         // get j2ee module type
442
ModuleType JavaDoc moduleType = j2eeModule.getModuleType();
443         if (moduleType == null) {
444             return null;
445         }
446
447         return (new Integer JavaDoc(moduleType.getValue()));
448     }
449
450     
451     /**
452      * Generic API to invoke deployment
453      * @see DeploymentProperties.java
454      */

455     public com.sun.enterprise.deployment.backend.DeploymentStatus deploy(Properties JavaDoc props)
456                             throws DeploymentException
457     {
458         DeploymentProperties dProps = new DeploymentProperties(props);
459         String JavaDoc archiveName = dProps.getArchiveName();
460         String JavaDoc name = dProps.getName(archiveName);
461         DeployableObjectType type = getTypeFromFile(name, archiveName);
462         if(archiveName == null)
463             throw new IllegalArgumentException JavaDoc("archiveName not specified");
464        
465         sLogger.log(Level.FINE, "mbean.begin_deploy", archiveName);
466                
467         java.io.File JavaDoc deployFile = new java.io.File JavaDoc(archiveName);
468         int actionCode = BaseDeployEvent.APPLICATION_DEPLOYED;
469         try {
470             InstanceEnvironment env = new InstanceEnvironment(getInstanceName());
471             DeploymentRequest req = new DeploymentRequest(
472                                         env,
473                                         type,
474                                         DeploymentCommand.DEPLOY);
475             
476             
477             /* If app exists & forceDeploy is false it's an error.
478              * It should be detected by the deployment backend.
479              */

480             boolean isRegistered = false ; //isRegistered(name, type);
481
ObjectName JavaDoc componentON =
482                 getRegisteredComponentObjectName(name, type);
483
484             if(componentON != null)
485                 isRegistered = true;
486
487             if(isRegistered)
488                 validate(componentON, REDEPLOY_ACTION);
489
490             if(type.isAPP())
491             {
492                 actionCode = BaseDeployEvent.APPLICATION_DEPLOYED;
493             }
494             else
495             {
496                 actionCode = BaseDeployEvent.MODULE_DEPLOYED;
497             }
498             
499             req.setFileSource(deployFile);
500             req.setName(name);
501             req.setForced(dProps.getForce());
502             // for redeployment
503
req.setCascade(true);
504             if(type.isWEB()) {
505                 req.setDefaultContextRoot(dProps.getDefaultContextRoot(
506                     archiveName));
507                 req.setContextRoot(dProps.getContextRoot());
508             }
509             req.setVerifying(dProps.getVerify());
510             req.setPrecompileJSP(dProps.getPrecompileJSP());
511             req.setGenerateRMIStubs(dProps.getGenerateRMIStubs());
512             req.setAvailabilityEnabled(dProps.getAvailabilityEnabled());
513             req.setStartOnDeploy(dProps.getEnable());
514             req.setDescription(dProps.getDescription());
515             req.setActionCode(actionCode);
516             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
517             final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
518                 name, isRegistered);
519             req.setTarget(target);
520             
521             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
522             //optionalAttributes.put(ServerTags.ENABLED, String.valueOf(bEnabled));
523
String JavaDoc virtualServers = dProps.getVirtualServers();
524             if(virtualServers!=null)
525                 optionalAttributes.put(ServerTags.VIRTUAL_SERVERS, dProps.getVirtualServers());
526             req.setOptionalAttributes(optionalAttributes);
527             if(props == null)
528                 props = new Properties JavaDoc();
529             else
530                 props = dProps.prune();
531             req.addOptionalArguments(props);
532             
533             setHostAndPort(req);
534             return getDeploymentService().deploy(req);
535         }
536         catch(Exception JavaDoc e) {
537             if (actionCode == BaseDeployEvent.APPLICATION_DEPLOYED) {
538                 sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
539             }
540             else {
541                 sLogger.log(Level.WARNING, "mbean.redeploy_failed", e);
542             }
543             DeploymentStatus ds = new DeploymentStatus();
544             ds.setStageException(e);
545             ds.setStageStatus(DeploymentStatus.FAILURE);
546             ds.setStageStatusMessage(e.getMessage());
547             ds.setStageDescription("Deployment");
548             return ds;
549         }
550         finally {
551             deleteFile(archiveName);
552         }
553     }
554         /////////////////////////////
555

556     
557     /**
558      * undeploys the specified app/module
559      * @param name name by which this module is registered
560      * @param props Properties to be used for undeploying
561      * @return true if app/module is unloaded successfully after undeployment,
562      * false otherwise. If the instance is not running the method returns
563      * <strong>true</strong>
564      * @throws DeploymentException if undeployment fails
565      * @see DeploymentProperties.java
566      */

567     public com.sun.enterprise.deployment.backend.DeploymentStatus undeploy(Properties JavaDoc props)
568                                     throws DeploymentException {
569         String JavaDoc name = props.getProperty(DeploymentProperties.NAME);
570         if(name == null)
571             throw new DeploymentException("name not specified in undeploy");
572         
573         sLogger.log(Level.FINE, "mbean.begin_undeploy", name);
574         try {
575                        
576             DeployableObjectType objectType = getRegisteredType(name);
577
578             ObjectName JavaDoc componentON =
579                 getRegisteredComponentObjectName(name,objectType);
580             validate(componentON, UNDEPLOY_ACTION);
581
582             //BUG 4739891 begin
583
if (objectType.isWEB()) {
584                 checkWebModuleReferences(name);
585             }
586             //BUG 4739891 end
587
DeploymentRequest req = new DeploymentRequest(
588                                          new InstanceEnvironment(getInstanceName()),
589                                          objectType, DeploymentCommand.UNDEPLOY);
590             DeploymentProperties dProps = new DeploymentProperties(props);
591             req.setName(name);
592             req.setCascade(dProps.getCascade());
593             req.setReload(dProps.getReload());
594             req.setForced(false);
595             DeploymentServiceUtils.setResourceOptionsInRequest(req, dProps);
596             
597             if(props == null)
598                 props = new Properties JavaDoc();
599             else
600                 props = dProps.prune();
601
602             req.addOptionalArguments(props);
603             
604             if(objectType.isAPP())
605                 req.setActionCode(BaseDeployEvent.APPLICATION_UNDEPLOYED);
606             else
607                 req.setActionCode(BaseDeployEvent.MODULE_UNDEPLOYED);
608             
609             final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
610                 name, true, true);
611             req.setTarget(target);
612             
613             return getDeploymentService().undeploy(req);
614         }
615         catch(Exception JavaDoc e) {
616             sLogger.log(Level.WARNING, "mbean.undeploy_failed", e);
617             DeploymentStatus ds = new DeploymentStatus();
618             ds.setStageException(e);
619             ds.setStageStatus(DeploymentStatus.FAILURE);
620             ds.setStageStatusMessage(e.getMessage());
621             ds.setStageDescription("Undeployment");
622             return ds;
623         }
624     }
625
626     public DeploymentStatus createApplicationReference(String JavaDoc targetName,
627         boolean enabled, String JavaDoc virtualServers, String JavaDoc referenceName) {
628         try {
629             sLogger.log(Level.FINE, "mbean.create_app_reference",
630                 referenceName);
631             return DeploymentService.getDeploymentService().associate(targetName, enabled, virtualServers, referenceName);
632         } catch (Exception JavaDoc e) {
633             sLogger.log(Level.WARNING, "mbean.create_app_reference_failed",
634                 e);
635             DeploymentStatus ds = new DeploymentStatus();
636             ds.setStageException(e);
637             ds.setStageStatus(DeploymentStatus.FAILURE);
638             ds.setStageStatusMessage(e.getMessage());
639             ds.setStageDescription("Association");
640             return ds;
641         }
642     }
643
644     public DeploymentStatus deleteApplicationReference(String JavaDoc targetName,
645         String JavaDoc referenceName) {
646         try {
647             sLogger.log(Level.FINE, "mbean.delete_app_reference",
648                 referenceName);
649             return DeploymentService.getDeploymentService(
650                 ).disassociate(targetName, referenceName);
651         } catch (Exception JavaDoc e) {
652             sLogger.log(Level.WARNING, "mbean.delete_app_reference_failed",
653                 e);
654             DeploymentStatus ds = new DeploymentStatus();
655             ds.setStageException(e);
656             ds.setStageStatus(DeploymentStatus.FAILURE);
657             ds.setStageStatusMessage(e.getMessage());
658             ds.setStageDescription("Disassociation");
659             return ds;
660         }
661     }
662
663    public DeploymentStatus createApplicationReference(String JavaDoc targetName,
664         String JavaDoc referenceName, Map JavaDoc options) {
665         try {
666             sLogger.log(Level.FINE, "mbean.create_app_reference",
667                 referenceName);
668             return DeploymentService.getDeploymentService().associate(targetName,
669                 referenceName, options);
670         } catch (Exception JavaDoc e) {
671             sLogger.log(Level.WARNING, "mbean.create_app_reference_failed",
672                 e);
673             DeploymentStatus ds = new DeploymentStatus();
674             ds.setStageException(e);
675             ds.setStageStatus(DeploymentStatus.FAILURE);
676             ds.setStageStatusMessage(e.getMessage());
677             ds.setStageDescription("Association");
678             return ds;
679         }
680     }
681
682     public Map JavaDoc createApplicationReferenceAndReturnStatusAsMap(
683         String JavaDoc targetName, String JavaDoc referenceName, Map JavaDoc options) {
684         DeploymentStatus oldStatus = createApplicationReference(targetName,
685             referenceName, options);
686         return oldStatus.asMap();
687     }
688
689     public DeploymentStatus deleteApplicationReference(String JavaDoc targetName,
690         String JavaDoc referenceName, Map JavaDoc options) {
691         try {
692             sLogger.log(Level.FINE, "mbean.delete_app_reference",
693                 referenceName);
694             return DeploymentService.getDeploymentService(
695                 ).disassociate(targetName, referenceName, options);
696         } catch (Exception JavaDoc e) {
697             sLogger.log(Level.WARNING, "mbean.delete_app_reference_failed",
698                 e);
699             DeploymentStatus ds = new DeploymentStatus();
700             ds.setStageException(e);
701             ds.setStageStatus(DeploymentStatus.FAILURE);
702             ds.setStageStatusMessage(e.getMessage());
703             ds.setStageDescription("Disassociation");
704             return ds;
705         }
706     }
707
708     public Map JavaDoc deleteApplicationReferenceAndReturnStatusAsMap(
709         String JavaDoc targetName, String JavaDoc referenceName, Map JavaDoc options) {
710         DeploymentStatus oldStatus = deleteApplicationReference(targetName,
711             referenceName, options);
712         return oldStatus.asMap();
713     }
714
715     public DeploymentStatus start(String JavaDoc moduleID, String JavaDoc targetName,
716         Map JavaDoc options) {
717         try {
718             sLogger.log(Level.FINE, "mbean.start", moduleID);
719             return DeploymentService.getDeploymentService().start(moduleID,
720                 targetName, options);
721         } catch (Exception JavaDoc e) {
722             sLogger.log(Level.WARNING, "mbean.start_failed", e);
723             DeploymentStatus ds = new DeploymentStatus();
724             ds.setStageException(e);
725             ds.setStageStatus(DeploymentStatus.FAILURE);
726             ds.setStageStatusMessage(e.getMessage());
727             ds.setStageDescription("Start");
728             return ds;
729         }
730     }
731
732     public Map JavaDoc startAndReturnStatusAsMap(
733         String JavaDoc moduleID, String JavaDoc targetName, Map JavaDoc options) {
734         DeploymentStatus oldStatus = start(moduleID, targetName, options);
735         return oldStatus.asMap();
736     }
737
738     public DeploymentStatus stop(String JavaDoc moduleID, String JavaDoc targetName,
739         Map JavaDoc options) {
740         try {
741             sLogger.log(Level.FINE, "mbean.stop", moduleID);
742             return DeploymentService.getDeploymentService().stop(moduleID,
743                 targetName, options);
744         } catch (Exception JavaDoc e) {
745             sLogger.log(Level.WARNING, "mbean.stop_failed", e);
746             DeploymentStatus ds = new DeploymentStatus();
747             ds.setStageException(e);
748             ds.setStageStatus(DeploymentStatus.FAILURE);
749             ds.setStageStatusMessage(e.getMessage());
750             ds.setStageDescription("Stop");
751             return ds;
752         }
753     }
754
755     public Map JavaDoc stopAndReturnStatusAsMap(
756         String JavaDoc moduleID, String JavaDoc targetName, Map JavaDoc options) {
757         DeploymentStatus oldStatus = stop(moduleID, targetName, options);
758         return oldStatus.asMap();
759     }
760
761     /**
762      * Deploys the specified application
763      * @param Properties properties object containing the following properties
764      * archiveName the complete path of the archive to be deployed.
765      * appName the name with which the application needs to be registered.
766      * forceDeploy True indicates that if this application has alreay
767      * been deployed it will be overwritten. False indicates
768      * that an existing application should not be overwritten
769      * and should result in exception. If there exists no deployed
770      * application and the forceDeploy is false, it is considered
771      * as normal deployment.
772      * bVerify true if application has to be verified
773      * bPreCompileJSP true if jsps in application are to be pre compiled
774      * cmp properties
775      * targetName target to which deployment should be done
776      * @throws DeploymentException if the deployment is not successful
777      * @return true if application is loaded successfully after deployment,
778      * false otherwise. If the instance is not running the method returns
779      * <strong>true</strong>
780      */

781     public boolean deployJ2EEApplication(Properties JavaDoc props)
782                                          throws DeploymentException {
783                                              
784         DeploymentProperties dProps = new DeploymentProperties(props);
785         String JavaDoc archiveName = dProps.getArchiveName();
786         if(archiveName == null)
787             throw new IllegalArgumentException JavaDoc("archiveName not specified");
788         sLogger.log(Level.FINE, "mbean.begin_deploy", archiveName);
789         java.io.File JavaDoc deployFile = new java.io.File JavaDoc(archiveName);
790         int actionCode = BaseDeployEvent.APPLICATION_DEPLOYED;
791         try {
792
793
794             InstanceEnvironment env = new InstanceEnvironment(getInstanceName());
795             DeploymentRequest req = new DeploymentRequest(
796                                         env,
797                                         DeployableObjectType.APP,
798                                         DeploymentCommand.DEPLOY);
799             
800             
801             String JavaDoc appName = dProps.getName(archiveName);
802             /* If app exists & forceDeploy is false it's an error.
803              * It should be detected by the deployment backend.
804              */

805             boolean isAppExists = isRegistered(appName, DeployableObjectType.APP);
806             actionCode = (isAppExists && dProps.getForce()) ?
807                              BaseDeployEvent.APPLICATION_REDEPLOYED : BaseDeployEvent.APPLICATION_DEPLOYED;
808             req.setFileSource(deployFile);
809             req.setName(appName);
810             req.setForced(dProps.getForce());
811             req.setVerifying(dProps.getVerify());
812             req.setPrecompileJSP(dProps.getPrecompileJSP());
813             req.setStartOnDeploy(dProps.getEnable());
814             req.setActionCode(actionCode);
815             final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
816                 appName, isAppExists);
817             req.setTarget(target);
818             
819             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
820             //optionalAttributes.put(ServerTags.ENABLED, String.valueOf(bEnabled));
821
String JavaDoc virtualServers = dProps.getVirtualServers();
822             if(virtualServers!=null)
823                 optionalAttributes.put(ServerTags.VIRTUAL_SERVERS, dProps.getVirtualServers());
824             req.setOptionalAttributes(optionalAttributes);
825             if(props == null)
826                 props = new Properties JavaDoc();
827             else
828                 props = dProps.prune();
829             req.addOptionalArguments(props);
830             
831             setHostAndPort(req);
832             
833             getDeploymentService().deploy(req);
834         }
835         catch(Exception JavaDoc e) {
836             if (actionCode == BaseDeployEvent.APPLICATION_DEPLOYED) {
837                 sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
838             }
839             else {
840                 sLogger.log(Level.WARNING, "mbean.redeploy_failed", e);
841             }
842             DeploymentException newE = new DeploymentException(e.getMessage());
843             newE.initCause(e);
844             throw newE;
845         }
846         finally {
847             deleteFile(archiveName);
848         }
849         return true;
850     }
851     
852     
853     /**
854      * Deploys the specified standalone ejb module
855      * @param Properties properties object containing following properties
856      * archiveName the complete path of the archive to be deployed.
857      * moduleName the name with which the ejb module needs to be registered.
858      * forceDeploy True indicates that if this module has alreay
859      * been deployed it will be overwritten. False indicates
860      * that an existing module should not be overwritten
861      * and should result in exception. If there exists no deployed
862      * application and the forceDeploy is false, it is considered
863      * as normal deployment.
864      * bVerify true if this archive has to be verified
865      * targetName target to which deployment should be done
866      * cmp properties
867      * @throws DeploymentException if the deployment is not successful
868      * @return true if module is loaded successfully after deployment,
869      * false otherwise. If the instance is not running the method returns
870      * <strong>true</strong>
871      */

872     public boolean deployEJBJarModule(Properties JavaDoc props)
873                                       throws DeploymentException {
874          
875         DeploymentProperties dProps = new DeploymentProperties(props);
876         String JavaDoc filePath = dProps.getArchiveName();
877         if (filePath == null) {
878             throw new IllegalArgumentException JavaDoc();
879         }
880         boolean loadStatus = true;
881         sLogger.log(Level.FINE, "deploymentservice.begin_deploy", filePath);
882         java.io.File JavaDoc deployFile = new java.io.File JavaDoc(filePath);
883         int actionCode = BaseDeployEvent.MODULE_DEPLOYED;
884         try {
885
886             
887             InstanceEnvironment env = new InstanceEnvironment(getInstanceName());
888             //Prepare Request
889
DeploymentRequest req = new DeploymentRequest(
890                                         env,
891                                         DeployableObjectType.EJB,
892                                         DeploymentCommand.DEPLOY);
893
894             String JavaDoc moduleName = dProps.getName(filePath);
895             boolean isModuleExists = isRegistered(moduleName,
896                                          DeployableObjectType.EJB);
897             actionCode = (isModuleExists && dProps.getForce()) ?
898                 BaseDeployEvent.MODULE_REDEPLOYED : BaseDeployEvent.MODULE_DEPLOYED;
899             req.setFileSource(deployFile);
900             req.setName(moduleName);
901             //req.setShared(isShared);
902
req.setForced(dProps.getForce());
903             req.setVerifying(dProps.getVerify());
904             req.setStartOnDeploy(dProps.getEnable());
905             req.setActionCode(actionCode);
906             final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
907                 moduleName, isModuleExists);
908             req.setTarget(target);
909             if(props == null)
910                 props = new Properties JavaDoc();
911             else
912                 props = dProps.prune();
913             req.addOptionalArguments(props);
914             //Request Ready
915

916             getDeploymentService().deploy(req);
917         }
918         catch(Exception JavaDoc e) {
919             if (actionCode == BaseDeployEvent.MODULE_DEPLOYED) {
920                 sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
921             }
922             else {
923                 sLogger.log(Level.WARNING, "mbean.redeploy_failed", e);
924             }
925             throw new DeploymentException(e.getMessage());
926         }
927         finally {
928             deleteFile(filePath);
929         }
930         return loadStatus;
931     }
932     
933     /**
934      * Deploys the specified standalone web module
935      * @param Properties properties object containing following properties
936      * archiveName the complete path of the archive to be deployed.
937      * webAppName the name with which the web module needs to be registered.
938      * contextRoot context root for this web module
939      * bEnabled webApp enabled if true
940      * virtualServers
941      * forceDeploy True indicates that if this application has alreay
942      * been deployed it will be overwritten. False indicates
943      * that an existing application should not be overwritten
944      * and should result in exception. If there exists no deployed
945      * application and the forceDeploy is false, it is considered
946      * as normal deployment.
947      * bVerify true if this archive has to be verified
948      * bPreCompileJSP true if jsps in application are to be pre compiled
949      * targetName target to which deployment should be done
950      * @throws DeploymentException if the deployment is not successful
951      * @return true if module is loaded successfully after deployment,
952      * false otherwise. If the instance is not running the method returns
953      * <strong>true</strong>
954      */

955     public boolean deployWarModule(Properties JavaDoc props)
956                                    throws DeploymentException {
957         
958         DeploymentProperties dProps = new DeploymentProperties(props);
959         String JavaDoc filePath = dProps.getArchiveName();
960         if (filePath == null) {
961             throw new IllegalArgumentException JavaDoc();
962         }
963         
964         boolean loadStatus = true;
965         sLogger.log(Level.FINE, "mbean.begin_deploy", filePath);
966         java.io.File JavaDoc deployFile = new java.io.File JavaDoc(filePath);
967         int actionCode = BaseDeployEvent.MODULE_DEPLOYED;
968         try {
969
970             InstanceEnvironment env = new InstanceEnvironment(getInstanceName());
971             
972             //Prepare Request
973
DeploymentRequest req = new DeploymentRequest(
974                                         env,
975                                         DeployableObjectType.WEB,
976                                         DeploymentCommand.DEPLOY);
977             
978             String JavaDoc webAppName = dProps.getName(filePath);
979             boolean isModuleExists = isRegistered(webAppName,
980                                          DeployableObjectType.WEB);
981             actionCode = (isModuleExists && dProps.getForce()) ?
982                               BaseDeployEvent.MODULE_REDEPLOYED : BaseDeployEvent.MODULE_DEPLOYED;
983                               
984             req.setFileSource(deployFile);
985             req.setName(webAppName);
986             req.setContextRoot(dProps.getContextRoot());
987             req.setForced(dProps.getForce());
988             req.setVerifying(dProps.getVerify());
989             req.setPrecompileJSP(dProps.getPrecompileJSP());
990             req.setStartOnDeploy(dProps.getEnable());
991             req.setActionCode(actionCode);
992             final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
993                 webAppName, isModuleExists);
994             req.setTarget(target);
995             //req.setShared(false);
996
// get the webserver hostname and ports
997
setHostAndPort(req);
998             Properties JavaDoc optionalAttributes = new Properties JavaDoc();
999             //optionalAttributes.put(ServerTags.ENABLED, String.valueOf(bEnabled));
1000
String JavaDoc virtualServers = dProps.getVirtualServers();
1001            if(virtualServers!=null)
1002                optionalAttributes.put(ServerTags.VIRTUAL_SERVERS, virtualServers);
1003            req.setOptionalAttributes(optionalAttributes);
1004                       
1005            getDeploymentService().deploy(req);
1006        }
1007        catch(Exception JavaDoc e) {
1008            if (actionCode == BaseDeployEvent.MODULE_DEPLOYED) {
1009                sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
1010            }
1011            else {
1012                sLogger.log(Level.WARNING, "mbean.redeploy_failed", e);
1013            }
1014            throw new DeploymentException(e.getMessage());
1015        }
1016        finally {
1017            deleteFile(filePath);
1018        }
1019        return loadStatus;
1020    }
1021    
1022    /**
1023     * Deploys the specified standalone ejb module
1024     * @param Properties properties object containing following properties
1025     * archiveName the complete path of the archive to be deployed.
1026     * moduleName the name with which the connector module needs to be registered.
1027     * forceDeploy True indicates that if this module has alreay
1028     * been deployed it will be overwritten. False indicates
1029     * that an existing module should not be overwritten
1030     * and should result in exception. If there exists no deployed
1031     * module and the forceDeploy is false, it is considered
1032     * as normal deployment.
1033     * bVerify true if this archive has to be verified
1034     * targetName target to which deployment should be done
1035     * @throws DeploymentException if the deployment is not successful
1036     * @return true if module is loaded successfully after deployment,
1037     * false otherwise. If the instance is not running the method returns
1038     * <strong>true</strong>
1039     */

1040    public boolean deployConnectorModule(Properties JavaDoc props)
1041                                         throws DeploymentException {
1042        
1043        DeploymentProperties dProps = new DeploymentProperties(props);
1044        String JavaDoc filePath = dProps.getArchiveName();
1045        if (filePath == null) {
1046            throw new IllegalArgumentException JavaDoc();
1047        }
1048        
1049        boolean loadStatus = true;
1050        sLogger.log(Level.FINE, "mbean.begin_deploy", filePath);
1051        java.io.File JavaDoc deployFile = new java.io.File JavaDoc(filePath);
1052        int actionCode = BaseDeployEvent.MODULE_DEPLOYED;
1053        try {
1054
1055            InstanceEnvironment env = new InstanceEnvironment(getInstanceName());
1056            
1057            DeploymentRequest req = new DeploymentRequest(
1058                                        env,
1059                                        DeployableObjectType.CONN,
1060                                        DeploymentCommand.DEPLOY);
1061            
1062            String JavaDoc moduleName = dProps.getName(filePath);
1063            boolean isModuleExists = isRegistered(moduleName,
1064                                         DeployableObjectType.CONN);
1065            actionCode = (isModuleExists && dProps.getForce()) ?
1066                BaseDeployEvent.MODULE_REDEPLOYED : BaseDeployEvent.MODULE_DEPLOYED;
1067            
1068            req.setFileSource(deployFile);
1069            req.setName(moduleName);
1070            req.setForced(dProps.getForce());
1071            req.setVerifying(dProps.getVerify());
1072            req.setActionCode(actionCode);
1073            final DeploymentTarget target = getAndValidateDeploymentTarget(dProps.getTarget(),
1074                moduleName, isModuleExists);
1075            req.setTarget(target);
1076            req.setStartOnDeploy(dProps.getEnable());
1077            //req.setShared(false);
1078

1079            setDeployDirOwner(req, env);
1080            getDeploymentService().deploy(req);
1081        }
1082        catch(Exception JavaDoc e) {
1083            if (actionCode == BaseDeployEvent.MODULE_DEPLOYED) {
1084                sLogger.log(Level.WARNING, "mbean.deploy_failed", e);
1085            }
1086            else {
1087                sLogger.log(Level.WARNING, "mbean.redeploy_failed", e);
1088            }
1089            throw new DeploymentException(e.getMessage());
1090        }
1091        finally {
1092            deleteFile(filePath);
1093        }
1094        return loadStatus;
1095    }
1096
1097    /**
1098     * Returns all deployable targets in this domain. All groups
1099     * and all servers(servers that are not part of any groups)
1100     * @return array of targets to which deployment can be performed
1101     * [ an array of 0 if there are no targets]
1102     * @throws MBeanConfigException
1103     */

1104
1105    public String JavaDoc[] getTargets() throws MBeanConfigException{
1106        try{
1107          
1108            ArrayList JavaDoc targetList = new ArrayList JavaDoc();
1109            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1110            //FIXME handle clusters
1111
//add groups
1112
/*
1113            ObjectName groupsON = new ObjectName(getDomainName()+":type=clusters,category=config");
1114            try{
1115            ObjectName[] groupONArr = (ObjectName[])mbs.invoke(groupsON, "getCluster", emptyParams, emptySignature);
1116            for(int i = 0; i < groupONArr.length; i++){
1117                targetList.add(mbs.getAttribute(groupONArr[i], "name"));
1118            }
1119            }catch(Exception e){
1120            }
1121            */

1122            //FIXME add only standalone servers
1123
//add servers
1124

1125            try{
1126                ObjectName JavaDoc serversON = new ObjectName JavaDoc(getDomainName()+":type=servers,category=config");
1127            ObjectName JavaDoc[] serverONArr = (ObjectName JavaDoc[])mbs.invoke(serversON, "getServer", emptyParams, emptySignature);
1128            for(int i = 0; i<serverONArr.length; i++){
1129                targetList.add(mbs.getAttribute(serverONArr[i], "name"));
1130            }
1131            }catch(Exception JavaDoc e)
1132            {
1133                targetList.add("server");
1134            }
1135            
1136            return (String JavaDoc[])targetList.toArray(new String JavaDoc[]{});
1137          
1138        }catch(Throwable JavaDoc t) {
1139            throw new MBeanConfigException(t.getMessage());
1140        }
1141    }
1142    
1143    /**
1144     * Returns all deployed modules of specified type on default target
1145     * @param moduleType type of the module(app|ejb|web|connector)
1146     * @return array of deployed modules of type moduleType
1147     * @throws MBeanConfigException
1148     */

1149    public String JavaDoc[] getAvailableModules(String JavaDoc moduleType) throws MBeanConfigException {
1150        String JavaDoc target = DEFAULT_TARGET;
1151        return getAvailableModules(moduleType, new String JavaDoc[]{target});
1152    }
1153    
1154    /**
1155     * Returns all deployed modules of specified type and on specified target
1156     * @param moduleType type of the module(war/jar/ear/rar)
1157     * @param target target server
1158     * @return array of deployed modules of type moduleType and on target
1159     */

1160    public String JavaDoc[] getAvailableModules(String JavaDoc moduleType, String JavaDoc[] targetList)
1161                                        throws MBeanConfigException {
1162        return getAvailableModules(moduleType, targetList, false);
1163    }
1164
1165    /**
1166     * Returns all user deployed modules of specified type and on specified
1167     * target. The result from this method excludes all system modules.
1168     * @param moduleType type of the module(war/jar/ear/rar)
1169     * @param targetList list of target servers
1170     * @return array of deployed modules of type moduleType and on target
1171     */

1172    public String JavaDoc[] getAvailableUserModules(String JavaDoc moduleType,
1173            String JavaDoc[] targetList)
1174            throws MBeanConfigException {
1175        return getAvailableModules(moduleType, targetList, true);
1176    }
1177
1178    /**
1179     * Get deployed modules of specified type on specified list of targets.
1180     * @param moduleType type of the module (war/jar/ear/rar/connector), see
1181     * the TYPE_* constants.
1182     * @param targetList list of target servers
1183     * @param excludeSystemApps whether to exclude system apps or not
1184     * @return array of deployed modules of specified type on specified
1185     * list of targets.
1186     */

1187    private String JavaDoc[] getAvailableModules(String JavaDoc moduleType, String JavaDoc[] targetList,
1188            boolean excludeSystemApps)
1189            throws MBeanConfigException {
1190        try{
1191            DeployableObjectType type = getDeployableObjectType(moduleType);
1192            ArrayList JavaDoc listOfModules = new ArrayList JavaDoc();
1193            for(int i = 0 ; i< targetList.length;i++)
1194            {
1195                listOfModules.addAll(getModules(targetList[i], type, null, excludeSystemApps));
1196            }
1197            return (String JavaDoc[])listOfModules.toArray(new String JavaDoc[listOfModules.size()]);
1198        }catch(Exception JavaDoc e){
1199            throw new MBeanConfigException(e.getMessage());
1200        }
1201    }
1202    
1203    /**
1204     * Returns an array of all currently running modules of specified type
1205     * and on specified target
1206     * @return array of running modules of type moduleType and on target
1207     * @param moduleType type of the module(war/jar/ear/rar)
1208     * @param target target server
1209     */

1210    public String JavaDoc[] getRunningModules(String JavaDoc moduleType, String JavaDoc[] targetList)
1211    throws MBeanConfigException {
1212        return getRunningModules(moduleType, targetList, false);
1213    }
1214
1215    /**
1216     * Returns an array of all currently running user modules of specified
1217     * type and on specified target
1218     * @return array of running modules of type moduleType and on target
1219     * @param moduleType type of the module(war/jar/ear/rar)
1220     * @param target target server
1221     */

1222    public String JavaDoc[] getRunningUserModules(String JavaDoc moduleType, String JavaDoc[] targetList)
1223    throws MBeanConfigException {
1224        return getRunningModules(moduleType, targetList, true);
1225    }
1226
1227    /**
1228     * Get running modules of specified type on specified list of targets.
1229     * @param moduleType type of the module (war/jar/ear/rar/connector), see
1230     * the TYPE_* constants.
1231     * @param targetList list of target servers
1232     * @param excludeSystemApps whether to exclude system apps or not
1233     * @return array of running modules of specified type on specified
1234     * list of targets.
1235     */

1236    private String JavaDoc[] getRunningModules(String JavaDoc moduleType, String JavaDoc[] targetList,
1237            boolean excludeSystemApps)
1238    throws MBeanConfigException {
1239        try{
1240            DeployableObjectType type = getDeployableObjectType(moduleType);
1241            ArrayList JavaDoc listOfModules= new ArrayList JavaDoc();
1242            for(int i = 0 ; i< targetList.length;i++)
1243            {
1244                listOfModules.addAll(getModules(targetList[i], type,
1245                        new Boolean JavaDoc(true), excludeSystemApps));
1246            }
1247            return (String JavaDoc[])listOfModules.toArray(new String JavaDoc[listOfModules.size()]);
1248        }catch(Exception JavaDoc e){
1249            throw new MBeanConfigException(e.getMessage());
1250        }
1251    }
1252    
1253    /**
1254     * Returns an array of all non running modules of specified type
1255     * and on target
1256     * @param moduleType type of the module(war/jar/ear/rar)
1257     * @param target target server
1258     * @return array of non running modules[ an array of length 0 if no running modules are present]
1259     */

1260    
1261    public String JavaDoc[] getNonRunningModules(String JavaDoc moduleType, String JavaDoc[] targetList)
1262    throws MBeanConfigException {
1263        return getNonRunningModules(moduleType, targetList, false);
1264    }
1265
1266    /**
1267     * Returns an array of all non running user modules of specified type
1268     * and on target
1269     * @param moduleType type of the module(war/jar/ear/rar)
1270     * @param target target server
1271     * @return array of non running modules[ an array of length 0 if no running modules are present]
1272     */

1273    public String JavaDoc[] getNonRunningUserModules(String JavaDoc moduleType, String JavaDoc[] targetList)
1274    throws MBeanConfigException {
1275        return getNonRunningModules(moduleType, targetList, false);
1276    }
1277
1278    /**
1279     * Get not running modules of specified type on specified list of targets.
1280     * @param moduleType type of the module (war/jar/ear/rar/connector), see
1281     * the TYPE_* constants.
1282     * @param targetList list of target servers
1283     * @param excludeSystemApps whether to exclude system apps or not
1284     * @return array of not running modules of specified type on specified
1285     * list of targets.
1286     */

1287    private String JavaDoc[] getNonRunningModules(String JavaDoc moduleType,
1288            String JavaDoc[] targetList, boolean excludeSystemApps)
1289    throws MBeanConfigException {
1290        try{
1291            DeployableObjectType type = getDeployableObjectType(moduleType);
1292            ArrayList JavaDoc listOfModules= new ArrayList JavaDoc();
1293            for(int i = 0 ; i< targetList.length;i++)
1294            {
1295                listOfModules.addAll(getModules(targetList[i], type, new Boolean JavaDoc(false), excludeSystemApps));
1296            }
1297            return (String JavaDoc[])listOfModules.toArray(new String JavaDoc[listOfModules.size()]);
1298        }catch(Exception JavaDoc e){
1299            throw new MBeanConfigException(e.getMessage());
1300        }
1301    }
1302    
1303    /**
1304     * Returns the list of deployed J2EEApplications. These are the
1305     * applications that are deployed to domain, and are registered
1306     * under <applications>
1307     * @return list of deployed j2ee applications
1308     * @throws ServerInstanceException
1309     */

1310    public String JavaDoc[] getDeployedJ2EEApplications() throws ServerInstanceException {
1311        String JavaDoc[] apps = new String JavaDoc[0];
1312        try {
1313            sLogger.log(Level.FINE, "mbean.list_components");
1314            Applications appsConfigBean =
1315            (Applications) ConfigBeansFactory.getConfigBeanByXPath(
1316            getConfigContext(), ServerXPathHelper.XPATH_APPLICATIONS);
1317            J2eeApplication[] j2eeApps = appsConfigBean.getJ2eeApplication();
1318            if (j2eeApps != null) {
1319                apps = new String JavaDoc[j2eeApps.length];
1320                for(int i=0; i<j2eeApps.length; i++) {
1321                    apps[i] = j2eeApps[i].getName();
1322                }
1323            }
1324        }
1325        catch (Exception JavaDoc e) {
1326            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1327            throw new ServerInstanceException(e.getLocalizedMessage());
1328        }
1329        return ( apps );
1330    }
1331    
1332    /**
1333     * Returns an array of standalone ejb module names that are deployed to
1334     * this server instance.
1335     * @return an array of deployed ejb module names. Returns an array of 0
1336     * length if none are deployed.
1337     * @throws ServerinstanceException
1338     */

1339    public String JavaDoc[] getDeployedEJBModules() throws ServerInstanceException {
1340        String JavaDoc[] ejbModules = new String JavaDoc[0];
1341        try {
1342            sLogger.log(Level.FINE, "mbean.list_components");
1343            Applications appsConfigBean =
1344            (Applications) ConfigBeansFactory.getConfigBeanByXPath(
1345            getConfigContext(), ServerXPathHelper.XPATH_APPLICATIONS);
1346            EjbModule[] modules = appsConfigBean.getEjbModule();
1347            if (modules != null) {
1348                ejbModules = new String JavaDoc[modules.length];
1349                for(int i=0; i<modules.length; i++) {
1350                    ejbModules[i] = modules[i].getName();
1351                }
1352            }
1353        }
1354        catch (Exception JavaDoc e) {
1355            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1356            throw new ServerInstanceException(e.getLocalizedMessage());
1357        }
1358        return ejbModules;
1359    }
1360    
1361    /**
1362     * Returns an array of standalone war module names that are deployed to
1363     * this server instance.
1364     * @return an array of deployed web module names. Returns an array of 0
1365     * length if none are deployed.
1366     * @throws ServerinstanceException
1367     */

1368    public String JavaDoc[] getDeployedWebModules() throws ServerInstanceException {
1369        String JavaDoc[] webModules = new String JavaDoc[0];
1370        try {
1371            sLogger.log(Level.FINE, "mbean.list_components");
1372            Applications appsConfigBean =
1373                (Applications) ConfigBeansFactory.getConfigBeanByXPath(
1374                     getConfigContext(), ServerXPathHelper.XPATH_APPLICATIONS);
1375            WebModule[] modules = appsConfigBean.getWebModule();
1376            if (modules != null) {
1377                webModules = new String JavaDoc[modules.length];
1378                for(int i=0; i<modules.length; i++) {
1379                    webModules[i] = modules[i].getName();
1380                }
1381            }
1382        }
1383        catch (Exception JavaDoc e) {
1384            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1385            throw new ServerInstanceException(e.getLocalizedMessage());
1386        }
1387        return webModules;
1388    }
1389    
1390    /**
1391     * Returns an array of deployed connectors.
1392     * @return an array of deployed connectors. Returns an array of 0 length
1393     * if none are deployed.
1394     * @throws ServerinstanceException
1395     */

1396    public String JavaDoc[] getDeployedConnectors() throws ServerInstanceException {
1397        String JavaDoc[] connectors = new String JavaDoc[0];
1398        try {
1399            sLogger.log(Level.FINE, "mbean.list_components");
1400            Applications appsConfigBean =
1401            (Applications) ConfigBeansFactory.getConfigBeanByXPath(
1402            getConfigContext(), ServerXPathHelper.XPATH_APPLICATIONS);
1403            ConnectorModule[] connectorConfigBeans =
1404            appsConfigBean.getConnectorModule();
1405            if (connectorConfigBeans != null) {
1406                connectors = new String JavaDoc[connectorConfigBeans.length];
1407                for(int i = 0; i < connectors.length; i++) {
1408                    connectors[i] = connectorConfigBeans[i].getName();
1409                }
1410            }
1411        }
1412        catch (Exception JavaDoc e) {
1413            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1414            throw new ServerInstanceException(e.getLocalizedMessage());
1415        }
1416        return connectors;
1417    }
1418    
1419    
1420    /**
1421     * Returns an array of all the deployed components.
1422     * @return an array of deployed components. Returns an array of 0 length
1423     * if none are deployed.
1424     * @throws ServerinstanceException
1425     */

1426    public ObjectName JavaDoc[] getAllDeployedComponents() throws ServerInstanceException {
1427                
1428        int totalCount=0;
1429        ObjectName JavaDoc[] allComponents = null;
1430        
1431        try {
1432            sLogger.log(Level.FINE, "mbean.list_components");
1433            ObjectName JavaDoc[] components= null;
1434            for(int count = 0; count < deployableObjectTypes.length; count++) {
1435                components = getAllRegisteredComponentsOfType(deployableObjectTypes[count]);
1436                if(components != null && components.length > 0) {
1437                    totalCount=totalCount+components.length;
1438                }
1439            }
1440            allComponents = new ObjectName JavaDoc[totalCount];
1441            
1442            if(totalCount > 0) {
1443                totalCount=0;
1444                for(int count = 0; count < deployableObjectTypes.length; count++) {
1445                    components = getAllRegisteredComponentsOfType(deployableObjectTypes[count]);
1446                    if(components != null && components.length > 0) {
1447                        
1448                        for(int count1=0; count1<components.length; count1++,totalCount++) {
1449                            //add component to main array
1450
allComponents[totalCount] = components[count1];
1451                            
1452                        }
1453                    }
1454                }
1455            }
1456            
1457        }
1458        catch (Exception JavaDoc e) {
1459            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1460            throw new ServerInstanceException(e.getLocalizedMessage());
1461        }
1462        return (allComponents);
1463    }
1464    
1465    
1466    /**
1467     * Returns the list of deployed J2EEApplications ObjectName. These are the
1468     * applications that are deployed to domain, and are registered
1469     * under <applications>
1470     * @return list of deployed j2ee applications
1471     * @throws ServerInstanceException
1472     */

1473    public ObjectName JavaDoc[] getAllDeployedJ2EEApplications() throws ServerInstanceException {
1474        return getAllRegisteredComponentsOfType(deployableObjectTypes[0]);
1475    }
1476    
1477    /**
1478     * Returns an array of standalone ejb module ObjectName that are deployed to
1479     * this server instance.
1480     * @return an array of deployed ejb module ObjectName. Returns an array of 0
1481     * length if none are deployed.
1482     * @throws ServerinstanceException
1483     */

1484    public ObjectName JavaDoc[] getAllDeployedEJBModules() throws ServerInstanceException {
1485        return getAllRegisteredComponentsOfType(deployableObjectTypes[1]);
1486    }
1487    
1488    /**
1489     * Returns an array of standalone war module ObjectName that are deployed to
1490     * this server instance.
1491     * @return an array of deployed web module ObjectName. Returns an array of 0
1492     * length if none are deployed.
1493     * @throws ServerinstanceException
1494     */

1495    public ObjectName JavaDoc[] getAllDeployedWebModules() throws ServerInstanceException {
1496       return getAllRegisteredComponentsOfType(deployableObjectTypes[2]);
1497    }
1498    
1499    /**
1500     * Returns an array of deployed connectors ObjectName.
1501     * @return an array of deployed connectors ObjectName. Returns an array of 0 length
1502     * if none are deployed.
1503     * @throws ServerinstanceException
1504     */

1505    public ObjectName JavaDoc[] getAllDeployedConnectors() throws ServerInstanceException {
1506        
1507        return getAllRegisteredComponentsOfType(deployableObjectTypes[3]);
1508    }
1509
1510    /**
1511     * Returns the names of connectors embedded within a deployed EAR.
1512     * @param appName The name of the deployed EAR. If the name is null,
1513     * searches for embedded connectors within all the EARs deployed on the
1514     * given target.
1515     * @param targetName Target used to filter the apps deployed on the
1516     * specific target. If target is domain, all the applications deployed to
1517     * the domain are searched.
1518     * @return Returns an array of names of the embedded connectors. The
1519     * returned array will atleast be of 0 length.
1520     * @throws ServerInstanceException
1521     */

1522    public String JavaDoc[] getEmbeddedConnectorNames(String JavaDoc appName,
1523        String JavaDoc targetName) throws ServerInstanceException
1524    {
1525        final List JavaDoc names = new ArrayList JavaDoc();
1526        try {
1527            final com.sun.enterprise.admin.target.Target target =
1528                getListTarget(targetName);
1529            final String JavaDoc[] apps = filterAppsByTargetAndAppName(target, appName);
1530            for (int i = 0; i < apps.length; i++) {
1531                final Application ad = getDescrForApplication(apps[i]);
1532                final String JavaDoc app_name = ad.getRegistrationName();
1533                final Set JavaDoc bds = ad.getRarDescriptors();
1534                for(Iterator JavaDoc it = bds.iterator(); it.hasNext(); ) {
1535                    final ConnectorDescriptor cd = (ConnectorDescriptor)it.next();
1536                    final String JavaDoc rarJndiName = app_name +
1537                        ConnectorConstants.EMBEDDEDRAR_NAME_DELIMITER +
1538                        FileUtils.makeFriendlyFilenameNoExtension(cd.getDeployName());
1539                    names.add(rarJndiName);
1540                }
1541            }
1542        } catch (ConfigException e) {
1543            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1544            throw new ServerInstanceException(e.getLocalizedMessage());
1545        }
1546        return (String JavaDoc[])names.toArray(new String JavaDoc[0]);
1547    }
1548
1549    String JavaDoc[] filterAppsByTargetAndAppName(
1550        com.sun.enterprise.admin.target.Target target, String JavaDoc appName)
1551        throws ConfigException
1552    {
1553        //1. Apply target filter
1554
/**
1555         * Begin_Note: The following logic should be part of
1556         * getAllDeployedJ2EEApplications(target).
1557         */

1558        ObjectName JavaDoc[] appObjectNames = getAllRegisteredComponentsOfType(
1559            deployableObjectTypes[0]);
1560        if (target.getType() !=
1561            com.sun.enterprise.admin.target.TargetType.DOMAIN) {
1562            final ApplicationRef[] appRefs = target.getApplicationRefs();
1563            appObjectNames = ObjectNameAppRefComparator.intersect(
1564                appObjectNames, appRefs);
1565        }
1566        //End_Note
1567
final Set JavaDoc s = new HashSet JavaDoc();
1568        if (null != appObjectNames) {
1569            for (int i = 0; i < appObjectNames.length; i++) {
1570                s.add(appObjectNames[i].getKeyProperty(NAME));
1571            }
1572        }
1573        //2. Apply appName filter
1574
if (null != appName) {
1575            if (s.contains(appName)) {
1576                return new String JavaDoc[] {appName};
1577            } else {
1578                throw new ConfigException(localStrings.getString(
1579                    "admin.mbeans.acmb.appRefDoesnotExistForTheTarget",
1580                    appName, target.getName()));
1581            }
1582        }
1583        return (String JavaDoc[])s.toArray(new String JavaDoc[0]);
1584    }
1585
1586    ////// new set of getAll methods that take target
1587

1588    /**
1589     * Returns an array of all the deployed components.
1590     * @param targetName all deployed components on the specified target
1591     * @return an array of deployed components. Returns an array of 0 length
1592     * if none are deployed.
1593     * @throws ServerinstanceException
1594     */

1595    public ObjectName JavaDoc[] getAllDeployedComponents(String JavaDoc targetName)
1596        throws ServerInstanceException
1597    {
1598        ObjectName JavaDoc[] oa = new ObjectName JavaDoc[0];
1599        try
1600        {
1601            final com.sun.enterprise.admin.target.Target target =
1602                getListTarget(targetName);
1603            final ObjectName JavaDoc[] allComponents = getAllDeployedComponents();
1604            if (target.getType() == TargetType.DOMAIN)
1605            {
1606                return allComponents;
1607            }
1608            final ApplicationRef[] appRefs = target.getApplicationRefs();
1609            oa = ObjectNameAppRefComparator.intersect(allComponents, appRefs);
1610        }
1611        catch (Exception JavaDoc e) {
1612            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1613            throw new ServerInstanceException(e.getLocalizedMessage());
1614        }
1615        return oa;
1616    }
1617
1618        protected com.sun.enterprise.admin.target.Target
1619    getListTarget(String JavaDoc targetName) throws ConfigException
1620    {
1621        return com.sun.enterprise.admin.target.TargetBuilder.INSTANCE.createTarget(
1622                    VALID_LIST_TYPES, targetName, getConfigContext());
1623    }
1624
1625    /**
1626     * Returns an array of all the user deployed components.
1627     * @return an array of user deployed components.
1628     * @throws ServerinstanceException
1629     */

1630    public ObjectName JavaDoc[] getAllUserDeployedComponents() throws ServerInstanceException {
1631                
1632        ObjectName JavaDoc [] allComponents = new ObjectName JavaDoc[0];
1633        
1634        ObjectName JavaDoc [] sysNuserComponents = getAllDeployedComponents();
1635        
1636        try {
1637            ArrayList JavaDoc arrList = new ArrayList JavaDoc();
1638            
1639            for (int i=0; i<sysNuserComponents.length; i++) {
1640                String JavaDoc type = sysNuserComponents[i].getKeyProperty("type");
1641                    // hack for app-client-module since it doesn't have
1642
// object type in the dtd
1643
if (type.equals("appclient-module")) {
1644                    arrList.add(sysNuserComponents[i]);
1645                    continue;
1646                }
1647                    // get the object-type attribute
1648
// to determine if it is a system app
1649
MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1650                String JavaDoc objectType = (String JavaDoc)mbs.getAttribute(sysNuserComponents[i], OBJECT_TYPE);
1651                if ((objectType != null) &&
1652                    (objectType.startsWith(Constants.SYSTEM_PREFIX))) {
1653                    continue;
1654                }
1655                    // add the object name
1656
arrList.add(sysNuserComponents[i]);
1657            }
1658            if (!arrList.isEmpty()) {
1659                allComponents = (ObjectName JavaDoc[])arrList.toArray(new ObjectName JavaDoc[arrList.size()]);
1660            }
1661
1662        } catch (Exception JavaDoc e) {
1663            sLogger.log(Level.WARNING, "ApplicationsConfigMBean.getAllUserDeployedComponents", e);
1664            throw new ServerInstanceException(e.getLocalizedMessage());
1665        }
1666        return (allComponents);
1667    }
1668
1669    /**
1670     * Returns an array of user deployed components.
1671     * @param targetName
1672     * @return an array of user deployed components. Returns an array of 0
1673     * length if none are deployed.
1674     * @throw ServerInstanceException
1675     */

1676    public ObjectName JavaDoc[] getAllUserDeployedComponents(String JavaDoc targetName)
1677        throws ServerInstanceException
1678    {
1679        ObjectName JavaDoc[] oa = new ObjectName JavaDoc[0];
1680        try
1681        {
1682            final com.sun.enterprise.admin.target.Target target =
1683                getListTarget(targetName);
1684            final ObjectName JavaDoc[] allComponents = getAllUserDeployedComponents();
1685            if (target.getType() == TargetType.DOMAIN)
1686            {
1687                return allComponents;
1688            }
1689            final ApplicationRef[] appRefs = target.getApplicationRefs();
1690            oa = ObjectNameAppRefComparator.intersect(allComponents, appRefs);
1691        }
1692        catch (Exception JavaDoc e) {
1693            sLogger.log(Level.WARNING, "mbean.list_failed", e);
1694            throw new ServerInstanceException(e.getLocalizedMessage());
1695        }
1696        return oa;
1697    }
1698
1699    /**
1700     * Returns the list of deployed J2EEApplications ObjectName. These are the
1701     * applications that are deployed to domain, and are registered
1702     * under <applications>
1703     * @target all deployed components on the specified target
1704     * @return list of deployed j2ee applications
1705     * @throws ServerInstanceException
1706     */

1707    public ObjectName JavaDoc[] getAllDeployedJ2EEApplications(String JavaDoc target) throws ServerInstanceException {
1708    //FIXME provide implementation for target
1709
return getAllRegisteredComponentsOfType(deployableObjectTypes[0]);
1710    }
1711
1712    /**
1713     * Returns an array of standalone ejb module ObjectName that are deployed to
1714     * this server instance.
1715     * @target all deployed components on the specified target
1716     * @return an array of deployed ejb module ObjectName. Returns an array of 0
1717     * length if none are deployed.
1718     * @throws ServerinstanceException
1719     */

1720    public ObjectName JavaDoc[] getAllDeployedEJBModules(String JavaDoc target) throws ServerInstanceException {
1721    //FIXME provide implementation for target
1722
return getAllRegisteredComponentsOfType(deployableObjectTypes[1]);
1723    }
1724
1725    /**
1726     * Returns an array of standalone war module ObjectName that are deployed to
1727     * this server instance.
1728     * @target all deployed components on the specified target
1729     * @return an array of deployed web module ObjectName. Returns an array of 0
1730     * length if none are deployed.
1731     * @throws ServerinstanceException
1732     */

1733    public ObjectName JavaDoc[] getAllDeployedWebModules(String JavaDoc target) throws ServerInstanceException {
1734    //FIXME provide implementation for target
1735
return getAllRegisteredComponentsOfType(deployableObjectTypes[2]);
1736    }
1737
1738    /**
1739     * Returns an array of deployed connectors ObjectName.
1740     * @target all deployed components on the specified target
1741     * @return an array of deployed connectors ObjectName. Returns an array of 0 length
1742     * if none are deployed.
1743     * @throws ServerinstanceException
1744     */

1745    public ObjectName JavaDoc[] getAllDeployedConnectors(String JavaDoc target) throws ServerInstanceException {
1746    //FIXME provide implementation for target
1747
return getAllRegisteredComponentsOfType(deployableObjectTypes[3]);
1748    }
1749
1750    /**
1751     * Returns an array of deployed appclient ObjectName.
1752     * @target all deployed components on the specified target
1753     * @return an array of deployed appclient ObjectName.
1754     * Returns an array of 0 length if none are deployed.
1755     * @throws ServerinstanceException
1756     */

1757    public ObjectName JavaDoc[] getAllDeployedAppclientModules(String JavaDoc target)
1758                            throws ServerInstanceException
1759    {
1760        //FIXME provide implementation for target
1761
return getAllRegisteredComponentsOfType(DeployableObjectType.CAR);
1762    }
1763    
1764    /**
1765     * Enables an application or module on the specified target
1766     * In case of a cluster, the application refs of the server
1767     * instances in that cluster are also enabled.
1768     * @param appName name of the application to be enabled
1769     * @param type
1770     * @param target target name on which app has to be enabled
1771     */

1772    public void enable(String JavaDoc appName, String JavaDoc type, String JavaDoc target)
1773    throws MBeanConfigException {
1774
1775        try{
1776            ObjectName JavaDoc componentON = null;
1777            if(type != null) {
1778                DeployableObjectType objectType = getDeployableObjectType(type);
1779                componentON = getRegisteredComponentObjectName(appName, objectType);
1780            } else {
1781                componentON = getRegisteredComponentObjectName(appName);
1782            }
1783
1784            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1785                
1786            //enable application in central repository
1787
//FIXME. This one should not be necessary once we fix JSR88 client to
1788
//have enabled=true upon deploying to domain
1789
Attribute JavaDoc attr = new Attribute JavaDoc("enabled","true");
1790            if(componentON != null) {
1791                mbs.setAttribute(componentON, attr);
1792            }
1793
1794            // if target is not domain, also enable app-refs for the target.
1795
// In case of cluster, also enable for every instance in a cluster
1796
if (!target.equals(DOMAIN_TARGET)) {
1797            setAppEnableInRefs(appName, target, true);
1798            }
1799
1800        }catch(Throwable JavaDoc te){
1801            sLogger.log(Level.SEVERE, "enable", te);
1802            sLogger.log(Level.FINE,"enable exception");
1803            throw new MBeanConfigException(te.getMessage());
1804        }
1805    }
1806    
1807    /**
1808     * Disable an application or module on the specified target
1809     * In case of a cluster, the application refs of the server
1810     * instances in that cluster are also disabled.
1811     * @param appName name of the application to be disabled
1812     * @param type
1813     * @param target target name on which app has to be disabled
1814     */

1815    public void disable(String JavaDoc appName, String JavaDoc type, String JavaDoc target)
1816    throws MBeanConfigException {
1817        try{
1818            ObjectName JavaDoc componentON = null;
1819
1820            if(type != null) {
1821                DeployableObjectType objectType = getDeployableObjectType(type);
1822                componentON = getRegisteredComponentObjectName(appName, objectType);
1823            }
1824            else {
1825                componentON = getRegisteredComponentObjectName(appName);
1826            }
1827
1828            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1829            
1830            Attribute JavaDoc attr = new Attribute JavaDoc("enabled","false");
1831            // if target is domain, disable the domain level
1832
// application enabled attribute
1833
if (target.equals(DOMAIN_TARGET)) {
1834                if(componentON != null ) {
1835                    mbs.setAttribute(componentON, attr);
1836                }
1837            } else {
1838            // otherwise disable app-refs for the target.
1839
// In case of cluster, also disable for every instance in a
1840
// cluster
1841
setAppEnableInRefs(appName, target, false);
1842            }
1843
1844        } catch(Throwable JavaDoc te){
1845            sLogger.log(Level.FINE,"disable exception");
1846            throw new MBeanConfigException(te.getMessage());
1847        }
1848    }
1849
1850
1851    /**
1852     * enable/disable app-refs for the target.
1853     * In case of cluster, also enable/disable
1854     * for every instance in a cluster
1855     */

1856    private void setAppEnableInRefs(String JavaDoc appName, String JavaDoc target, boolean enable)
1857                                throws Exception JavaDoc {
1858        Attribute JavaDoc attr = new Attribute JavaDoc("enabled", "" + enable);
1859        MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1860        ObjectName JavaDoc apprefON = getRegisteredAppRefObjectName(appName, target);
1861
1862    if (apprefON != null) {
1863            mbs.setAttribute(apprefON,attr);
1864    }
1865
1866        if (isCluster(target)) {
1867        ObjectName JavaDoc[] ons = getAllRefObjectNames(appName, target);
1868        if (ons != null) {
1869        for (int i = 0; i < ons.length; i ++ ) {
1870                    mbs.setAttribute(ons[i],attr);
1871        }
1872            }
1873        }
1874        
1875    }
1876
1877    /**
1878     * gets object names for application refs in all server
1879     * instances in the cluster
1880     */

1881    private ObjectName JavaDoc[] getAllRefObjectNames(String JavaDoc appName, String JavaDoc cluster)
1882                                throws Exception JavaDoc {
1883    Server JavaDoc[] servers = ServerHelper.getServersInCluster(getConfigContext(), cluster);
1884    if(servers == null) return null;
1885    ObjectName JavaDoc[] ons = new ObjectName JavaDoc[servers.length];
1886        MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1887    ObjectName JavaDoc serverON = null;
1888    for (int j = 0; j < servers.length; j ++ ) {
1889            serverON = super.getServerObjectName(servers[j].getName());
1890            ObjectName JavaDoc[] apprefONArr = (ObjectName JavaDoc[])mbs.invoke(serverON,
1891                    "getApplicationRef", emptyParams, emptySignature);
1892            for(int i =0; i< apprefONArr.length;i++)
1893            {
1894                String JavaDoc ref = (String JavaDoc)mbs.getAttribute(apprefONArr[i], "ref");
1895                if(appName.equals(ref))
1896            ons[j] = apprefONArr[i];
1897            }
1898    }
1899    return ons;
1900    }
1901
1902    private boolean isCluster(String JavaDoc targetName)
1903                    throws Exception JavaDoc {
1904        final com.sun.enterprise.admin.target.Target target =
1905            com.sun.enterprise.admin.target.TargetBuilder.INSTANCE.createTarget(
1906                VALID_LIST_TYPES, targetName, getConfigContext());
1907        if (target.getType() == TargetType.CLUSTER) {
1908        return true;
1909        }
1910    return false;
1911    }
1912
1913    /**
1914     * Returns the status of the application as in config.
1915     * is specified target is null/blank/"domain" then only the
1916     * enabled flag of actual application is used. Else enabled
1917     * flag of application-ref is also used to determine the
1918     * enabled status
1919     * @param name name of the component whose status is returned
1920     * @target name of the target [server/group/domain]
1921     * @throws MBeanConfigException in case of any exception
1922     */

1923    public boolean getStatus(String JavaDoc name, String JavaDoc target)
1924                      throws MBeanConfigException
1925    {
1926        try{
1927            boolean appEnabled = true;
1928            boolean appRefEnabled = true;
1929            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1930            ObjectName JavaDoc componentON = null;
1931            
1932            try{
1933                componentON = getRegisteredComponentObjectName(name);
1934            }catch(Exception JavaDoc e){
1935                if(componentON == null)
1936                    throw new MBeanConfigException(e.getMessage());
1937            }
1938            String JavaDoc appEnabledStr = (String JavaDoc)mbs.getAttribute(componentON,
1939                                                   ServerTags.ENABLED);
1940
1941            if("false".equalsIgnoreCase(appEnabledStr))
1942                appEnabled = false;
1943
1944            if(!isDefaultTarget(target))
1945            {
1946                ObjectName JavaDoc apprefON =
1947                            getRegisteredAppRefObjectName(name, target);
1948                String JavaDoc appRefEnabledStr =
1949                        (String JavaDoc)mbs.getAttribute(apprefON, ServerTags.ENABLED);
1950                if("false".equalsIgnoreCase(appRefEnabledStr))
1951                    appRefEnabled = false;
1952
1953            }
1954
1955            if(appEnabled && appRefEnabled)
1956            {
1957                return true;
1958            }
1959
1960            return false;
1961
1962        }catch(Exception JavaDoc e){
1963            sLogger.log(Level.WARNING,"Exception in getStatus:"+e.getMessage());
1964            throw new MBeanConfigException(e.getMessage());
1965        }
1966    }
1967
1968    
1969    /**
1970     * Returns true if redeployment of is supported
1971     * @return true/false
1972     */

1973    public boolean isRedeploySupported()
1974    throws MBeanConfigException {
1975        return true;
1976    }
1977    
1978    ////////////Application Versioning/////////////
1979

1980    /**
1981     * Returns a list of all available versions of an application
1982     * @param appName
1983     * @param type type of the application
1984     * @return list of versions of the app
1985     */

1986    public String JavaDoc[] getAvailableVersions(String JavaDoc appName, String JavaDoc type) throws MBeanConfigException {
1987        throw new MBeanConfigException("Notyet supported");
1988    }
1989    
1990    /**
1991     * Returns the default(currently active) version of the specified application
1992     * or module
1993     * @param appName
1994     * @param type type of the application
1995     * @return default Version
1996     **/

1997    public String JavaDoc getDefaultVersion(String JavaDoc appName, String JavaDoc type) throws MBeanConfigException {
1998        return "";
1999    }
2000    
2001    /**
2002     * Returns the last modified time for an application or module
2003     * @param appName
2004     * @param type type of the application
2005     * @return lastModifiedTime
2006     */

2007    public String JavaDoc getLastModified(String JavaDoc appName, String JavaDoc type) throws MBeanConfigException {
2008        return "";
2009    }
2010    
2011    /**
2012     * Returns true if repository cleaner is enabled
2013     * @return boolean
2014     */

2015    public boolean isRepositoryCleanerEnabled() throws MBeanConfigException {
2016        return true;
2017    }
2018    
2019    /**
2020     * Returns the polling interval for repository cleaner
2021     * @return int
2022     */

2023    public int getRepositoryCleanerPollingInterval() throws MBeanConfigException {
2024        return 2;
2025    }
2026    
2027    /**
2028     * Sets the repository cleaner interval to specified time
2029     * @param interval polling interval for repository cleaner
2030     */

2031    public void setRepositoryCleanerPollingInterval(int interval)
2032    throws MBeanConfigException {
2033    }
2034    
2035    /**
2036     * Returns maximum application versions stored in application repository
2037     * @return int
2038     */

2039    public int getMaxApplicationVersions() throws MBeanConfigException {
2040        return 10;
2041    }
2042    
2043    /**
2044     * Sets maximum application version stored in application repository to
2045     * specified number
2046     * @param maxVersion maximum app version in app repository
2047     */

2048    public void setMaxApplicationVersions(int maxVersions)
2049    throws MBeanConfigException {
2050    }
2051    
2052    ////////////////Auto Deployment////////////////////
2053

2054    /**
2055     * Returns true if autoDeployment is enabled
2056     * @return boolean
2057     */

2058    public boolean isAutoDeployEnabled() throws MBeanConfigException {
2059        return true;
2060    }
2061    
2062    /**
2063     * Enables auto deployment
2064     */

2065    public void setAutoDeployEnabled() throws MBeanConfigException {
2066    }
2067    
2068    /**
2069     * Returns true if auto deployment jspPreCompilation is enabled
2070     * @return boolean
2071     */

2072    public boolean isAutoDeployJspPreCompilationEnabled()
2073    throws MBeanConfigException {
2074        return true;
2075    }
2076    
2077    /**
2078     * Enabled auto deployment jspPreCompilation
2079     */

2080    public void setAutoDeployJspPreCompilationEnabled()
2081    throws MBeanConfigException {
2082    }
2083    
2084    /*
2085     * The following lificeycle module realated operations are added to fulfil
2086     * request unified API for all applications (bug #4934857)
2087     */

2088    /**
2089     */

2090    public ObjectName JavaDoc[] getLifecycleModule(String JavaDoc targetName) throws Exception JavaDoc
2091    {
2092        final com.sun.enterprise.admin.target.Target target =
2093            com.sun.enterprise.admin.target.TargetBuilder.INSTANCE.createTarget(
2094                VALID_LIST_TYPES, targetName, getConfigContext());
2095        final ObjectName JavaDoc[] registeredModules =
2096            (ObjectName JavaDoc[])invoke("getLifecycleModule", null, null);
2097        if (target.getType() == TargetType.DOMAIN)
2098        {
2099            return registeredModules;
2100        }
2101        final ApplicationRef[] refs = target.getApplicationRefs();
2102        final ArrayList JavaDoc al = new ArrayList JavaDoc();
2103        for (int i = 0; i < registeredModules.length; i++)
2104        {
2105            final String JavaDoc name = registeredModules[i].getKeyProperty(
2106                ServerTags.NAME);
2107            for (int j = 0; j < refs.length; j++)
2108            {
2109                if (refs[j].getRef().equals(name))
2110                {
2111                    al.add(registeredModules[i]);
2112                    continue;
2113                }
2114            }
2115        }
2116        final ObjectName JavaDoc[] refModules = new ObjectName JavaDoc[al.size()];
2117        for (int i = 0; i < refModules.length; i++)
2118        {
2119            refModules[i] = (ObjectName JavaDoc)al.get(i);
2120        }
2121        return refModules;
2122    }
2123
2124    /**
2125     */

2126    public ObjectName JavaDoc getLifecycleModuleByName(String JavaDoc key, String JavaDoc targetName)
2127        throws Exception JavaDoc
2128    {
2129        final com.sun.enterprise.admin.target.Target target =
2130            com.sun.enterprise.admin.target.TargetBuilder.INSTANCE.createTarget(
2131                VALID_LIST_TYPES, targetName, getConfigContext());
2132        final ObjectName JavaDoc on = (ObjectName JavaDoc)invoke("getLifecycleModuleByName",
2133            new Object JavaDoc[]{key}, new String JavaDoc[]{"java.lang.String"});
2134        if (!(target.getType() == TargetType.DOMAIN))
2135        {
2136            final ApplicationRef[] refs = target.getApplicationRefs();
2137            boolean isReffed = false;
2138            for (int i = 0; i < refs.length; i++)
2139            {
2140                if (refs[i].getRef().equals(key))
2141                {
2142                    isReffed = true;
2143                    break;
2144                }
2145            }
2146            if (!isReffed)
2147            {
2148                throw new ConfigException(localStrings.getString(
2149                    "applicationRefDoesnotExist", targetName, key));
2150            }
2151        }
2152        return on;
2153    }
2154
2155    static Map JavaDoc getAttributeValues(AttributeList JavaDoc attributeList, String JavaDoc[] names)
2156    {
2157        int len = names.length;
2158        final Map JavaDoc values = new HashMap JavaDoc(len);
2159        final Iterator JavaDoc it = attributeList.iterator();
2160        while (it.hasNext())
2161        {
2162            final Attribute JavaDoc a = (Attribute JavaDoc)it.next();
2163            final String JavaDoc name = a.getName();
2164            for (int i = 0; i < len; i++)
2165            {
2166                if (name.equals(names[i]))
2167                {
2168                    values.put(name, a.getValue());
2169                }
2170            }
2171        }
2172        return values;
2173    }
2174
2175    static final String JavaDoc NAME = ServerTags.NAME;
2176    static final String JavaDoc ENABLED = ServerTags.ENABLED;
2177
2178    public Boolean JavaDoc isLifecycleModuleRegistered(String JavaDoc name)
2179    {
2180        Boolean JavaDoc isRegistered = Boolean.FALSE;
2181        try
2182        {
2183            final ObjectName JavaDoc on = (ObjectName JavaDoc)invoke("getLifecycleModuleByName",
2184                new Object JavaDoc[]{name}, new String JavaDoc[]{"java.lang.String"});
2185            if(on != null) {
2186                isRegistered = Boolean.TRUE;
2187            }
2188        }
2189        catch (Exception JavaDoc e)
2190        {
2191            //ignore ok.
2192
}
2193        return isRegistered;
2194    }
2195
2196    /**
2197     * Creates a life cycle module element and adds an app ref to the given
2198     * target.
2199     * @param attribute_list
2200     * @param targetName
2201     * @return Returns ObjectName corresponding to the created life cycle
2202     * module.
2203     * @throws Exception
2204     * @deprecated Use method with another signature with Properties instead
2205     */

2206    public ObjectName JavaDoc createLifecycleModule(AttributeList JavaDoc attribute_list,
2207                                            String JavaDoc targetName)
2208        throws Exception JavaDoc
2209    {
2210        return createLifecycleModule(attribute_list, null, targetName);
2211
2212    }
2213    
2214    /**
2215     * Creates a life cycle module element and adds an app ref to the given
2216     * target.
2217     * @param attribute_list
2218     * @param targetName
2219     * @param props
2220     * @return Returns ObjectName corresponding to the created life cycle
2221     * module.
2222     * @throws Exception
2223     */

2224    public ObjectName JavaDoc createLifecycleModule(AttributeList JavaDoc attribute_list,
2225                                            Properties JavaDoc props,
2226                                            String JavaDoc targetName)
2227        throws Exception JavaDoc
2228    {
2229        final Map JavaDoc values = getAttributeValues(attribute_list,
2230                                new String JavaDoc[]{NAME, ENABLED});
2231        final String JavaDoc name = (String JavaDoc)values.get(NAME);
2232
2233    ConfigContext ctx = getConfigContext();
2234    ConfigBean app = ApplicationHelper.findApplication(ctx, name);
2235    if ( (app!=null) && !(app instanceof LifecycleModule) ) {
2236
2237        throw new ConfigException(localStrings.getString(
2238            "admin.mbeans.acmb.duplicateLCMName", name));
2239    }
2240
2241        Boolean JavaDoc isRegistered = isLifecycleModuleRegistered(name);
2242        final DeploymentTarget target = getAndValidateDeploymentTarget(
2243            targetName, name, isRegistered.booleanValue(), false);
2244        /**
2245            TODO: There is a catch here. What if the module was already
2246            registered. Should we just add the app reference to the given
2247            target or should we allow the following config call to raise an
2248            exception?
2249         */

2250        final ObjectName JavaDoc on = (ObjectName JavaDoc)invoke("createLifecycleModule",
2251                    new Object JavaDoc[]{attribute_list},
2252                    new String JavaDoc[]{"javax.management.AttributeList"});
2253
2254                    
2255        //add properties into lifecycle element
2256
if (props!=null && props.size()>0) {
2257            //get created bean
2258
ArrayList JavaDoc arr = new ArrayList JavaDoc();
2259            for (Enumeration JavaDoc e = props.propertyNames(); e.hasMoreElements() ;) {
2260                String JavaDoc propName = (String JavaDoc)e.nextElement();
2261                String JavaDoc propValue = (String JavaDoc)props.getProperty(propName);
2262                if (propValue != null) {
2263                    ElementProperty ep = new ElementProperty();
2264                    ep.setName(propName);
2265                    ep.setValue(propValue);
2266                    arr.add(ep);
2267                }
2268            }
2269            if(arr.size()>0)
2270            {
2271                LifecycleModule lcm = (LifecycleModule)ApplicationHelper.findApplication(ctx, name);
2272                lcm.setElementProperty((ElementProperty[])arr.toArray(new ElementProperty[arr.size()]));
2273            }
2274        }
2275
2276        final String JavaDoc isEnabled = (String JavaDoc)values.get(ENABLED);
2277        boolean enabled = new Boolean JavaDoc(isEnabled).booleanValue();
2278        target.addAppReference(name, enabled, null);
2279        return on;
2280    }
2281
2282    /**
2283     * Creates a reference for a lifecycle module in the given target
2284     * @param referenceName the module ID
2285     * @param targetName the target
2286     * @param options
2287     * @return returns a DeploymentStatus
2288     */

2289    public DeploymentStatus createLifecycleModuleReference(String JavaDoc referenceName, String JavaDoc targetName, Map JavaDoc options) {
2290        DeploymentStatus ds = new DeploymentStatus();
2291        ds.setStageDescription("CreateLifecycleModuleReference");
2292        try {
2293            final DeploymentTarget target = getAndValidateDeploymentTarget(
2294                targetName, referenceName, false, false);
2295            boolean enabled = (new DeploymentProperties(options)).getEnable();
2296            target.addAppReference(referenceName, enabled, null);
2297            ds.setStageStatus(DeploymentStatus.SUCCESS);
2298        } catch(Exception JavaDoc e) {
2299            ds.setStageException(e);
2300            ds.setStageStatus(DeploymentStatus.FAILURE);
2301            ds.setStageStatusMessage(e.getMessage());
2302        }
2303        return ds;
2304    }
2305    
2306    /**
2307     * Deletes a reference for a lifecycle module in the given target
2308     * @param referenceName the module ID
2309     * @param targetName the target
2310     * @param options
2311     * @return returns a DeploymentStatus
2312     * @throws Exception
2313     */

2314    public DeploymentStatus removeLifecycleModuleReference(String JavaDoc referenceName, String JavaDoc targetName) {
2315        DeploymentStatus ds = new DeploymentStatus();
2316        ds.setStageDescription("RemoveLifecycleModuleReference");
2317        try {
2318            final DeploymentTarget target = getAndValidateDeploymentTarget(
2319                targetName, referenceName, false, false);
2320            target.removeAppReference(referenceName);
2321            ds.setStageStatus(DeploymentStatus.SUCCESS);
2322        } catch(Exception JavaDoc e) {
2323            ds.setStageException(e);
2324            ds.setStageStatus(DeploymentStatus.FAILURE);
2325            ds.setStageStatusMessage(e.getMessage());
2326        }
2327        return ds;
2328    }
2329
2330    /**
2331     * Removes the app reference to the life cycle module from the given target.
2332     * Performs integrity checks and removes the corresponding life cycle
2333     * module element from the config.
2334     * @param name
2335     * @param targetName
2336     * @throws Exception
2337     */

2338    public void removeLifecycleModuleByName(String JavaDoc name, String JavaDoc targetName)
2339        throws Exception JavaDoc
2340    {
2341        Boolean JavaDoc isRegistered = isLifecycleModuleRegistered(name);
2342        final DeploymentTarget target = getAndValidateDeploymentTarget(
2343            targetName, name, isRegistered.booleanValue(), true);
2344        target.removeAppReference(name);
2345        invoke("removeLifecycleModuleByName", new Object JavaDoc[]{name},
2346            new String JavaDoc[]{"java.lang.String"});
2347    }
2348    
2349    ////////////////////////////////////////////////////////////////////////////
2350
// Helper methods
2351
////////////////////////////////////////////////////////////////////////////
2352

2353    /**
2354     *
2355     */

2356    private DeploymentService getDeploymentService() throws DeploymentException {
2357        if(deployService == null) {
2358            deployService = DeploymentService.getDeploymentService(
2359                                getConfigContext());
2360        }
2361        return deployService;
2362    }
2363
2364    /**
2365     *
2366     */

2367    private String JavaDoc getInstanceName() throws DeploymentException
2368    {
2369
2370        if(mInstanceName == null)
2371        {
2372            try{
2373                MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
2374                ObjectName JavaDoc serversON = new ObjectName JavaDoc(getDomainName()+":type=servers,category=config");
2375                ObjectName JavaDoc[] serverONArr = (ObjectName JavaDoc[])mbs.invoke(serversON, "getServer", new Object JavaDoc[]{}, new String JavaDoc[]{});
2376                mInstanceName = (String JavaDoc)mbs.getAttribute(serverONArr[0], "name");
2377            }catch(Exception JavaDoc e){
2378                sLogger.log(Level.WARNING,"Could not obtain instanceName");
2379                throw new DeploymentException("Could not obtain instanceName");
2380            }
2381        }
2382        return mInstanceName;
2383    }
2384     
2385    /**
2386     * Checks if application or module of name name and type type
2387     * is already registered in the config
2388     * @param name name of the app/module
2389     * @param type [Application,Ejb,Web,Connector,Appclient]
2390     * @returns true if specified app/module is registered
2391     */

2392     private boolean isRegistered(String JavaDoc name, DeployableObjectType type) {
2393        try {
2394            if(getRegisteredComponentObjectName(name,type) != null)
2395                return true;
2396            else
2397                return false;
2398        }
2399        catch (Exception JavaDoc e) {
2400            sLogger.log(Level.WARNING, "appexists failed", e); //noi18N
2401
}
2402        return true;
2403    }
2404     
2405    /**
2406     * Returns the type of the registered component.
2407     * If the component is not registered throws a DeploymentException
2408     * @param name name of the component
2409     * @return type DeployableObjectType of the registered component(app/module)
2410     */

2411    private DeployableObjectType getRegisteredType(String JavaDoc name) throws DeploymentException
2412    {
2413        try{
2414            for(int i = 0; i< deployableObjectTypes.length; i++)
2415            {
2416                if(isRegistered(name, deployableObjectTypes[i]))
2417                    return deployableObjectTypes[i];
2418            }
2419        }catch(Exception JavaDoc e){
2420            throw new DeploymentException(e.getMessage());
2421        }
2422        throw new DeploymentException("Component not registered");
2423    }
2424    
2425    /**
2426     * This method returns the deployableObjectType of an archive by checking the
2427     * deployable descriptors in the archive
2428     * @param filePath absolute path to the archive
2429     * @return type DeployableObjectType
2430     */

2431    private DeployableObjectType getTypeFromFile(String JavaDoc moduleID, String JavaDoc filePath) throws DeploymentException{
2432        return DeploymentServiceUtils.getTypeFromFile(moduleID, filePath);
2433    }
2434    
2435    /**
2436     * This method checks if any of the virtual servers has the given web
2437     * module as default-web-module. If yes, it throws exception.
2438     * @param webModuleName the name of the web module.
2439     * @throws ConfigException if any of the virtual servers has this web
2440     * module as default-web-module.
2441     */

2442    private void checkWebModuleReferences(String JavaDoc webModuleName)
2443    throws ConfigException {
2444        ArrayList JavaDoc virtualServerIds = new ArrayList JavaDoc();
2445        
2446        //ms1 Server rootElement = ServerBeansFactory.getServerBean(context);
2447
Config config = (Config) ConfigBeansFactory.getConfigBeanByXPath(getConfigContext(),ServerXPathHelper.XPATH_CONFIG);
2448        HttpService httpService = config.getHttpService();
2449        VirtualServer[] virtualServers = httpService.getVirtualServer();
2450        for (int j = 0; j < virtualServers.length; j++) {
2451            VirtualServer aServer = virtualServers[j];
2452            String JavaDoc defWebModule = aServer.getDefaultWebModule();
2453            if ((defWebModule != null) &&
2454            (defWebModule.equals(webModuleName))) {
2455                virtualServerIds.add(aServer.getId());
2456            }
2457        }
2458
2459        if (!virtualServerIds.isEmpty()) {
2460            throw new ConfigException(localStrings.getString(
2461                                    "admin.mbeans.acmb.def_web_module_refs_exist",
2462                                                            virtualServerIds.toString(), webModuleName));
2463        }
2464    }
2465    
2466    
2467    /**
2468     * Deletes a file from the temporary location.
2469     * Deletes the given file only if it is in the temporary location.
2470     * FIXME: After starting to use Repository object, this method will not be required.
2471     */

2472    private void deleteFile(String JavaDoc filePath) {
2473        
2474        try{
2475            File JavaDoc f = new File JavaDoc(filePath);
2476        if (f.exists()) {
2477            File JavaDoc parentDir = f.getParentFile();
2478            File JavaDoc tmpDir = new File JavaDoc(AdminService.getAdminService().
2479            getTempDirPath(), getInstanceName());
2480            /* note that the above call may return a null */
2481            if (tmpDir != null && tmpDir.equals(parentDir)) {
2482                boolean couldDelete = f.delete();
2483                if (couldDelete) {
2484                    sLogger.log(Level.FINE, "mbean.delete_temp_file_ok", filePath);
2485                }
2486                else {
2487                    sLogger.log(Level.INFO, "mbean.delete_temp_file_failed", filePath);
2488                }
2489            }
2490        }
2491        }catch(Exception JavaDoc e){
2492            sLogger.log(Level.WARNING,"could not deletefile"+filePath);
2493        }
2494    }
2495    
2496    
2497    
2498
2499    /**
2500     * Converts moduleType in string to DeployableObjectType
2501     * @param moduleType application/ejb/web/connector
2502     * @return DeployableObjectType
2503     * @throws DeploymentException
2504     */

2505    private DeployableObjectType getDeployableObjectType(String JavaDoc moduleType) throws DeploymentException {
2506        if(moduleType.equals(TYPE_APPLICATION) || moduleType.equals(JSR88_TYPE_APPLICATION)) {
2507            return DeployableObjectType.APP;
2508        }
2509        else if(moduleType.equals(TYPE_EJB) || moduleType.equals(JSR88_TYPE_EJB)) {
2510            return DeployableObjectType.EJB;
2511        }
2512        else if(moduleType.equals(TYPE_WEB) || moduleType.equals(JSR88_TYPE_WEB)) {
2513            return DeployableObjectType.WEB;
2514        }
2515        else if(moduleType.equals(TYPE_CONNECTOR) || moduleType.equals(JSR88_TYPE_CONNECTOR)) {
2516            return DeployableObjectType.CONN;
2517        }
2518        else if(moduleType.equals(TYPE_APPCLIENT) || moduleType.equals(JSR88_TYPE_APPCLIENT)) {
2519            return DeployableObjectType.CAR;
2520        }
2521        else if(moduleType.equals(XModuleType.LCM.toString())) {
2522            return DeployableObjectType.LCM;
2523        }
2524        else if(moduleType.equals(XModuleType.CMB.toString())) {
2525            return DeployableObjectType.CMB;
2526        }
2527        else {
2528            throw new DeploymentException("Unknown deployable object type");
2529        }
2530    }
2531    
2532    /**
2533     * legacy method from managedserverinstance
2534     * @param dir
2535     * @param user
2536     */

2537    private void chownDir(File JavaDoc dir, String JavaDoc user) {
2538        if (dir == null || user == null || user.trim().equals("")) {
2539            return;
2540        }
2541        String JavaDoc err = null;
2542        /*installConfig is removed and we need better alternative */
2543        /*
2544        installConfig cfg = new installConfig();
2545        err = cfg.chownDir(dir.getAbsolutePath(), user);
2546        if (err != null) {
2547            sLogger.log(Level.WARNING, err);
2548        }
2549         */

2550    }
2551    
2552    /**
2553     * @throws ServerInstanceException
2554     */

2555    
2556    public HostAndPort getHostAndPort() throws ServerInstanceException {
2557        return getHostAndPort(false);
2558    }
2559    
2560    /**
2561     * @param securityEnabled
2562     * @throws ServerInstanceException
2563     */

2564    public HostAndPort getHostAndPort(boolean securityEnabled) throws ServerInstanceException {
2565        HostAndPort hAndp = null;
2566        try {
2567            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
2568            ObjectName JavaDoc objectName = new ObjectName JavaDoc(getDomainName()+":type=configs,category=config");
2569            String JavaDoc operationName1 = "getConfig";
2570            ObjectName JavaDoc[] configs = (ObjectName JavaDoc[])mbs.invoke(objectName,operationName1, emptyParams,emptySignature);
2571            String JavaDoc configName = (String JavaDoc)mbs.getAttribute(configs[0], "name");
2572            ObjectName JavaDoc httpService = new ObjectName JavaDoc(getDomainName()+":type=http-service,config="+configName+",category=config");
2573            String JavaDoc operationName2 = "getHttpListener";
2574            ObjectName JavaDoc[] httpListener = (ObjectName JavaDoc[])mbs.invoke(httpService, operationName2,emptyParams,emptySignature);
2575
2576            String JavaDoc serverName = null;
2577            int port = 0;
2578            for (int i = 0; i < httpListener.length; i++) {
2579                AttributeList JavaDoc attrs = mbs.getAttributes(httpListener[i],
2580                        httpListenerAttrNames);
2581                Boolean JavaDoc bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
2582                        attrs, LISTENER_ENABLED));
2583                boolean enabled = ((bb == null) ? false : bb.booleanValue());
2584                if (!enabled) {
2585                    // Listener is not enabled
2586
continue;
2587                }
2588                String JavaDoc vs = (String JavaDoc)getNamedAttributeValue(attrs, DEF_VS);
2589                if (ADMIN_VS.equals(vs)) {
2590                    // Listener is reserved for administration
2591
continue;
2592                }
2593                bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
2594                        attrs, SEC_ENABLED));
2595                boolean sec_on = ((bb == null) ? false : bb.booleanValue());
2596                if (securityEnabled == sec_on) {
2597                    serverName = (String JavaDoc)getNamedAttributeValue(attrs,
2598                            SERVER_NAME);
2599                    if (serverName == null || serverName.trim().equals("")) {
2600                        serverName = getDefaultHostName();
2601                    }
2602                    String JavaDoc portStr = (String JavaDoc)getNamedAttributeValue(attrs,
2603                            PORT);
2604                    String JavaDoc redirPort = (String JavaDoc)getNamedAttributeValue(attrs,
2605                            REDIRECT_PORT);
2606                    if (redirPort != null && !redirPort.trim().equals("")) {
2607                        portStr = redirPort;
2608                    }
2609                    String JavaDoc resolvedPort =
2610                        new PropertyResolver(getConfigContext(),
2611                            getInstanceName()).resolve(portStr);
2612                    port = Integer.parseInt(resolvedPort);
2613                    break;
2614                }
2615            }
2616            hAndp = new HostAndPort(serverName, port);
2617        }
2618        catch (Exception JavaDoc e) {
2619            throw new ServerInstanceException(e.getLocalizedMessage());
2620        }
2621        return hAndp;
2622    }
2623    
2624    /**
2625     * Gets the host and port for a given stand-alone module id
2626     *
2627     * @param standAloneModuleId
2628     * @param securityEnabled
2629     * @throws ServerInstanceException
2630     */

2631    public HostAndPort getHostAndPort(String JavaDoc standAloneModuleId, boolean securityEnabled)
2632    throws ServerInstanceException {
2633
2634        HostAndPort hAndp = null;
2635    boolean setHP = false;
2636
2637        try {
2638
2639        // Application Ref element for the given module
2640

2641        String JavaDoc appRefXPath = ServerXPathHelper.getServerIdXpath(getInstanceName())
2642                 + ServerXPathHelper.XPATH_SEPARATOR
2643                 + ServerTags.APPLICATION_REF + "[@"
2644                 + ServerTags.REF + "='" + standAloneModuleId + "']";
2645
2646        ApplicationRef appRef = (ApplicationRef) ConfigBeansFactory.getConfigBeanByXPath(
2647                                     getConfigContext(), appRefXPath);
2648
2649            // if no virtual server, pick up first
2650
if (appRef.getVirtualServers()!=null) {
2651                return getHostAndPort(securityEnabled);
2652            }
2653            
2654        // Get the list of virtual servers from the Application Ref
2655

2656        String JavaDoc appRefvs = null;
2657            List JavaDoc vsList = StringUtils.parseStringList(appRef.getVirtualServers(), " ,");
2658            if (vsList==null) {
2659                return getHostAndPort(securityEnabled);
2660            }
2661        ListIterator JavaDoc vsListIter = vsList.listIterator();
2662
2663        // Iterate for each of the virtual servers
2664

2665        while(vsListIter.hasNext()) {
2666                String JavaDoc virtualServer = (String JavaDoc) vsListIter.next();
2667                HostAndPort hp = getVirtualServerHostAndPort(virtualServer, securityEnabled);
2668                if (hp!=null) {
2669                    return hp;
2670                }
2671            }
2672        } catch (Exception JavaDoc e) {
2673            throw new ServerInstanceException(e.getLocalizedMessage());
2674        }
2675        
2676        return null;
2677    }
2678    
2679    /**
2680     *
2681     */

2682    public HostAndPort getVirtualServerHostAndPort(String JavaDoc vs, boolean securityEnabled)
2683        throws ServerInstanceException
2684    {
2685        String JavaDoc serverName = null;
2686        int port = 0;
2687        
2688        try {
2689            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
2690            
2691            ObjectName JavaDoc objectName = new ObjectName JavaDoc(
2692            getDomainName()+":type=configs,category=config");
2693            String JavaDoc operationName1 = "getConfig";
2694            ObjectName JavaDoc[] configs = (
2695            ObjectName JavaDoc[])mbs.invoke(objectName,operationName1,
2696            emptyParams,emptySignature);
2697            String JavaDoc configName = (String JavaDoc)mbs.getAttribute(configs[0], "name");
2698            ObjectName JavaDoc httpService = new ObjectName JavaDoc(
2699            getDomainName()+":type=http-service,config="+configName+",category=config");
2700            
2701            // http listeners for the given config
2702

2703            String JavaDoc operationName2 = "getHttpListener";
2704            ObjectName JavaDoc[] httpListener = (ObjectName JavaDoc[])mbs.invoke(httpService,
2705            operationName2,emptyParams,emptySignature);
2706            
2707            // virtual servers for the given config
2708

2709            operationName2 = "getVirtualServer";
2710            ObjectName JavaDoc[] virtualServer = (ObjectName JavaDoc[])mbs.invoke(httpService,
2711            operationName2,emptyParams,emptySignature);
2712            
2713            // iterate for each of the config virtual server
2714

2715            for (int i = 0; i < virtualServer.length; i++) {
2716                
2717                AttributeList JavaDoc vsAttrs = mbs.getAttributes(virtualServer[i], vsAttrNames);
2718                
2719                // virtual server id check
2720
//
2721
// if the virtual server obtained from application ref
2722
// does not match with the virtual server from config
2723
// then continue with next virtual server
2724

2725                String JavaDoc id = (String JavaDoc)getNamedAttributeValue(vsAttrs, ID);
2726                if (! id.equals(vs)) {
2727                    continue;
2728                }
2729                
2730                // should we check for state, let us assume ON for PE
2731

2732                // http listener
2733
//
2734
// Obtain the http listeners list from the virtual server
2735
// and iterate to match with the http listeners from config.
2736
// When a match is found get the host and port data
2737

2738                String JavaDoc httpListeners = (String JavaDoc) getNamedAttributeValue(vsAttrs, "http-listeners");
2739                String JavaDoc vsHttpListener = null;
2740                List JavaDoc httpListenerList = StringUtils.parseStringList(httpListeners, " ,");
2741                ListIterator JavaDoc hlListIter = httpListenerList.listIterator();
2742                
2743                while(hlListIter.hasNext()) {
2744                    
2745                    vsHttpListener = (String JavaDoc) hlListIter.next();
2746                    
2747                    for (int j = 0; j < httpListener.length; j++) {
2748                        
2749                        AttributeList JavaDoc attrs = mbs.getAttributes(httpListener[j],
2750                        httpListenerAttrNames);
2751                        
2752                        // http listener id check
2753
String JavaDoc listenerId = (String JavaDoc)getNamedAttributeValue(attrs, ID);
2754                        if (! listenerId.equals(vsHttpListener)) {
2755                            continue;
2756                        }
2757                        
2758                        Boolean JavaDoc bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
2759                        attrs, LISTENER_ENABLED));
2760                        boolean enabled = ((bb == null) ? false : bb.booleanValue());
2761                        if (!enabled) {
2762                            // Listener is not enabled
2763
continue;
2764                        }
2765                        bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue( attrs, SEC_ENABLED));
2766                        boolean sec_on = ((bb == null) ? false : bb.booleanValue());
2767                        if (securityEnabled == sec_on) {
2768                            serverName = (String JavaDoc)getNamedAttributeValue(attrs, SERVER_NAME);
2769                            if (serverName == null || serverName.trim().equals("")) {
2770                                serverName = getDefaultHostName();
2771                            }
2772                            String JavaDoc portStr = (String JavaDoc)getNamedAttributeValue(attrs, PORT);
2773                            String JavaDoc redirPort = (String JavaDoc)getNamedAttributeValue(attrs, REDIRECT_PORT);
2774                            if (redirPort != null && !redirPort.trim().equals("")) {
2775                                portStr = redirPort;
2776                            }
2777                            final String JavaDoc resolvedPort =
2778                                    new PropertyResolver(getConfigContext(),
2779                                        getInstanceName()).resolve(portStr);
2780                            port = Integer.parseInt(resolvedPort);
2781                            return new HostAndPort(serverName, port);
2782                        }
2783                    }
2784                }
2785            }
2786        } catch (Exception JavaDoc e) {
2787            throw new ServerInstanceException(e.getLocalizedMessage());
2788        }
2789        return null;
2790    }
2791    
2792    /**
2793     * @param request DeploymentRequest
2794     * @param env instance environment
2795     */

2796    private void setDeployDirOwner(DeploymentRequest request,
2797    InstanceEnvironment env) {
2798        //Need an alternative. Ramakanth. 04/23/2003
2799
/*
2800        try {
2801            String instanceUser = env.getInstanceUser();
2802            File deployDir = request.getDeployedDirectory();
2803            chownDir(deployDir, instanceUser);
2804            File stubsDir = request.getStubsDirectory();
2805            chownDir(stubsDir, instanceUser);
2806            File jspDir = request.getJSPDirectory();
2807            chownDir(jspDir, instanceUser);
2808        } catch (Throwable t) {
2809            sLogger.log(Level.WARNING, "mbean.deploy_chown_failed",
2810            t.getMessage());
2811            sLogger.log(Level.FINE, "general.unexpected_exception", t);
2812        }
2813         */

2814    }
2815    
2816    
2817    private ObjectName JavaDoc[] getAllRegisteredComponentsOfType(DeployableObjectType type) {
2818        String JavaDoc operationName = null;
2819        ObjectName JavaDoc[] ONArr = null;
2820        try{
2821            if(type.isAPP())
2822                operationName = "getJ2eeApplication";
2823            else if(type.isEJB())
2824                operationName = "getEjbModule";
2825            else if(type.isWEB())
2826                operationName = "getWebModule";
2827            else if(type.isCONN())
2828                operationName = "getConnectorModule";
2829            else if(type.isCAR())
2830                operationName = "getAppclientModule";
2831            
2832            ONArr = (ObjectName JavaDoc[])invoke(operationName,emptyParams,emptySignature);
2833        }catch(Exception JavaDoc e){
2834            sLogger.log(Level.FINE, e.getMessage());
2835            ONArr = new ObjectName JavaDoc[]{};
2836        }
2837        return ONArr;
2838    }
2839    
2840    private ArrayList JavaDoc getModules(String JavaDoc target, DeployableObjectType type, Boolean JavaDoc state, boolean excludeSystemApps) throws Exception JavaDoc
2841    {
2842        ArrayList JavaDoc list = new ArrayList JavaDoc();
2843        String JavaDoc operationName = "getApplicationRef";
2844        try{
2845            ObjectName JavaDoc[] appONArr = getAllRegisteredComponentsOfType(type);
2846            ObjectName JavaDoc serverON = new ObjectName JavaDoc(getDomainName()+":type=server,name="
2847            +target+",category=config");
2848            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
2849            ObjectName JavaDoc[] apprefONArr = (ObjectName JavaDoc[])mbs.invoke(serverON, operationName,
2850                emptyParams, emptySignature);
2851            for(int i =0 ; i< apprefONArr.length ; i++) {
2852                String JavaDoc refName = (String JavaDoc)mbs.getAttribute(apprefONArr[i], "ref");
2853
2854                     String JavaDoc refenabled = (String JavaDoc)mbs.getAttribute(apprefONArr[i], "enabled");
2855                     //if refEnabled only determines a stop/start then neednot do this below.
2856
for(int j =0 ; j < appONArr.length ; j++) {
2857                         String JavaDoc name = (String JavaDoc)mbs.getAttribute(appONArr[j], "name");
2858                         if(name.equals(refName)) {
2859                             /*
2860                              *Use an assumed value of "user" for app client modules, because they do not
2861                              *have an explicit object type attribute.
2862                              */

2863                             String JavaDoc objectType = (type.equals(DeployableObjectType.CAR)
2864                                ? Constants.USER
2865                                : (String JavaDoc)mbs.getAttribute(appONArr[j], OBJECT_TYPE));
2866                             if (excludeSystemApps
2867                                     && (objectType != null)
2868                                     && (objectType.startsWith(Constants.SYSTEM_PREFIX))) {
2869                                 break;
2870                             }
2871                             if(state == null) {
2872                                 list.add(refName);
2873                             }else {
2874                                 /*
2875                                  *App client modules do not support the "enabled" attribute, so assume any
2876                                  *app client module is enabled. For other types, ask the MBean if the module
2877                                  *is enabled or not.
2878                                  */

2879                                 String JavaDoc enabled = (type.equals(DeployableObjectType.CAR)
2880                                    ? "true"
2881                                    : (String JavaDoc)mbs.getAttribute(appONArr[j], "enabled"));
2882                                 if(state.equals(Boolean.TRUE)) {
2883                                     if(enabled.equalsIgnoreCase("true") && refenabled.equalsIgnoreCase("true"))
2884                                         list.add(refName);
2885                                 }
2886                                 else if(state.equals(Boolean.FALSE)) {
2887                                     if(enabled.equalsIgnoreCase("false") || refenabled.equalsIgnoreCase("false"))
2888                                         list.add(refName);
2889                                 }
2890                             }
2891                         }
2892                     
2893                }
2894                      
2895                }
2896        }catch(Exception JavaDoc e) {
2897            sLogger.log(Level.FINE, e.getMessage());
2898            throw e;
2899        }
2900        return list;
2901    }
2902    
2903    private ObjectName JavaDoc constructComponentObjectName(String JavaDoc name, DeployableObjectType type){
2904        ObjectName JavaDoc ON = null;
2905        try{
2906            if(type.isAPP())
2907                ON = new ObjectName JavaDoc(getDomainName()+":type=j2ee-application,name="+name+",category=config");
2908            else if(type.isEJB())
2909                ON = new ObjectName JavaDoc(getDomainName()+":type=ejb-module,name="+name+",category=config");
2910            else if(type.isAPP())
2911                ON = new ObjectName JavaDoc(getDomainName()+":type=web-module,name="+name+",category=config");
2912            else if(type.isAPP())
2913                ON = new ObjectName JavaDoc(getDomainName()+":type=connector-module,name="+name+",category=config");
2914            else if(type.isAPP())
2915                ON = new ObjectName JavaDoc(getDomainName()+":type=appclient-module,name="+name+",category=config");
2916        }catch(Exception JavaDoc e){
2917        }
2918        return ON;
2919    }
2920
2921    /**
2922     *
2923     */

2924    private ObjectName JavaDoc getRegisteredComponentObjectName(String JavaDoc name, DeployableObjectType type) {
2925        ObjectName JavaDoc ret = null;
2926        try {
2927            String JavaDoc operationName = null;
2928            if(type.equals(DeployableObjectType.APP)) {
2929                operationName = "getJ2eeApplicationByName";
2930            }
2931            else if(type.equals(DeployableObjectType.EJB)) {
2932                operationName = "getEjbModuleByName";
2933            }
2934            else if(type.equals(DeployableObjectType.WEB)) {
2935                operationName = "getWebModuleByName";
2936            }
2937            else if(type.equals(DeployableObjectType.CONN)) {
2938                operationName = "getConnectorModuleByName";
2939            }
2940            else if(type.equals(DeployableObjectType.CAR)) {
2941                operationName = "getAppclientModuleByName";
2942            }
2943            else if(type.equals(DeployableObjectType.LCM)) {
2944                operationName = "getLifecycleModuleByName";
2945            }
2946            else if(type.equals(DeployableObjectType.CMB)) {
2947                operationName = "getMbeanByName";
2948            }
2949            Object JavaDoc[] params = new Object JavaDoc[]{name};
2950            String JavaDoc[] signature = new String JavaDoc[]{"java.lang.String"};
2951            ret = (ObjectName JavaDoc)invoke(operationName, params, signature);
2952            
2953        }catch (Exception JavaDoc e) {
2954// sLogger.log(Level.WARNING, "appexists failed", e); //noi18N
2955
}
2956        return ret;
2957    }
2958
2959    private ObjectName JavaDoc getRegisteredComponentObjectName(String JavaDoc name)
2960                                                  throws DeploymentException {
2961        ObjectName JavaDoc ret = null;
2962
2963       for(int i=0 ; i < deployableObjectTypes.length ; i++)
2964       {
2965           ret = getRegisteredComponentObjectName(name,deployableObjectTypes[i]);
2966           if(ret != null)
2967               return ret;
2968       }
2969       throw new DeploymentException("Component not registered");
2970    }
2971
2972    private ObjectName JavaDoc getRegisteredAppRefObjectName(String JavaDoc name, String JavaDoc targetName)
2973        throws DeploymentException
2974    {
2975        try{
2976            final com.sun.enterprise.admin.target.Target target =
2977                com.sun.enterprise.admin.target.TargetBuilder.INSTANCE.
2978                createTarget(VALID_LIST_TYPES, targetName, getConfigContext());
2979            assert target != null;
2980
2981            ObjectName JavaDoc targetON = null;
2982            if (target.getType() ==
2983                    com.sun.enterprise.admin.target.TargetType.CLUSTER) {
2984                targetON = super.getClusterObjectName(targetName);
2985            } else if (target.getType() ==
2986                    com.sun.enterprise.admin.target.TargetType.DOMAIN) {
2987                //Domain will not have app refs.
2988
return null;
2989            } else {
2990                targetON = super.getServerObjectName(targetName);
2991            }
2992            assert targetON != null;
2993
2994            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
2995            ObjectName JavaDoc[] apprefONArr = (ObjectName JavaDoc[])mbs.invoke(targetON,
2996               "getApplicationRef", emptyParams, emptySignature);
2997            for(int i =0; i< apprefONArr.length;i++)
2998            {
2999                String JavaDoc ref = (String JavaDoc)mbs.getAttribute(apprefONArr[i], "ref");
3000                if(name.equals(ref))
3001                    return apprefONArr[i];
3002            }
3003       }catch(Exception JavaDoc e){
3004          throw new DeploymentException(e.getMessage());
3005       }
3006       throw new DeploymentException("Component not registered");
3007    }
3008
3009
3010    // Code for retrieving list of components within an application
3011
// or module.
3012

3013    /**
3014     * Returns the list of sub-components for a given module
3015     *
3016     * This method needs to be updated for SE/EE to include target
3017     *
3018     * @return list of sub-components for a given module
3019     * @throws ServerInstanceException
3020     */

3021    public String JavaDoc[] getModuleComponents(String JavaDoc standAloneModuleName)
3022                throws ServerInstanceException {
3023
3024        String JavaDoc [] modComponents = new String JavaDoc[0];
3025
3026        if ((standAloneModuleName == null) || (standAloneModuleName.length() < 1)) {
3027                throw new ServerInstanceException(
3028            localStrings.getString("admin.mbeans.ssmb.invalid_app_or_module_name", ""));
3029        }
3030
3031        try {
3032            sLogger.log(Level.FINE,
3033                "ApplicationsConfigMBean.getModuleComponents for " + standAloneModuleName);
3034
3035            // Get module type which is required for getting module descriptor.
3036
// This process validates the existence of given module.
3037

3038            String JavaDoc j2eeType = getJ2eeType(standAloneModuleName);
3039
3040            if (j2eeType == null) {
3041                throw new ServerInstanceException(
3042            localStrings.getString("admin.mbeans.ssmb.invalid_app_or_module_name",
3043            standAloneModuleName));
3044            }
3045
3046            // Get the module descriptor and
3047
// list of component names
3048

3049            if (j2eeType.equals("EJBModule")) {
3050                BundleDescriptor bd = getDescrForStandAloneEjbModule(standAloneModuleName);
3051                modComponents = getValidatedObjectNames(
3052            getEjbModuleComponents((EjbBundleDescriptor)bd));
3053                return modComponents;
3054            } else if (j2eeType.equals("WebModule")) {
3055                BundleDescriptor bd = getDescrForStandAloneWebModule(standAloneModuleName);
3056                modComponents = getValidatedObjectNames(
3057                    getWebModuleComponents((WebBundleDescriptor)bd));
3058                return modComponents;
3059            } else if (j2eeType.equals("ResourceAdapterModule")) {
3060                BundleDescriptor bd = getDescrForStandAloneRarModule(standAloneModuleName);
3061                modComponents = getValidatedObjectNames(
3062                    getRarModuleComponents((ConnectorDescriptor)bd));
3063                return modComponents;
3064            } else if (j2eeType.equals("AppClientModule")) {
3065                BundleDescriptor bd = getDescrForStandAloneCarModule(standAloneModuleName);
3066                modComponents = getValidatedObjectNames(getCarModuleComponents(bd));
3067                return modComponents;
3068            } else if (j2eeType.equals("J2EEApplication")) {
3069                Application ad = getDescrForApplication(standAloneModuleName);
3070                modComponents = getValidatedObjectNames(getApplicationComponents(ad));
3071                return modComponents;
3072            } else {
3073                throw new ServerInstanceException(
3074            localStrings.getString("admin.mbeans.ssmb.invalid_app_or_module_name",
3075            standAloneModuleName));
3076            }
3077
3078        } catch (Exception JavaDoc e) {
3079            sLogger.log(Level.WARNING, "ApplicationsConfigMBean.getModuleComponents failed", e);
3080            throw new ServerInstanceException(e.getLocalizedMessage());
3081        }
3082
3083    }
3084
3085
3086    /**
3087     * Returns the list of sub-components for a given module within an application
3088     *
3089     * This method needs to be updated for SE/EE to include target
3090     *
3091     * @return list of sub-components for a given module
3092     * @throws ServerInstanceException
3093     */

3094    public String JavaDoc[] getModuleComponents(String JavaDoc appName, String JavaDoc modName)
3095                throws ServerInstanceException {
3096
3097        String JavaDoc [] modComponents = new String JavaDoc[0];
3098
3099        if ((modName == null) || (modName.length() < 1)) {
3100                throw new ServerInstanceException("invalid ModuleName");
3101        }
3102
3103        try {
3104            sLogger.log(Level.FINE,
3105                "ApplicationsConfigMBean.getModuleComponents for application = " +
3106                appName + " and module = " + modName);
3107
3108            // Get application descriptor
3109

3110            AppsManager am = InstanceFactory.createAppsManager(getInstanceName());
3111        Application appD = null;
3112        try {
3113            appD = (Application) DeploymentUtils.getDescriptor(appName, am);
3114        } catch (java.lang.NullPointerException JavaDoc npe) {
3115                throw new ServerInstanceException(
3116            localStrings.getString("admin.mbeans.ssmb.invalid_appname", appName));
3117        }
3118
3119            // Get the bundle descriptor for the given module
3120
// and determine its' type
3121

3122            BundleDescriptor bd = null;
3123            ModuleType JavaDoc modType = null;
3124            java.util.Set JavaDoc bds = appD.getBundleDescriptors();
3125            for(Iterator JavaDoc it=bds.iterator(); it.hasNext(); ) {
3126                bd = (BundleDescriptor)it.next();
3127                if ((bd.getModuleDescriptor().getArchiveUri()).equals(modName) ||
3128                     bd.getModuleID().equals(modName) ||
3129             bd.getName().equals(modName)) {
3130                        modType = bd.getModuleType();
3131            break;
3132                }
3133            }
3134
3135            // invoke approprite module to list components
3136

3137            if (modType == ModuleType.EJB) {
3138                modComponents = getValidatedObjectNames(
3139                    getEjbModuleComponents((EjbBundleDescriptor)bd));
3140                return modComponents;
3141            } else if (modType == ModuleType.WAR) {
3142                modComponents = getValidatedObjectNames(
3143                    getWebModuleComponents((WebBundleDescriptor)bd));
3144                return modComponents;
3145            } else if (modType == ModuleType.RAR) {
3146                modComponents = getValidatedObjectNames(
3147                    getRarModuleComponents((ConnectorDescriptor)bd));
3148                return modComponents;
3149            } else if (modType == ModuleType.CAR) {
3150                modComponents = getValidatedObjectNames(
3151                    getCarModuleComponents(bd));
3152                return modComponents;
3153            } else {
3154                    throw new ServerInstanceException("invalid module or application name");
3155            }
3156
3157        } catch (Exception JavaDoc e) {
3158            sLogger.log(Level.WARNING, "ApplicationsConfigMBean.getModuleComponents failed", e);
3159            throw new ServerInstanceException(e.getLocalizedMessage());
3160        }
3161
3162    }
3163
3164    /**
3165     * Returns j2ee type for the given module.
3166     * @return j2ee type for the given module
3167     * @throws ServerInstanceException
3168     */

3169    String JavaDoc getJ2eeType(String JavaDoc dName)
3170                throws ServerInstanceException {
3171
3172        // iterate through each of j2ee types
3173

3174        String JavaDoc j2eeType = null;
3175
3176        try {
3177
3178            // Application
3179
Applications appsConfigBean =
3180                    (Applications) ConfigBeansFactory.getConfigBeanByXPath(
3181                    getConfigContext(), ServerXPathHelper.XPATH_APPLICATIONS);
3182
3183            // J2EEApplication
3184
J2eeApplication[] j2eeApps = appsConfigBean.getJ2eeApplication();
3185            if (j2eeApps != null) {
3186                for(int i=0; i<j2eeApps.length; i++) {
3187                    if ((j2eeApps[i].getName()).equals(dName)) {
3188                        return "J2EEApplication";
3189                    }
3190                }
3191            }
3192
3193            // EJBModule
3194
EjbModule[] eModules = appsConfigBean.getEjbModule();
3195            if (eModules != null) {
3196                for(int i=0; i<eModules.length; i++) {
3197                    if ((eModules[i].getName()).equals(dName)) {
3198                        return "EJBModule";
3199                    }
3200                }
3201            }
3202
3203            // WebModule
3204
WebModule[] wModules = appsConfigBean.getWebModule();
3205            if (wModules != null) {
3206                for(int i=0; i<wModules.length; i++) {
3207                    if ((wModules[i].getName()).equals(dName)) {
3208                        return "WebModule";
3209                    }
3210                }
3211            }
3212
3213            // ResourceAdapterModule
3214
ConnectorModule[] connectorConfigBeans = appsConfigBean.getConnectorModule();
3215            if (connectorConfigBeans != null) {
3216                for(int i = 0; i < connectorConfigBeans.length; i++) {
3217                    if ((connectorConfigBeans[i].getName()).equals(dName)) {
3218                        return "ResourceAdapterModule";
3219                    }
3220                }
3221            }
3222
3223        } catch (Exception JavaDoc e) {
3224                throw new ServerInstanceException(e.getLocalizedMessage());
3225        }
3226        return j2eeType;
3227    }
3228
3229    /**
3230     * Returns ejb module components
3231     * @return String [] ejb module components
3232     * @throws ServerInstanceException
3233     */

3234    BundleDescriptor getDescrForStandAloneEjbModule (String JavaDoc ejbModuleName)
3235                throws ServerInstanceException {
3236        try {
3237            EjbModulesManager ejbModMgr =
3238                InstanceFactory.createEjbModuleManager(getInstanceName());
3239            return (BundleDescriptor)
3240                DeploymentUtils.getDescriptor(ejbModuleName, ejbModMgr);
3241        } catch (Exception JavaDoc e) {
3242            throw new ServerInstanceException(e.getLocalizedMessage());
3243        }
3244
3245    }
3246
3247    String JavaDoc [] getEjbModuleComponents(EjbBundleDescriptor bd)
3248                throws ServerInstanceException {
3249
3250        String JavaDoc [] sArr = null;
3251        
3252        try {
3253                java.util.Set JavaDoc ejbs = bd.getEjbs();
3254        ManagementObjectManager mom = Switch.getSwitch().getManagementObjectManager();
3255                String JavaDoc moduleName = mom.getModuleName(bd);
3256                String JavaDoc applicationName = mom.getApplicationName(bd);
3257                EjbDescriptor ed = null;
3258                sArr = new String JavaDoc[ejbs.size()];
3259                int i=0;
3260                String JavaDoc j2eeType = null;
3261
3262                for(Iterator JavaDoc it=ejbs.iterator(); it.hasNext(); ) {
3263                        ed = (EjbDescriptor) it.next();
3264                        j2eeType = mom.getJ2eeTypeForEjb(ed);
3265                        sArr[i] = ("j2eeType=" + j2eeType + "," +
3266                                   "name=" + ed.getName() + "," +
3267                                   "EJBModule=" + moduleName + "," +
3268                                   "J2EEApplication=" + applicationName);
3269                        i++;
3270                }
3271                
3272        } catch (Exception JavaDoc e) {
3273                throw new ServerInstanceException(e.getLocalizedMessage());
3274        }
3275
3276        return sArr;
3277    }
3278
3279    /**
3280     * Returns web module components
3281     * @return String [] web module components
3282     * @throws ServerInstanceException
3283     */

3284    BundleDescriptor getDescrForStandAloneWebModule (String JavaDoc moduleName)
3285                throws ServerInstanceException {
3286        try {
3287            WebModulesManager webModMgr =
3288                InstanceFactory.createWebModuleManager(getInstanceName());
3289            return (BundleDescriptor)
3290                DeploymentUtils.getDescriptor(moduleName, webModMgr);
3291        } catch (Exception JavaDoc e) {
3292            throw new ServerInstanceException(e.getLocalizedMessage());
3293        }
3294    }
3295
3296    String JavaDoc [] getWebModuleComponents(WebBundleDescriptor bd)
3297                throws ServerInstanceException {
3298
3299        String JavaDoc [] sArr = null;
3300        
3301        try {
3302                java.util.Set JavaDoc webDescriptors = bd.getWebDescriptors();
3303        ManagementObjectManager mom = Switch.getSwitch().getManagementObjectManager();
3304                String JavaDoc moduleName = mom.getModuleName(bd);
3305                String JavaDoc applicationName = mom.getApplicationName(bd);
3306                WebComponentDescriptor wd = null;
3307                sArr = new String JavaDoc[webDescriptors.size()];
3308                int i=0;
3309                String JavaDoc j2eeType = null;
3310        String JavaDoc servletName = null;
3311        String JavaDoc cName = null;
3312        String JavaDoc dName = null;
3313        String JavaDoc sName = null;
3314
3315                for(Iterator JavaDoc it=webDescriptors.iterator(); it.hasNext(); ) {
3316                        wd = (WebComponentDescriptor) it.next();
3317
3318            dName = wd.getDisplayName();
3319            sName = wd.getName();
3320            cName = wd.getCanonicalName();
3321
3322            if ((dName != null) && (dName.length() > 0)) {
3323                servletName = dName;
3324            } else if ((sName != null) && (sName.length() > 0)) {
3325                servletName = sName;
3326            } else if ((cName != null) && (cName.length() > 0)) {
3327                servletName = cName;
3328            } else {
3329                servletName = "";
3330            }
3331
3332                        j2eeType = "Servlet";
3333                        sArr[i] = ("j2eeType=" + j2eeType + "," +
3334                                   "name=" + servletName + "," +
3335                                   "WebModule=" + moduleName + "," +
3336                                   "J2EEApplication=" + applicationName);
3337                        i++;
3338                }
3339                
3340        } catch (Exception JavaDoc e) {
3341                throw new ServerInstanceException(e.getLocalizedMessage());
3342        }
3343
3344        return sArr;
3345    }
3346
3347
3348    BundleDescriptor getDescrForStandAloneCarModule (String JavaDoc moduleName)
3349                throws ServerInstanceException {
3350        try {
3351            AppclientModulesManager appClModMgr =
3352                InstanceFactory.createAppclientModulesManager(getInstanceName());
3353            return (BundleDescriptor)
3354                DeploymentUtils.getDescriptor(moduleName, appClModMgr);
3355        } catch (Exception JavaDoc e) {
3356            throw new ServerInstanceException(e.getLocalizedMessage());
3357        }
3358    }
3359
3360
3361    String JavaDoc [] getCarModuleComponents(BundleDescriptor bd)
3362                throws ServerInstanceException {
3363
3364        String JavaDoc [] sArr = new String JavaDoc[1];
3365        
3366        try {
3367        ManagementObjectManager mom = Switch.getSwitch().getManagementObjectManager();
3368                String JavaDoc moduleName = bd.getModuleID();
3369                String JavaDoc applicationName = mom.getApplicationName(bd);
3370        sArr[0] = ("j2eeType=AppClientModule," +
3371                "name=" + moduleName + "," +
3372                "J2EEApplication=" + applicationName);
3373        } catch (Exception JavaDoc e) {
3374                throw new ServerInstanceException(e.getLocalizedMessage());
3375        }
3376
3377        return sArr;
3378    }
3379
3380
3381    /**
3382     * Returns connector module components
3383     * @return String [] connector module components
3384     * @throws ServerInstanceException
3385     */

3386    BundleDescriptor getDescrForStandAloneRarModule (String JavaDoc moduleName)
3387                throws ServerInstanceException {
3388        try {
3389            ConnectorModulesManager connModMgr =
3390                InstanceFactory.createConnectorModulesManager(getInstanceName());
3391            return (BundleDescriptor)
3392                DeploymentUtils.getDescriptor(moduleName, connModMgr);
3393        } catch (Exception JavaDoc e) {
3394            throw new ServerInstanceException(e.getLocalizedMessage());
3395        }
3396    }
3397
3398    String JavaDoc [] getRarModuleComponents(ConnectorDescriptor bd)
3399                throws ServerInstanceException {
3400
3401        String JavaDoc [] sArr = null;
3402        
3403        try {
3404        ManagementObjectManager mom = Switch.getSwitch().getManagementObjectManager();
3405                String JavaDoc moduleName = mom.getModuleName(bd);
3406                String JavaDoc applicationName = mom.getApplicationName(bd);
3407                String JavaDoc j2eeType = null;
3408                int i = 0;
3409
3410                // Assign memory for inbound and outbound vars
3411
InboundResourceAdapter ibRA = bd.getInboundResourceAdapter();
3412                OutboundResourceAdapter obRA = bd.getOutboundResourceAdapter();
3413                int kount = 0;
3414                if (ibRA != null) { kount = kount + 1; }
3415                if (obRA != null) { kount = kount + 1; }
3416                if (kount > 0) {sArr = new String JavaDoc[kount];}
3417
3418                // Inbound
3419

3420                if (ibRA != null) {
3421                        j2eeType = "ResourceAdapter";
3422                        sArr[i] = ("j2eeType=" + j2eeType + "," +
3423                                   "name=" + ibRA.getName() + "," +
3424                                   "ResourceAdapterModule=" + moduleName + "," +
3425                                   "J2EEApplication=" + applicationName);
3426                        i++;
3427                }
3428
3429                // OutBound
3430

3431                if (obRA != null) {
3432                        j2eeType = "ResourceAdapter";
3433                        sArr[i] = ("j2eeType=" + j2eeType + "," +
3434                                   "name=" + obRA.getName() + "," +
3435                                   "ResourceAdapterModule=" + moduleName + "," +
3436                                   "J2EEApplication=" + applicationName);
3437                        i++;
3438                }
3439
3440        } catch (Exception JavaDoc e) {
3441                throw new ServerInstanceException(e.getLocalizedMessage());
3442        }
3443
3444        return sArr;
3445    }
3446
3447
3448    /**
3449     * Returns components within an application
3450     * @return String [] application components
3451     * @throws ServerInstanceException
3452     */

3453    Application getDescrForApplication (String JavaDoc appName)
3454                throws ServerInstanceException {
3455        try {
3456            AppsManager appsMgr =
3457                InstanceFactory.createAppsManager(getInstanceName());
3458            return (Application)
3459                DeploymentUtils.getDescriptor(appName, appsMgr);
3460        } catch (Exception JavaDoc e) {
3461            throw new ServerInstanceException(e.getLocalizedMessage());
3462        }
3463    }
3464
3465    /**
3466     * Returns an array of system resource adapters name string.
3467     * Presently we need this seperate methode as the system resource adapters are
3468     * not registered in the config. this method will not be required if the system
3469     * resource adapters (connector modules) will have entry in domain.xml
3470     * @return an array of syestem connectors name string.
3471     * @throws ServerinstanceException
3472     */

3473    public String JavaDoc[] getAllSystemConnectors() throws ServerInstanceException {
3474        return ConnectorConstants.systemRarNames;
3475    }
3476    
3477    String JavaDoc [] getApplicationComponents(Application ad)
3478                throws ServerInstanceException {
3479
3480        String JavaDoc [] sArr = null;
3481        
3482        try {
3483        ManagementObjectManager mom = Switch.getSwitch().getManagementObjectManager();
3484                String JavaDoc applicationName = ad.getRegistrationName();
3485                String JavaDoc j2eeType = null;
3486
3487        java.util.Set JavaDoc bds = null;
3488        BundleDescriptor bd = null;
3489
3490        // Determine number of modules and initialize the String array
3491
int i = 0;
3492        sArr = new String JavaDoc [ ad.getApplicationClientDescriptors().size() +
3493                    ad.getEjbBundleDescriptors().size() +
3494                    ad.getRarDescriptors().size() +
3495                    ad.getWebBundleDescriptors().size() ];
3496
3497        // App client modules
3498
bds = ad.getApplicationClientDescriptors();
3499        for(Iterator JavaDoc it=bds.iterator(); it.hasNext(); ) {
3500            bd = (BundleDescriptor) it.next();
3501            sArr[i] = ("j2eeType=AppClientModule" + "," +
3502                   "name=" + bd.getModuleDescriptor().getArchiveUri() + "," +
3503                   "J2EEApplication=" + applicationName);
3504            i++;
3505        }
3506
3507        // Ejb modules
3508
bds = ad.getEjbBundleDescriptors();
3509        for(Iterator JavaDoc it=bds.iterator(); it.hasNext(); ) {
3510            bd = (BundleDescriptor) it.next();
3511            sArr[i] = ("j2eeType=EJBModule" + "," +
3512                   "name=" + bd.getModuleDescriptor().getArchiveUri() + "," +
3513                   "J2EEApplication=" + applicationName);
3514            i++;
3515        }
3516
3517        // Connector modules
3518
bds = ad.getRarDescriptors();
3519        for(Iterator JavaDoc it=bds.iterator(); it.hasNext(); ) {
3520            bd = (BundleDescriptor) it.next();
3521            sArr[i] = ("j2eeType=ResourceAdapterModule" + "," +
3522                   "name=" + bd.getModuleDescriptor().getArchiveUri() + "," +
3523                   "J2EEApplication=" + applicationName);
3524            i++;
3525        }
3526
3527        // Web modules
3528
bds = ad.getWebBundleDescriptors();
3529        for(Iterator JavaDoc it=bds.iterator(); it.hasNext(); ) {
3530            bd = (BundleDescriptor) it.next();
3531            sArr[i] = ("j2eeType=WebModule" + "," +
3532                   "name=" + bd.getModuleDescriptor().getArchiveUri() + "," +
3533                   "J2EEApplication=" + applicationName);
3534            i++;
3535        }
3536
3537
3538        } catch (Exception JavaDoc e) {
3539                throw new ServerInstanceException(e.getLocalizedMessage());
3540        }
3541
3542        return sArr;
3543    }
3544
3545    // Method to validate and return object names
3546

3547    private String JavaDoc [] getValidatedObjectNames(String JavaDoc [] strArr)
3548                throws ServerInstanceException {
3549
3550    // Append the domain name and server name to the input string array
3551
// and return it.
3552

3553    String JavaDoc [] sArr = new String JavaDoc[strArr.length];
3554
3555    try {
3556        for (int i=0; i<strArr.length; i++) {
3557            sArr[i] = ("com.sun.appserv" + ":" +
3558                   strArr[i] + "," +
3559                   "J2EEServer=" + getInstanceName());
3560        }
3561        } catch (Exception JavaDoc e) {
3562                throw new ServerInstanceException(e.getLocalizedMessage());
3563        }
3564
3565    return sArr;
3566
3567    }
3568
3569    /**
3570     * Determines whether the specified target is default target.
3571     * if CLI/GUI specifies a null, blank, "domain" target, it is
3572     * considered to be default target.
3573     * @param target target name
3574     * @return true if specified target is default
3575     */

3576    private boolean isDefaultTarget(String JavaDoc target)
3577    {
3578        if(target == null
3579           || target.length() == 0
3580           || target.equalsIgnoreCase(DEFAULT_TARGET))
3581        {
3582            return true;
3583        }
3584        else
3585        {
3586            return false;
3587        }
3588    }
3589
3590    /**
3591     * Set http listener host and port in deployment request. If the server
3592     * is not configured properly the defaults used are localhost:8080 for
3593     * clear and localhost:8181 for SSL.
3594     */

3595    private void setHostAndPort(DeploymentRequest req)
3596            throws ServerInstanceException {
3597                
3598        String JavaDoc virtualServers = (String JavaDoc) req.getOptionalAttributes().get(ServerTags.VIRTUAL_SERVERS);
3599        if (virtualServers==null) {
3600            HostAndPort hap = getHostAndPort(false);
3601            if(hap != null) {
3602                req.setHttpHostName(getHostName(hap));
3603                req.setHttpPort(getPort(hap, false));
3604            }
3605            hap = getHostAndPort(true);
3606            if(hap != null) {
3607                req.setHttpsHostName(getHostName(hap));
3608                req.setHttpsPort(getPort(hap, true));
3609            }
3610        } else {
3611            StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(virtualServers,",");
3612            if (st.hasMoreTokens()) {
3613                String JavaDoc aVirtualServer = st.nextToken();
3614                HostAndPort hap = getVirtualServerHostAndPort(aVirtualServer, false);
3615                if(hap != null) {
3616                    req.setHttpHostName(getHostName(hap));
3617                    req.setHttpPort(getPort(hap, false));
3618                }
3619                hap = getVirtualServerHostAndPort(aVirtualServer, true);
3620                if(hap != null) {
3621                    req.setHttpsHostName(getHostName(hap));
3622                    req.setHttpsPort(getPort(hap, true));
3623                }
3624            }
3625        }
3626    }
3627            
3628    public String JavaDoc getHostName(HostAndPort hap) {
3629        String JavaDoc hostName = hap.getHost();
3630        if (hostName == null || hostName.trim().equals("")) {
3631            hostName = getDefaultHostName();
3632        }
3633        return hostName;
3634    }
3635
3636    private String JavaDoc getDefaultHostName() {
3637        String JavaDoc defaultHostName = "localhost";
3638        try {
3639            InetAddress JavaDoc host = InetAddress.getLocalHost();
3640            defaultHostName = host.getCanonicalHostName();
3641        } catch(UnknownHostException JavaDoc uhe) {
3642            sLogger.log(Level.FINEST, "mbean.get_local_host_error", uhe);
3643            sLogger.log(Level.INFO, "mbean.use_default_host");
3644        }
3645        return defaultHostName;
3646    }
3647
3648    private int getPort(HostAndPort hap, boolean securityEnabled) {
3649        int port = hap.getPort();
3650        if (port == 0) {
3651            port = getDefaultPort(securityEnabled);
3652        }
3653        return port;
3654    }
3655
3656    private int getDefaultPort(boolean securityEnabled) {
3657        int port = 0;
3658        if (securityEnabled) {
3659            port = 8181;
3660        } else {
3661            port = 8080;
3662        }
3663        sLogger.log(Level.INFO, "mbean.use_default_port", String.valueOf(port));
3664        return port;
3665    }
3666
3667    /**
3668     * Get value of named attribute from attributes list. If an attribute with
3669     * specified name does not exist, the method returns null. If there are
3670     * than one attributes with same name then the method returns value of
3671     * first matching attribute.
3672     *
3673     * @param attrs list of attributes
3674     * @param attrName name of the attribute
3675     * @return value of the specified attrName or null if the attrName is
3676     * not present in specified attrs
3677     */

3678    private Object JavaDoc getNamedAttributeValue(AttributeList JavaDoc attrs,
3679            String JavaDoc attrName) {
3680        if (attrs == null || attrName == null) {
3681            return null;
3682        }
3683        Object JavaDoc value = null;
3684        Iterator JavaDoc iter = attrs.iterator();
3685        while (iter.hasNext()) {
3686           Attribute JavaDoc attr = (Attribute JavaDoc)iter.next();
3687           if (attrName.equals(attr.getName())) {
3688               value = attr.getValue();
3689               break;
3690           }
3691        }
3692        return value;
3693    }
3694
3695    /**
3696     * This method checks if the objectName specified is of
3697     * a system application/module
3698     * @param componentON objectName of the application
3699     * @param action deploy/redeploy/undeploy/enable/disable
3700     * @throws MBeanConfigException if application/module is
3701     * of type system
3702     */

3703    private void validate(ObjectName JavaDoc componentON, String JavaDoc action)
3704        throws MBeanConfigException {
3705       
3706        if(componentON == null)
3707            return;
3708
3709    //
3710
// fix for bug#s 4939623 and 4939625
3711
// if the type is appclient-module return
3712
// since DTD doesn't have object-type attribute for appclient-module
3713
//
3714

3715    String JavaDoc componentType = componentON.getKeyProperty(ServerTags.TYPE);
3716    if ((componentType != null) && (componentType.length() > 0)) {
3717        if (componentType.equals(ServerTags.APPCLIENT_MODULE)) {
3718            return;
3719        }
3720    }
3721
3722        boolean allowSystemAppModification =
3723            (Boolean.valueOf(System.getProperty(
3724                Constants.ALLOW_SYSAPP_DEPLOYMENT, "false")).booleanValue());
3725        
3726        if(allowSystemAppModification)
3727            return;
3728            
3729        String JavaDoc objectType = null;
3730        try{
3731            
3732            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
3733            objectType = (String JavaDoc)mbs.getAttribute(componentON, OBJECT_TYPE);
3734            
3735        }catch(Exception JavaDoc e){
3736            String JavaDoc msg = localStrings.getString(
3737                "admin.mbeans.acmb.exception_object_type");
3738            sLogger.log(Level.FINE, msg);
3739            throw new MBeanConfigException(e.getMessage());
3740        }
3741        
3742        if(objectType!= null && objectType.startsWith(Constants.SYSTEM_PREFIX))
3743        {
3744            String JavaDoc msg = localStrings.getString(
3745                "admin.mbeans.acmb.component_is_system",new Object JavaDoc[]{action});
3746            throw new MBeanConfigException(msg);
3747        }
3748    
3749    }
3750
3751    public void associate(String JavaDoc appName, String JavaDoc target)
3752    throws MBeanException, MBeanConfigException {
3753    }
3754    
3755    public void disassociate(String JavaDoc appName, String JavaDoc target)
3756    throws MBeanException, MBeanConfigException {
3757    }
3758
3759    private DeploymentTargetFactory getTargetFactory() {
3760        return DeploymentTargetFactory.getDeploymentTargetFactory();
3761    }
3762    
3763    // Begin EE: 4946914 - Cluster deployment support
3764

3765    protected static final String JavaDoc ADMIN_VS = "__asadmin";
3766
3767     // Attribue names for http listeners
3768
protected static final String JavaDoc PORT = "port";
3769    protected static final String JavaDoc DEF_VS = "default-virtual-server";
3770    protected static final String JavaDoc SERVER_NAME = "server-name";
3771    protected static final String JavaDoc REDIRECT_PORT = "redirect-port";
3772    protected static final String JavaDoc SEC_ENABLED = "security-enabled";
3773    protected static final String JavaDoc LISTENER_ENABLED = "enabled";
3774    protected static final String JavaDoc OBJECT_TYPE = "object-type";
3775        
3776    // Attribute names for virtual server
3777
protected static final String JavaDoc HOSTS = "hosts";
3778    protected static final String JavaDoc HTTP_LISTENERS = "http_listeners";
3779    protected static final String JavaDoc DEFAULT_WEB_MODULE = "default_web_module";
3780    protected static final String JavaDoc STATE = "state";
3781    protected static final String JavaDoc ID = "id";
3782    
3783    //actions
3784
protected static final String JavaDoc DEPLOY_ACTION = "deploy";
3785    protected static final String JavaDoc REDEPLOY_ACTION = "redeploy";
3786    protected static final String JavaDoc UNDEPLOY_ACTION = "undeploy";
3787    protected static final String JavaDoc ENABLE_ACTION = "enable";
3788    protected static final String JavaDoc DISABLE_ACTION = "disable";
3789
3790
3791    protected static String JavaDoc[] httpListenerAttrNames = {LISTENER_ENABLED,
3792            DEF_VS, SERVER_NAME, REDIRECT_PORT, PORT, SEC_ENABLED, ID };
3793            
3794    protected static String JavaDoc[] vsAttrNames = {HOSTS, HTTP_LISTENERS,
3795        DEFAULT_WEB_MODULE, STATE, ID};
3796            
3797    // End EE: 4946914 - Cluster deployment support
3798

3799    private static final class ObjectNameAppRefComparator
3800    {
3801        private ObjectNameAppRefComparator()
3802        {
3803        }
3804
3805        private static int compare(ObjectName JavaDoc on, ApplicationRef ref)
3806        {
3807            String JavaDoc k1 = on.getKeyProperty(NAME);
3808            String JavaDoc k2 = ref.getRef();
3809            return k1.compareTo(k2);
3810        }
3811
3812        public static ObjectName JavaDoc[] intersect(final ObjectName JavaDoc[] oa,
3813                                             final ApplicationRef[] ra)
3814        {
3815            if ((null == oa) || (0 == oa.length) ||
3816                (null == ra) || (0 == ra.length))
3817            {
3818                return new ObjectName JavaDoc[0];
3819            }
3820            final ArrayList JavaDoc al = new ArrayList JavaDoc();
3821            for (int i = 0; i < ra.length; i++)
3822            {
3823                for (int j = 0; j < oa.length; j++)
3824                {
3825                    if (0 == compare(oa[j], ra[i]))
3826                    {
3827                        al.add(oa[j]);
3828                        break;
3829                    }
3830                }
3831            }
3832            return (ObjectName JavaDoc[])al.toArray(new ObjectName JavaDoc[al.size()]);
3833        }
3834    }
3835
3836
3837    /**
3838     * Returns deployment descriptor locations for the given
3839     * combination of standAloneModuleName and subComponentName.
3840     *
3841     * For a j2ee_application of type ear, both values for
3842     * standAloneModuleName and subComponentName must be supplied.
3843     *
3844     * In case of stand alone module, the subComponentName will be null.
3845     *
3846     * @return String [] list of deployment descriptor locations
3847     * null if no descriptors found
3848     */

3849
3850     public String JavaDoc [] getDeploymentDescriptorLocations (
3851    String JavaDoc standAloneModuleName, String JavaDoc subComponentName)
3852    throws ServerInstanceException {
3853
3854        sLogger.log(Level.FINE, "getDeploymentDescriptorLocations - begin" +
3855        " standAloneModuleName = " + standAloneModuleName +
3856        " subComponentName = " + subComponentName);
3857
3858    // local variables
3859
J2EEModule j2eeModule = null;
3860
3861    // initialization
3862
if (subComponentName != null) {
3863        j2eeModule = new J2EEModule(standAloneModuleName, subComponentName);
3864    } else {
3865        j2eeModule = new J2EEModule(standAloneModuleName);
3866    }
3867
3868    // get j2ee module type
3869
ModuleType JavaDoc moduleType = j2eeModule.getModuleType();
3870    if (moduleType == null) {
3871        throw new ServerInstanceException(
3872        localStrings.getString("admin.mbeans.acmb.invalidModuleType"));
3873    }
3874        sLogger.log(Level.FINE, "getDeploymentDescriptorLocations - moduleType" + moduleType);
3875
3876    // get dd location
3877
String JavaDoc ddLocation = j2eeModule.getDeploymentDescriptorsLocation();
3878    if (ddLocation == null) {
3879        throw new ServerInstanceException(
3880        localStrings.getString("admin.mbeans.acmb.invalidDeplDescrLoc"));
3881    }
3882        sLogger.log(Level.FINE, "getDeploymentDescriptorLocations - ddLocation" + ddLocation);
3883
3884    // get the list of descriptor locations for the above j2ee module type
3885
String JavaDoc [] ddList = DescriptorList.getDescriptorsList(moduleType);
3886    if ((ddList == null) || (ddList.length < 1)) {
3887        return null;
3888    }
3889    ArrayList JavaDoc arrL = new ArrayList JavaDoc();
3890    String JavaDoc fileLocation = null;
3891    for (int i=0; i<ddList.length; i++) {
3892        // if the descriptor exists then add to the list
3893
fileLocation = ddLocation + File.separator + ddList[i];
3894        try {
3895            File JavaDoc file = new File JavaDoc(fileLocation);
3896            if (file.exists()) {
3897                arrL.add(fileLocation);
3898            }
3899        } catch (Exception JavaDoc e) {
3900                sLogger.log(Level.WARNING,
3901            "getDeploymentDescriptorLocations - descriptor does not exist for " +
3902            fileLocation);
3903            // continue with next file
3904
}
3905    }
3906
3907    // return dd locations array
3908
if (arrL.size() > 0) {
3909        String JavaDoc [] strArr = new String JavaDoc[arrL.size()];
3910        for (int j=0; j<arrL.size(); j++) {
3911            strArr[j] = (String JavaDoc) arrL.get(j);
3912                sLogger.log(Level.FINE,
3913                "getDeploymentDescriptorLocations: " +
3914                "next dd location = " + strArr[j]);
3915        }
3916        return strArr;
3917    }
3918    return null;
3919     }
3920
3921
3922     /**
3923      * Returns xml deployment descriptor as string
3924      * @param String deploymentDescriptorLocation for whcih the descriptor
3925      * needs to be returned.
3926      */

3927      public String JavaDoc getDeploymentDescriptor(
3928        String JavaDoc deploymentDescriptorLocation)
3929        throws ServerInstanceException {
3930
3931            sLogger.log(Level.FINE, "getDeploymentDescriptor - begin" +
3932        " deploymentDescriptorLocation = " + deploymentDescriptorLocation);
3933
3934        if (deploymentDescriptorLocation == null) return null;
3935
3936        J2EEModule j2eeModule = new J2EEModule();
3937
3938        String JavaDoc str = j2eeModule.getStringForDDxml(deploymentDescriptorLocation);
3939
3940        if (str != null) {
3941                sLogger.log(Level.FINE, "getDeploymentDescriptor: for " +
3942            deploymentDescriptorLocation + " = " +
3943            str);
3944        }
3945
3946        return str;
3947      }
3948
3949    public String JavaDoc createMBean(String JavaDoc target, String JavaDoc className) throws CustomMBeanException {
3950        return ( cmo.createMBean(target, className) );
3951    }
3952
3953    public String JavaDoc createMBean(String JavaDoc target, Map JavaDoc<String JavaDoc, String JavaDoc> params) throws CustomMBeanException {
3954        Map JavaDoc<String JavaDoc,String JavaDoc> paramsCopy = new HashMap JavaDoc<String JavaDoc,String JavaDoc>(params);
3955        return ( cmo.createMBean(target, paramsCopy) );
3956    }
3957
3958    public String JavaDoc createMBean(String JavaDoc target, Map JavaDoc<String JavaDoc, String JavaDoc> params, Map JavaDoc<String JavaDoc, String JavaDoc> attributes) throws CustomMBeanException {
3959        Map JavaDoc<String JavaDoc,String JavaDoc> paramsCopy = new HashMap JavaDoc<String JavaDoc,String JavaDoc>(params);
3960        return ( cmo.createMBean(target, paramsCopy, attributes) );
3961    }
3962
3963    public void createMBeanRef(String JavaDoc target, String JavaDoc ref) throws CustomMBeanException {
3964        cmo.createMBeanRef(target, ref);
3965    }
3966
3967    public String JavaDoc deleteMBean(String JavaDoc target, String JavaDoc name) throws CustomMBeanException {
3968        return ( cmo.deleteMBean(target, name) );
3969    }
3970
3971    public void deleteMBeanRef(String JavaDoc target, String JavaDoc ref) throws CustomMBeanException {
3972        cmo.deleteMBeanRef(target, ref);
3973    }
3974
3975    public boolean existsMBean(String JavaDoc target, String JavaDoc name) throws CustomMBeanException {
3976        return ( cmcq.existsMBean(target, name) );
3977    }
3978
3979    public boolean isMBeanEnabled(String JavaDoc target, String JavaDoc name) throws CustomMBeanException {
3980        return ( cmcq.isMBeanEnabled(target, name) );
3981    }
3982
3983    public List JavaDoc<ObjectName JavaDoc> listMBeanConfigObjectNames(String JavaDoc target) throws CustomMBeanException {
3984        return ( cmcq.listMBeanConfigObjectNames(target) );
3985    }
3986
3987    public List JavaDoc<ObjectName JavaDoc> listMBeanConfigObjectNames(String JavaDoc target, int type, boolean state) throws CustomMBeanException {
3988        return (cmcq.listMBeanConfigObjectNames(target, type, state) );
3989    }
3990
3991    public List JavaDoc<String JavaDoc> listMBeanNames(String JavaDoc target) throws CustomMBeanException {
3992        return ( cmcq.listMBeanNames(target) );
3993    }
3994
3995    /**
3996     * Return the MBeanInfo of a given Custom MBean.
3997     * The MBean must be loadable from the standard App Server location.
3998     * The code does this:
3999     * <ul>
4000     * <li>Register the MBean in the MBeanServer
4001     * <li>Fetch and save the MBeanInfo
4002     * <li>Unregister the MBean
4003     * </ul>
4004     * Note that if the MBean can't be deployed successfully then this method won't work.
4005     * @param classname
4006     * @throws com.sun.enterprise.admin.mbeans.custom.CustomMBeanException
4007     * @return The MBeanInfo object
4008     */

4009    public MBeanInfo JavaDoc getMBeanInfo(String JavaDoc classname) throws CustomMBeanException {
4010        return ( cmo.getMBeanInfo(classname) );
4011    }
4012}
4013
Popular Tags