KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > ear > EarServiceImpl


1 /**
2  * JOnAS: Java(TM) Open Application Server
3  * Copyright (C) 1999-2005 Bull S.A.
4  * Contact: jonas-team@objectweb.org
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
19  * USA
20  *
21  * --------------------------------------------------------------------------
22  * $Id: EarServiceImpl.java,v 1.63 2005/07/27 11:14:43 benoitf Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.jonas.ear;
27
28 import java.io.File JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.net.MalformedURLException JavaDoc;
31 import java.net.URL JavaDoc;
32 import java.net.URLClassLoader JavaDoc;
33 import java.security.Policy JavaDoc;
34 import java.util.ArrayList JavaDoc;
35 import java.util.Date JavaDoc;
36 import java.util.Enumeration JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.util.Hashtable JavaDoc;
39 import java.util.Iterator JavaDoc;
40 import java.util.LinkedList JavaDoc;
41 import java.util.List JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.Set JavaDoc;
44 import java.util.StringTokenizer JavaDoc;
45 import java.util.Vector JavaDoc;
46
47 import javax.management.InstanceAlreadyExistsException JavaDoc;
48 import javax.management.MBeanRegistrationException JavaDoc;
49 import javax.management.MBeanServer JavaDoc;
50 import javax.management.NotCompliantMBeanException JavaDoc;
51 import javax.management.ObjectName JavaDoc;
52 import javax.management.modelmbean.ModelMBean JavaDoc;
53 import javax.naming.Context JavaDoc;
54 import javax.naming.NamingException JavaDoc;
55 import javax.security.jacc.PolicyConfiguration JavaDoc;
56 import javax.security.jacc.PolicyConfigurationFactory JavaDoc;
57 import javax.security.jacc.PolicyContextException JavaDoc;
58
59 import org.apache.commons.modeler.ManagedBean;
60 import org.apache.commons.modeler.Registry;
61 import org.objectweb.jonas.client.AppClientModule;
62 import org.objectweb.jonas.common.JModule;
63 import org.objectweb.jonas.common.JProp;
64 import org.objectweb.jonas.common.Log;
65 import org.objectweb.jonas.container.EJBService;
66 import org.objectweb.jonas.container.EJBServiceImpl;
67 import org.objectweb.jonas.ear.lib.EarClassPathManager;
68 import org.objectweb.jonas.ear.lib.EarClassPathManagerException;
69 import org.objectweb.jonas.ear.lib.JarList;
70 import org.objectweb.jonas.ear.lib.JarListException;
71 import org.objectweb.jonas.jmx.J2eeObjectName;
72 import org.objectweb.jonas.jmx.JmxService;
73 import org.objectweb.jonas.jmx.JonasObjectName;
74 import org.objectweb.jonas.management.JonasMBeanTools;
75 import org.objectweb.jonas.naming.CompNamingContext;
76 import org.objectweb.jonas.resource.ResourceService;
77 import org.objectweb.jonas.resource.ResourceServiceException;
78 import org.objectweb.jonas.security.jacc.JPolicyUserRoleMapping;
79 import org.objectweb.jonas.server.JClassLoader;
80 import org.objectweb.jonas.server.LoaderManager;
81 import org.objectweb.jonas.service.AbsServiceImpl;
82 import org.objectweb.jonas.service.ServiceException;
83 import org.objectweb.jonas.service.ServiceManager;
84 import org.objectweb.jonas.web.JWebContainerService;
85 import org.objectweb.jonas.web.JWebContainerServiceException;
86 import org.objectweb.jonas.ws.AbsWebServicesServiceImpl;
87 import org.objectweb.jonas.ws.WSServiceException;
88 import org.objectweb.jonas.ws.WebServicesService;
89 import org.objectweb.jonas_client.deployment.api.ClientContainerDeploymentDesc;
90 import org.objectweb.jonas_client.deployment.api.ClientContainerDeploymentDescException;
91 import org.objectweb.jonas_client.deployment.lib.wrapper.ClientManagerWrapper;
92 import org.objectweb.jonas_ear.deployment.api.EarDeploymentDesc;
93 import org.objectweb.jonas_ear.deployment.api.EarDeploymentDescException;
94 import org.objectweb.jonas_ear.deployment.lib.wrapper.EarManagerWrapper;
95 import org.objectweb.jonas_ear.deployment.xml.Web;
96
97 import org.objectweb.jonas_ejb.deployment.lib.wrapper.EjbManagerWrapper;
98 import org.objectweb.jonas_lib.deployment.work.CleanerException;
99 import org.objectweb.jonas_lib.deployment.work.DeployerLog;
100 import org.objectweb.jonas_lib.deployment.work.DeployerLogException;
101 import org.objectweb.jonas_lib.deployment.work.EarCleanTask;
102 import org.objectweb.jonas_lib.deployment.work.EarFileManager;
103 import org.objectweb.jonas_lib.deployment.work.FileManagerException;
104 import org.objectweb.jonas_lib.deployment.work.WorkCleaner;
105 import org.objectweb.jonas_lib.loader.ClientClassLoader;
106 import org.objectweb.jonas_lib.loader.EjbJarClassLoader;
107 import org.objectweb.jonas_web.deployment.lib.wrapper.WebManagerWrapper;
108 import org.objectweb.util.monolog.api.BasicLevel;
109 import org.objectweb.util.monolog.api.Logger;
110
111 /**
112  * JOnAS EAR Service Implementation class. This class provides an implementation
113  * of the ear service.
114  * @author Florent Benoit
115  * @author Ludovic Bert Contributor(s): Adriana Danes: highlight configuration
116  * properties Eric Hardesty: added ability to include rar files in an
117  * ear Michel-Ange Anton : new JSR77 MBean
118  */

119 public class EarServiceImpl extends AbsServiceImpl implements EarService, EarServiceImplMBean {
120
121     /**
122      * The name of the JONAS_BASE directory.
123      */

124     protected static final String JavaDoc JONAS_BASE = JProp.getJonasBase();
125
126     /**
127      * The name of the apps directory.
128      */

129     protected static final String JavaDoc APPS_DIR = JONAS_BASE + File.separator + "apps";
130
131     /**
132      * The name of the working directory.
133      */

134     protected static final String JavaDoc WORK_DIR = JProp.getWorkDir();
135
136     /**
137      * The name of the working apps directory.
138      */

139     protected static final String JavaDoc WORK_APPS_DIR = WORK_DIR + File.separator + "apps";
140
141     /**
142      * Property for ear to deploy at runtime
143      */

144     protected static final String JavaDoc DESCRIPTORS = "jonas.service.ear.descriptors";
145
146     /**
147      * Directories property for autoload
148      */

149     protected static final String JavaDoc AUTOLOADDIR = "jonas.service.ear.autoloaddir";
150
151     /**
152      * Property for parsing with validation or not
153      */

154     protected static final String JavaDoc PARSINGWITHVALIDATION = "jonas.service.ear.parsingwithvalidation";
155
156     /**
157      * Property for the class of the EAR service
158      */

159     protected static final String JavaDoc CLASS = "jonas.service.ear.class";
160
161     /**
162      * Logger for this service.
163      */

164     private static Logger logger = null;
165
166     /**
167      * Reference to the cleaner
168      */

169     private static WorkCleaner workCleaner = null;
170
171     /**
172      * Reference to a MBean server.
173      */

174     private MBeanServer JavaDoc mbeanServer = null;
175
176     /**
177      * List of the ear names to load when starting the EarService
178      */

179     private Vector JavaDoc earNames = new Vector JavaDoc();
180
181     /**
182      * Reference to the Ejb service.
183      */

184     private EJBService ejbService = null;
185
186     /**
187      * Reference to the WebContainer service.
188      */

189     private JWebContainerService webContainerService = null;
190
191     /**
192      * Reference to the WebServices service.
193      */

194     private WebServicesService wsService = null;
195
196     /**
197      * Reference to the Resource service.
198      */

199     private ResourceService resourceService = null;
200
201     /**
202      * List of loaded ear
203      */

204     private Hashtable JavaDoc ears = null;
205
206     /**
207      * List of autoloaded directories.
208      */

209     private ArrayList JavaDoc autoloadDirectories = new ArrayList JavaDoc();
210
211     /**
212      * Reference on the DeployerLog which is the class that manage the
213      * accesses to the log file (to remove the ear).
214      */

215     private DeployerLog earDeployerLog = null;
216
217     /**
218      * Application Classloader
219      */

220     private ClassLoader JavaDoc appsClassLoader;
221
222     /**
223      * Init the EAR service.
224      * @param ctx the configuration of the Ear service.
225      * @throws ServiceException if the initialization failed.
226      */

227     protected void doInit(Context JavaDoc ctx) throws ServiceException {
228
229         //we init the logger
230
logger = Log.getLogger(Log.JONAS_EAR_PREFIX);
231
232         // get apps ClassLoader
233
try {
234             LoaderManager lm = LoaderManager.getInstance();
235             appsClassLoader = lm.getAppsLoader();
236         } catch (Exception JavaDoc e) {
237             logger.log(BasicLevel.ERROR, "Cannot get the Applications ClassLoader from EAR Container Service: " + e);
238             throw new ServiceException("Cannot get the Applications ClassLoader from EAR Container Service", e);
239         }
240
241         ServiceManager sm = null;
242
243         try {
244             sm = ServiceManager.getInstance();
245         } catch (Exception JavaDoc e) {
246             String JavaDoc err = "Cannot get ServiceManager instance";
247             logger.log(BasicLevel.ERROR, err);
248             throw new ServiceException(err, e);
249         }
250
251         // Get the JMX Server via JMX Service
252
try {
253             mbeanServer = ((JmxService) sm.getJmxService()).getJmxServer();
254         } catch (ServiceException e) {
255             // the JMX service may not be started
256
mbeanServer = null;
257         }
258
259         // Get the EJB service
260
try {
261             ejbService = (EJBService) sm.getEjbService();
262         } catch (ServiceException e) {
263             //not started
264
ejbService = null;
265         }
266
267         // Get the Web Container service
268
try {
269             webContainerService = (JWebContainerService) sm.getWebContainerService();
270         } catch (ServiceException e) {
271             //not started
272
webContainerService = null;
273         }
274
275         // Get the WebServices service
276
try {
277             wsService = (WebServicesService) sm.getWebServicesService();
278         } catch (ServiceException e) {
279             //not started
280
wsService = null;
281         }
282
283         // Get the Resource service
284
try {
285             resourceService = (ResourceService) sm.getResourceService();
286         } catch (ServiceException e) {
287             //not started
288
resourceService = null;
289         }
290
291         // Set the XML parsing mode to no validation
292
String JavaDoc parsingMode = "false";
293         try {
294             parsingMode = (String JavaDoc) ctx.lookup(PARSINGWITHVALIDATION);
295         } catch (NamingException JavaDoc e) {
296             /*
297              * No problem if there is no value for 'parsingwithvalidation'
298              * (false by default)
299              */

300             if (logger.isLoggable(BasicLevel.DEBUG)) {
301                 logger.log(BasicLevel.DEBUG, "No XML parsing validation property, use default");
302             }
303         }
304         EarManagerWrapper.setParsingWithValidation("true".equalsIgnoreCase(parsingMode));
305         if ("false".equalsIgnoreCase(parsingMode)) {
306             if (logger.isLoggable(BasicLevel.DEBUG)) {
307                 logger.log(BasicLevel.DEBUG, "Ear XML parsing without validation");
308             }
309         } else {
310             if (logger.isLoggable(BasicLevel.DEBUG)) {
311                 logger.log(BasicLevel.DEBUG, "Ear XML parsing with validation");
312             }
313         }
314
315         // Init the ear names to be loaded when starting
316
String JavaDoc descsValue = null;
317         try {
318             descsValue = (String JavaDoc) ctx.lookup(DESCRIPTORS);
319         } catch (NamingException JavaDoc e) {
320             if (logger.isLoggable(BasicLevel.DEBUG)) {
321                 logger.log(BasicLevel.DEBUG, "No property DESCRIPTORS");
322             }
323             // No problem if there is no value for 'descriptors'
324
//(no ear to load)
325
}
326         if (descsValue != null) {
327             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(descsValue, ",");
328             while (st.hasMoreTokens()) {
329                 String JavaDoc fileName = st.nextToken().trim();
330                 earNames.add(fileName);
331             }
332         }
333
334         // Add the ears of the jonas.service.ear.autoloaddir property
335
String JavaDoc dirValue = null;
336         ArrayList JavaDoc autoDirs = new ArrayList JavaDoc();
337         try {
338             dirValue = (String JavaDoc) ctx.lookup(AUTOLOADDIR);
339         } catch (NamingException JavaDoc e) {
340             if (logger.isLoggable(BasicLevel.DEBUG)) {
341                 logger.log(BasicLevel.DEBUG, "No AUTOLOADDIR property");
342             }
343             // No problem if there is no value for 'autoloaddir'
344
//(no ear to load)
345
}
346         if (dirValue != null) {
347             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(dirValue, ",");
348             while (st.hasMoreTokens()) {
349                 String JavaDoc dirName = st.nextToken().trim();
350                 addEars(dirName);
351                 autoDirs.add(dirName);
352             }
353         }
354         // Build autoload directories
355
File JavaDoc oFile;
356         Iterator JavaDoc it = autoDirs.iterator();
357         while (it.hasNext()) {
358             String JavaDoc dirName = (String JavaDoc) it.next();
359             try {
360                 oFile = new File JavaDoc(APPS_DIR, dirName);
361                 if (!oFile.exists()) {
362                     oFile = new File JavaDoc(dirName);
363                 }
364                 if (oFile.exists()) {
365                     autoloadDirectories.add(oFile.getCanonicalPath());
366                 }
367             } catch (Exception JavaDoc e) {
368                 String JavaDoc err = "Error when trying to verify Application EAR autoload directory : " + dirName;
369                 logger.log(BasicLevel.ERROR, err, e);
370             }
371         }
372
373         //create hashtable of the ears ( Url of an ear ---> Ear structure)
374
ears = new Hashtable JavaDoc();
375
376         // Init the rar deployment desc manager.
377
//rarDDManager = RarDeploymentDescManager.getInstance();
378
}
379
380     /**
381      * Stop the EAR service.
382      * @throws ServiceException if the stop failed.
383      */

384     protected void doStop() throws ServiceException {
385
386         //undeploy the loaded ears files
387
URL JavaDoc earFileName = null;
388         //For each ear file, we delegate the operation to the
389
//unDeployEar method
390
for (Enumeration JavaDoc earEntries = ears.keys(); earEntries.hasMoreElements();) {
391             earFileName = (URL JavaDoc) earEntries.nextElement();
392             //Try to undeploy the ear
393
try {
394                 Context JavaDoc ctx = new CompNamingContext(earFileName.getFile());
395                 ctx.rebind("filename", earFileName);
396                 unDeployEar(ctx);
397             } catch (Exception JavaDoc e) {
398                 //We don't stop the process of undeploying the ears.
399
//We only display an error in the logger.
400
String JavaDoc err = "Error when undeploying the ear :" + earFileName;
401                 logger.log(BasicLevel.ERROR, err, e);
402             }
403         }
404
405         if (mbeanServer != null) {
406             try {
407                 // unregister EarService MBean : EarServiceImplMBean
408
mbeanServer.unregisterMBean(JonasObjectName.earService());
409             } catch (Exception JavaDoc e) {
410                 logger.log(BasicLevel.ERROR, "Cannot stop the EarService", e);
411             }
412         }
413
414         //The service is stopped
415
if (logger.isLoggable(BasicLevel.DEBUG)) {
416             logger.log(BasicLevel.DEBUG, "EarService stopped");
417         }
418
419     }
420
421     /**
422      * Deploy an EAR file with sending JAR file to the EJB container and WAR
423      * file to the WEB container and RAR file to the resource service.
424      * @param ctx the context which contains the configuration in order to
425      * deploy an EAR.
426      * @return The ObjectName of the J2EE Application MBean associated to the
427      * deployed EAR the Application Container
428      * @throws EarServiceException if the deployment of the EAR failed.
429      */

430     public String JavaDoc deployEar(Context JavaDoc ctx) throws EarServiceException {
431
432         //We have one of the ejb or web services launched
433
if ((webContainerService == null) && (ejbService == null)) {
434             throw new EarServiceException(
435                     "The ear service requires that at least the service ejb or web is launched for deploying an ear file.");
436         }
437
438         //We get the fileName
439
// Get the file name and check if file exists
440
String JavaDoc fileName;
441         try {
442             fileName = (String JavaDoc) ctx.lookup("filename");
443         } catch (NamingException JavaDoc e) {
444             throw new EarServiceException("Error during performing lookup a fileName", e);
445         }
446
447         File JavaDoc f = null;
448         try {
449             //We search the file
450
f = new File JavaDoc(fileName).getCanonicalFile();
451
452             if (!f.exists()) {
453                 boolean found = false;
454                 String JavaDoc earFileName = null;
455                 if (fileName.toLowerCase().endsWith(".ear")) {
456                     // In case of the name is a ear file name, check also in
457
// the JONAS_BASE/apps directory
458
earFileName = APPS_DIR + File.separator + fileName;
459                     f = new File JavaDoc(earFileName).getCanonicalFile();
460                     found = f.exists();
461                 }
462                 if (found) {
463                     fileName = earFileName;
464                 } else {
465                     String JavaDoc err = "deployEar: The file " + fileName
466                             + " was not found neither in the current directory nor in the " + APPS_DIR + " directory";
467                     logger.log(BasicLevel.ERROR, err);
468                     throw new EarServiceException(err);
469                 }
470             }
471         } catch (IOException JavaDoc e) {
472             String JavaDoc err = "Error when trying to get the canonical file from " + fileName;
473             logger.log(BasicLevel.ERROR, err + " " + e.getMessage());
474             throw new EarServiceException(err, e);
475         }
476
477         //Make the url for the specified fileName and the earRootUrl
478
URL JavaDoc[] earUrl = new URL JavaDoc[1];
479         URL JavaDoc earRootUrl = null;
480
481         try {
482             earUrl[0] = f.toURL();
483             earRootUrl = (new File JavaDoc(WORK_APPS_DIR + File.separator + getJonasServerName())).toURL();
484         } catch (MalformedURLException JavaDoc e) {
485             String JavaDoc err = "Invalid ear file name '" + fileName;
486             logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
487             throw new EarServiceException(err, e);
488         }
489
490         //Check if the ear is already deployed or not
491
if (ears.get(earUrl[0]) != null) {
492             String JavaDoc err = "The ear file : " + f.getName() + " is already deployed ('" + earUrl[0].getFile()
493                     + "'). You must undeploy the application " + "before a new deployment.";
494             logger.log(BasicLevel.ERROR, err);
495             throw new EarServiceException(err);
496         }
497
498         //Create classLoader
499
//parent classloader is the current classloader
500
URLClassLoader JavaDoc loaderCls = new URLClassLoader JavaDoc(earUrl, appsClassLoader);
501
502         EarDeploymentDesc earDD = null;
503         if (logger.isLoggable(BasicLevel.DEBUG)) {
504             logger.log(BasicLevel.DEBUG, "Getting the deployment descriptor of the file" + f.getName());
505         }
506         try {
507             earDD = EarManagerWrapper.getDeploymentDesc(earUrl[0].getFile(), loaderCls);
508         } catch (EarDeploymentDescException e) {
509             String JavaDoc err = "Error in the Deployment descriptor '" + fileName + "': " + e;
510             logger.log(BasicLevel.ERROR, err);
511             throw new EarServiceException(err, e);
512         }
513
514         //We get the tags from the Deployment descriptor
515
Web[] webTags = earDD.getWebTags();
516         String JavaDoc[] ejbTags = earDD.getEjbTags();
517         String JavaDoc[] connectorTags = earDD.getConnectorTags();
518         String JavaDoc[] clientTags = earDD.getClientTags();
519         String JavaDoc[] altDDClients = earDD.getAltDDClients();
520         String JavaDoc[] altDDEjbs = earDD.getAltDDEjbs();
521         String JavaDoc[] altDDWebs = earDD.getAltDDWebs();
522         String JavaDoc[] altDDConnectors = earDD.getAltDDConnectors();
523         String JavaDoc[] securityRoles = earDD.getSecurityRolesNames();
524
525         //Check if all modules are inside the EAR file
526
//no relatives mode like ../../file1.jar
527

528         File JavaDoc fEar = new File JavaDoc(earUrl[0].getFile());
529         File JavaDoc tmpFile = null;
530
531         try {
532             File JavaDoc fCanonicEar = fEar.getCanonicalFile();
533             for (int i = 0; i < ejbTags.length; i++) {
534                 tmpFile = new File JavaDoc(fEar, ejbTags[i]);
535                 tmpFile = tmpFile.getCanonicalFile();
536                 if (!tmpFile.getPath().startsWith(fCanonicEar.getPath())) {
537                     String JavaDoc err = "Error : The ejb-jar file " + ejbTags[i] + " is not inside the ear file " + fEar;
538                     logger.log(BasicLevel.ERROR, err);
539                     throw new EarServiceException(err);
540                 }
541             }
542
543             for (int i = 0; i < webTags.length; i++) {
544                 tmpFile = new File JavaDoc(fEar, webTags[i].getWebUri());
545                 tmpFile = tmpFile.getCanonicalFile();
546                 if (!tmpFile.getPath().startsWith(fCanonicEar.getPath())) {
547                     String JavaDoc err = "Error : The war file " + webTags[i].getWebUri() + " is not inside the ear file "
548                             + fEar;
549                     logger.log(BasicLevel.ERROR, err);
550                     throw new EarServiceException(err);
551                 }
552             }
553
554             for (int i = 0; i < connectorTags.length; i++) {
555                 tmpFile = new File JavaDoc(fEar, connectorTags[i]);
556                 tmpFile = tmpFile.getCanonicalFile();
557                 if (!tmpFile.getPath().startsWith(fCanonicEar.getPath())) {
558                     String JavaDoc err = "Error : The rar file " + connectorTags[i] + " is not inside the ear file " + fEar;
559                     logger.log(BasicLevel.ERROR, err);
560                     throw new EarServiceException(err);
561                 }
562             }
563
564
565             for (int i = 0; i < clientTags.length; i++) {
566                 tmpFile = new File JavaDoc(fEar, clientTags[i]);
567                 tmpFile = tmpFile.getCanonicalFile();
568
569                 if (!tmpFile.getPath().startsWith(fCanonicEar.getPath())) {
570                     String JavaDoc err = "Error : The client jar file " + clientTags[i] + " is not inside the ear file " + fEar;
571                     throw new EarServiceException(err);
572                 }
573             }
574         } catch (IOException JavaDoc ioe) {
575             String JavaDoc err = "Error while trying to get the canonical file of " + tmpFile;
576             logger.log(BasicLevel.ERROR, err + " : " + ioe.getMessage());
577             throw new EarServiceException(err, ioe);
578         }
579
580         //Changing array into JarList
581
JarList ejbsList = new JarList(ejbTags);
582         JarList warsList = new JarList(webTags);
583         JarList connectorsList = new JarList(connectorTags);
584         JarList clientsList = new JarList(clientTags);
585
586         //Unpack the ear file and get the unpacked dir
587
URL JavaDoc dirUnpackURL = null;
588         try {
589             dirUnpackURL = EarFileManager.unpackEar(earUrl[0], earRootUrl);
590         } catch (FileManagerException e) {
591             String JavaDoc err = "Error while unpacking the file '" + earUrl[0] + "'";
592             logger.log(BasicLevel.ERROR, err + " : " + e.getMessage());
593             throw new EarServiceException(err, e);
594         }
595
596         //the file is unpacked. Log it only if the ear is a file and not a
597
// directory
598
if (new File JavaDoc(earUrl[0].getFile()).isFile()) {
599             try {
600                 earDeployerLog.addEntry(new File JavaDoc(earUrl[0].getFile()), new File JavaDoc(dirUnpackURL.getFile()));
601             } catch (DeployerLogException e) {
602                 String JavaDoc err = "Error while adding the " + earUrl[0] + " entry in the log file";
603                 logger.log(BasicLevel.ERROR, err + " : " + e.getMessage());
604                 throw new EarServiceException(err, e);
605             }
606         }
607
608         //We have successfully unpacked the ear file, now we analyze manifest
609
// Class-path:
610
EarClassPathManager earCPManager = null;
611         try {
612             earCPManager = new EarClassPathManager(ejbsList, warsList, dirUnpackURL);
613         } catch (EarClassPathManagerException e) {
614             String JavaDoc err = "Error while creating the Ear class path manager of the ear : '" + earUrl[0] + "'";
615             logger.log(BasicLevel.ERROR, err + " : " + e.getMessage());
616             throw new EarServiceException(err, e);
617         }
618
619         URL JavaDoc[] classpathURLs = null;
620         //Get the urls of the ear class path manager
621
try {
622             classpathURLs = earCPManager.getResolvedClassPath();
623         } catch (EarClassPathManagerException e) {
624             String JavaDoc err = "Error while trying to resolve the classpath of the ejbjars and wars of the ear : '"
625                     + earUrl[0] + "'";
626             logger.log(BasicLevel.ERROR, err + " : " + e.getMessage());
627             throw new EarServiceException(err, e);
628         }
629
630         /*
631          * We have the urls to load at our level We can now create our
632          * classLoader
633          */

634         if (logger.isLoggable(BasicLevel.DEBUG)) {
635             logger.log(BasicLevel.DEBUG, "Creating the EAR classLoader");
636         }
637         JClassLoader earClassLoader = new JClassLoader(earUrl[0].toExternalForm() , new URL JavaDoc[0], appsClassLoader);
638
639         //Extract the urls of the jarList
640
URL JavaDoc[] jarUrls = null;
641         URL JavaDoc[] warUrls = null;
642         URL JavaDoc[] connectorUrls = null;
643         URL JavaDoc[] clientUrls = null;
644         try {
645             jarUrls = ejbsList.getURLs(dirUnpackURL.toExternalForm());
646             warUrls = warsList.getURLs(dirUnpackURL.toExternalForm());
647             connectorUrls = connectorsList.getURLs(dirUnpackURL.toExternalForm());
648             clientUrls = clientsList.getURLs(dirUnpackURL.toExternalForm());
649         } catch (JarListException e) {
650             String JavaDoc err = "Error while geting the Urls from jarlist of the ear : '" + earUrl[0] + "'";
651             logger.log(BasicLevel.ERROR, err + " : " + e.getMessage());
652             throw new EarServiceException(err, e);
653         }
654
655         //Extract context roots for wars
656
//They are in webTags. Dump into warsContextRoots
657
String JavaDoc[] warsContextRoots = new String JavaDoc[webTags.length];
658         String JavaDoc ctxRoot = null;
659         for (int i = 0; i < webTags.length; i++) {
660             ctxRoot = webTags[i].getContextRoot();
661             if (ctxRoot != null) {
662                 warsContextRoots[i] = ctxRoot;
663             }
664         }
665
666         //Fill Alt-DD for Ejbs and Wars and Rars
667
String JavaDoc altdd = null;
668         File JavaDoc fAltDD = null;
669
670         //Transorm the array altDDWebs into an array with the absolute URL to
671
// the file
672
URL JavaDoc[] warsAltDDs = new URL JavaDoc[altDDWebs.length];
673         for (int i = 0; i < altDDWebs.length; i++) {
674             if (altDDWebs[i] != null) {
675                 altdd = altDDWebs[i];
676                 if (altdd != null) {
677                     try {
678                         fAltDD = new File JavaDoc(new URL JavaDoc(dirUnpackURL.toExternalForm() + File.separator + altdd).getFile());
679                         warsAltDDs[i] = fAltDD.getCanonicalFile().toURL();
680                     } catch (MalformedURLException JavaDoc e) {
681                         String JavaDoc err = "Can't build URL for alt-dd '" + altdd;
682                         logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
683                         throw new EarServiceException(err, e);
684                     } catch (IOException JavaDoc ioe) {
685                         String JavaDoc err = "Can't get canonicalFile() for the file '" + fAltDD;
686                         logger.log(BasicLevel.ERROR, err + "': " + ioe.getMessage());
687                         throw new EarServiceException(err, ioe);
688                     }
689                 }
690             }
691         }
692
693         URL JavaDoc[] ejbsAltDDs = new URL JavaDoc[altDDEjbs.length];
694         for (int i = 0; i < altDDEjbs.length; i++) {
695             if (altDDEjbs[i] != null) {
696                 altdd = altDDEjbs[i];
697                 if (altdd != null) {
698                     try {
699                         fAltDD = new File JavaDoc(new URL JavaDoc(dirUnpackURL.toExternalForm() + File.separator + altdd).getFile());
700                         ejbsAltDDs[i] = fAltDD.getCanonicalFile().toURL();
701                     } catch (MalformedURLException JavaDoc e) {
702                         String JavaDoc err = "Can't build URL for alt-dd '" + altdd;
703                         logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
704                         throw new EarServiceException(err, e);
705                     } catch (IOException JavaDoc ioe) {
706                         String JavaDoc err = "Can't get canonicalFile() for the file '" + fAltDD;
707                         logger.log(BasicLevel.ERROR, err + "': " + ioe.getMessage());
708                         throw new EarServiceException(err, ioe);
709                     }
710                 }
711             }
712         }
713
714         URL JavaDoc[] connectorsAltDDs = new URL JavaDoc[altDDConnectors.length];
715         for (int i = 0; i < altDDConnectors.length; i++) {
716             if (altDDConnectors[i] != null) {
717                 altdd = altDDConnectors[i];
718                 if (altdd != null) {
719                     try {
720                         fAltDD = new File JavaDoc(new URL JavaDoc(dirUnpackURL.toExternalForm() + File.separator + altdd).getFile());
721                         connectorsAltDDs[i] = fAltDD.getCanonicalFile().toURL();
722                     } catch (MalformedURLException JavaDoc e) {
723                         String JavaDoc err = "Can't build URL for alt-dd '" + altdd;
724                         logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
725                         throw new EarServiceException(err, e);
726                     } catch (IOException JavaDoc ioe) {
727                         String JavaDoc err = "Can't get canonicalFile() for the file '" + fAltDD;
728                         logger.log(BasicLevel.ERROR, err + "': " + ioe.getMessage());
729                         throw new EarServiceException(err, ioe);
730                     }
731                 }
732             }
733         }
734
735         URL JavaDoc[] clientAltDDs = new URL JavaDoc[altDDClients.length];
736         for (int i = 0; i < altDDClients.length; i++) {
737             if (altDDClients[i] != null) {
738                 altdd = altDDClients[i];
739                 if (altdd != null) {
740                     try {
741                         fAltDD = new File JavaDoc(new URL JavaDoc(dirUnpackURL.toExternalForm() + File.separator + altdd).getFile());
742                         clientAltDDs[i] = fAltDD.getCanonicalFile().toURL();
743                     } catch (MalformedURLException JavaDoc e) {
744                         String JavaDoc err = "Can't build URL for alt-dd '" + altdd;
745                         logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
746                         throw new EarServiceException(err, e);
747                     } catch (IOException JavaDoc ioe) {
748                         String JavaDoc err = "Can't get canonicalFile() for the file '" + fAltDD;
749                         logger.log(BasicLevel.ERROR, err + "': " + ioe.getMessage());
750                         throw new EarServiceException(err, ioe);
751                     }
752                 }
753             }
754         }
755         //Extract roles name from the securityRole array
756
String JavaDoc[] roleNames = new String JavaDoc[securityRoles.length];
757         String JavaDoc affRoleNames = "";
758         for (int i = 0; i < securityRoles.length; i++) {
759             roleNames[i] = securityRoles[i];
760             affRoleNames += roleNames[i] + ";";
761         }
762
763         if (logger.isLoggable(BasicLevel.DEBUG)) {
764             logger.log(BasicLevel.DEBUG, "role names = " + affRoleNames);
765         }
766
767         /**
768          * Now this is the deployment step with sending
769          * + rars to the rar service
770          * + jars to the ejb service
771          * + wars to the web container service
772          * + jars and wars to web services service
773          */

774
775         /**
776          * Check that GenIC was applied on ejb-jar prior to sending them to EJB service.
777          * As classloader is defined in this service, classes after will not be taken
778          * into account. So GenIC should be called before creating Classloader.
779          */

780         if (jarUrls.length > 0 && ejbService != null) {
781             // Check GenIC :
782
for (int i = 0; i < jarUrls.length; i++) {
783                 ejbService.checkGenIC(jarUrls[i].getFile());
784             }
785         }
786
787
788
789         /**
790          * Ejb ClassLoader is needed for WebServices deployment so We create it
791          * in advance ...
792          */

793         // Set the list of the ejb-jar, war and clients that can do an ejb-link in this
794
// ear application. This array can be empty.
795
// The alternate urls are given
796
EjbManagerWrapper.setAvailableEjbJarsAndAltDDs(earClassLoader, jarUrls, ejbsAltDDs);
797         WebManagerWrapper.setAltDD(earClassLoader, warUrls, warsAltDDs);
798         ClientManagerWrapper.setAltDD(earClassLoader, clientUrls, clientAltDDs);
799
800         // Construct the ejb classloader for all the ejb-jars of the same
801
// ear application. Because there is one ejb classloader for all
802
// the ejb-jars of the same ear application.
803
URL JavaDoc[] urls = new URL JavaDoc[jarUrls.length + classpathURLs.length];
804         System.arraycopy(jarUrls, 0, urls, 0, jarUrls.length);
805         System.arraycopy(classpathURLs, 0, urls, jarUrls.length, classpathURLs.length);
806         URLClassLoader JavaDoc ejbClassLoader;
807         try {
808             ejbClassLoader = new EjbJarClassLoader(urls, earClassLoader);
809         } catch (IOException JavaDoc ioe) {
810             String JavaDoc err = "Cannot Create EJB ClassLoader for EAR '" + fileName + "'";
811             logger.log(BasicLevel.ERROR, err + " : " + ioe.getMessage());
812             throw new EarServiceException(err, ioe);
813         }
814
815         // Set the list of the rars that can be referenced in this
816
// ear application. This array can be empty.
817
// The alternate urls are given
818

819         //rarDDManager.setAvailableRarsAndAltDDs(earClassLoader, connectorUrls,
820
// connectorsAltDDs);
821

822         //Only if the connectorUrls is not empty
823
//And if the service is started
824
if (resourceService != null && (connectorUrls.length > 0)) {
825             try {
826                 CompNamingContext contctx = null;
827                 try {
828                     contctx = new CompNamingContext(dirUnpackURL.getFile());
829                     contctx.rebind("earUrl", earUrl[0]);
830                     contctx.rebind("urls", connectorUrls);
831                     contctx.rebind("earClassLoader", earClassLoader);
832                     contctx.rebind("altDDs", connectorsAltDDs);
833                 } catch (NamingException JavaDoc e) {
834                     String JavaDoc err = "Can not bind params for the resource service, Can't deploy rars ";
835                     throw new ResourceServiceException(err, e);
836                 }
837                 resourceService.deployRars(contctx);
838             } catch (ServiceException e) {
839                 String JavaDoc err = "Error during the deployment of the rars files of the Ear file " + fileName;
840                 logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
841                 //remove DDesc
842
//resourceService.removeCache(earClassLoader);
843
throw new EarServiceException(err, e);
844             }
845         }
846
847         // Only if the WebServicesService is started
848
if (wsService != null) {
849             try {
850                 Hashtable JavaDoc ctxRoots = new Hashtable JavaDoc();
851                 for (int w = 0; w < webTags.length; w++) {
852                     ctxRoots.put(warUrls[w], webTags[w].getContextRoot());
853                 }
854                 CompNamingContext contctx = null;
855                 try {
856                     contctx = new CompNamingContext(dirUnpackURL.getFile());
857                     contctx.rebind("unpackDir", dirUnpackURL.toExternalForm());
858                     contctx.rebind("jarUrls", jarUrls);
859                     contctx.rebind("warUrls", warUrls);
860                     contctx.rebind("earURL", earUrl[0]);
861                     contctx.rebind("ejbClassLoader", ejbClassLoader);
862                     contctx.rebind("earClassLoader", earClassLoader);
863                     contctx.rebind("warCtxRootMapping", ctxRoots);
864                 } catch (NamingException JavaDoc e) {
865                     String JavaDoc err = "Cannot bind params for the WebServices service, Can't deploy Web Services Endpoints ";
866                     throw new WSServiceException(err, e);
867                 }
868                 wsService.deployWebServices(contctx);
869             } catch (ServiceException se) {
870                 String JavaDoc err = "Error during the deployment of the WebServices of the Ear file " + fileName;
871                 logger.log(BasicLevel.ERROR, err + " : " + se.getMessage());
872                 wsService.removeCache(earClassLoader);
873                 try {
874                     if (logger.isLoggable(BasicLevel.DEBUG)) {
875                         logger.log(BasicLevel.DEBUG, "Undeploying Rars of the ear " + fileName);
876                     }
877                     if (resourceService != null && connectorUrls.length > 0) {
878                         // remove Resource
879
resourceService.unDeployRars(connectorUrls, earUrl[0]);
880                     }
881                 } catch (ServiceException se2) {
882                     err = "Error during the undeployment of the rars files of the Ear file " + fileName;
883                     logger.log(BasicLevel.ERROR, err + "': " + se2.getMessage());
884                 }
885
886                 throw new EarServiceException(err, se);
887             }
888         }
889
890         // ejbClassLoader created above
891

892         //Only if the jarUrls is not empty
893
//And if the service is started
894
if (ejbService != null && (jarUrls.length > 0)) {
895             try {
896                 CompNamingContext contctx = null;
897                 try {
898                     contctx = new CompNamingContext(dirUnpackURL.getFile());
899                     contctx.rebind("earRootUrl", dirUnpackURL);
900                     contctx.rebind("earUrl", earUrl[0]);
901                     contctx.rebind("jarURLs", jarUrls);
902                     contctx.rebind("earClassLoader", earClassLoader);
903                     contctx.rebind("ejbClassLoader", ejbClassLoader);
904                     contctx.rebind("roleNames", roleNames);
905                 } catch (NamingException JavaDoc e) {
906                     String JavaDoc err = "Can not bind params for the ejb service, Can't deploy jars ";
907                     throw new EarServiceException(err, e);
908                 }
909                 ejbService.deployJars(contctx);
910             } catch (ServiceException e) {
911                 String JavaDoc err = "Error during the deployment of the jars files of the Ear file " + fileName;
912                 logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
913                 //remove DDesc
914
ejbService.removeCache(earClassLoader);
915                 // Remove the deployed rars
916
if (resourceService != null && connectorUrls.length > 0) {
917                     // remove Resource
918
resourceService.unDeployRars(connectorUrls, earUrl[0]);
919                 }
920                 throw new EarServiceException(err, e);
921             }
922         }
923
924         /*
925          * We have deploy the ejb-jar files if the service is active And we have
926          * the ejbClassLoader
927          */

928
929         /*
930          * We're going to deploy wars Parent ClassLoader for web container is
931          * ejbclassloader if ejbService is active, and a classloader with the
932          * visibility of jar file if ejbservice is not active.
933          */

934
935         ClassLoader JavaDoc parentWarClassLoader = ejbClassLoader;
936
937         //Only if the warUrls is not empty
938
//And if the service is started
939
if (webContainerService != null && (warUrls.length > 0)) {
940             try {
941                 CompNamingContext contctx = null;
942                 try {
943                     contctx = new CompNamingContext(dirUnpackURL.getFile());
944                     contctx.rebind("earURL", earUrl[0]);
945                     contctx.rebind("urls", warUrls);
946                     contctx.rebind("parentClassLoader", parentWarClassLoader);
947                     contctx.rebind("earClassLoader", earClassLoader);
948                     contctx.rebind("altDDs", warsAltDDs);
949                     contctx.rebind("contextRoots", warsContextRoots);
950                 } catch (NamingException JavaDoc e) {
951                     String JavaDoc err = "Can not bind params for the web container service, Can't deploy wars ";
952                     throw new EarServiceException(err, e);
953                 }
954                 webContainerService.deployWars(contctx);
955
956             } catch (JWebContainerServiceException e) {
957                 String JavaDoc err = "Error during the deployment of the wars file of the Ear file " + fileName;
958                 logger.log(BasicLevel.ERROR, err + "': " + e.getMessage());
959                 //remove DDesc
960
webContainerService.removeCache(earClassLoader);
961                 err = "Undeploy the jars loaded from this ear";
962                 if (logger.isLoggable(BasicLevel.DEBUG)) {
963                     logger.log(BasicLevel.DEBUG, err);
964                 }
965                 try {
966                     if (ejbService != null && (jarUrls.length > 0)) {
967                         //remove DDesc
968
ejbService.removeCache(earClassLoader);
969                         //remove the ejbs
970
ejbService.unDeployJars(jarUrls);
971                     }
972                     // Remove the deployed rars
973
if (resourceService != null && connectorUrls.length > 0) {
974                         // remove Resource
975
resourceService.unDeployRars(connectorUrls, earUrl[0]);
976                     }
977                 } catch (ServiceException se) {
978                     err = "Error during the undeployment of the jars file of the Ear file " + fileName;
979                     logger.log(BasicLevel.ERROR, err + "': " + se.getMessage());
980                     throw new EarServiceException(err, e);
981                 }
982
983                 throw new EarServiceException(err, e);
984             }
985         }
986
987         // Link the JACC policy configuration objects of EJB and WebApp together and commit them to be available.
988
linkPolicyObjects(earDD.getUserToRoleMapping(), jarUrls, warUrls);
989
990         if (logger.isLoggable(BasicLevel.DEBUG)) {
991             logger.log(BasicLevel.DEBUG, "We store the rars/wars/jars associated to the url :" + earUrl[0]);
992         }
993
994         // Complete the Deployment of the WebServices
995
// Only if the WebServicesService is started
996
if (wsService != null) {
997             try {
998                 CompNamingContext contctx = null;
999                 try {
1000                    contctx = new CompNamingContext(earRootUrl.getFile());
1001                    contctx.rebind(AbsWebServicesServiceImpl.CLASSLOADER_CTX_PARAM, earClassLoader);
1002                    ObjectName JavaDoc name = J2eeObjectName.J2EEApplication(getDomainName(), getJonasServerName(), buildJ2eeApplicationName(earUrl[0]));
1003                    contctx.rebind(WebServicesService.PARENT_OBJECTNAME_CTX_PARAM , name);
1004                    contctx.rebind(WebServicesService.ISINEAR_CTX_PARAM, Boolean.TRUE);
1005
1006                } catch (NamingException JavaDoc e) {
1007                    String JavaDoc err = "Can not bind params for the WebServices service, "
1008                            + "can't complete deployment of Web Services Endpoints";
1009                    throw new JWebContainerServiceException(err, e);
1010                }
1011                wsService.completeWSDeployment(contctx);
1012            } catch (ServiceException se) {
1013                String JavaDoc err = "Error during the deployment of the WebServices of the Ear file '" + earRootUrl + "'";
1014                logger.log(BasicLevel.ERROR, err + " : " + se.getMessage());
1015                try {
1016                    if (logger.isLoggable(BasicLevel.DEBUG)) {
1017                        logger.log(BasicLevel.DEBUG, "Undeploy the WebApps loaded from this ear");
1018                    }
1019                    if (webContainerService != null && (warUrls.length > 0)) {
1020                        //remove DDesc
1021
webContainerService.removeCache(earClassLoader);
1022                        //remove the webapps
1023
webContainerService.unDeployWars(warUrls);
1024                    }
1025                    if (logger.isLoggable(BasicLevel.DEBUG)) {
1026                        logger.log(BasicLevel.DEBUG, "Undeploy the EjbJars loaded from this ear");
1027                    }
1028                    if (ejbService != null && (jarUrls.length > 0)) {
1029                        //remove DDesc
1030
ejbService.removeCache(earClassLoader);
1031                        //remove the ejbs
1032
ejbService.unDeployJars(jarUrls);
1033                    }
1034                    // Remove the deployed rars
1035
if (logger.isLoggable(BasicLevel.DEBUG)) {
1036                        logger.log(BasicLevel.DEBUG, "Undeploy the Resources loaded from this ear");
1037                    }
1038                    if (resourceService != null && connectorUrls.length > 0) {
1039                        // remove Resource
1040
resourceService.unDeployRars(connectorUrls, earUrl[0]);
1041                    }
1042                } catch (ServiceException se2) {
1043                    err = "Error during the undeployment of the webapps/ejbjars/rars file of the Ear file " + fileName;
1044                    logger.log(BasicLevel.ERROR, err + "': " + se2.getMessage());
1045                }
1046                throw new JWebContainerServiceException(err, se);
1047            }
1048        }
1049
1050
1051        // Management support
1052
// ------------------
1053

1054        // Build the 'name' used to construct the J2EEApplication ObjectName
1055
String JavaDoc sJ2EEApplicationName = buildJ2eeApplicationName(earUrl[0]);
1056
1057        // Create AppClientModule MBeans first
1058
AppClientModule[] appClientModules = null;
1059        ObjectName JavaDoc[] onAppClientModules = null;
1060        if (clientUrls.length > 0) {
1061            appClientModules = new AppClientModule[clientUrls.length];
1062            onAppClientModules = new ObjectName JavaDoc[clientUrls.length];
1063        }
1064
1065        String JavaDoc moduleName = null;
1066        String JavaDoc moduleFileName = null;
1067        String JavaDoc moduleDD = null;
1068        String JavaDoc jonasModuleDD = null;
1069        ClientContainerDeploymentDesc clientContainerDD = null;
1070        for (int i = 0; i < clientUrls.length; i++) {
1071            ClassLoader JavaDoc moduleCL = null;
1072            try {
1073                moduleCL = new ClientClassLoader(clientUrls[i], ejbClassLoader);
1074            } catch (IOException JavaDoc ioe) {
1075                // fail case :
1076
// we use the ejbjar classloader, but the descriptor loading will fail
1077
moduleCL = ejbClassLoader;
1078                // TODO Find a better Exception handling ?
1079
}
1080            moduleName = EJBServiceImpl.buildEJBModuleName(clientUrls[i]);
1081            moduleFileName = clientUrls[i].getPath();
1082            try {
1083                clientContainerDD = ClientManagerWrapper.getDeploymentDesc(clientUrls[i], moduleCL, earClassLoader);
1084                moduleDD = clientContainerDD.getXmlContent();
1085                jonasModuleDD = clientContainerDD.getJOnASXmlContent();
1086            } catch (ClientContainerDeploymentDescException e) {
1087                // make debug trace
1088
String JavaDoc err = "Cannot read the deployment descriptors ': " + clientUrls[i] + "'" + e.toString();
1089                logger.log(BasicLevel.ERROR, err, e);
1090            }
1091            onAppClientModules[i] = J2eeObjectName.getAppClientModule(getDomainName(), getJonasServerName(), sJ2EEApplicationName, moduleName);
1092            appClientModules[i] = new AppClientModule(onAppClientModules[i].toString()
1093                    , moduleFileName
1094                    , moduleDD
1095                    , jonasModuleDD);
1096        }
1097        URL JavaDoc clientUrl = null;
1098        try {
1099            if (mbeanServer != null) {
1100                Registry oRegistry = JonasMBeanTools.getRegistry();
1101                ManagedBean oManaged = null;
1102                ModelMBean JavaDoc oMBean = null;
1103                // Register AppClientModule MBeans
1104
if (appClientModules != null) {
1105                    oManaged = oRegistry.findManagedBean("AppClientModule");
1106                    for (int i = 0; i < appClientModules.length; i++) {
1107                        clientUrl = clientUrls[i];
1108                        oMBean = oManaged.createMBean(appClientModules[i]);
1109                        mbeanServer.registerMBean(oMBean, onAppClientModules[i]);
1110                    }
1111                }
1112            }
1113        } catch (Exception JavaDoc eare) {
1114            logger.log(BasicLevel.ERROR, "Can not register the MBean for the client jar " + clientUrl, eare);
1115        }
1116
1117        // Remove the Deployment descriptors
1118
if (ejbService != null) {
1119            ejbService.removeCache(earClassLoader);
1120        }
1121
1122        if (webContainerService != null) {
1123            webContainerService.removeCache(earClassLoader);
1124        }
1125
1126        if (wsService != null) {
1127            wsService.removeCache(earClassLoader);
1128        }
1129
1130        // Create J2EEApplication MBeans
1131
ObjectName JavaDoc onEar = J2eeObjectName.J2EEApplication(getDomainName(), getJonasServerName(), sJ2EEApplicationName);
1132        // Store the ejb-jar, war and the rar urls associated with the ear URL
1133
// in case of success deploy
1134
Ear ear = new Ear(onEar.toString(), sJ2EEApplicationName, dirUnpackURL.getFile(), earUrl[0], earDD.getXmlContent(), jarUrls, warUrls,
1135                connectorUrls);
1136
1137        try {
1138            if (mbeanServer != null) {
1139                Registry oRegistry = JonasMBeanTools.getRegistry();
1140                ManagedBean oManaged = oRegistry.findManagedBean("J2EEApplication");
1141                ModelMBean JavaDoc oMBean = oManaged.createMBean(ear);
1142                // Register Ear MBean (all the J2EEModule MBeans are already registered
1143
mbeanServer.registerMBean(oMBean, onEar);
1144            }
1145        } catch (Exception JavaDoc eare) {
1146            logger.log(BasicLevel.ERROR, "Can not register the MBean for the ear " + earUrl[0], eare);
1147        }
1148
1149
1150        ears.put(earUrl[0], ear);
1151
1152        logger.log(BasicLevel.INFO, "Ear " + earUrl[0] + " available.");
1153
1154        //set the timestamp dir
1155
File JavaDoc dirUnpackFile = new File JavaDoc(dirUnpackURL.getFile());
1156        dirUnpackFile.setLastModified((new Date JavaDoc()).getTime());
1157
1158        // return ObjectName of the J2EEApplication MBean
1159
return onEar.toString();
1160    }
1161
1162    /**
1163     * Deploy an ear with its given fileName
1164     * @param fileName file to deploy (ear)
1165     * @return The ObjectName of the J2EE Application MBean associated to the
1166     * deployed EAR
1167     * @throws Exception if the deployment of the EAR failed.
1168     * @see org.objectweb.jonas.ear.EarService#deployEar(java.lang.String)
1169     */

1170    public String JavaDoc deployEar(String JavaDoc fileName) throws Exception JavaDoc {
1171        return deployEarMBean(fileName);
1172    }
1173
1174    /**
1175     * Deploy an EAR by delegating the operation to the deployEar() method. This
1176     * is used by jonasAdmin management application.
1177     * @param fileName the fileName of the ear which must be be deployed.
1178     * @return The ObjectName of the J2EE Application MBean associated to the
1179     * deployed EAR
1180     * @throws Exception if the deployment of the EAR failed.
1181     */

1182    public String JavaDoc deployEarMBean(String JavaDoc fileName) throws Exception JavaDoc {
1183        Context JavaDoc ctx = null;
1184        String JavaDoc mbeanOn = null;
1185        try {
1186            ctx = new CompNamingContext(fileName);
1187            ctx.rebind("filename", fileName);
1188        } catch (NamingException JavaDoc e) {
1189            String JavaDoc err = "Error when deploying the ear file ";
1190            logger.log(BasicLevel.ERROR, err, e);
1191            throw e;
1192        }
1193        try {
1194            mbeanOn = deployEar(ctx);
1195        } catch (ServiceException e) {
1196            logger.log(BasicLevel.ERROR, "Cannot deploy file '" + fileName + "'");
1197            throw new Exception JavaDoc("Cannot deploy file '" + fileName + "'", e);
1198        }
1199        return mbeanOn;
1200    }
1201
1202    /**
1203     * Start the EAR service.
1204     * @throws ServiceException if the startup failed.
1205     */

1206    protected void doStart() throws ServiceException {
1207
1208        //url
1209
URL JavaDoc earApps = null;
1210        try {
1211            earApps = new File JavaDoc(WORK_APPS_DIR + File.separator + getJonasServerName()).toURL();
1212        } catch (MalformedURLException JavaDoc mue) {
1213            throw new ServiceException("Error when trying to get the URL of the jonasroot/apps directory", mue);
1214        }
1215
1216        File JavaDoc fLog = new File JavaDoc(earApps.getFile() + File.separator + getJonasServerName() + ".log");
1217        if (!fLog.exists()) {
1218            try {
1219                //create
1220
fLog.getParentFile().mkdirs();
1221                fLog.createNewFile();
1222            } catch (IOException JavaDoc e) {
1223                throw new ServiceException("cannot create the log file" + fLog, e);
1224            }
1225        }
1226
1227        //get the logger
1228
try {
1229            earDeployerLog = new DeployerLog(fLog);
1230        } catch (DeployerLogException e) {
1231            throw new ServiceException("Can not get an EarDeployerLog", e);
1232        }
1233
1234        // create the ear deployment work file control task
1235
EarCleanTask earCleanTask = new EarCleanTask(earApps, earDeployerLog);
1236
1237        //get the cleaner ref
1238
workCleaner = WorkCleaner.getInstance();
1239
1240        // add the ear deployment work file control task
1241
try {
1242            workCleaner.registerTask(earCleanTask);
1243        } catch (CleanerException ce) {
1244            throw new ServiceException("Cannot register the EAR clean task", ce);
1245        }
1246
1247        // force the cleaning now
1248
workCleaner.executeTasks();
1249
1250        // Deploy all ear which are in descriptors section
1251
Iterator JavaDoc it = earNames.iterator();
1252        while (it.hasNext()) {
1253            String JavaDoc fileName = (String JavaDoc) it.next();
1254            Context JavaDoc contctx = null;
1255            try {
1256                contctx = new CompNamingContext(fileName);
1257                contctx.rebind("filename", fileName);
1258            } catch (NamingException JavaDoc e) {
1259                throw new ServiceException("Cannot start the EarService", e);
1260            }
1261            deployEar(contctx);
1262        }
1263
1264        try {
1265            // Register EarService MBean : EarServiceImplMBean
1266
if (mbeanServer != null) {
1267                mbeanServer.registerMBean(this, JonasObjectName.earService());
1268            }
1269        } catch (InstanceAlreadyExistsException JavaDoc iae) {
1270            throw new ServiceException("Cannot start the EarService Already Exists", iae);
1271        } catch (MBeanRegistrationException JavaDoc mbre) {
1272            throw new ServiceException("Cannot start the EarService (MBean registration error)", mbre);
1273        } catch (NotCompliantMBeanException JavaDoc ncmbe) {
1274            throw new ServiceException("Cannot start the EarService (MBean Not compliant error)", ncmbe);
1275        }
1276    }
1277
1278    /**
1279     * Undeploy an EAR by sending the request to the EJB container and to the
1280     * WEB container and the Resource service.
1281     * @param ctx the context which contains the configuration in order to
1282     * undeploy an EAR.
1283     * @throws EarServiceException if the undeployment of the EAR failed.
1284     */

1285    public void unDeployEar(Context JavaDoc ctx) throws EarServiceException {
1286
1287        //Get the ear url param which we want to undeploy
1288
URL JavaDoc earUrl = null;
1289        try {
1290            earUrl = (URL JavaDoc) ctx.lookup("filename");
1291        } catch (NamingException JavaDoc e) {
1292            throw new EarServiceException("Trying to remove the ear file but there is no filename specified", e);
1293        }
1294
1295        //This ear is in loaded EARs files ?
1296
Ear ear = (Ear) ears.get(earUrl);
1297
1298        //Not loaded
1299
if (ear == null) {
1300            throw new EarServiceException("Trying to remove the ear file " + earUrl.getFile()
1301                    + " but this file was not found in the loaded Ear files");
1302        }
1303
1304        //undeploy wars if the web container service is started
1305
URL JavaDoc[] warsToUndeploy = ear.getWars();
1306        if (webContainerService != null && (warsToUndeploy.length > 0)) {
1307            webContainerService.unDeployWars(warsToUndeploy);
1308        }
1309
1310        //undeploy jars if the ejb service is started
1311
URL JavaDoc[] jarsToUndeploy = ear.getEjbJars();
1312        if (ejbService != null && (jarsToUndeploy.length > 0)) {
1313            ejbService.unDeployJars(jarsToUndeploy);
1314        }
1315
1316        //undeploy rars if the resource service is started
1317
URL JavaDoc[] rarsToUndeploy = ear.getRars();
1318        if (resourceService != null && (rarsToUndeploy.length > 0)) {
1319            resourceService.unDeployRars(rarsToUndeploy, earUrl);
1320        }
1321
1322        File JavaDoc f = new File JavaDoc(earUrl.getFile());
1323        //Undeploy successful, we remove the ear
1324

1325        //Only if there is no Exception !
1326
ears.remove(earUrl);
1327        //unregister mbean
1328
if (mbeanServer != null) {
1329            // Build the ObjectName if the ear's MBea
1330
//String sJ2EEApplicationName = buildJ2eeApplicationName(earUrl);
1331
//ObjectName onEar =
1332
// J2eeObjectName.J2EEApplication(getDomainName(),
1333
// getJonasServerName(), sJ2EEApplicationName);
1334
// Un-regsiter the MBean
1335
try {
1336                // unregister J2EEApplication
1337
ObjectName JavaDoc onJ2EEApplication = ObjectName.getInstance(ear.getObjectName());
1338                String JavaDoc appName = onJ2EEApplication.getKeyProperty("name");
1339                String JavaDoc domainName = onJ2EEApplication.getDomain();
1340                String JavaDoc serverName = onJ2EEApplication.getKeyProperty("J2EEServer");
1341                mbeanServer.unregisterMBean(onJ2EEApplication);
1342                // ubregister the AppClientModules, if any
1343
ObjectName JavaDoc onAppClientModules = J2eeObjectName.getAppClientModules(domainName, serverName, appName);
1344                List JavaDoc onList = J2eeObjectName.queryObjectNames(onAppClientModules);
1345                for (int i = 0; i < onList.size(); i++) {
1346                    mbeanServer.unregisterMBean((ObjectName JavaDoc) onList.get(i));
1347                }
1348            } catch (Exception JavaDoc e) {
1349                logger.log(BasicLevel.ERROR, "Cannot remove the MBean for the ear " + earUrl.getFile(), e);
1350            }
1351        }
1352
1353        logger.log(BasicLevel.INFO, "Ear " + f.getName() + " no longer available.");
1354
1355    }
1356
1357    /**
1358     * Undeploy an EAR by delegating the operation to the unDeployEar() method.
1359     * This is used for JMX management.
1360     * @param fileName the fileName of the ear which must be be undeployed.
1361     * @throws Exception if the undeployment of the EAR failed.
1362     * @see org.objectweb.jonas.ear.EarService#unDeployEar(java.lang.String)
1363     */

1364    public void unDeployEar(String JavaDoc fileName) throws Exception JavaDoc {
1365        unDeployEarMBean(fileName);
1366    }
1367
1368    /**
1369     * Undeploy an EAR by delegating the operation to the unDeployEar() method.
1370     * This is used for JMX management.
1371     * @param fileName the fileName of the ear which must be be undeployed.
1372     * @throws Exception if the undeployment of the EAR failed.
1373     */

1374    public void unDeployEarMBean(String JavaDoc fileName) throws Exception JavaDoc {
1375
1376        /*
1377         * We have only the name of the file, not its associated path, so we
1378         * look in the current directory and in the ear applications directory
1379         */

1380
1381        //We check if the url exists in the hashtable
1382
//compare: First in the current dir, after in the apps directory
1383
URL JavaDoc url = null;
1384        URL JavaDoc earUrl = null;
1385        boolean found = false;
1386        try {
1387            Enumeration JavaDoc e = ears.keys();
1388            url = new File JavaDoc(fileName).getCanonicalFile().toURL();
1389            while (e.hasMoreElements() && !found) {
1390                earUrl = (URL JavaDoc) e.nextElement();
1391                if (earUrl.equals(url)) {
1392                    //We have found
1393
found = true;
1394                }
1395            }
1396
1397            if (fileName.toLowerCase().endsWith(".ear") && !found) {
1398                // In case of the name is an ear check also in
1399
// the JONAS_BASE/apps directory
1400
String JavaDoc earFileName = APPS_DIR + File.separator + fileName;
1401                e = ears.keys();
1402                url = new File JavaDoc(earFileName).getCanonicalFile().toURL();
1403                while (e.hasMoreElements() && !found) {
1404                    earUrl = (URL JavaDoc) e.nextElement();
1405                    if (earUrl.equals(url)) {
1406                        //We have found
1407
found = true;
1408                    }
1409                }
1410            }
1411            if (!found) {
1412                String JavaDoc err = "Cannot undeploy the ear '" + fileName + "', it is not deployed.";
1413                logger.log(BasicLevel.ERROR, err);
1414                throw new Exception JavaDoc(err);
1415            }
1416        } catch (MalformedURLException JavaDoc mue) {
1417            String JavaDoc err = "Error when trying to get the url from" + fileName;
1418            logger.log(BasicLevel.ERROR, err);
1419            throw new Exception JavaDoc(err, mue);
1420        } catch (IOException JavaDoc ioe) {
1421            String JavaDoc err = "Error when trying to get the canonical file from " + fileName;
1422            logger.log(BasicLevel.ERROR, err + ioe.getMessage());
1423            throw new Exception JavaDoc(err, ioe);
1424        }
1425
1426        //We've got the file, now we bind the params
1427
Context JavaDoc ctx = null;
1428        try {
1429            ctx = new CompNamingContext(fileName);
1430            //The fileName is an url
1431
ctx.rebind("filename", url);
1432        } catch (NamingException JavaDoc e) {
1433            String JavaDoc err = "Error when binding parameters";
1434            logger.log(BasicLevel.ERROR, err + e.getMessage());
1435            throw new Exception JavaDoc(err, e);
1436        }
1437
1438        //Call the function
1439
try {
1440            unDeployEar(ctx);
1441        } catch (EarServiceException e) {
1442            throw new Exception JavaDoc(e);
1443        }
1444
1445    }
1446
1447    /**
1448     * @return current number of ears deployed in the JOnAS server
1449     */

1450    public Integer JavaDoc getCurrentNumberOfEars() {
1451        return new Integer JavaDoc(ears.size());
1452    }
1453
1454    /**
1455     * Return the list of installed Applications. The EAR files or the
1456     * directories with expanded Applications are searched in JONAS_BASE/apps
1457     * and all Applications directories 'autoload'.
1458     * @return The list of EAR files or the directories with expanded
1459     * Applications found
1460     * @throws Exception if the list can't be retrieved
1461     */

1462    public List JavaDoc getInstalledEars() throws Exception JavaDoc {
1463        // get EAR files found in JONAS_BASE/apps
1464
ArrayList JavaDoc al = JModule.getInstalledContainersInDir(APPS_DIR, JModule.EAR_EXTENSION, JModule.EAR_CHILD_DIR,
1465                JModule.EAR_CONFIRM_FILE);
1466        // get EAR files found in all autoload directories
1467
Iterator JavaDoc it = autoloadDirectories.iterator();
1468        while (it.hasNext()) {
1469            String JavaDoc name = (String JavaDoc) it.next();
1470            al.addAll(JModule.getInstalledContainersInDir(name, JModule.EAR_EXTENSION, JModule.EAR_CHILD_DIR,
1471                    JModule.EAR_CONFIRM_FILE));
1472        }
1473        return al;
1474    }
1475
1476    /**
1477     * This method is added temporarily. It will disapear when Ears will have
1478     * their associated MBeans (when Ears will become manageable)
1479     * @return the names of the ears currently deployed in the JOnAS server
1480     */

1481    public Set JavaDoc getEarNames() {
1482        HashSet JavaDoc names = new HashSet JavaDoc();
1483        URL JavaDoc earUrl = null;
1484        for (Enumeration JavaDoc e = ears.keys(); e.hasMoreElements();) {
1485            earUrl = (URL JavaDoc) e.nextElement();
1486            names.add(earUrl.getFile());
1487        }
1488        return names;
1489    }
1490
1491    /**
1492     * Add recursively the ears of the specified directory. If the dir has a
1493     * relative path, this path is relative from where the Application Server is
1494     * launched. If the dir is not found it will be searched in
1495     * $JONAS_BASE/apps/ directory.
1496     * @param dirPath the path to the directory containing the ears to load.
1497     */

1498    private void addEars(String JavaDoc dirPath) {
1499        boolean found = false;
1500
1501        // Look the directory relative to the $JONAS_BASE/apps directory
1502
File JavaDoc dir = new File JavaDoc(APPS_DIR + File.separator + dirPath);
1503        found = dir.isDirectory();
1504
1505        if (found) {
1506            addEarsFrom(dir);
1507        } else {
1508            String JavaDoc err = "Warning: Cannot load dir: '" + dirPath + "' ";
1509            err += "is not a directory or directory doesn't exist";
1510            logger.log(BasicLevel.WARN, err);
1511        }
1512    }
1513
1514    /**
1515     * Add the ears of the specified directory.
1516     * @param dir the directory from which the ears are loaded.
1517     * @throws EarServiceException if the argument is not a directory
1518     */

1519    private void addEarsFrom(File JavaDoc dir) throws EarServiceException {
1520        try {
1521            if (dir.isDirectory()) {
1522                File JavaDoc[] files = dir.listFiles();
1523                for (int i = 0; i < files.length; i++) {
1524                    if (files[i].getPath().toLowerCase().endsWith(".ear")) {
1525                        earNames.add(files[i].getCanonicalPath());
1526                    } else {
1527                        if (files[i].isDirectory()) {
1528                            addEarsFrom(files[i]);
1529                        }
1530                    }
1531                }
1532            } else {
1533                String JavaDoc err = "Cannot load dir: '" + dir.getPath();
1534                err += "' is not a directory";
1535                logger.log(BasicLevel.ERROR, err);
1536                throw new EarServiceException(err);
1537            }
1538        } catch (IOException JavaDoc e) {
1539            String JavaDoc err = "Invalid file name '" + dir.getPath();
1540            logger.log(BasicLevel.ERROR, err);
1541            throw new EarServiceException(err, e);
1542        }
1543    }
1544
1545    /**
1546     * Test if the specified filename is already deployed or not. This method
1547     * is a management method provided by the EarServerice MBean.
1548     * @param fileName the name of the ear file.
1549     * @return true if the ear is deployed, else false.
1550     */

1551    public boolean isEarLoaded(String JavaDoc fileName) {
1552
1553        URL JavaDoc url = null;
1554        boolean isLoaded = false;
1555        try {
1556            // Absolute filename
1557
try {
1558                url = new File JavaDoc(fileName).getCanonicalFile().toURL();
1559                //Check if the ear is already deployed or not
1560
if (ears.get(url) != null) {
1561                    isLoaded = true;
1562                } else {
1563                    // Not found force to test in relative Apps directory
1564
url = null;
1565                }
1566            } catch (Exception JavaDoc e) {
1567                url = null;
1568            }
1569            // Relative filename
1570
if (url == null) {
1571                url = new File JavaDoc(APPS_DIR + File.separator + fileName).getCanonicalFile().toURL();
1572                //Check if the ear is already deployed or not
1573
if (ears.get(url) != null) {
1574                    isLoaded = true;
1575                }
1576            }
1577        } catch (Exception JavaDoc e) {
1578            String JavaDoc err = "Can not found if the ear is deployed or not";
1579            logger.log(BasicLevel.ERROR, err);
1580            return false;
1581        }
1582
1583        return isLoaded;
1584    }
1585
1586    /**
1587     * Test if the specified filename is already deployed or not. This
1588     * method is defined in the EarService interface.
1589     * @param fileName the name of the ear file.
1590     * @return true if the ear is deployed, else false.
1591     */

1592    public Boolean JavaDoc isEarDeployed(String JavaDoc fileName) {
1593        return new Boolean JavaDoc(isEarLoaded(fileName));
1594    }
1595
1596    /**
1597     * Test if the specified unpack name is already deployed or not. This
1598     * method is defined in the EarService interface.
1599     * @param unpackName the name of the ear file.
1600     * @return true if the ear is deployed, else false.
1601     */

1602    public boolean isEarDeployedByUnpackName(String JavaDoc unpackName) {
1603        if (logger.isLoggable(BasicLevel.DEBUG)) {
1604            logger.log(BasicLevel.DEBUG, "entering for unpackName= " + unpackName);
1605        }
1606        // for each ear loaded
1607
Enumeration JavaDoc lc = ears.elements();
1608        while (lc.hasMoreElements()) {
1609            Ear ear = (Ear) lc.nextElement();
1610
1611            // get unpack name of the ear
1612
String JavaDoc deployedUnpackName = new File JavaDoc(ear.getUnpackName()).getName();
1613            if (logger.isLoggable(BasicLevel.DEBUG)) {
1614                logger.log(BasicLevel.DEBUG, "deployedUnpackName=" + deployedUnpackName);
1615            }
1616
1617            if (deployedUnpackName.equals(unpackName)) {
1618                return true;
1619            }
1620            // else, go to the next loop
1621
}
1622        // not found
1623
return false;
1624    }
1625
1626
1627    /**
1628     * Return the list of all loaded Applications.
1629     * @return The list of deployed Applications
1630     */

1631    public List JavaDoc getDeployedEars() {
1632        ArrayList JavaDoc al = new ArrayList JavaDoc();
1633        Ear oEar;
1634        URL JavaDoc oURL;
1635        for (Enumeration JavaDoc enumEars = ears.elements(); enumEars.hasMoreElements();) {
1636            oEar = (Ear) enumEars.nextElement();
1637            oURL = oEar.getEarUrl();
1638            al.add(oURL.getFile());
1639        }
1640        return al;
1641    }
1642
1643    /**
1644     * Return the list of installed Applications ready to deploy.
1645     * @return The list of deployable Applications
1646     * @throws Exception if the list can't be built
1647     */

1648    public List JavaDoc getDeployableEars() throws Exception JavaDoc {
1649        List JavaDoc al = getInstalledEars();
1650        al.removeAll(getDeployedEars());
1651        return al;
1652    }
1653
1654    /**
1655     * Return the list of "autoload" directories for applications.
1656     * @return The list of all "autoload" directories
1657     */

1658    public List JavaDoc getAutoloadDirectories() {
1659        ArrayList JavaDoc al = new ArrayList JavaDoc();
1660        Iterator JavaDoc it = autoloadDirectories.iterator();
1661        while (it.hasNext()) {
1662            String JavaDoc fileName = (String JavaDoc) it.next();
1663            try {
1664                al.add(new File JavaDoc(fileName).toURL().getPath());
1665            } catch (Exception JavaDoc e) {
1666                if (logger.isLoggable(BasicLevel.DEBUG)) {
1667                    logger.log(BasicLevel.DEBUG, "Can't get autoload directories : " + e.getMessage());
1668                }
1669            }
1670        }
1671        return al;
1672    }
1673
1674    /**
1675     * Return the Apps directory.
1676     * @return The Apps directory
1677     */

1678    public String JavaDoc getAppsDirectory() {
1679        String JavaDoc sRet = null;
1680        try {
1681            sRet = (new File JavaDoc(APPS_DIR)).toURL().getPath();
1682        } catch (Exception JavaDoc e) {
1683            throw new RuntimeException JavaDoc("Cannot get the APPS directory", e);
1684        }
1685        return sRet;
1686    }
1687
1688    /**
1689     * Build the J2EEApplication name.
1690     * @param pUrl The URL of Ear file
1691     * @return The J2EEApplication name
1692     */

1693    public static String JavaDoc buildJ2eeApplicationName(URL JavaDoc pUrl) {
1694        String JavaDoc sName = null;
1695        try {
1696            sName = new File JavaDoc(pUrl.getFile()).getName();
1697            if ("file".equals(pUrl.getProtocol())) {
1698                sName = buildJ2eeApplicationName(sName);
1699            }
1700        } catch (NullPointerException JavaDoc e) {
1701            if (logger != null) {
1702                if (logger.isLoggable(BasicLevel.DEBUG)) {
1703                    logger.log(BasicLevel.DEBUG, "Can't build j2ee application", e);
1704                }
1705            }
1706        }
1707        return sName;
1708    }
1709
1710    /**
1711     * Build the J2EEApplication name.
1712     * @param pFilename The name of Ear file
1713     * @return The J2EEApplication name
1714     */

1715    public static String JavaDoc buildJ2eeApplicationName(String JavaDoc pFilename) {
1716        String JavaDoc sName = null;
1717        try {
1718            sName = new File JavaDoc(pFilename).getName();
1719            int iPos = sName.lastIndexOf('.');
1720            if (iPos > -1) {
1721                sName = sName.substring(0, iPos);
1722            }
1723        } catch (NullPointerException JavaDoc e) {
1724            if (logger != null) {
1725                if (logger.isLoggable(BasicLevel.DEBUG)) {
1726                    logger.log(BasicLevel.DEBUG, "Can't build j2ee application : " + e.getMessage());
1727                }
1728            }
1729        }
1730        return sName;
1731    }
1732
1733    /**
1734     * Link policy configuration objects of EJB and Web Component
1735     * @param userToRoleMapping mapping for user-to-role
1736     * @param jarUrls list of jars which have been deployed
1737     * @param warUrls list of wars which have been deployed
1738     * @throws EarServiceException if the policy objects can't be linked
1739     */

1740    private void linkPolicyObjects(Map JavaDoc userToRoleMapping, URL JavaDoc[] jarUrls, URL JavaDoc[] warUrls) throws EarServiceException {
1741        List JavaDoc ctxIDs = new LinkedList JavaDoc();
1742        // Get contextID of EJB
1743
if (ejbService != null) {
1744            for (int u = 0; u < jarUrls.length; u++) {
1745                ctxIDs.add(ejbService.getContainer(jarUrls[u].getFile()).getContextId());
1746            }
1747        }
1748        // Now for WebApp
1749
if (webContainerService != null) {
1750            for (int u = 0; u < warUrls.length; u++) {
1751                ctxIDs.add(webContainerService.getWar(warUrls[u]).getContextId());
1752            }
1753        }
1754
1755        PolicyConfigurationFactory JavaDoc pcFactory = null;
1756        try {
1757            pcFactory = PolicyConfigurationFactory.getPolicyConfigurationFactory();
1758        } catch (Exception JavaDoc cnfe) {
1759            String JavaDoc err = "Cannot retrieve current policy configuration factory";
1760            logger.log(BasicLevel.ERROR, err + "': " + cnfe.getMessage());
1761            throw new EarServiceException(err, cnfe);
1762        }
1763
1764        try {
1765            // Now link the policy configuration objects
1766
for (Iterator JavaDoc itCtxId = ctxIDs.iterator(); itCtxId.hasNext();) {
1767                String JavaDoc toBeLinkedCtxId = (String JavaDoc) itCtxId.next();
1768                PolicyConfiguration JavaDoc toBeLinkedPC = pcFactory.getPolicyConfiguration(toBeLinkedCtxId, false);
1769                for (Iterator JavaDoc linkCId = ctxIDs.iterator(); linkCId.hasNext();) {
1770                    String JavaDoc linkedCtxId = (String JavaDoc) linkCId.next();
1771                    if (!toBeLinkedCtxId.equals(linkedCtxId)) {
1772                        PolicyConfiguration JavaDoc linkedPC = pcFactory.getPolicyConfiguration(linkedCtxId, false);
1773                        toBeLinkedPC.linkConfiguration(linkedPC);
1774                    }
1775                }
1776            }
1777        } catch (PolicyContextException JavaDoc pce) {
1778            String JavaDoc err = "Cannot retrieve a policy configuration";
1779            logger.log(BasicLevel.ERROR, err + "': " + pce.getMessage());
1780            throw new EarServiceException(err, pce);
1781        }
1782
1783        // Do user-to-role mapping
1784
if (userToRoleMapping != null) {
1785            for (Iterator JavaDoc itCtxId = ctxIDs.iterator(); itCtxId.hasNext();) {
1786                String JavaDoc contextId = (String JavaDoc) itCtxId.next();
1787                for (Iterator JavaDoc itMapping = userToRoleMapping.keySet().iterator(); itMapping.hasNext();) {
1788                    String JavaDoc principalName = (String JavaDoc) itMapping.next();
1789                    List JavaDoc roles = (List JavaDoc) userToRoleMapping.get(principalName);
1790                    String JavaDoc[] roleNames = (String JavaDoc[]) roles.toArray(new String JavaDoc[roles.size()]);
1791                    JPolicyUserRoleMapping.addUserToRoleMapping(contextId, principalName, roleNames);
1792                }
1793            }
1794
1795        }
1796
1797
1798        String JavaDoc ctxId = null;
1799        try {
1800            // And to finish, commit the policy configuration objects
1801
for (Iterator JavaDoc itCtxId = ctxIDs.iterator(); itCtxId.hasNext();) {
1802                ctxId = (String JavaDoc) itCtxId.next();
1803                PolicyConfiguration JavaDoc pc = pcFactory.getPolicyConfiguration(ctxId, false);
1804                pc.commit();
1805            }
1806        } catch (PolicyContextException JavaDoc pce) {
1807            String JavaDoc err = "Cannot commit policy configuration with Id '" + ctxId + "'";
1808            logger.log(BasicLevel.ERROR, err + "': " + pce.getMessage());
1809            throw new EarServiceException(err, pce);
1810        }
1811
1812        // refresh policy
1813
Policy.getPolicy().refresh();
1814    }
1815
1816}
Popular Tags