KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > deployment > phasing > DeploymentServiceUtils


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.deployment.phasing;
25
26 import com.sun.enterprise.admin.common.exception.DeploymentException;
27 import com.sun.enterprise.admin.common.exception.ServerInstanceException;
28 import com.sun.enterprise.admin.common.MBeanServerFactory;
29 import com.sun.enterprise.admin.common.ObjectNames;
30 import com.sun.enterprise.admin.event.AdminEvent;
31 import com.sun.enterprise.admin.event.AdminEventCache;
32 import com.sun.enterprise.admin.event.AdminEventListenerException;
33 import com.sun.enterprise.admin.event.AdminEventMulticaster;
34 import com.sun.enterprise.admin.event.AdminEventResult;
35 import com.sun.enterprise.admin.event.EventBuilder;
36 import com.sun.enterprise.admin.event.EventContext;
37 import com.sun.enterprise.admin.event.EventStack;
38 import com.sun.enterprise.admin.event.ModuleDeployEvent;
39 import com.sun.enterprise.admin.server.core.AdminService;
40 import com.sun.enterprise.admin.server.core.DeploymentNotificationHelper;
41 import com.sun.enterprise.admin.target.TargetType;
42 import com.sun.enterprise.admin.util.HostAndPort;
43 import com.sun.enterprise.config.ConfigBean;
44 import com.sun.enterprise.config.ConfigBeansFactory;
45 import com.sun.enterprise.config.ConfigContext;
46 import com.sun.enterprise.config.ConfigException;
47 import com.sun.enterprise.config.serverbeans.ApplicationHelper;
48 import com.sun.enterprise.config.serverbeans.ClusterHelper;
49 import com.sun.enterprise.config.serverbeans.Config;
50 import com.sun.enterprise.config.serverbeans.HttpService;
51 import com.sun.enterprise.config.serverbeans.PropertyResolver;
52 import com.sun.enterprise.config.serverbeans.ServerHelper;
53 import com.sun.enterprise.config.serverbeans.ServerTags;
54 import com.sun.enterprise.config.serverbeans.ServerXPathHelper;
55 import com.sun.enterprise.config.serverbeans.VirtualServer;
56 import com.sun.enterprise.deployment.Application;
57 import com.sun.enterprise.deployment.archivist.Archivist;
58 import com.sun.enterprise.deployment.archivist.ArchivistFactory;
59 import com.sun.enterprise.deployment.backend.AppDD;
60 import com.sun.enterprise.deployment.backend.ClientJarMakerRegistry;
61 import com.sun.enterprise.deployment.backend.DeployableObjectType;
62 import com.sun.enterprise.deployment.backend.DeploymentLogger;
63 import com.sun.enterprise.deployment.backend.DeploymentRequest;
64 import com.sun.enterprise.deployment.backend.DeploymentRequestRegistry;
65 import com.sun.enterprise.deployment.backend.IASDeploymentException;
66 import com.sun.enterprise.deployment.interfaces.DeploymentImplConstants;
67 import com.sun.enterprise.deployment.pluggable.DeploymentFactory;
68 import com.sun.enterprise.deployment.util.DeploymentProperties;
69 import com.sun.enterprise.deployment.util.ModuleDescriptor;
70 import com.sun.enterprise.deployment.WebBundleDescriptor;
71 import com.sun.enterprise.instance.AppsManager;
72 import com.sun.enterprise.instance.WebModulesManager;
73 import com.sun.enterprise.instance.EjbModulesManager;
74 import com.sun.enterprise.instance.ConnectorModulesManager;
75 import com.sun.enterprise.instance.AppclientModulesManager;
76 import com.sun.enterprise.instance.BaseManager;
77 import com.sun.enterprise.instance.InstanceEnvironment;
78 import com.sun.enterprise.server.ApplicationServer;
79 import com.sun.enterprise.server.Constants;
80 import com.sun.enterprise.util.i18n.StringManager;
81 import com.sun.enterprise.util.io.FileUtils;
82 import com.sun.enterprise.util.RelativePathResolver;
83 import com.sun.enterprise.util.StringUtils;
84 import com.sun.enterprise.util.SystemPropertyConstants;
85 import com.sun.enterprise.util.FileUtil;
86 import com.sun.enterprise.resource.Resource;
87 import com.sun.enterprise.resource.ResourcesXMLParser;
88
89 import java.io.File JavaDoc;
90 import java.io.FilenameFilter JavaDoc;
91 import java.util.Enumeration JavaDoc;
92 import java.util.logging.Level JavaDoc;
93 import java.util.logging.Logger JavaDoc;
94 import java.util.Properties JavaDoc;
95 import java.util.ArrayList JavaDoc;
96 import java.util.Map JavaDoc;
97 import java.util.Iterator JavaDoc;
98 import java.util.List JavaDoc;
99 import java.util.ListIterator JavaDoc;
100 import java.util.StringTokenizer JavaDoc;
101 import java.util.Set JavaDoc;
102 import java.util.HashSet JavaDoc;
103 import java.util.HashMap JavaDoc;
104 import java.net.URL JavaDoc;
105 import java.net.URLClassLoader JavaDoc;
106 import java.net.InetAddress JavaDoc;
107 import java.net.UnknownHostException JavaDoc;
108 import javax.enterprise.deploy.shared.ModuleType JavaDoc;
109 import javax.management.Attribute JavaDoc;
110 import javax.management.AttributeList JavaDoc;
111 import javax.management.InstanceNotFoundException JavaDoc;
112 import javax.management.MBeanException JavaDoc;
113 import javax.management.MBeanServer JavaDoc;
114 import javax.management.ObjectName JavaDoc;
115
116 public class DeploymentServiceUtils {
117
118     /** Deployment Logger object for this class */
119     public static final Logger sLogger = DeploymentLogger.get();
120
121     /** string manager */
122     private static StringManager localStrings =
123         StringManager.getManager( DeploymentServiceUtils.class );
124
125     private static final Object JavaDoc[] emptyParams = new Object JavaDoc[]{};
126     private static final String JavaDoc[] emptySignature = new String JavaDoc[]{};
127
128     /**
129      * @return the path for the client jar file of a deployed application
130      */

131     public static String JavaDoc getClientJarPath(String JavaDoc moduleID) {
132         
133         // let's ensure first that our client jar is ready.
134
ClientJarMakerRegistry registry = ClientJarMakerRegistry.getInstance();
135         
136         if (registry.isRegistered(moduleID)) {
137             
138             // let's wait until it is finished.
139
registry.waitForCompletion(moduleID);
140         }
141         
142         return moduleID + DeploymentImplConstants.ClientJarSuffix;
143         
144     }
145
146     /**
147      * This method is used by StartPhase, StopPhases to multicast start/stop
148      * events to the listeners. To multicast to a particular server the managedServerInstance
149      * representing that particular server is used
150      * @param eventType APPLICATION_DEPLOYED/APPLICATION_UNDEPLOYED/APPLICATION_REDEPLOYED
151      * MODULE_DEPLOYED/MODULE_REDEPLOYED/MODULE_UNDEPLOYED
152      * @param entityName app/module name
153      * @param targetName server to which event has to be sent
154      */

155     static boolean multicastEvent(int eventType, String JavaDoc entityName,
156                   String JavaDoc targetName) throws IASDeploymentException {
157         return multicastEvent(eventType, entityName, null, targetName);
158     }
159
160     static boolean multicastEvent(int eventType, String JavaDoc entityName,
161                   String JavaDoc moduleType, String JavaDoc targetName)
162     throws IASDeploymentException {
163         return multicastEvent(eventType,entityName,moduleType, false, targetName);
164     }
165     
166     /**
167      * This method is used by StartPhase, StopPhases to multicast start/stop
168      * events to the listeners. To multicast to a particular server the managedServerInstance
169      * representing that particular server is used
170      * @param eventType APPLICATION_DEPLOYED/APPLICATION_UNDEPLOYED/APPLICATION_REDEPLOYED
171      * MODULE_DEPLOYED/MODULE_REDEPLOYED/MODULE_UNDEPLOYED
172      * @param entityName app/module name
173      * @param moduleType ejb/web/connector
174      * @param targetName server to which event has to be sent
175      */

176     static boolean multicastEvent(int eventType, String JavaDoc entityName,
177                   String JavaDoc moduleType, boolean cascade, String JavaDoc targetName) throws IASDeploymentException {
178         return multicastEvent(eventType, entityName, moduleType, cascade, false, targetName) ;
179     }
180
181     static boolean multicastEvent(int eventType, String JavaDoc entityName,
182                                   String JavaDoc moduleType, boolean cascade, boolean forceDeploy, String JavaDoc targetName) throws IASDeploymentException {
183         return multicastEvent(eventType, entityName, moduleType, cascade, forceDeploy, Constants.LOAD_UNSET, targetName) ;
184     }
185     
186     public static boolean multicastEvent(int eventType, String JavaDoc entityName,
187                   String JavaDoc moduleType, boolean cascade, boolean forceDeploy, int loadUnloadAction, String JavaDoc targetName)
188     throws IASDeploymentException {
189
190         // Flush config changes before sending the event. The events API
191
// requires that config be saved prior to sending event.
192
try {
193             ConfigContext config = getConfigContext();
194             if (config != null && config.isChanged()) {
195                 config.flush();
196             } else {
197                 // Server is initializing. Can not flush config changes.
198
}
199         } catch (ConfigException ce) {
200             throw new IASDeploymentException(ce);
201         }
202     try {
203         return DeploymentNotificationHelper.multicastEvent(eventType, entityName,
204                                   moduleType, cascade, forceDeploy, loadUnloadAction, targetName);
205     } catch (Throwable JavaDoc t) {
206         IASDeploymentException iasEx = new IASDeploymentException(t.getMessage());
207         iasEx.initCause(t);
208         throw iasEx;
209         }
210         // unreachable
211
}
212
213     /**
214      * Get module type string using the DeployableObjectType. This string is used
215      * while multicasting events to remote servers
216      * @param moduleType deployableObjectType of the module
217      * @return String
218      * DeployableObjectType.APP = null
219      * DeployableObjectType.EJB = "ejb"
220      * DeployableObjectType.WEB = "web"
221      * DeployableObjectType.CONNECTOR = "connector"
222      */

223     public static String JavaDoc getModuleTypeString(DeployableObjectType moduleType)
224     {
225         String JavaDoc moduleTypeString = null;
226         if (moduleType.equals(DeployableObjectType.EJB))
227         {
228             moduleTypeString = ModuleDeployEvent.TYPE_EJBMODULE;
229         }
230         else if(moduleType.equals(DeployableObjectType.WEB))
231         {
232             moduleTypeString = ModuleDeployEvent.TYPE_WEBMODULE;
233         }
234         else if(moduleType.equals(DeployableObjectType.CONN))
235         {
236             moduleTypeString = ModuleDeployEvent.TYPE_CONNECTOR;
237         }
238         else if (moduleType.equals(DeployableObjectType.CAR))
239         {
240             moduleTypeString = ModuleDeployEvent.TYPE_APPCLIENT;
241         }
242         return moduleTypeString;
243     }
244
245     public static BaseManager getInstanceManager(
246         DeployableObjectType moduleType) {
247         try {
248             InstanceEnvironment insEnv =
249                 new InstanceEnvironment(getInstanceName());
250             if (moduleType.equals(DeployableObjectType.APP)) {
251                 return new AppsManager(insEnv);
252             } else if (moduleType.equals(DeployableObjectType.EJB)) {
253                 return new EjbModulesManager(insEnv);
254             } else if(moduleType.equals(DeployableObjectType.WEB)) {
255                 return new WebModulesManager(insEnv);
256             } else if(moduleType.equals(DeployableObjectType.CONN)) {
257                 return new ConnectorModulesManager(insEnv);
258             } else if (moduleType.equals(DeployableObjectType.CAR)) {
259                 return new AppclientModulesManager(insEnv);
260             } else {
261                 // invalid module type
262
return null;
263             }
264         } catch (Exception JavaDoc e) {
265             return null;
266         }
267     }
268
269
270     /** This method is for j2ee application with embedded web modules.
271      * First it tries to get application from AppsManager of DAS,
272      * if it's not already loaded there, then we load from disk.
273      * Since this method might read from disk, it could be time-consuming.
274      * The context roots in sun-application.xml will override the ones
275      * defined in application.xml.
276      * The method returns String[0] when there is no web module in the
277      * application.
278      *
279      * @param name of the j2ee app registered in the config
280      * @return the context roots of the embedded web modules in j2ee
281      * application
282      */

283     public static String JavaDoc[] getContextRootsForEmbeddedWebApp(String JavaDoc appName)
284         throws IASDeploymentException {
285         try {
286             AppsManager appsManager =
287                 new AppsManager(new InstanceEnvironment(getInstanceName()));
288             Application application =
289                 appsManager.getRegisteredDescriptor(appName);
290             // if the application already loaded on DAS
291
if (application != null) {
292                 ArrayList JavaDoc contextRoots = new ArrayList JavaDoc();
293                 for (Iterator JavaDoc itr = application.getWebBundleDescriptors().iterator(); itr.hasNext();) {
294                     WebBundleDescriptor wbd = (WebBundleDescriptor) itr.next();
295                     contextRoots.add(wbd.getContextRoot());
296                 }
297                 return (String JavaDoc[])contextRoots.toArray(new String JavaDoc[contextRoots.size()]);
298             // if not, read from disk
299
} else {
300                 // load from generated/xml dir first
301
// print a warning if generated/xml dir is not there
302
// and load from original dir (upgrade scenario)
303
String JavaDoc xmlDir = appsManager.getGeneratedXMLLocation(appName);
304                 if (!FileUtils.safeIsDirectory(xmlDir)) {
305                     String JavaDoc appDir = appsManager.getLocation(appName);
306                     // log a warning message in the server log
307
sLogger.log(Level.WARNING, "core.no_xmldir",
308                         new Object JavaDoc[]{xmlDir, appDir});
309                     xmlDir = appDir;
310                 }
311                 AppDD appDD = new AppDD(new File JavaDoc(xmlDir));
312                 return appDD.getContextRoots();
313             }
314         } catch (Exception JavaDoc e) {
315             if (e instanceof IASDeploymentException) {
316                 throw (IASDeploymentException)e;
317             } else {
318                 throw new IASDeploymentException(e);
319             }
320         }
321     }
322
323     public static List JavaDoc<String JavaDoc> getTargetNamesFromTargetString (
324         String JavaDoc targetString) {
325         if (targetString == null) {
326             return null;
327         }
328         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(targetString);
329         List JavaDoc<String JavaDoc> targetNames = new ArrayList JavaDoc<String JavaDoc>();
330         while (st.hasMoreTokens()) {
331             targetNames.add(st.nextToken());
332         }
333         return targetNames;
334     }
335
336     public static void setResourceOptionsInRequest (DeploymentRequest req,
337         DeploymentProperties props) {
338         req.setResourceAction(props.getResourceAction());
339         req.setResourceTargetList(props.getResourceTargetList());
340     }
341
342     public static FilenameFilter JavaDoc getFilenameFilter(final String JavaDoc fileName){
343         FilenameFilter JavaDoc filter = new FilenameFilter JavaDoc() {
344             public boolean accept(File JavaDoc dir, String JavaDoc name) {
345                 if ( (new File JavaDoc(dir, name)).isDirectory()) {
346                     return true;
347                 } else if (name !=null && name.equals(fileName)){
348                     return true;
349                 } else {
350                     return false;
351                 }
352             }
353         };
354         return filter;
355     }
356
357     public static List JavaDoc<Resource> getResources(String JavaDoc appId,
358         DeployableObjectType moduleType) {
359         try {
360             // retrieve all the sun-resources.xml under the
361
// generated/xml directory
362
String JavaDoc directoryToLook =
363                 getInstanceManager(moduleType).getGeneratedXMLLocation(appId);
364             Set JavaDoc listOfFiles = FileUtil.getAllFilesUnder(
365                 new File JavaDoc(directoryToLook),
366                 getFilenameFilter(SUN_RESOURCE_XML), true);
367
368             // get the expected paths
369
ArrayList JavaDoc<String JavaDoc> expectedXMLPaths = new ArrayList JavaDoc<String JavaDoc>();
370             Application app = getInstanceManager(
371                 moduleType).getRegisteredDescriptor(appId);
372
373             if (app != null) {
374                 if (app.isVirtual()) {
375                     // for standalone module, it's under the root META-INF
376
expectedXMLPaths.add(SUN_RESOURCE_XML_PATH);
377                 } else {
378                     // for application
379
// first add the one under app root
380
expectedXMLPaths.add(SUN_RESOURCE_XML_PATH);
381                     // then add the ones under sub module root
382
for (Iterator JavaDoc itr = app.getModules();itr.hasNext();) {
383                         ModuleDescriptor aModule =
384                             (ModuleDescriptor) itr.next();
385                         String JavaDoc moduleUri = FileUtils.makeFriendlyFileName(
386                             aModule.getArchiveUri());
387                         String JavaDoc subModulePath = moduleUri +
388                            File.separator + SUN_RESOURCE_XML_PATH;
389                         expectedXMLPaths.add(subModulePath);
390                     }
391                 }
392             } else {
393                 // the default
394
expectedXMLPaths.add(SUN_RESOURCE_XML_PATH);
395             }
396                                                                                 
397             // process all the sun-resources.xml and add them
398
// to a hashmap for further processing
399
HashMap JavaDoc<String JavaDoc, List JavaDoc<Resource>> resourcesListMap =
400                 new HashMap JavaDoc<String JavaDoc, List JavaDoc<Resource>>();
401                
402             for (Iterator JavaDoc fIter = listOfFiles.iterator(); fIter.hasNext(); ) {
403                 File JavaDoc file = (File JavaDoc)fIter.next();
404                 String JavaDoc filePath = file.getPath();
405                 String JavaDoc xmlFilePath =
406                     (new File JavaDoc(directoryToLook, filePath)).getAbsolutePath();
407                 if (expectedXMLPaths.contains(filePath)) {
408                     ResourcesXMLParser allResources =
409                         new ResourcesXMLParser(xmlFilePath);
410                     resourcesListMap.put(filePath,
411                         allResources.getResourcesList());
412                 } else {
413                     sLogger.log(Level.WARNING,
414                         "enterprise.deployment.ignore.sun.resources.xml",
415                          xmlFilePath);
416                 }
417             }
418
419             // this will be called until the duplicate/conflict
420
// logic is ready
421
// return processResourcesListMap(resourcesListMap);
422

423             return simpleProcessResourcesListMap(resourcesListMap);
424
425         } catch (Exception JavaDoc e) {
426             sLogger.log(Level.WARNING,
427                 "enterprise.deployment.error.get.resources",
428                 e.getMessage());
429             return new ArrayList JavaDoc<Resource>();
430         }
431     }
432
433     // this method just adds all the resources from all the lists
434
// doesn't do anything with conflicts or duplicates
435
private static List JavaDoc<Resource> simpleProcessResourcesListMap(
436         HashMap JavaDoc<String JavaDoc, List JavaDoc<Resource>> resourcesListMap) {
437         List JavaDoc<Resource> globalList = new ArrayList JavaDoc<Resource>();
438         for (Iterator JavaDoc<List JavaDoc<Resource>> mapIter =
439             resourcesListMap.values().iterator(); mapIter.hasNext();) {
440             globalList.addAll(mapIter.next());
441         }
442         return globalList;
443     }
444
445     // this method will go over all the resources list
446
// inside the archive and resolve for conflicts, duplicates
447
private static List JavaDoc<Resource> processResourcesListMap(
448         HashMap JavaDoc<String JavaDoc, List JavaDoc<Resource>> resourcesListMap) {
449
450         // whether we have top level sun-resources.xml
451
// we need to process it separately
452
boolean hasTopLevel = false;
453
454         // the final resolved list to return
455
List JavaDoc <Resource> globalResourcesList = new ArrayList JavaDoc<Resource>();
456
457         // we need to resolve the duplicates and conflicts
458
// process the submodule level first and top level last
459

460         // process for submodule level first
461
// rule here: who appears later, who wins
462
for (Iterator JavaDoc<String JavaDoc> mapIter = resourcesListMap.keySet().iterator();
463             mapIter.hasNext();){
464             String JavaDoc path = mapIter.next();
465             if (path.equals(SUN_RESOURCE_XML_PATH)) {
466                 hasTopLevel = true;
467                 continue;
468             } else {
469                 processResourceListForXMLPath(globalResourcesList,
470                     resourcesListMap, path);
471             }
472         }
473       
474         // now process the top level
475
if (hasTopLevel) {
476             processResourceListForXMLPath(globalResourcesList,
477                 resourcesListMap, SUN_RESOURCE_XML_PATH);
478         }
479         
480         return globalResourcesList;
481     }
482
483     private static void processResourceListForXMLPath(
484         List JavaDoc<Resource> globalResourcesList,
485         HashMap JavaDoc<String JavaDoc, List JavaDoc<Resource>> resourcesListMap, String JavaDoc xmlPath) {
486         List JavaDoc<Resource> resourcesList = resourcesListMap.get(xmlPath);
487         for (Iterator JavaDoc<Resource> resIter = resourcesList.iterator();
488             resIter.hasNext();) {
489             Resource newResource = resIter.next();
490             // add the resource to the global list
491
// after checking with the current elements in the list
492
for (Iterator JavaDoc<Resource> globalResIter =
493                 globalResourcesList.iterator(); globalResIter.hasNext();) {
494                 Resource resourceInList = globalResIter.next();
495                 if (newResource.equals(resourceInList) ||
496                     newResource.isAConflict(resourceInList)) {
497                     globalResourcesList.remove(resourceInList);
498                     break;
499                 }
500             }
501             globalResourcesList.add(newResource);
502         }
503     }
504
505     //We must convert the absolute path back into a path of the
506
//form ${com.sun.aas.instanceRoot}/applications/... so that
507
//domain.xml is non-installation location specific.
508
public static String JavaDoc getLocation(File JavaDoc appDir)
509     {
510         if (appDir != null) {
511             return (RelativePathResolver.unresolvePath(
512                         appDir.getAbsolutePath(),
513                         new String JavaDoc[] {SystemPropertyConstants.INSTANCE_ROOT_PROPERTY,
514                         SystemPropertyConstants.INSTALL_ROOT_PROPERTY}));
515         } else {
516             return null;
517         }
518     }
519
520     // The following methods are related to get/set attributes of a deployed
521
// app/module
522

523     // Retrieving the location attribute
524
public static String JavaDoc getLocation(String JavaDoc appId, DeployableObjectType type)
525         throws IASDeploymentException {
526         try {
527             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
528             String JavaDoc getOperationName = getGetOperationName(type);
529             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
530             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appId},new String JavaDoc[]{"java.lang.String"});
531             String JavaDoc location = (String JavaDoc)mbs.getAttribute(componentON,
532                 ServerTags.LOCATION);
533             return (new RelativePathResolver()).resolve(location);
534         } catch (Exception JavaDoc e) {
535             throw new IASDeploymentException(e);
536         }
537     }
538
539     // Retrieving the enabled attribute
540
public static boolean isEnabled(String JavaDoc appId, DeployableObjectType type)
541         throws IASDeploymentException {
542         try {
543             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
544             String JavaDoc getOperationName = getGetOperationName(type);
545             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
546             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appId},new String JavaDoc[]{"java.lang.String"});
547
548             String JavaDoc enabled = (String JavaDoc)mbs.getAttribute(componentON,
549                 ServerTags.ENABLED);
550             return Boolean.valueOf(enabled).booleanValue();
551         } catch (Exception JavaDoc e) {
552             throw new IASDeploymentException(e);
553         }
554     }
555
556     // Retrieving the directory-deployed attribute
557
public static boolean isDirectoryDeployed(String JavaDoc appId,
558         DeployableObjectType type) throws IASDeploymentException {
559         try {
560             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
561             String JavaDoc getOperationName = getGetOperationName(type);
562             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
563             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appId},new String JavaDoc[]{"java.lang.String"});
564
565             String JavaDoc directoryDeployed = (String JavaDoc)mbs.getAttribute(componentON,
566                 ServerTags.DIRECTORY_DEPLOYED);
567             return Boolean.valueOf(directoryDeployed).booleanValue();
568         } catch (Exception JavaDoc e) {
569             throw new IASDeploymentException(e);
570         }
571     }
572
573     // Retrieving the object-type attribute
574
public static String JavaDoc getObjectType(String JavaDoc appId, DeployableObjectType type)
575         throws IASDeploymentException {
576         try {
577             // appclient module does not have object type
578
if (type.isCAR()) {
579                 return null;
580             }
581             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
582             String JavaDoc getOperationName = getGetOperationName(type);
583             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
584             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appId},new String JavaDoc[]{"java.lang.String"});
585
586             String JavaDoc objectType =
587                 (String JavaDoc)mbs.getAttribute(componentON, ServerTags.OBJECT_TYPE);
588             return objectType;
589         } catch (Exception JavaDoc e) {
590             throw new IASDeploymentException(e);
591         }
592     }
593
594     // Set the context-root attribute
595
public static void setContextRoot(String JavaDoc appId, DeployableObjectType type,
596                       String JavaDoc contextRoot) throws IASDeploymentException {
597         try {
598             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
599             String JavaDoc getOperationName = getGetOperationName(type);
600             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
601             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appId},new String JavaDoc[]{"java.lang.String"});
602
603        
604             if (contextRoot != null && contextRoot.length() > 0 ) {
605                 Attribute JavaDoc contextRootAttr = new Attribute JavaDoc(ServerTags.CONTEXT_ROOT,
606                     contextRoot);
607                 mbs.setAttribute(componentON, contextRootAttr);
608             }
609         } catch (Exception JavaDoc e) {
610             throw new IASDeploymentException(e);
611         }
612     }
613
614     // Retrieving the object-type attribute
615
public static boolean isSystem(String JavaDoc appId, DeployableObjectType type)
616         throws IASDeploymentException{
617         String JavaDoc objectType = getObjectType(appId, type);
618         if (objectType != null) {
619             return objectType.startsWith(SYSTEM_PREFIX);
620         } else {
621             return false;
622         }
623     }
624
625     private static AttributeList JavaDoc populateAttributeList(
626         DeploymentRequest request) throws IASDeploymentException {
627         AttributeList JavaDoc attrList = new AttributeList JavaDoc();
628
629         String JavaDoc name = request.getName();
630         // name attribute
631
if (name != null && name.length() > 0 ) {
632             Attribute JavaDoc nameAttr = new Attribute JavaDoc(ServerTags.NAME, name);
633             attrList.add(nameAttr);
634         }
635
636         // location attribute
637
String JavaDoc location = getLocation(request.getDeployedDirectory());
638         if (location != null && location.length() > 0 ) {
639             Attribute JavaDoc locationAttr = new Attribute JavaDoc(ServerTags.LOCATION, location);
640             attrList.add(locationAttr);
641         }
642
643         // description attribute
644
String JavaDoc description = request.getDescription();
645         if (description != null && description.length() > 0 ) {
646             Attribute JavaDoc descriptionAttr =
647                 new Attribute JavaDoc(ServerTags.DESCRIPTION, description);
648             attrList.add(descriptionAttr);
649         }
650
651         // enable attribute does not apply to app client module
652
if (! request.getType().isCAR()) {
653             String JavaDoc enabled = String.valueOf(request.isStartOnDeploy());
654             if (enabled != null && enabled.length() > 0 ) {
655                 Attribute JavaDoc enableAttr = new Attribute JavaDoc(ServerTags.ENABLED, enabled);
656                 attrList.add(enableAttr);
657             }
658         }
659
660         // java-web-start-enabled attribute
661
// applies to application and appclient module
662
if (request.getType().isAPP() || request.getType().isCAR()) {
663             String JavaDoc jwsEnabled =
664                 String.valueOf(request.isJavaWebStartEnabled());
665             if (jwsEnabled != null && jwsEnabled.length() > 0 ) {
666                 Attribute JavaDoc jwsEnableAttr = new Attribute JavaDoc(
667                     ServerTags.JAVA_WEB_START_ENABLED, jwsEnabled);
668                 attrList.add(jwsEnableAttr);
669             }
670         }
671
672         // libraries attribute
673
// applies to application, ejb, web module
674
if (request.getType().isAPP() || request.getType().isEJB() ||
675             request.getType().isWEB()) {
676             String JavaDoc libraries = request.getLibraries();
677             if (libraries != null && libraries.length() > 0 ) {
678                 Attribute JavaDoc librariesAttr = new Attribute JavaDoc(
679                     ServerTags.LIBRARIES, libraries);
680                 attrList.add(librariesAttr);
681             }
682         }
683
684         // context-root attribute only apply to web module
685
if (request.getType().isWEB()) {
686             String JavaDoc contextRoot = request.getContextRoot();
687             if (contextRoot != null && contextRoot.length() > 0 ) {
688                 Attribute JavaDoc contextRootAttr =
689                     new Attribute JavaDoc(ServerTags.CONTEXT_ROOT, contextRoot);
690                 attrList.add(contextRootAttr);
691             }
692         }
693
694         // availability-enabled attribute does not apply to app client
695
// or connector module
696
if (! request.getType().isCAR() && ! request.getType().isCONN()) {
697             String JavaDoc availEnabled = String.valueOf(request.isAvailabilityEnabled());
698             if (availEnabled!= null && availEnabled.length() > 0 ) {
699                 Attribute JavaDoc availEnabledAttr =
700                     new Attribute JavaDoc(ServerTags.AVAILABILITY_ENABLED, availEnabled);
701                 attrList.add(availEnabledAttr);
702             }
703         }
704
705         // directory-deployed attribute
706
String JavaDoc dirDeployed = String.valueOf(request.isDirectory());
707         if (dirDeployed != null && dirDeployed.length() > 0 ) {
708             Attribute JavaDoc dirDeployedAttr =
709                 new Attribute JavaDoc(ServerTags.DIRECTORY_DEPLOYED, dirDeployed);
710             attrList.add(dirDeployedAttr);
711         }
712
713
714         // other optional attributes like object-type
715
Properties optionalAttributes = request.getOptionalAttributes();
716         if (optionalAttributes != null) {
717             // remove the virtual-server attribute which belongs
718
// to application-ref
719
// cloning is done so that the original Properties object
720
// is not tampered with. The original Properties object is
721
// referred to in a few other places.
722
Properties mProps = (Properties) optionalAttributes.clone();
723             try {
724                 mProps.remove(ServerTags.VIRTUAL_SERVERS);
725             } catch(Exception JavaDoc re) {}
726
727             Enumeration JavaDoc tags = mProps.keys();
728             while(tags.hasMoreElements()) {
729                 String JavaDoc tag = (String JavaDoc)tags.nextElement();
730                 String JavaDoc value = mProps.getProperty(tag);
731                 if (tag != null & tag.length() > 0 &&
732                     value != null && value.length() > 0) {
733                     Attribute JavaDoc optionalAttr = new Attribute JavaDoc(tag, value);
734                     attrList.add(optionalAttr);
735                 }
736             }
737         }
738
739         return attrList;
740     }
741
742     // used when adding app/module to config
743
public static void addToConfig(DeploymentRequest request)
744         throws IASDeploymentException {
745         try {
746             DeployableObjectType type = request.getType();
747             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
748             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
749
750             String JavaDoc createOperationName = getCreateOperationName(type);
751
752             AttributeList JavaDoc attrList = populateAttributeList(request);
753
754             String JavaDoc[] signature = new String JavaDoc[] {AttributeList JavaDoc.class.getName()};
755             Object JavaDoc[] params = new Object JavaDoc[] {attrList};
756             mbs.invoke(appsConfigMBean, createOperationName, params, signature);
757             getConfigContext().flush();
758             getConfigContext().resetConfigChangeList();
759         } catch (Exception JavaDoc e) {
760             if (e instanceof IASDeploymentException) {
761                 throw (IASDeploymentException)e;
762             } else {
763                 throw new IASDeploymentException(e);
764             }
765         }
766     }
767
768     // used when updating config
769
public static void updateConfig(DeploymentRequest request)
770         throws IASDeploymentException {
771         try {
772             String JavaDoc name = request.getName();
773             ConfigBean appBean =
774                 ApplicationHelper.findApplication(getConfigContext(), name);
775             if (appBean != null) {
776                 for (Iterator JavaDoc itr = populateAttributeList(request).iterator();
777                      itr.hasNext();) {
778                     Attribute JavaDoc attr = (Attribute JavaDoc)itr.next();
779                     appBean.setAttributeValue(attr.getName(),
780                                               (String JavaDoc)attr.getValue());
781                 }
782                 getConfigContext().flush();
783                 getConfigContext().resetConfigChangeList();
784             }
785         } catch (Exception JavaDoc e) {
786             if (e instanceof IASDeploymentException) {
787                 throw (IASDeploymentException)e;
788             } else {
789                 throw new IASDeploymentException(e);
790             }
791         }
792     }
793
794     // used when removing app/module to config
795
public static void removeFromConfig(String JavaDoc name, DeployableObjectType type)
796         throws IASDeploymentException {
797         try {
798             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
799             String JavaDoc getOperationName = getGetOperationName(type);
800             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
801             ObjectName JavaDoc componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{name},new String JavaDoc[]{"java.lang.String"});
802             if(componentON != null){
803                 String JavaDoc removeOperationName = getRemoveOperationName(type);
804                 mbs.invoke(appsConfigMBean, removeOperationName, new Object JavaDoc[]{name},new String JavaDoc[]{"java.lang.String"});
805                 getConfigContext().flush();
806                 getConfigContext().resetConfigChangeList();
807             }
808         } catch (Exception JavaDoc e) {
809             throw new IASDeploymentException(e);
810         }
811     }
812
813     public static boolean isRegistered(String JavaDoc appName,
814                        DeployableObjectType type) throws IASDeploymentException {
815         try {
816             MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
817             String JavaDoc getOperationName = getGetOperationName(type);
818             ObjectName JavaDoc appsConfigMBean = new ObjectName JavaDoc(appsConfigMBeanName);
819             ObjectName JavaDoc componentON = null;
820
821             try {
822                 componentON = (ObjectName JavaDoc)mbs.invoke(appsConfigMBean, getOperationName, new Object JavaDoc[]{appName}, new String JavaDoc[]{"java.lang.String"});
823             } catch(Exception JavaDoc cn) {
824             }
825
826             if(componentON != null){
827                 return true;
828             }
829             return false;
830         } catch (Exception JavaDoc e) {
831             throw new IASDeploymentException(e);
832         }
833     }
834
835     public static ConfigContext getConfigContext() {
836         try {
837             AdminService adminService = AdminService.getAdminService();
838             if (adminService != null) {
839                 ConfigContext config =
840                         adminService.getAdminContext().getAdminConfigContext();
841                 return config;
842             } else {
843                return null;
844             }
845         } catch (Exception JavaDoc e) {
846             return null;
847         }
848     }
849
850     public static String JavaDoc getInstanceName() {
851          return ApplicationServer.getServerContext().getInstanceName();
852     }
853
854     public static String JavaDoc getDomainName()
855         throws IASDeploymentException {
856         try {
857            AdminService adminService = AdminService.getAdminService();
858             if (adminService != null) {
859                 String JavaDoc domainName =
860                         adminService.getAdminContext().getDomainName();
861                 return domainName;
862             } else {
863                return null;
864             }
865         } catch (Exception JavaDoc e) {
866             throw new IASDeploymentException(e);
867         }
868     }
869
870             
871     /**
872      * This method checks if the app specified is of
873      * a system application/module
874      * @param appID name of the application
875      * @param type object type of the application
876      * @param action deploy/redeploy/undeploy/enable/disable
877      * @throws IASDeploymentException if application/module is
878      * of type system
879      */

880     public static void validate(String JavaDoc appID, DeployableObjectType type,
881         String JavaDoc action) throws IASDeploymentException {
882         boolean allowSystemAppModification =
883             (Boolean.valueOf(System.getProperty(
884                 Constants.ALLOW_SYSAPP_DEPLOYMENT, "false")).booleanValue());
885
886         if(allowSystemAppModification)
887             return;
888         if (isSystem(appID, type)) {
889             String JavaDoc msg = localStrings.getString(
890                 "enterprise.deployment.phasing.component_is_system",
891                 new Object JavaDoc[]{ action, appID });
892             throw new IASDeploymentException(msg);
893         }
894     }
895
896     /**
897      * This method checks if any of the virtual servers has the given web
898      * module as default-web-module. If yes, it throws exception.
899      * @param webModuleName the name of the web module.
900      * @throws ConfigException if any of the virtual servers has this web
901      * module as default-web-module.
902      */

903     public static void checkWebModuleReferences(String JavaDoc webModuleName)
904     throws IASDeploymentException {
905         ArrayList JavaDoc virtualServerIds = new ArrayList JavaDoc();
906
907         try {
908             Config config = (Config) ConfigBeansFactory.getConfigBeanByXPath(
909                 getConfigContext(), ServerXPathHelper.XPATH_CONFIG);
910             HttpService httpService = config.getHttpService();
911             VirtualServer[] virtualServers = httpService.getVirtualServer();
912             for (int j = 0; j < virtualServers.length; j++) {
913                 VirtualServer aServer = virtualServers[j];
914                 String JavaDoc defWebModule = aServer.getDefaultWebModule();
915                 if ((defWebModule != null) &&
916                 (defWebModule.equals(webModuleName))) {
917                     virtualServerIds.add(aServer.getId());
918                 }
919             }
920         } catch (Exception JavaDoc e) {
921             throw new IASDeploymentException(e);
922         }
923         if (!virtualServerIds.isEmpty()) {
924             throw new IASDeploymentException(localStrings.getString(
925                 "enterprise.deployment.phasing.def_web_module_refs_exist",
926                 virtualServerIds.toString(), webModuleName));
927         }
928     }
929
930     public static void checkAbort(String JavaDoc moduleID)
931         throws IASDeploymentException {
932         DeploymentRequest request =
933             DeploymentRequestRegistry.getRegistry().getDeploymentRequest(
934                 moduleID);
935         if (request != null && request.isAborted()) {
936             DeploymentRequestRegistry.getRegistry().removeDeploymentRequest(
937                 moduleID);
938             String JavaDoc msg = localStrings.getString(
939                 "enterprise.deployment.phasing.operation.abort",
940                 new Object JavaDoc[]{ moduleID });
941             throw new IASDeploymentException(msg);
942         }
943     }
944
945    /**
946      * This method returns the deployableObjectType of an archive by checking
947      * the deployable descriptors in the archive
948      * @param filePath absolute path to the archive
949      * @return type DeployableObjectType
950      */

951     public static DeployableObjectType getTypeFromFile(String JavaDoc name, String JavaDoc filePath)
952         throws DeploymentException {
953
954         if(filePath == null)
955             throw new DeploymentException("deploy file not specified");
956
957         try {
958             //@@@ special handling the deployment of .class POJO webservice
959
//class.
960
if (filePath.endsWith(".class")) {
961                 // get the top directory from the moduleID, in the case of
962
// autodeploy, the moduleID will be the full class name (with package)
963
// with . replaced with _
964
StringTokenizer JavaDoc tk = new StringTokenizer JavaDoc(name, "_");
965                 File JavaDoc f = new File JavaDoc(filePath);
966                 for (int i=0;i<tk.countTokens();i++) {
967                     f = f.getParentFile();
968                 }
969                 try {
970                     // it's important to not cache this because the class can
971
// change overtime... we need to load the last one.
972
URL JavaDoc[] urls = new URL JavaDoc[1];
973                     urls[0] = f.toURL();
974                     URLClassLoader JavaDoc cLoader = new URLClassLoader JavaDoc(urls,
975                                 DeploymentServiceUtils.class.getClassLoader());
976                     String JavaDoc className = name.replaceAll("_", ".");
977                     Class JavaDoc clazz = cLoader.loadClass(className);
978                     if (clazz!=null && clazz.getAnnotation(javax.ejb.Stateless JavaDoc.class)!=null) {
979                         return DeployableObjectType.EJB;
980                     } else {
981                         return DeployableObjectType.WEB;
982                     }
983                 } catch(Exception JavaDoc e) {
984                     return DeployableObjectType.WEB;
985                 }
986             }
987
988             Archivist archivist =
989                 ArchivistFactory.getArchivistForArchive(filePath);
990             ModuleType JavaDoc moduleType = archivist.getModuleType();
991             return getDeployableObjectType(moduleType);
992         } catch(Exception JavaDoc ex) {
993             DeploymentException de = new DeploymentException(
994                 localStrings.getString(
995                     "enterprise.deployment.unknown.application.type", filePath));
996             de.initCause(ex);
997             throw de;
998         }
999     }
1000
1001    public static DeploymentTarget getAndValidateDeploymentTarget(String JavaDoc
1002        targetName, String JavaDoc appName, boolean isDeleting)
1003        throws IASDeploymentException {
1004        try {
1005            final DeploymentTarget target = DeploymentTargetFactory.getDeploymentTargetFactory().getTarget(getConfigContext(), getDomainName(), targetName);
1006            if (targetName == null) {
1007                // If the targetName passed in was null, we need to set it
1008
// to its default value.
1009
targetName = target.getTarget().getName();
1010            }
1011            if (target.getTarget().getType() == TargetType.SERVER ||
1012                target.getTarget().getType() == TargetType.DAS) {
1013                // make sure we have the reference before we delete it
1014
if (isDeleting) {
1015                    if (!ServerHelper.serverReferencesApplication(
1016                        getConfigContext(), targetName, appName)) {
1017                        throw new IASDeploymentException(localStrings.getString("serverApplicationRefDoesNotExist", targetName, appName));
1018                    }
1019                // make sure we don't have the reference already before
1020
// we create it again
1021
} else {
1022                   if (ServerHelper.serverReferencesApplication(
1023                        getConfigContext(), targetName, appName)) {
1024                        throw new IASDeploymentException(localStrings.getString("serverApplicationRefAlreadyExists", appName, targetName));
1025                   }
1026                }
1027            } else if (target.getTarget().getType() == TargetType.CLUSTER){
1028               // make sure we have the reference before we delete it
1029
if (isDeleting) {
1030                    if (!ClusterHelper.clusterReferencesApplication(
1031                        getConfigContext(), targetName, appName)) {
1032                        throw new IASDeploymentException(localStrings.getString("clusterApplicationRefDoesNotExist", targetName, appName));
1033                    }
1034                // make sure we don't have the reference already before
1035
// we create it again
1036
} else {
1037                    if (ClusterHelper.clusterReferencesApplication(
1038                        getConfigContext(), targetName, appName)) {
1039                        throw new IASDeploymentException(localStrings.getString("clusterApplicationRefAlreadyExists", appName, targetName));
1040                    }
1041                }
1042            }
1043         
1044            return target;
1045        } catch (IASDeploymentException ex) {
1046            throw (ex);
1047        } catch (Exception JavaDoc ex) {
1048            throw new IASDeploymentException(ex);
1049        }
1050    }
1051
1052    /**
1053     * Set http listener host and port in deployment request. If the server
1054     * is not configured properly the defaults used are localhost:8080 for
1055     * clear and localhost:8181 for SSL.
1056     */

1057    public static void setHostAndPort(DeploymentRequest req)
1058            throws ServerInstanceException {
1059
1060        String JavaDoc virtualServers = (String JavaDoc) req.getOptionalAttributes().get(ServerTags.VIRTUAL_SERVERS);
1061        if (virtualServers==null) {
1062            HostAndPort hap = getHostAndPort(false);
1063            if(hap != null) {
1064                req.setHttpHostName(getHostName(hap));
1065                req.setHttpPort(getPort(hap, false));
1066            }
1067            hap = getHostAndPort(true);
1068            if(hap != null) {
1069                req.setHttpsHostName(getHostName(hap));
1070                req.setHttpsPort(getPort(hap, true));
1071            }
1072        } else {
1073            StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(virtualServers,",");
1074            if (st.hasMoreTokens()) {
1075                String JavaDoc aVirtualServer = st.nextToken();
1076                HostAndPort hap = getVirtualServerHostAndPort(aVirtualServer, false);
1077                if(hap != null) {
1078                    req.setHttpHostName(getHostName(hap));
1079
1080                    req.setHttpPort(getPort(hap, false));
1081                }
1082                hap = getVirtualServerHostAndPort(aVirtualServer, true);
1083                if(hap != null) {
1084                    req.setHttpsHostName(getHostName(hap));
1085                    req.setHttpsPort(getPort(hap, true));
1086                }
1087            }
1088        }
1089    }
1090
1091    private static String JavaDoc getHostName(HostAndPort hap) {
1092        String JavaDoc hostName = hap.getHost();
1093        if (hostName == null || hostName.trim().equals("")) {
1094            hostName = getDefaultHostName();
1095        }
1096        return hostName;
1097    }
1098
1099    private static String JavaDoc getDefaultHostName() {
1100        String JavaDoc defaultHostName = "localhost";
1101        try {
1102            InetAddress JavaDoc host = InetAddress.getLocalHost();
1103            defaultHostName = host.getCanonicalHostName();
1104        } catch(UnknownHostException JavaDoc uhe) {
1105            sLogger.log(Level.FINEST, "mbean.get_local_host_error", uhe);
1106            sLogger.log(Level.INFO, "mbean.use_default_host");
1107
1108       }
1109        return defaultHostName;
1110    }
1111
1112    private static int getPort(HostAndPort hap, boolean securityEnabled) {
1113        int port = hap.getPort();
1114        if (port == 0) {
1115            port = getDefaultPort(securityEnabled);
1116        }
1117        return port;
1118    }
1119
1120    private static int getDefaultPort(boolean securityEnabled) {
1121        int port = 0;
1122        if (securityEnabled) {
1123            port = 8181;
1124        } else {
1125            port = 8080;
1126        }
1127        sLogger.log(Level.INFO, "mbean.use_default_port", String.valueOf(port));
1128        return port;
1129    }
1130
1131    /**
1132     * Get value of named attribute from attributes list. If an attribute with
1133     * specified name does not exist, the method returns null. If there are
1134     * than one attributes with same name then the method returns value of
1135     * first matching attribute.
1136     *
1137     * @param attrs list of attributes
1138     * @param attrName name of the attribute
1139     * @return value of the specified attrName or null if the attrName is
1140     * not present in specified attrs
1141     */

1142    private static Object JavaDoc getNamedAttributeValue(AttributeList JavaDoc attrs,
1143            String JavaDoc attrName) {
1144        if (attrs == null || attrName == null) {
1145            return null;
1146        }
1147        Object JavaDoc value = null;
1148        Iterator JavaDoc iter = attrs.iterator();
1149        while (iter.hasNext()) {
1150           Attribute JavaDoc attr = (Attribute JavaDoc)iter.next();
1151           if (attrName.equals(attr.getName())) {
1152               value = attr.getValue();
1153               break;
1154           }
1155        }
1156        return value;
1157    }
1158
1159    /**
1160     * @param securityEnabled
1161     * @throws ServerInstanceException
1162     */

1163    private static HostAndPort getHostAndPort(boolean securityEnabled) throws ServerInstanceException {
1164        HostAndPort hAndp = null;
1165        try {
1166            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1167            ObjectName JavaDoc objectName = new ObjectName JavaDoc(getDomainName()+":type=configs,category=config");
1168            String JavaDoc operationName1 = "getConfig";
1169            ObjectName JavaDoc[] configs = (ObjectName JavaDoc[])mbs.invoke(objectName,operationName1, emptyParams,emptySignature);
1170            String JavaDoc configName = (String JavaDoc)mbs.getAttribute(configs[0], "name");
1171            ObjectName JavaDoc httpService = new ObjectName JavaDoc(getDomainName()+":type=http-service,config="+configName+",category=config");
1172            String JavaDoc operationName2 = "getHttpListener";
1173            ObjectName JavaDoc[] httpListener = (ObjectName JavaDoc[])mbs.invoke(httpService, operationName2,emptyParams,emptySignature);
1174
1175            String JavaDoc serverName = null;
1176            int port = 0;
1177            for (int i = 0; i < httpListener.length; i++) {
1178                AttributeList JavaDoc attrs = mbs.getAttributes(httpListener[i],
1179                        httpListenerAttrNames);
1180                Boolean JavaDoc bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
1181                        attrs, LISTENER_ENABLED));
1182                boolean enabled = ((bb == null) ? false : bb.booleanValue());
1183                if (!enabled) {
1184                    // Listener is not enabled
1185
continue;
1186                }
1187                String JavaDoc vs = (String JavaDoc)getNamedAttributeValue(attrs, DEF_VS);
1188                if (ADMIN_VS.equals(vs)) {
1189                    // Listener is reserved for administration
1190
continue;
1191                }
1192                bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
1193                        attrs, SEC_ENABLED));
1194                boolean sec_on = ((bb == null) ? false : bb.booleanValue());
1195                if (securityEnabled == sec_on) {
1196                    serverName = (String JavaDoc)getNamedAttributeValue(attrs,
1197                            SERVER_NAME);
1198                    if (serverName == null || serverName.trim().equals("")) {
1199                        serverName = getDefaultHostName();
1200                    }
1201
1202                    String JavaDoc portStr = (String JavaDoc)getNamedAttributeValue(attrs,
1203                            PORT);
1204                    String JavaDoc redirPort = (String JavaDoc)getNamedAttributeValue(attrs,
1205                            REDIRECT_PORT);
1206                    if (redirPort != null && !redirPort.trim().equals("")) {
1207                        portStr = redirPort;
1208                    }
1209                    String JavaDoc resolvedPort =
1210                        new PropertyResolver(getConfigContext(),
1211                            getInstanceName()).resolve(portStr);
1212                    port = Integer.parseInt(resolvedPort);
1213                    break;
1214                }
1215            }
1216            hAndp = new HostAndPort(serverName, port);
1217        }
1218        catch (Exception JavaDoc e) {
1219            throw new ServerInstanceException(e.getLocalizedMessage());
1220        }
1221        return hAndp;
1222    }
1223
1224    private static HostAndPort getVirtualServerHostAndPort(String JavaDoc vs, boolean securityEnabled)
1225        throws ServerInstanceException
1226    {
1227        String JavaDoc serverName = null;
1228        int port = 0;
1229
1230        try {
1231            MBeanServer JavaDoc mbs = MBeanServerFactory.getMBeanServer();
1232
1233            ObjectName JavaDoc objectName = new ObjectName JavaDoc(
1234            getDomainName()+":type=configs,category=config");
1235            String JavaDoc operationName1 = "getConfig";
1236            ObjectName JavaDoc[] configs = (
1237            ObjectName JavaDoc[])mbs.invoke(objectName,operationName1,
1238            emptyParams,emptySignature);
1239            String JavaDoc configName = (String JavaDoc)mbs.getAttribute(configs[0], "name");
1240            ObjectName JavaDoc httpService = new ObjectName JavaDoc(
1241            getDomainName()+":type=http-service,config="+configName+",category=config");
1242
1243            // http listeners for the given config
1244

1245            String JavaDoc operationName2 = "getHttpListener";
1246            ObjectName JavaDoc[] httpListener = (ObjectName JavaDoc[])mbs.invoke(httpService,
1247            operationName2,emptyParams,emptySignature);
1248
1249            // virtual servers for the given config
1250

1251            operationName2 = "getVirtualServer";
1252            ObjectName JavaDoc[] virtualServer = (ObjectName JavaDoc[])mbs.invoke(httpService,
1253            operationName2,emptyParams,emptySignature);
1254
1255            // iterate for each of the config virtual server
1256

1257            for (int i = 0; i < virtualServer.length; i++) {
1258
1259                AttributeList JavaDoc vsAttrs = mbs.getAttributes(virtualServer[i], vsAttrNames);
1260
1261                // virtual server id check
1262
//
1263
// if the virtual server obtained from application ref
1264
// does not match with the virtual server from config
1265
// then continue with next virtual server
1266

1267                String JavaDoc id = (String JavaDoc)getNamedAttributeValue(vsAttrs, ID);
1268                if (! id.equals(vs)) {
1269                    continue;
1270                }
1271
1272                // should we check for state, let us assume ON for PE
1273

1274                // http listener
1275
//
1276
// Obtain the http listeners list from the virtual server
1277
// and iterate to match with the http listeners from config.
1278
// When a match is found get the host and port data
1279

1280                String JavaDoc httpListeners = (String JavaDoc) getNamedAttributeValue(vsAttrs, "http-listeners");
1281                String JavaDoc vsHttpListener = null;
1282                List JavaDoc httpListenerList = StringUtils.parseStringList(httpListeners, " ,");
1283                ListIterator JavaDoc hlListIter = httpListenerList.listIterator();
1284
1285                while(hlListIter.hasNext()) {
1286
1287                    vsHttpListener = (String JavaDoc) hlListIter.next();
1288
1289                    for (int j = 0; j < httpListener.length; j++) {
1290
1291                        AttributeList JavaDoc attrs = mbs.getAttributes(httpListener[j],
1292                        httpListenerAttrNames);
1293
1294                        // http listener id check
1295
String JavaDoc listenerId = (String JavaDoc)getNamedAttributeValue(attrs, ID);
1296                        if (! listenerId.equals(vsHttpListener)) {
1297                            continue;
1298                        }
1299
1300                        Boolean JavaDoc bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue(
1301                        attrs, LISTENER_ENABLED));
1302                        boolean enabled = ((bb == null) ? false : bb.booleanValue());
1303                        if (!enabled) {
1304                            // Listener is not enabled
1305
continue;
1306                        }
1307                        bb = Boolean.valueOf((String JavaDoc)getNamedAttributeValue( attrs, SEC_ENABLED));
1308                        boolean sec_on = ((bb == null) ? false : bb.booleanValue());
1309                        if (securityEnabled == sec_on) {
1310                            serverName = (String JavaDoc)getNamedAttributeValue(attrs, SERVER_NAME);
1311                            if (serverName == null || serverName.trim().equals("")) {
1312                                serverName = getDefaultHostName();
1313                            }
1314                            String JavaDoc portStr = (String JavaDoc)getNamedAttributeValue(attrs, PORT);
1315                            String JavaDoc redirPort = (String JavaDoc)getNamedAttributeValue(attrs, REDIRECT_PORT);
1316                            if (redirPort != null && !redirPort.trim().equals("")) {
1317                                portStr = redirPort;
1318                            }
1319                            final String JavaDoc resolvedPort =
1320                                    new PropertyResolver(getConfigContext(),
1321                                        getInstanceName()).resolve(portStr);
1322                            port = Integer.parseInt(resolvedPort);
1323                            return new HostAndPort(serverName, port);
1324                        }
1325                    }
1326                }
1327            }
1328        } catch (Exception JavaDoc e) {
1329            throw new ServerInstanceException(e.getLocalizedMessage());
1330        }
1331        return null;
1332    }
1333
1334    public static DeploymentTarget getDeploymentTarget(String JavaDoc targetName)
1335        throws IASDeploymentException {
1336        try {
1337            final DeploymentTarget target = DeploymentTargetFactory.getDeploymentTargetFactory().getTarget(getConfigContext(), getDomainName(), targetName);
1338            return target;
1339        } catch (IASDeploymentException ex) {
1340            throw (ex);
1341        } catch (Exception JavaDoc ex) {
1342            throw new IASDeploymentException(ex);
1343        }
1344    }
1345
1346
1347    public static void checkAppReferencesBeforeUndeployFromDomain(
1348        String JavaDoc appName) throws IASDeploymentException {
1349        try {
1350            // make sure no one reference the app before we undeploy it
1351
if (ApplicationHelper.isApplicationReferenced(
1352                getConfigContext(), appName)) {
1353                throw new IASDeploymentException(localStrings.getString("applicationIsReferenced", appName, ApplicationHelper.getApplicationReferenceesAsString(getConfigContext(), appName)));
1354            }
1355        } catch (IASDeploymentException ex) {
1356            throw (ex);
1357        } catch (Exception JavaDoc ex) {
1358            throw new IASDeploymentException(ex);
1359        }
1360    }
1361
1362    /**
1363     * Returns the type of the registered component.
1364     * If the component is not registered throws a DeploymentException
1365     * @param name name of the component
1366     * @return type DeployableObjectType of the registered component(app/module)
1367     */

1368    public static DeployableObjectType getRegisteredType(String JavaDoc name)
1369        throws DeploymentException {
1370        try{
1371            for(int i = 0; i< deployableObjectTypes.length; i++)
1372            {
1373                if (isRegistered(name, deployableObjectTypes[i])) {
1374                    return deployableObjectTypes[i];
1375                }
1376            }
1377        }catch(Exception JavaDoc e){
1378            throw new DeploymentException(e.getMessage());
1379        }
1380        String JavaDoc msg = localStrings.getString(
1381            "enterprise.deployment.component.not.registered", name);
1382        throw new DeploymentException(msg);
1383    }
1384
1385    static String JavaDoc getCreateOperationName(DeployableObjectType type)
1386        throws IASDeploymentException {
1387        if (type.isAPP()) {
1388            return CREATE_J2EE_APPLICATION;
1389        }
1390        else if(type.isEJB()) {
1391            return CREATE_EJB_MODULE;
1392        }
1393        else if(type.isWEB()) {
1394            return CREATE_WEB_MODULE;
1395        }
1396        else if(type.isCONN()) {
1397            return CREATE_CONNECTOR_MODULE;
1398        }
1399        else if(type.isCAR()) {
1400            return CREATE_APPCLIENT_MODULE;
1401        }
1402        else return null;
1403    }
1404
1405    static String JavaDoc getGetOperationName(DeployableObjectType type)
1406        throws IASDeploymentException {
1407        if (type.isAPP()) {
1408            return GET_J2EE_APPLICATION;
1409        }
1410        else if (type.isEJB()) {
1411            return GET_EJB_MODULE;
1412        }
1413        else if (type.isWEB()) {
1414            return GET_WEB_MODULE;
1415        }
1416        else if (type.isCONN()) {
1417            return GET_CONNECTOR_MODULE;
1418        }
1419        else if (type.isCAR()) {
1420            return GET_APPCLIENT_MODULE;
1421        }
1422        else return null;
1423    }
1424
1425    static String JavaDoc getRemoveOperationName(DeployableObjectType type)
1426        throws IASDeploymentException {
1427    if(type.isAPP()) {
1428        return REMOVE_J2EE_APPLICATION;
1429    }
1430    else if(type.isEJB()) {
1431        return REMOVE_EJB_MODULE;
1432    }
1433    else if(type.isWEB()) {
1434        return REMOVE_WEB_MODULE;
1435    }
1436    else if(type.isCONN()) {
1437        return REMOVE_CONNECTOR_MODULE;
1438    }
1439    else if(type.isCAR()) {
1440        return REMOVE_APPCLIENT_MODULE;
1441    }
1442    else return null;
1443    }
1444
1445    /**
1446     * This method should be removed once we remove the use of
1447     * DeployableObjectType.
1448     */

1449    public static DeployableObjectType getDeployableObjectType(ModuleType JavaDoc type) {
1450        if (ModuleType.EAR.equals(type)) {
1451            return DeployableObjectType.APP;
1452        } else if (ModuleType.EJB.equals(type)) {
1453            return DeployableObjectType.EJB;
1454        } else if (ModuleType.WAR.equals(type)) {
1455            return DeployableObjectType.WEB;
1456        } else if (ModuleType.CAR.equals(type)) {
1457            return DeployableObjectType.CAR;
1458        } else if (ModuleType.RAR.equals(type)) {
1459            return DeployableObjectType.CONN;
1460        }
1461        return null;
1462    }
1463
1464    /** string constants */
1465    private static final String JavaDoc CREATE_J2EE_APPLICATION =
1466        "createJ2eeApplication";
1467    private static final String JavaDoc CREATE_EJB_MODULE =
1468        "createEjbModule";
1469    private static final String JavaDoc CREATE_WEB_MODULE =
1470        "createWebModule";
1471    private static final String JavaDoc CREATE_CONNECTOR_MODULE =
1472        "createConnectorModule";
1473    private static final String JavaDoc CREATE_APPCLIENT_MODULE =
1474        "createAppclientModule";
1475    private static final String JavaDoc GET_J2EE_APPLICATION =
1476        "getJ2eeApplicationByName";
1477    private static final String JavaDoc GET_EJB_MODULE =
1478        "getEjbModuleByName";
1479    private static final String JavaDoc GET_WEB_MODULE =
1480        "getWebModuleByName";
1481    private static final String JavaDoc GET_CONNECTOR_MODULE =
1482        "getConnectorModuleByName";
1483    private static final String JavaDoc GET_APPCLIENT_MODULE =
1484        "getAppclientModuleByName";
1485    private static final String JavaDoc REMOVE_J2EE_APPLICATION =
1486        "removeJ2eeApplicationByName";
1487    private static final String JavaDoc REMOVE_EJB_MODULE =
1488        "removeEjbModuleByName";
1489    private static final String JavaDoc REMOVE_WEB_MODULE =
1490        "removeWebModuleByName";
1491    private static final String JavaDoc REMOVE_CONNECTOR_MODULE =
1492        "removeConnectorModuleByName";
1493    private static final String JavaDoc REMOVE_APPCLIENT_MODULE =
1494        "removeAppclientModuleByName";
1495
1496    private static final String JavaDoc appsConfigMBeanName =
1497        "com.sun.appserv:type=applications,category=config";
1498    private static final String JavaDoc SYSTEM_PREFIX = "system-";
1499 
1500    private static final String JavaDoc ADMIN_VS = "__asadmin";
1501
1502     // Attribue names for http listeners
1503
private static final String JavaDoc PORT = "port";
1504    private static final String JavaDoc DEF_VS = "default-virtual-server";
1505    private static final String JavaDoc SERVER_NAME = "server-name";
1506    private static final String JavaDoc REDIRECT_PORT = "redirect-port";
1507    private static final String JavaDoc SEC_ENABLED = "security-enabled";
1508    private static final String JavaDoc LISTENER_ENABLED = "enabled";
1509    private static final String JavaDoc OBJECT_TYPE = "object-type";
1510
1511    // Attribute names for virtual server
1512
private static final String JavaDoc HOSTS = "hosts";
1513    private static final String JavaDoc HTTP_LISTENERS = "http_listeners";
1514    private static final String JavaDoc DEFAULT_WEB_MODULE = "default_web_module";
1515    private static final String JavaDoc STATE = "state";
1516    private static final String JavaDoc ID = "id";
1517
1518    // resouces constants
1519
private static final String JavaDoc SUN_RESOURCE_XML = "sun-resources.xml";
1520    private static final String JavaDoc SUN_RESOURCE_XML_PATH =
1521        "META-INF" + File.separator + "sun-resources.xml";
1522
1523    private static final DeployableObjectType[] deployableObjectTypes =
1524        new DeployableObjectType[] { DeployableObjectType.APP,
1525        DeployableObjectType.EJB, DeployableObjectType.WEB,
1526        DeployableObjectType.CONN, DeployableObjectType.CAR };
1527
1528    private static String JavaDoc[] httpListenerAttrNames = {LISTENER_ENABLED,
1529            DEF_VS, SERVER_NAME, REDIRECT_PORT, PORT, SEC_ENABLED, ID };
1530
1531    private static String JavaDoc[] vsAttrNames = {HOSTS, HTTP_LISTENERS,
1532            DEFAULT_WEB_MODULE, STATE, ID};
1533
1534}
1535
Popular Tags