KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > objectweb > jonas > container > EJBServiceImpl


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: EJBServiceImpl.java,v 1.116 2005/07/28 13:35:38 durieuxp Exp $
23  * --------------------------------------------------------------------------
24  */

25
26 package org.objectweb.jonas.container;
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.util.ArrayList JavaDoc;
34 import java.util.Enumeration JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.HashSet JavaDoc;
37 import java.util.Iterator JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.Properties JavaDoc;
41 import java.util.Set JavaDoc;
42 import java.util.StringTokenizer JavaDoc;
43 import java.util.Vector JavaDoc;
44 import java.util.jar.Attributes JavaDoc;
45 import java.util.jar.JarFile JavaDoc;
46 import java.util.jar.Manifest JavaDoc;
47
48 import javax.management.MBeanException JavaDoc;
49 import javax.management.MBeanServer JavaDoc;
50 import javax.management.ObjectName JavaDoc;
51 import javax.management.OperationsException JavaDoc;
52 import javax.management.modelmbean.ModelMBean JavaDoc;
53 import javax.naming.Context JavaDoc;
54 import javax.naming.InitialContext JavaDoc;
55 import javax.naming.NamingException JavaDoc;
56
57 import org.apache.commons.modeler.ManagedBean;
58 import org.apache.commons.modeler.Registry;
59
60 import org.objectweb.transaction.jta.TransactionManager;
61
62 import org.objectweb.carol.util.configuration.ConfigurationRepository;
63 import org.objectweb.carol.util.configuration.ProtocolConfiguration;
64
65 import org.objectweb.jonas_ejb.container.BeanFactory;
66 import org.objectweb.jonas_ejb.container.Container;
67 import org.objectweb.jonas_ejb.container.JContainer;
68 import org.objectweb.jonas_ejb.container.JEntityFactory;
69 import org.objectweb.jonas_ejb.container.JMdbEndpointFactory;
70 import org.objectweb.jonas_ejb.container.JMdbFactory;
71 import org.objectweb.jonas_ejb.container.JSessionFactory;
72 import org.objectweb.jonas_ejb.container.JStatelessFactory;
73 import org.objectweb.jonas_ejb.container.PermissionManager;
74 import org.objectweb.jonas_ejb.deployment.api.BeanDesc;
75 import org.objectweb.jonas_ejb.deployment.api.DeploymentDesc;
76 import org.objectweb.jonas_ejb.deployment.api.EntityBmpDesc;
77 import org.objectweb.jonas_ejb.deployment.api.EntityCmpDesc;
78 import org.objectweb.jonas_ejb.deployment.api.SessionStatefulDesc;
79 import org.objectweb.jonas_ejb.deployment.api.SessionStatelessDesc;
80 import org.objectweb.jonas_ejb.deployment.lib.wrapper.EjbManagerWrapper;
81
82 import org.objectweb.jonas_lib.JWorkManager;
83 import org.objectweb.jonas_lib.deployment.api.DeploymentDescException;
84 import org.objectweb.jonas_lib.deployment.work.CleanerException;
85 import org.objectweb.jonas_lib.deployment.work.DeployerLog;
86 import org.objectweb.jonas_lib.deployment.work.DeployerLogException;
87 import org.objectweb.jonas_lib.deployment.work.FileManager;
88 import org.objectweb.jonas_lib.deployment.work.JarCleanTask;
89 import org.objectweb.jonas_lib.deployment.work.WorkCleaner;
90 import org.objectweb.jonas_lib.files.FileUtils;
91 import org.objectweb.jonas_lib.loader.EjbJarClassLoader;
92 import org.objectweb.jonas_lib.version.Version;
93
94 import org.objectweb.jonas_jms.api.JmsManager;
95
96 import org.objectweb.jonas.common.JModule;
97 import org.objectweb.jonas.common.JProp;
98 import org.objectweb.jonas.common.Log;
99 import org.objectweb.jonas.ear.EarServiceImpl;
100 import org.objectweb.jonas.jms.JmsService;
101 import org.objectweb.jonas.jmx.J2eeObjectName;
102 import org.objectweb.jonas.jmx.JmxService;
103 import org.objectweb.jonas.jmx.JonasObjectName;
104 import org.objectweb.jonas.jtm.TransactionService;
105 import org.objectweb.jonas.management.JonasMBeanTools;
106 import org.objectweb.jonas.naming.CompNamingContext;
107 import org.objectweb.jonas.naming.NamingManager;
108 import org.objectweb.jonas.security.SecurityService;
109 import org.objectweb.jonas.server.LoaderManager;
110 import org.objectweb.jonas.server.WorkManagerMBean;
111 import org.objectweb.jonas.service.AbsServiceImpl;
112 import org.objectweb.jonas.service.ServiceException;
113 import org.objectweb.jonas.service.ServiceManager;
114
115 import org.objectweb.util.monolog.api.BasicLevel;
116 import org.objectweb.util.monolog.api.Logger;
117
118 /**
119  * Implementation of the EJB Container Service for jonas. This class works only
120  * with jonas_ejb classes.
121  * @author Philippe Coq
122  * @author Jeff Mesnil (Security)
123  * @author Markus Karg (Novell port)
124  * @author Christophe Ney (for making easier Enhydra integration)
125  * @author Adriana Danes (complete management methods)
126  * @author Florent Benoit & Ludovic Bert (Ear service, deployJars, undeployJars)
127  * @author Benjamin Bonnet (max thread pool size)
128  * @author Michel-Ange Anton (JSR77 MBean : EJBModule)
129  * @author Adriana Danes (JSR77)
130  */

131 public class EJBServiceImpl extends AbsServiceImpl implements EJBService, EJBServiceImplMBean {
132
133     /** server logger */
134     private static Logger servlog = null;
135
136     /** loader logger */
137     private static Logger loaderlog = null;
138
139     /**
140      * Transaction manager reference (tm can be accessed directly from
141      * everywhere in the package.)
142      */

143     private TransactionManager tm = null;
144
145     /** JMS manager reference */
146     private JmsManager jms = null;
147
148     /** JMX Server */
149     private MBeanServer JavaDoc mbeanServer = null;
150
151     /** Security service reference */
152     private SecurityService securityService = null;
153
154     /**
155      * Reference to the cleaner
156      */

157     private static WorkCleaner workCleaner = null;
158
159     private Registry oRegistry = null;
160
161     /**
162      * List of the ejb names to load when starting the EJB Container Service
163      */

164     private Vector JavaDoc ejbNames = new Vector JavaDoc();
165
166     /** We have a Container by ejb-jar file. */
167     private Vector JavaDoc containers = new Vector JavaDoc();
168
169     /** WorkManager thread pool size */
170     public static final String JavaDoc MINWORKTHREADS = "jonas.service.ejb.minworkthreads";
171     private static final int DEFAULT_MINWORKTHREADS = 3;
172     public static final String JavaDoc MAXWORKTHREADS = "jonas.service.ejb.maxworkthreads ";
173     private static final int DEFAULT_MAXWORKTHREADS = 80;
174     public static final String JavaDoc THREADWAITTIMEOUT = "jonas.service.ejb.threadwaittimeout";
175     private static final int DEFAULT_THREADWAITTIMEOUT = 60;
176     private JWorkManager workManager;
177
178     /**
179      * The name of the JONAS_BASE directory.
180      */

181     protected static final String JavaDoc JONAS_BASE = JProp.getJonasBase();
182
183     /**
184      * The name of the directory containing the ejb-jar files.
185      */

186     protected static final String JavaDoc EJBJARS_DIR = JONAS_BASE + File.separator + "ejbjars";
187
188     /**
189      * List of autoloaded directories.
190      */

191     private ArrayList JavaDoc autoloadDirectories = new ArrayList JavaDoc();
192
193     /** base for properties */
194     public static final String JavaDoc JONAS_EJB = "jonas.service.ejb";
195
196     /** autoloaddir property */
197     public static final String JavaDoc AUTOLOADDIR = JONAS_EJB + ".autoloaddir";
198
199     /** parsing with validation property */
200     public static final String JavaDoc PARSINGWITHVALIDATION = JONAS_EJB + ".parsingwithvalidation";
201
202     /** descriptors property */
203     public static final String JavaDoc DESCRIPTORS = JONAS_EJB + ".descriptors";
204
205     /** EJB service class */
206     public static final String JavaDoc CLASS = JONAS_EJB + ".class";
207
208     /** BeanManaged Management properties */
209     public static final String JavaDoc BMP = "Bean-Managed";
210
211     /** ContainerManaged Management properties */
212     public static final String JavaDoc CMP = "Container-Managed";
213
214     /** applications parent classloader */
215     private ClassLoader JavaDoc appsClassLoader = null;
216
217     /**
218      * The name of the working directory.
219      */

220     private static final String JavaDoc WORK_DIR = JProp.getWorkDir();
221
222     /**
223      * The name of the working ejbjars directory.
224      */

225     private static final String JavaDoc WORK_EJBJARS_DIR = WORK_DIR + File.separator + "ejbjars";
226
227     /**
228      *
229      */

230     private static String JavaDoc ejbjarsDir = null;
231
232     /**
233      * Reference on the DeployerLog which is the class that manage the accesses
234      * to the log file (to remove the jar).
235      */

236     private DeployerLog jarDeployerLog = null;
237
238     // -------------------------------------------------------------------
239
// JOnAS Service Implementation
240
// -------------------------------------------------------------------
241

242     /**
243      * Init the Service. Configuration information is passed thru a Context
244      * object.
245      */

246     public void doInit(Context JavaDoc ctx) throws ServiceException {
247         servlog = Log.getLogger(Log.JONAS_SERVER_PREFIX);
248         loaderlog = Log.getLogger(Log.JONAS_LOADER_PREFIX);
249
250         if (servlog.isLoggable(BasicLevel.DEBUG)) {
251             servlog.log(BasicLevel.DEBUG, "");
252         }
253
254         // get apps ClassLoader
255
try {
256             LoaderManager lm = LoaderManager.getInstance();
257             appsClassLoader = lm.getAppsLoader();
258         } catch (Exception JavaDoc e) {
259             servlog.log(BasicLevel.ERROR, "Cannot get the Applications ClassLoader from EJB Container Service");
260             throw new ServiceException("Cannot get the Applications ClassLoader from EJB Container Service", e);
261         }
262
263         ServiceManager serviceManager = null;
264         try {
265             serviceManager = ServiceManager.getInstance();
266         } catch (Exception JavaDoc e) {
267             servlog.log(BasicLevel.ERROR, "Cannot initialize the EJB Container Service");
268             throw new ServiceException("Cannot initialize the EJB Container Service", e);
269         }
270         // Get the used services
271
try {
272             // Get the Transaction Manager via the jtm service
273
TransactionService jtmService = (TransactionService) serviceManager.getTransactionService();
274             tm = jtmService.getTransactionManager();
275         } catch (ServiceException e) {
276             servlog.log(BasicLevel.ERROR, "Cannot initialize the EJB Container Service");
277             throw new ServiceException("Cannot initialize the EJB Container Service", e);
278         }
279
280         try {
281             // Get the Security service
282
securityService = (SecurityService) serviceManager.getSecurityService();
283         } catch (ServiceException se) {
284             // The Security service may not be started
285
securityService = null;
286         }
287
288         try {
289             // Get the JMS manager via the JMS service
290
JmsService jmsService = (JmsService) serviceManager.getJmsService();
291             jms = jmsService.getJmsManager();
292         } catch (ServiceException e) {
293             // the JMS service may not be started
294
jms = null;
295         }
296
297         try {
298             // Get the JMX Server via JMX Service
299
JmxService jmxService = (JmxService) serviceManager.getJmxService();
300             mbeanServer = jmxService.getJmxServer();
301         } catch (ServiceException e) {
302             // the JMX service may not be started
303
mbeanServer = null;
304         }
305         oRegistry = JonasMBeanTools.getRegistry();
306
307         // Set the XML parsing mode to no validation
308
String JavaDoc parsingMode;
309         try {
310             parsingMode = (String JavaDoc) ctx.lookup(PARSINGWITHVALIDATION);
311         } catch (NamingException JavaDoc e) {
312             // No problem if there is no value for 'parsingwithvalidation'
313
// (false by default)
314
parsingMode = "false";
315         }
316         if ("false".equalsIgnoreCase(parsingMode)) {
317             EjbManagerWrapper.setParsingWithValidation(false);
318             if (servlog.isLoggable(BasicLevel.DEBUG)) {
319                 servlog.log(BasicLevel.DEBUG, "XML parsing without validation");
320             }
321         } else {
322             if (servlog.isLoggable(BasicLevel.DEBUG)) {
323                 servlog.log(BasicLevel.DEBUG, "XML parsing with validation");
324             }
325         }
326
327         // Init the ejb names to be loaded when starting
328
String JavaDoc descsValue;
329         try {
330             descsValue = (String JavaDoc) ctx.lookup(DESCRIPTORS);
331         } catch (NamingException JavaDoc e) {
332             // No problem if there is no value for 'descriptors' (no ejb to
333
// load)
334
descsValue = null;
335         }
336         if (descsValue != null) {
337             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(descsValue, ",");
338             while (st.hasMoreTokens()) {
339                 String JavaDoc fileName = st.nextToken().trim();
340                 ejbNames.add(fileName);
341             }
342         }
343
344         // Add the jars of the jonas.service.ejb.autoloaddir property
345
String JavaDoc dirValue;
346         ArrayList JavaDoc autoDirs = new ArrayList JavaDoc();
347         try {
348             dirValue = (String JavaDoc) ctx.lookup(AUTOLOADDIR);
349         } catch (NamingException JavaDoc e) {
350             // No problem if there is no value for 'autoloaddir'
351
//(no ejb to load)
352
dirValue = null;
353         }
354         if (dirValue != null) {
355             StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(dirValue, ",");
356             while (st.hasMoreTokens()) {
357                 String JavaDoc dirName = st.nextToken().trim();
358                 addEjbjars(dirName);
359                 autoDirs.add(dirName);
360             }
361         }
362         // Build autoload directories
363
File JavaDoc oFile;
364         for (int i = 0; i < autoDirs.size(); i++) {
365             try {
366                 oFile = new File JavaDoc(EJBJARS_DIR, autoDirs.get(i).toString());
367                 if (oFile.exists()) {
368                     autoloadDirectories.add(oFile.getCanonicalPath());
369                 } else {
370                     oFile = new File JavaDoc(autoDirs.get(i).toString());
371                 }
372             } catch (Exception JavaDoc e) {
373                 String JavaDoc err = "Error when trying to verify Ejbjar autoload directory : " + autoDirs.get(i);
374                 servlog.log(BasicLevel.ERROR, err, e);
375             }
376         }
377
378         // Create the WorkManager (thread Pool)
379
int minworkthreads = DEFAULT_MINWORKTHREADS;
380         try {
381             String JavaDoc plz = (String JavaDoc) ctx.lookup(MINWORKTHREADS);
382             minworkthreads = (new Integer JavaDoc(plz)).intValue();
383         } catch (NamingException JavaDoc e) {
384             // default value will be used.
385
}
386         int maxworkthreads = DEFAULT_MAXWORKTHREADS;
387         try {
388             String JavaDoc mxplz = (String JavaDoc) ctx.lookup(MAXWORKTHREADS);
389             maxworkthreads = (new Integer JavaDoc(mxplz)).intValue();
390         } catch (NamingException JavaDoc e) {
391             // default value will be used.
392
}
393         int threadwaittimeout = DEFAULT_THREADWAITTIMEOUT;
394         try {
395             String JavaDoc tto = (String JavaDoc) ctx.lookup(THREADWAITTIMEOUT);
396             threadwaittimeout = (new Integer JavaDoc(tto)).intValue();
397         } catch (NamingException JavaDoc e) {
398             // default value will be used.
399
}
400         workManager = new JWorkManager(minworkthreads, maxworkthreads, tm, threadwaittimeout);
401
402         // Create and register the MBean for this WorkManager
403
ObjectName JavaDoc mbn;
404         try {
405             mbn = JonasObjectName.workManager();
406             ManagedBean oManaged = oRegistry.findManagedBean("WorkManager");
407             ModelMBean JavaDoc oMBean = oManaged.createMBean(new WorkManagerMBean(workManager));
408             mbeanServer.registerMBean(oMBean, mbn);
409         } catch (Exception JavaDoc e) {
410             servlog.log(BasicLevel.ERROR, "Cannot create MBean", e);
411         }
412
413         if (servlog.isLoggable(BasicLevel.DEBUG)) {
414             servlog.log(BasicLevel.DEBUG, "EJB Container Service initialized");
415         }
416     }
417     
418     public JWorkManager getWorkManager() {
419         return workManager;
420     }
421
422     /**
423      * Start the Service Initialization of the service is already done.
424      */

425     public void doStart() throws ServiceException {
426
427         ejbjarsDir = WORK_EJBJARS_DIR + File.separator + getJonasServerName();
428
429         URL JavaDoc ejbjarsUrl = null;
430         try {
431             ejbjarsUrl = new File JavaDoc(ejbjarsDir).toURL();
432         } catch (MalformedURLException JavaDoc mue) {
433             throw new ServiceException("Error when trying to get the URL of the jonasroot/apps directory", mue);
434         }
435
436         File JavaDoc fLog = new File JavaDoc(ejbjarsUrl.getFile() + File.separator + getJonasServerName() + ".log");
437         if (!fLog.exists()) {
438             try {
439                 //create
440
fLog.getParentFile().mkdirs();
441                 fLog.createNewFile();
442             } catch (IOException JavaDoc e) {
443                 throw new ServiceException("cannot create the log file" + fLog, e);
444             }
445         }
446
447         //get the logger
448
try {
449             jarDeployerLog = new DeployerLog(fLog);
450         } catch (DeployerLogException e) {
451             throw new ServiceException("Can not get an EarDeployerLog", e);
452         }
453
454         // create the jar deployment work file control task
455
JarCleanTask jarCleanTask = new JarCleanTask(jarDeployerLog);
456
457         //get the cleaner ref
458
workCleaner = WorkCleaner.getInstance();
459
460         // add the jar deployment work file control task
461
try {
462             workCleaner.registerTask(jarCleanTask);
463         } catch (CleanerException ce) {
464             throw new ServiceException("Cannot register the JAR clean task", ce);
465
466         }
467
468         // force the cleaning immediately
469
workCleaner.executeTasks();
470
471         // Creates all predefined containers
472
// 1 container per ejbjar file.
473
String JavaDoc fileName = null;
474         Context JavaDoc contctx = null;
475         for (int i = 0; i < ejbNames.size(); i++) {
476             fileName = (String JavaDoc) ejbNames.elementAt(i);
477             try {
478                 contctx = new CompNamingContext(fileName);
479                 contctx.rebind("filename", fileName);
480             } catch (NamingException JavaDoc ne) {
481                 servlog.log(BasicLevel.WARN, "Cannot create container for " + fileName
482                         + " because of a NamingException : " + ne.toString());
483             }
484
485             try {
486                 createContainer(contctx);
487             } catch (Exception JavaDoc e) {
488                 servlog.log(BasicLevel.WARN, "Cannot create container for " + fileName, e);
489                 // Close naming context
490
try {
491                     contctx.close();
492                 } catch (NamingException JavaDoc nne) {
493                     if (servlog.isLoggable(BasicLevel.DEBUG)) {
494                         servlog.log(BasicLevel.DEBUG, "Cannot close deploy context for " + fileName, nne);
495                     }
496                 }
497             }
498         }
499
500         // Register EJBService MBean : EJBServiceImplMBean
501
if (mbeanServer != null) {
502             try {
503                 mbeanServer.registerMBean(this, JonasObjectName.ejbService());
504             } catch (MBeanException JavaDoc mbe) {
505                 // registration failed because a MBeanException
506
servlog.log(BasicLevel.WARN, "Cannot register the EJB Container Service in the MBean Server.");
507                 servlog.log(BasicLevel.WARN, "Regstration failure cause : " + mbe.getTargetException().toString());
508             } catch (OperationsException JavaDoc me) {
509                 // registration failed because a OperationsException JMX
510
// Exception
511
servlog.log(BasicLevel.WARN, "Cannot register the EJB Container Service in the MBean Server.", me);
512             }
513         }
514     }
515
516     /**
517      * Stop the service: - Remove all JOnAS Containers. - Unbinds all the
518      * EJBHome names from JNDI
519      */

520     public void doStop() {
521
522         Enumeration JavaDoc lc = containers.elements();
523         while (lc.hasMoreElements()) {
524             Container cont = (Container) lc.nextElement();
525             removeContainer(cont);
526         }
527         if (mbeanServer != null) {
528             try {
529                 // unregister EJBService MBean : EJBServiceImplMBean
530
mbeanServer.unregisterMBean(JonasObjectName.ejbService());
531             } catch (Exception JavaDoc e) {
532                 servlog.log(BasicLevel.ERROR, "Cannot stop the EJB Container Service", e);
533             }
534         }
535
536         if (servlog.isLoggable(BasicLevel.DEBUG)) {
537             servlog.log(BasicLevel.DEBUG, "EJB Container Service stopped");
538         }
539     }
540
541     // -------------------------------------------------------------------
542
// EJBService Implementation
543
// -------------------------------------------------------------------
544

545     /**
546      * Create a JOnAS Container for all the beans that are described in a .xml
547      * file, or belong to .jar file.
548      * @return The ObjectName of the MBean associated to the container (i.e. to
549      * the deployed module)
550      * @throws Exception if an error occur during the creation of the container.
551      */

552     public String JavaDoc createContainer(Context JavaDoc ctx) throws Exception JavaDoc {
553         if (servlog.isLoggable(BasicLevel.DEBUG)) {
554             servlog.log(BasicLevel.DEBUG, "");
555         }
556
557         // Get the file name
558
String JavaDoc fileName = (String JavaDoc) ctx.lookup("filename");
559         File JavaDoc f = new File JavaDoc(fileName).getCanonicalFile();
560
561         boolean isEjbJar = fileName.toLowerCase().endsWith(".jar");
562
563         // check if the file exists
564
// In case of the name is a ejb-jar file name, check also in
565
// the JONAS_BASE/ejbjars directory
566
try {
567             if (!f.exists() && isEjbJar) {
568                 String JavaDoc ejbjarFileName = EJBJARS_DIR + File.separator + fileName;
569                 f = new File JavaDoc(ejbjarFileName).getCanonicalFile();
570                 if (!f.exists()) {
571                     servlog.log(BasicLevel.ERROR, "createContainer: " + fileName + " not found");
572                     throw new NamingException JavaDoc(fileName + " not found");
573                 }
574             }
575         } catch (IOException JavaDoc e) {
576             String JavaDoc err = "Invalid ejbjar file name '" + fileName;
577             servlog.log(BasicLevel.ERROR, err);
578             throw new Exception JavaDoc(err, e);
579         }
580         boolean isEjbJarFile = isEjbJar && f.isFile();
581         boolean isEjbJarXml = fileName.toLowerCase().endsWith(".xml") && f.isFile();
582
583         // Force fileName with slash to avoid conflict under Windows (slash and
584
// back-slash)
585
try {
586             fileName = f.toURL().getPath();
587         } catch (MalformedURLException JavaDoc e) {
588             servlog.log(BasicLevel.ERROR, "Invalid ejb-jar file name '" + fileName + "'", e);
589         }
590
591         if (f.isFile()) {
592             if (!isEjbJar && !isEjbJarXml) {
593                 throw new ServiceException("The ejbjar to deploy is not a jar file nor an xml file");
594             }
595         }
596
597         // Check if container already exists
598
if (getContainer(fileName) != null) {
599             servlog.log(BasicLevel.ERROR, "createContainer: " + fileName + " already exists");
600             throw new Exception JavaDoc("Container already exists");
601         }
602
603         // In order to avoid lock problem after undeploy
604
// the jar file is copied under the working directory before its loading
605
// ! only if the ejbjars isn't included in an ear
606
boolean isInEar = true;
607         try {
608             ctx.lookup("earClassLoader");
609         } catch (NamingException JavaDoc ne) {
610             isInEar = false;
611         }
612
613         // if need, call Genic. Only in single ejb-jar mode.
614
// In ear case, this has been checked by ear service.
615
if (!isInEar) {
616             checkGenIC(fileName);
617         }
618
619
620         String JavaDoc wkFileName = null;
621
622         if (!isInEar && isEjbJarFile) {
623             // Get the destination file
624
wkFileName = ejbjarsDir + File.separator + FileManager.fileToTimeStampDir(f.toURL(), ".jar");
625
626             if (servlog.isLoggable(BasicLevel.DEBUG)) {
627                 servlog.log(BasicLevel.DEBUG, "filename=" + fileName);
628                 servlog.log(BasicLevel.DEBUG, "wkFilename=" + wkFileName);
629             }
630
631             // copy the file
632
FileUtils.copyFile(fileName, wkFileName);
633
634             // add an entry in the log file
635
try {
636                 jarDeployerLog.addEntry(f, new File JavaDoc(wkFileName));
637             } catch (DeployerLogException e) {
638                 String JavaDoc err = "Error while adding the " + fileName + " entry in the log file";
639                 servlog.log(BasicLevel.ERROR, err + " : " + e.getMessage());
640                 throw new Exception JavaDoc(err, e);
641             }
642
643             if (servlog.isLoggable(BasicLevel.DEBUG)) {
644                 servlog.log(BasicLevel.DEBUG, "Create wk file :" + wkFileName);
645             }
646
647         } else {
648             // in this case, no needs to copy the file
649
wkFileName = fileName;
650             if (servlog.isLoggable(BasicLevel.DEBUG)) {
651                 servlog.log(BasicLevel.DEBUG, "No needs wk file :" + wkFileName);
652             }
653         }
654
655         // Classloader
656
URL JavaDoc[] url = null;
657         try {
658             url = new URL JavaDoc[1];
659             url[0] = (new File JavaDoc(wkFileName)).toURL();
660         } catch (MalformedURLException JavaDoc e) {
661             servlog.log(BasicLevel.ERROR, "Invalid ejb-jar file name '" + wkFileName + "'", e);
662         }
663
664         // Get the classloaders
665
URLClassLoader JavaDoc ejbClassLoader = null;
666         URLClassLoader JavaDoc earClassLoader = null;
667         try {
668             earClassLoader = (URLClassLoader JavaDoc) ctx.lookup("earClassLoader");
669             ejbClassLoader = (URLClassLoader JavaDoc) ctx.lookup("ejbClassLoader");
670             if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
671                 loaderlog.log(BasicLevel.DEBUG, "earClassLoader=" + earClassLoader);
672             }
673         } catch (NamingException JavaDoc ne) {
674             // no ear classloader => ejb application case (not ear case).
675
if (isEjbJar) {
676                 ejbClassLoader = new EjbJarClassLoader(url, appsClassLoader);
677             } else {
678                 ejbClassLoader = (URLClassLoader JavaDoc) appsClassLoader;
679             }
680             if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
681                 loaderlog.log(BasicLevel.DEBUG, "parent Loader=" + appsClassLoader);
682             }
683         }
684         if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
685             loaderlog.log(BasicLevel.DEBUG, "ejbClassLoader=" + ejbClassLoader);
686         }
687
688         // Get the deployment descriptor from file
689
DeploymentDesc dd = null;
690         try {
691             // ejb-jar file
692
dd = EjbManagerWrapper.getDeploymentDesc(url[0], ejbClassLoader, earClassLoader);
693         } catch (DeploymentDescException e) {
694             String JavaDoc err = "Cannot read the deployment descriptors '" + fileName + "'";
695             servlog.log(BasicLevel.ERROR, err);
696             throw new ServiceException(err, e);
697         }
698
699         // container name
700
String JavaDoc cname = buildEJBModuleName(fileName);
701         if (cname == null) {
702             //use displayName
703
cname = "EJB container ";
704             if (dd.getDisplayName() != null) {
705                 cname += dd.getDisplayName();
706             }
707         }
708
709         // Create the Container Object
710
JContainer cont = new JContainer(cname, fileName, wkFileName, ejbClassLoader);
711         cont.setContainerNaming(NamingManager.getInstance());
712         cont.setTransactionManager(tm);
713         cont.setPrincipalFactory(new PrincipalFactoryImpl());
714         cont.setJmsManager(jms);
715
716         // Set the name of the ear application containing this container
717
// in the case of an ear application.
718
String JavaDoc earFileName;
719         try {
720             earFileName = (String JavaDoc) ctx.lookup("earFileName");
721             cont.setEarFileName(earFileName);
722         } catch (NamingException JavaDoc ne) {
723             earFileName = null;
724         }
725
726         // unset the security if no security service
727
if (securityService == null) {
728             if (servlog.isLoggable(BasicLevel.DEBUG)) {
729                 servlog.log(BasicLevel.DEBUG, "EJB Container Service: working without Security Service");
730             }
731             cont.setSecurity(false);
732         } else {
733             PermissionManager permissionManager = null;
734             try {
735                 permissionManager = new PermissionManager(dd, cont.getContextId());
736                 permissionManager.translateEjbDeploymentDescriptor();
737                 // if not in ear case, commit the policy configuration, else it
738
// is done
739
// by EAR service after linking all policy configuration objects
740
if (!isInEar) {
741                     permissionManager.commit();
742                 }
743             } catch (Exception JavaDoc e) {
744                 servlog.log(BasicLevel.ERROR, "Can't build permission manager object for the ejbjar '" + fileName + "'", e);
745             }
746             cont.setPermissionManager(permissionManager);
747         }
748
749         // Give access to the WorkManager
750
cont.setWorkManager(workManager);
751
752         String JavaDoc domainName = getDomainName();
753         String JavaDoc serverName = getJonasServerName();
754         String JavaDoc j2eeAppName = EarServiceImpl.buildJ2eeApplicationName(earFileName);
755         EJBModule ejbModuleMBean = null;
756         ObjectName JavaDoc onEjbModule = null;
757
758         // MBeans to register if the deployment is successful
759
Map JavaDoc mbeansToRegister = new HashMap JavaDoc();
760
761         // EJBModule MBean registering
762
if (mbeanServer != null) {
763             // Use the conatiner name (the 'name' constructor parameter of
764
// JContainer class)
765
// as the "name" keyProperty for the J2ee ObjectName construction
766
onEjbModule = J2eeObjectName.getEJBModule(domainName, serverName, j2eeAppName, cname);
767
768             ejbModuleMBean = new EJBModule(onEjbModule.toString(), cont, fileName, cname);
769             ejbModuleMBean.setDeploymentDescriptor(dd.getXmlContent());
770             ejbModuleMBean.setJonasDeploymentDescriptor(dd.getJOnASXmlContent());
771
772             // Use Jakarta Common Modeler API
773
ManagedBean oManaged = oRegistry.findManagedBean("EJBModule");
774             ModelMBean JavaDoc oMBean = oManaged.createMBean(ejbModuleMBean);
775             mbeansToRegister.put(oMBean, onEjbModule);
776         }
777
778         // Process each bean from the DD
779
BeanDesc[] beans = dd.getBeanDesc();
780         for (int i = 0; i < beans.length; i++) {
781             BeanFactory bf = cont.addBean(beans[i]);
782             beans[i].setBeanFactory(bf);
783             if (mbeanServer != null) {
784                 try {
785                     // register MBean for this ejb
786
String JavaDoc beanName = beans[i].getEjbName();
787                     if ((beans[i] instanceof EntityBmpDesc) || (beans[i] instanceof EntityCmpDesc)) {
788                         JEntityFactory jef = (JEntityFactory) bf;
789                         ObjectName JavaDoc onEntityBean = J2eeObjectName.getEntityBean(domainName, cname, serverName,
790                                 j2eeAppName, beanName);
791                         EntityBean entityBeanMBean; // new EntityBean
792
// declaration
793
if (beans[i] instanceof EntityBmpDesc) {
794                             entityBeanMBean = new EntityBean(onEntityBean.toString(), jef, BMP);
795                         } else {
796                             entityBeanMBean = new EntityBean(onEntityBean.toString(), jef, CMP);
797                         }
798                         ManagedBean oManaged = oRegistry.findManagedBean("EntityBean");
799                         ModelMBean JavaDoc oMBean = oManaged.createMBean(entityBeanMBean);
800                         mbeansToRegister.put(oMBean, onEntityBean);
801                         // Update the EJBModule
802
ejbModuleMBean.addEjb(onEntityBean.toString());
803                     } else if (beans[i] instanceof SessionStatefulDesc) {
804                         JSessionFactory jsf = (JSessionFactory) bf;
805                         ObjectName JavaDoc onStatefulSessionBean = J2eeObjectName.getStatefulSessionBean(domainName, cname,
806                                 serverName, j2eeAppName, beanName);
807                         StatefulSessionBean sessionBeanMBean = new StatefulSessionBean(
808                                 onStatefulSessionBean.toString(), jsf);
809                         ManagedBean oManaged = oRegistry.findManagedBean("StatefulSessionBean");
810                         ModelMBean JavaDoc oMBean = oManaged.createMBean(sessionBeanMBean);
811                         mbeansToRegister.put(oMBean, onStatefulSessionBean);
812                         // Update the EJBModule
813
ejbModuleMBean.addEjb(onStatefulSessionBean.toString());
814                     } else if (beans[i] instanceof SessionStatelessDesc) {
815                         JStatelessFactory jsf = (JStatelessFactory) bf;
816                         ObjectName JavaDoc onStatelessSessionBean = J2eeObjectName.getStatelessSessionBean(domainName, cname,
817                                 serverName, j2eeAppName, beanName);
818                         StatelessSessionBean sessionBeanMBean = new StatelessSessionBean(onStatelessSessionBean
819                                 .toString(), jsf);
820                         ManagedBean oManaged = oRegistry.findManagedBean("StatelessSessionBean");
821                         ModelMBean JavaDoc oMBean = oManaged.createMBean(sessionBeanMBean);
822                         mbeansToRegister.put(oMBean, onStatelessSessionBean);
823                         // Update the EJBModule
824
ejbModuleMBean.addEjb(onStatelessSessionBean.toString());
825                     } else {
826                         ObjectName JavaDoc onMessageDrivenBean = J2eeObjectName.getMessageDrivenBean(domainName, cname,
827                                 serverName, j2eeAppName, beanName);
828                         MessageDrivenBean messageDrivenBeanMBean = null;
829                         if (bf instanceof JMdbFactory) {
830                             JMdbFactory jmf = (JMdbFactory) bf;
831                             messageDrivenBeanMBean = new MessageDrivenBean(onMessageDrivenBean.toString(), jmf);
832                         } else {
833                             JMdbEndpointFactory jmf = (JMdbEndpointFactory) bf;
834                             messageDrivenBeanMBean = new MessageDrivenBean(onMessageDrivenBean.toString(), jmf);
835                         }
836                         ManagedBean oManaged = oRegistry.findManagedBean("MessageDrivenBean");
837                         ModelMBean JavaDoc oMBean = oManaged.createMBean(messageDrivenBeanMBean);
838                         mbeansToRegister.put(oMBean, onMessageDrivenBean);
839                         // Update the EJBModule
840
ejbModuleMBean.addEjb(onMessageDrivenBean.toString());
841                     }
842                 } catch (Exception JavaDoc e) {
843                     servlog.log(BasicLevel.ERROR, "Cannot create container", e);
844                 }
845             }
846         }
847         // Init now pools of instances, in case min-pool-size have been defined.
848
// This must be done once all beans have been deployed.
849
for (int i = 0; i < beans.length; i++) {
850             BeanFactory bf = beans[i].getBeanFactory();
851             bf.initInstancePool();
852         }
853
854         // Deployment was successful, add the bean as deployed and create the
855
// MBeans
856
containers.addElement(cont);
857         for (Iterator JavaDoc it = mbeansToRegister.keySet().iterator(); it.hasNext();) {
858             ModelMBean JavaDoc mbean = (ModelMBean JavaDoc) it.next();
859             ObjectName JavaDoc oName = (ObjectName JavaDoc) mbeansToRegister.get(mbean);
860             mbeanServer.registerMBean(mbean, oName);
861
862         }
863
864         if (servlog.isLoggable(BasicLevel.DEBUG)) {
865             servlog.log(BasicLevel.DEBUG, "created container for " + fileName);
866         }
867         //return cont;
868
return onEjbModule.toString();
869     }
870
871     /**
872      * Get the Container by its file name (.xml or .jar)
873      * @param fileName given file name on which
874      * @return Container
875      */

876     public Container getContainer(String JavaDoc fileName) {
877         if (servlog.isLoggable(BasicLevel.DEBUG)) {
878             servlog.log(BasicLevel.DEBUG, fileName);
879         }
880
881         // In case of the name is a ejb-jar file name, check also in
882
// the JONAS_BASE/ejbjars directory and JONAS_BASE/ejbjars/autoload
883

884         String JavaDoc ejbjarFileName = EJBJARS_DIR + File.separator + fileName;
885         File JavaDoc f = null;
886         String JavaDoc pathEjbJarDirFile;
887         String JavaDoc pathFile = "";
888         try {
889             f = new File JavaDoc(ejbjarFileName).getCanonicalFile();
890             // Force pathEjbJarDirFile with slash to avoid conflict under
891
// Windows (slash and back-slash)
892
pathEjbJarDirFile = f.toURL().getPath();
893         } catch (Exception JavaDoc e) {
894             // If filename was an absolute path, it can throw an exception
895
// The pathFile will be empty
896
pathEjbJarDirFile = "";
897         }
898         try {
899             f = new File JavaDoc(fileName).getCanonicalFile();
900             // Force pathFile with slash to avoid conflict under Windows (slash
901
// and back-slash)
902
pathFile = f.toURL().getPath();
903         } catch (Exception JavaDoc e) {
904             String JavaDoc err = "Error while trying to get canonical file '" + fileName + "'";
905             servlog.log(BasicLevel.ERROR, err);
906             return null;
907         }
908
909         // for each container loaded
910
Enumeration JavaDoc lc = containers.elements();
911         while (lc.hasMoreElements()) {
912             Container cont = (JContainer) lc.nextElement();
913             String JavaDoc contName = cont.getExternalFileName();
914
915             // first, search abs path
916
if (contName.equals(pathFile)) {
917                 return cont;
918             } else if (contName.equals(pathEjbJarDirFile)) {
919                 // next, search in ejbjar path
920
return cont;
921             } else {
922                 // else search in autoloadir
923
List JavaDoc lAlDirs = getAutoloadDirectories();
924                 for (int i = 0; i < lAlDirs.size(); i++) {
925                     String JavaDoc alDir = (String JavaDoc) lAlDirs.get(i);
926
927                     String JavaDoc alFileName = alDir + File.separator + fileName;
928                     try {
929                         f = new File JavaDoc(alFileName).getCanonicalFile();
930                         // Force alFileName with slash to avoid conflict under
931
// Windows (slash and back-slash)
932
alFileName = f.toURL().getPath();
933                     } catch (Exception JavaDoc e) {
934                         // If filename was an absolute path, it can throw an
935
// exception
936
alFileName = alDir + File.separator + fileName;
937                     }
938                     if (servlog.isLoggable(BasicLevel.DEBUG)) {
939                         servlog.log(BasicLevel.DEBUG, "alFileName= " + alFileName);
940                     }
941
942                     if (contName.equals(alFileName)) {
943                         return cont;
944                     }
945                 }
946             }
947         }
948
949         // not found
950
return null;
951     }
952
953     /**
954      * Remove a JOnAS container
955      */

956     public void removeContainer(Container cont) {
957         if (servlog.isLoggable(BasicLevel.DEBUG)) {
958             servlog.log(BasicLevel.DEBUG, cont.getName());
959         }
960
961         if (mbeanServer != null) {
962             String JavaDoc moduleName = cont.getName();
963             String JavaDoc earFileName = cont.getEarFileName();
964             String JavaDoc earName = null;
965             if (earFileName != null) {
966                 earName = EarServiceImpl.buildJ2eeApplicationName(earFileName);
967             }
968             String JavaDoc domainName = getDomainName();
969             String JavaDoc serverName = getJonasServerName();
970             ObjectName JavaDoc onEjbModule = J2eeObjectName.getEJBModule(domainName, serverName, earName, moduleName);
971
972             // try to remove MBeans corresponding to the EJBs in the module
973
ObjectName JavaDoc onEjb = null;
974             try {
975                 String JavaDoc[] onEjbs = (String JavaDoc[]) mbeanServer.getAttribute(onEjbModule, "ejbs");
976                 for (int i = 0; i < onEjbs.length; i++) {
977                     onEjb = new ObjectName JavaDoc(onEjbs[i]);
978                     mbeanServer.unregisterMBean(onEjb);
979                 }
980             } catch (Exception JavaDoc e) {
981                 servlog.log(BasicLevel.ERROR, "Problem when trying to unregsiter MBean " + onEjb.toString(), e);
982             }
983
984             // try to remove MBean corresponding to the module
985
try {
986                 mbeanServer.unregisterMBean(onEjbModule);
987                 if (servlog.isLoggable(BasicLevel.DEBUG)) {
988                     servlog.log(BasicLevel.DEBUG, "unregistered MBean: " + onEjbModule.toString());
989                 }
990             } catch (Exception JavaDoc e) {
991                 servlog.log(BasicLevel.ERROR, "Problem when trying to unregsiter MBean " + onEjbModule.toString(), e);
992             }
993         }
994         cont.remove();
995         containers.removeElement(cont);
996
997         // Run the garbage collector
998
Runtime.getRuntime().gc();
999
1000    }
1001
1002    /**
1003     * List JOnAS container created by EJB Service
1004     */

1005    public Container[] listContainers() {
1006        if (servlog.isLoggable(BasicLevel.DEBUG)) {
1007            servlog.log(BasicLevel.DEBUG, "size= " + containers.size());
1008        }
1009
1010        Container[] ret = new Container[containers.size()];
1011        containers.copyInto(ret);
1012        return ret;
1013    }
1014
1015    /**
1016     * Synchronized all entity bean containers
1017     * @param passivate passivate instances after synchronization.
1018     */

1019    public void syncAllEntities(boolean passivate) {
1020        if (servlog.isLoggable(BasicLevel.DEBUG)) {
1021            servlog.log(BasicLevel.DEBUG, "");
1022        }
1023
1024        Enumeration JavaDoc lc = containers.elements();
1025        while (lc.hasMoreElements()) {
1026            JContainer cont = (JContainer) lc.nextElement();
1027            cont.syncAll(passivate);
1028        }
1029    }
1030
1031    /** ******* MBEan methods ******** */
1032
1033    /**
1034     * MBean method
1035     * @return Integer Total Number of Container currently in JOnAS
1036     */

1037    public Integer JavaDoc getCurrentNumberOfContainer() {
1038        return new Integer JavaDoc(containers.size());
1039    }
1040
1041    /**
1042     * MBean method
1043     * @return Integer Total Number of Bean Type currently in JOnAS
1044     */

1045    public Integer JavaDoc getTotalCurrentNumberOfBeanType() {
1046        int count = 0;
1047        Enumeration JavaDoc lc = containers.elements();
1048        while (lc.hasMoreElements()) {
1049            JContainer cont = (JContainer) lc.nextElement();
1050            count += cont.getBeanNb();
1051        }
1052        return new Integer JavaDoc(count);
1053    }
1054
1055    /**
1056     * MBean method
1057     * @return Integer Total Number of Bmp Type currently in JOnAS
1058     */

1059    public Integer JavaDoc getTotalCurrentNumberOfBMPType() {
1060        int count = 0;
1061        Enumeration JavaDoc lc = containers.elements();
1062        while (lc.hasMoreElements()) {
1063            JContainer cont = (JContainer) lc.nextElement();
1064            count += cont.getEntityBMPNb();
1065        }
1066        return new Integer JavaDoc(count);
1067    }
1068
1069    /**
1070     * MBean method
1071     * @return Integer Total Number of Cmp Type currently in JOnAS
1072     */

1073    public Integer JavaDoc getTotalCurrentNumberOfCMPType() {
1074        int count = 0;
1075        Enumeration JavaDoc lc = containers.elements();
1076        while (lc.hasMoreElements()) {
1077            JContainer cont = (JContainer) lc.nextElement();
1078            count += cont.getEntityCMPNb();
1079        }
1080        return new Integer JavaDoc(count);
1081    }
1082
1083    /**
1084     * MBean method
1085     * @return Integer Total Number of Sbf Type currently in JOnAS
1086     */

1087    public Integer JavaDoc getTotalCurrentNumberOfSBFType() {
1088        int count = 0;
1089        Enumeration JavaDoc lc = containers.elements();
1090        while (lc.hasMoreElements()) {
1091            JContainer cont = (JContainer) lc.nextElement();
1092            count += cont.getStatefulSessionNb();
1093        }
1094        return new Integer JavaDoc(count);
1095    }
1096
1097    /**
1098     * MBean method
1099     * @return Integer Total Number of Sbl Type currently in JOnAS
1100     */

1101    public Integer JavaDoc getTotalCurrentNumberOfSBLType() {
1102        int count = 0;
1103        Enumeration JavaDoc lc = containers.elements();
1104        while (lc.hasMoreElements()) {
1105            JContainer cont = (JContainer) lc.nextElement();
1106            count += cont.getStatelessSessionNb();
1107        }
1108        return new Integer JavaDoc(count);
1109    }
1110
1111    /**
1112     * MBean method
1113     * @return Integer Total Number of Mdb Type currently in JOnAS
1114     */

1115    public Integer JavaDoc getTotalCurrentNumberOfMDBType() {
1116        int count = 0;
1117        Enumeration JavaDoc lc = containers.elements();
1118        while (lc.hasMoreElements()) {
1119            JContainer cont = (JContainer) lc.nextElement();
1120            count += cont.getMessageDrivenNb();
1121        }
1122        return new Integer JavaDoc(count);
1123    }
1124
1125    public void removeContainer(String JavaDoc fileName) throws Exception JavaDoc {
1126        removeContainerMBean(fileName);
1127    }
1128
1129    /**
1130     * MBean method remove a container application
1131     * @param fileName the Name of this container
1132     */

1133    public void removeContainerMBean(String JavaDoc fileName) throws Exception JavaDoc {
1134        Container cont = null;
1135        try {
1136            cont = getContainer(fileName);
1137        } catch (Exception JavaDoc e) {
1138            String JavaDoc err = "Error while trying to find file '" + fileName + "'";
1139            servlog.log(BasicLevel.ERROR, err);
1140            throw new Exception JavaDoc(err, e);
1141        }
1142
1143        if (cont != null) {
1144            removeContainer(cont, false);
1145        } else {
1146            String JavaDoc err = "Cannot remove the non-existant container '" + fileName + "'";
1147            servlog.log(BasicLevel.ERROR, err);
1148            throw new Exception JavaDoc(err);
1149        }
1150    }
1151
1152    public String JavaDoc createContainer(String JavaDoc file) throws Exception JavaDoc {
1153        return createContainerMBean(file);
1154    }
1155
1156    /**
1157     * MBean method allowing to create an EJB container for the EJBs contained
1158     * in a .jar (or .xml) file.
1159     * @param file Name of the file to be deployed
1160     * @return The ObjectName of the MBean associated to the container (to the
1161     * deployed module)
1162     */

1163    public String JavaDoc createContainerMBean(String JavaDoc file) throws Exception JavaDoc {
1164        String JavaDoc ejbModuleObjectName = null;
1165        try {
1166            Context JavaDoc contctx = new CompNamingContext(file);
1167            contctx.rebind("filename", file);
1168            ejbModuleObjectName = createContainer(contctx);
1169        } catch (Exception JavaDoc e) {
1170            throw new Exception JavaDoc("Cannot create Container", e);
1171        }
1172        return ejbModuleObjectName;
1173    }
1174
1175    /**
1176     * Test if the specified file is already deployed (if a container is created
1177     * for this jar).
1178     * @param fileName the name of the jar file
1179     * @return true if the jar was deployed, false otherwise
1180     */

1181    public Boolean JavaDoc isJarDeployed(String JavaDoc fileName) {
1182        return new Boolean JavaDoc(isJarLoaded(fileName));
1183    }
1184
1185    /**
1186     * Test if the specified jar identified with its work name is already
1187     * deployed (if a container is created for this jar).
1188     * @param workFileName the internal name of the jar file (working copy)
1189     * @return true if the jar was deployed, false otherwise
1190     */

1191    public boolean isJarDeployedByWorkName(String JavaDoc workFileName) {
1192        if (servlog.isLoggable(BasicLevel.DEBUG)) {
1193            servlog.log(BasicLevel.DEBUG, workFileName);
1194        }
1195
1196        // for each container loaded
1197
Enumeration JavaDoc lc = containers.elements();
1198        while (lc.hasMoreElements()) {
1199            Container cont = (JContainer) lc.nextElement();
1200
1201            // get name of the container (basename)
1202
// cont.getFileName return the internal name (working copy)
1203
String JavaDoc contName = new File JavaDoc(cont.getFileName()).getName();
1204            if (contName.equals(workFileName)) {
1205                return true;
1206            }
1207        }
1208
1209        // not found
1210
return false;
1211    }
1212
1213    // Kind of resources:
1214
static final int DATASOURCE = 1;
1215
1216    static final int JMS_DESTINATION = 2;
1217
1218    static final int JMS_FACTORY = 3;
1219
1220    static final int MAIL_FACTORY = 4;
1221
1222    /**
1223     * This method is used by the getXXXDependence MBean methods. It gathers the
1224     * ObjectNames of the EJBs using a given resource.
1225     * @param name the resource name
1226     * @type the resource type
1227     * @return the ObjectNames of all the ejb using this resource
1228     */

1229    Set JavaDoc getDependence(String JavaDoc name, int type) {
1230        Set JavaDoc resultObjectName = null; // to be returned by this method
1231
Set JavaDoc resultProperties = new HashSet JavaDoc(); // constructed by the JContainer
1232
Enumeration JavaDoc lc = containers.elements();
1233        try {
1234            Context JavaDoc ctx = new InitialContext JavaDoc();
1235            ctx.lookup(name);
1236            ctx.close();
1237            // this resource is rebind
1238
while (lc.hasMoreElements()) {
1239                JContainer cont = (JContainer) lc.nextElement();
1240                Set JavaDoc depProps = null; // Dependences described as a set of
1241
// Properties objects
1242
switch (type) {
1243
1244                case DATASOURCE:
1245                    depProps = cont.getDataSourceDependence(name);
1246                    break;
1247
1248                case JMS_DESTINATION:
1249                    depProps = cont.getJmsDestinationDependence(name);
1250                    break;
1251
1252                case JMS_FACTORY:
1253                    depProps = cont.getJmsConnectionFactoryDependence(name);
1254                    break;
1255
1256                case MAIL_FACTORY:
1257                    depProps = cont.getMailFactoryDependence(name);
1258                    break;
1259
1260                }
1261                resultProperties.addAll(depProps);
1262                // change string to ObjectName
1263
try {
1264                    resultObjectName = convertToObjectNames(resultProperties);
1265                } catch (Exception JavaDoc e) {
1266                    servlog.log(BasicLevel.ERROR, "EjbServiceImpl: Object Name Error", e);
1267                }
1268            }
1269        } catch (NamingException JavaDoc ne) {
1270            // unexisting ds
1271
resultObjectName = new HashSet JavaDoc();
1272        }
1273        return resultObjectName;
1274    }
1275
1276    /**
1277     * Converts a Set of properties to ObjectNames
1278     * @param resultProperties properties to be converted
1279     * @return Returns a Set of ObjectNames
1280     */

1281    private Set JavaDoc convertToObjectNames(Set JavaDoc resultProperties) {
1282        Set JavaDoc resultObjectName = new HashSet JavaDoc();
1283        Iterator JavaDoc it = resultProperties.iterator();
1284        String JavaDoc domainName = getDomainName();
1285        String JavaDoc serverName = getJonasServerName();
1286        Properties JavaDoc item = null; // a item in resultProperties
1287
String JavaDoc ejbType = null;
1288        String JavaDoc ejbName = null;
1289        String JavaDoc fileName = null;
1290        String JavaDoc earFileName = null;
1291        String JavaDoc moduleName = null;
1292        String JavaDoc j2eeAppName = null;
1293        while (it.hasNext()) {
1294            item = (Properties JavaDoc) it.next();
1295            ObjectName JavaDoc ejbObjectName = null;
1296            // See JContainer.beansDependence() method for info about the
1297
// Properties object containt
1298
ejbType = item.getProperty("type");
1299            ejbName = item.getProperty("name");
1300            fileName = item.getProperty("fname");
1301            earFileName = item.getProperty("earFileName");
1302            //moduleName = buildEJBModuleName(fileName);
1303
moduleName = item.getProperty("cname");
1304            if (earFileName != null) {
1305                j2eeAppName = EarServiceImpl.buildJ2eeApplicationName(earFileName);
1306            }
1307
1308            if (ejbType.equals("ejbbmp") || ejbType.equals("ejbcmp")) {
1309                ejbObjectName = J2eeObjectName.getEntityBean(domainName, moduleName, serverName, j2eeAppName, ejbName);
1310            } else if (ejbType.equals("ejbsbf")) {
1311                ejbObjectName = J2eeObjectName.getStatefulSessionBean(domainName, moduleName, serverName, j2eeAppName,
1312                        ejbName);
1313            } else if (ejbType.equals("ejbsbl")) {
1314                ejbObjectName = J2eeObjectName.getStatelessSessionBean(domainName, moduleName, serverName, j2eeAppName,
1315                        ejbName);
1316            } else if (ejbType.equals("ejbmdb")) {
1317                ejbObjectName = J2eeObjectName.getMessageDrivenBean(domainName, moduleName, serverName, j2eeAppName,
1318                        ejbName);
1319            }
1320            if (ejbObjectName != null) {
1321                resultObjectName.add(ejbObjectName);
1322            }
1323        }
1324        return resultObjectName;
1325    }
1326
1327    /**
1328     * MBean method
1329     * @return the ObjectName of all the ejbs using this datasource.
1330     */

1331    public Set JavaDoc getDataSourceDependence(String JavaDoc dsName) {
1332        return getDependence(dsName, DATASOURCE);
1333    }
1334
1335    /**
1336     * Manangement method
1337     * @return the ObjectName of all the ejb using this destination.
1338     */

1339    public Set JavaDoc getJmsDestinationDependence(String JavaDoc destName) {
1340        return getDependence(destName, JMS_DESTINATION);
1341    }
1342
1343    /**
1344     * Management method
1345     * @return the ObjectName of all the ejb using this Connection Factory.
1346     */

1347    public Set JavaDoc getJmsConnectionFactoryDependence(String JavaDoc cfName) {
1348        return getDependence(cfName, JMS_FACTORY);
1349    }
1350
1351    /**
1352     * Management method
1353     * @return the ObjectName of all the ejb using a given Mail Factory.
1354     */

1355    public Set JavaDoc getMailFactoryDependence(String JavaDoc mfName) {
1356        return getDependence(mfName, MAIL_FACTORY);
1357    }
1358
1359    /**
1360     * Return the list of installed EJB containers. The JAR files or the
1361     * directories with expanded EJB container are searched in
1362     * JONAS_BASE/ejbjars and all ejbjar directories 'autoload'.
1363     * @return The list of JAR files or the directories with expanded EJB
1364     * container found
1365     * @throws Exception if the list can't be retrieved
1366     */

1367    public List JavaDoc getInstalledJars() throws Exception JavaDoc {
1368        // get JAR files found in JONAS_BASE/ejbjars
1369
ArrayList JavaDoc al = JModule.getInstalledContainersInDir(EJBJARS_DIR, JModule.EJBJAR_EXTENSION,
1370                JModule.EJBJAR_CHILD_DIR, JModule.EJBJAR_CONFIRM_FILE);
1371        // get JAR files found in all autoload directories
1372
for (int i = 0; i < autoloadDirectories.size(); i++) {
1373            al.addAll(JModule.getInstalledContainersInDir(autoloadDirectories.get(i).toString(),
1374                    JModule.EJBJAR_EXTENSION, JModule.EJBJAR_CHILD_DIR, JModule.EJBJAR_CONFIRM_FILE));
1375        }
1376        return al;
1377    }
1378
1379    /**
1380     * Deploy the given ejb-jars of an ear file with the specified parent
1381     * classloader (ear classloader). (This method is only used for the ear
1382     * applications, not for the ejb-jar applications).
1383     * @param ctx the context containing the configuration to deploy the
1384     * ejbjars. <BR>This context contains the following parameters :
1385     * <BR>- earRootUrl the root of the ear application. <BR>- earURL
1386     * filename of the EAR. <BR>- earClassLoader the ear classLoader of
1387     * the ear application. <BR>- ejbClassLoader the ejb classLoader for
1388     * the ejbjars. <BR>- jarURLs the list of the urls of the ejb-jars
1389     * to deploy. <BR>- roleNames the role names of the security-role.
1390     * <BR>
1391     * @throws ServiceException if an error occurs during the deployment.
1392     */

1393    public void deployJars(Context JavaDoc ctx) throws ServiceException {
1394
1395        // Get the 6 parameters from the context
1396
// - earRootUrl the root of the ear application.
1397
// - earClassLoader the ear classLoader of the ear application.
1398
// - ejbClassLoader the ejb classLoader for the ejbjars.
1399
// - jarURLs the list of the urls of the ejb-jars to deploy.
1400
// - roleNames the role names of the security-role
1401
URL JavaDoc earRootUrl = null;
1402        URL JavaDoc earUrl = null;
1403        ClassLoader JavaDoc earClassLoader = null;
1404        ClassLoader JavaDoc ejbClassLoader = null;
1405        URL JavaDoc[] jarURLs = null;
1406        String JavaDoc[] roleNames = null;
1407        try {
1408            earRootUrl = (URL JavaDoc) ctx.lookup("earRootUrl");
1409            earUrl = (URL JavaDoc) ctx.lookup("earUrl");
1410            earClassLoader = (ClassLoader JavaDoc) ctx.lookup("earClassLoader");
1411            ejbClassLoader = (ClassLoader JavaDoc) ctx.lookup("ejbClassLoader");
1412            jarURLs = (URL JavaDoc[]) ctx.lookup("jarURLs");
1413            roleNames = (String JavaDoc[]) ctx.lookup("roleNames");
1414        } catch (NamingException JavaDoc e) {
1415            String JavaDoc err = "Error while getting parameter from context param :" + e.getMessage();
1416            servlog.log(BasicLevel.ERROR, err);
1417            throw new ServiceException(err, e);
1418        }
1419
1420        // Deploy all the ejb-jars of the ear application.
1421
for (int i = 0; i < jarURLs.length; i++) {
1422
1423            // Get the name of an ejb-jar to deploy.
1424
String JavaDoc fileName = jarURLs[i].getFile();
1425            if (servlog.isLoggable(BasicLevel.DEBUG)) {
1426                servlog.log(BasicLevel.DEBUG, "Deploy '" + fileName + "' for the ear service.");
1427            }
1428
1429            // The context to give for the creation of the container
1430
// associated to the ejb-jar.
1431
Context JavaDoc contctx = null;
1432            try {
1433                contctx = new CompNamingContext(fileName);
1434                contctx.rebind("filename", fileName);
1435                contctx.rebind("earClassLoader", earClassLoader);
1436                contctx.rebind("ejbClassLoader", ejbClassLoader);
1437                contctx.rebind("earRoot", earRootUrl.getFile());
1438                contctx.rebind("earFileName", earUrl.getFile());
1439                contctx.rebind("roleNames", roleNames);
1440                createContainer(contctx);
1441            } catch (Exception JavaDoc e) {
1442                // An ejb-jar is corrupted so undeploy all the deployed jar
1443
// of the ear application.
1444
servlog.log(BasicLevel.ERROR, "Error when deploying '" + fileName + "'", e);
1445                servlog.log(BasicLevel.ERROR, "Undeploy ejb-jar of the ear application");
1446
1447                for (int j = 0; j <= i; j++) {
1448                    Container cont = getContainer(jarURLs[j].getFile());
1449                    if (cont != null) {
1450                        removeContainer(cont, true);
1451                    } else {
1452                        servlog.log(BasicLevel.ERROR, "Cannot remove the non-existant container '" + fileName + "'");
1453                    }
1454                }
1455                throw new ServiceException("Error during the deployment", e);
1456            }
1457        }
1458        //return ejbClassLoader;
1459
}
1460
1461    /**
1462     * Undeploy the given ejb-jars of an ear file. (This method is only used for
1463     * the ear applications, not for the ejb-jar applications).
1464     * @param urls the list of the urls of the ejb-jars to undeploy.
1465     */

1466    public void unDeployJars(URL JavaDoc[] urls) {
1467        for (int i = 0; i < urls.length; i++) {
1468            String JavaDoc fileName = urls[i].getFile();
1469            Container cont = getContainer(urls[i].getFile());
1470            if (cont != null) {
1471                removeContainer(cont, true);
1472            } else {
1473                servlog.log(BasicLevel.ERROR, "Cannot remove the non-existant container '" + fileName + "'");
1474            }
1475        }
1476    }
1477
1478    /**
1479     * Remove the specified container.
1480     * @param cont the container to remove.
1481     * @param isEarCase true if only if the removeContainer method is called in
1482     * the ear case, false otherwise.
1483     */

1484    public void removeContainer(Container cont, boolean isEarCase) {
1485        if (isEarCase == (cont.getEarFileName() != null)) {
1486            removeContainer(cont);
1487        } else {
1488            String JavaDoc err = "Cannot remove container '" + cont.getName()
1489                    + "' it is in an ear application. You must undeploy the ear associated.";
1490            servlog.log(BasicLevel.ERROR, err);
1491        }
1492    }
1493
1494    /**
1495     * Make a cleanup of the cache of deployment descriptor. This method must be
1496     * invoked after the ear deployment by the EAR service. the deployment of an
1497     * ear by .
1498     * @param earClassLoader the ClassLoader of the ear application to remove
1499     * from the cache.
1500     */

1501    public void removeCache(ClassLoader JavaDoc earClassLoader) {
1502        EjbManagerWrapper.removeCache(earClassLoader);
1503    }
1504
1505    /**
1506     * Add recursively the ejbjars of the specified directory. If the dir has a
1507     * relative path, this path is relative from where the Application Server is
1508     * launched. If the dir is not found it will be searched in
1509     * $JONAS_BASE/ejbjars/ directory.
1510     * @param dirPath the path to the directory containing the ejbjars to load.
1511     */

1512    private void addEjbjars(String JavaDoc dirPath) {
1513        boolean found = false;
1514
1515        // Look the directory relative to the $JONAS_BASE/ejbjars directory
1516
File JavaDoc dir = new File JavaDoc(EJBJARS_DIR + File.separator + dirPath);
1517        found = dir.isDirectory();
1518
1519        if (found) {
1520            addEjbjarsFrom(dir);
1521        } else {
1522            String JavaDoc err = "Warning: Cannot load dir: '" + dirPath + "' ";
1523            err += "is not a directory or directory doesn't exist";
1524            servlog.log(BasicLevel.WARN, err);
1525        }
1526    }
1527
1528    /**
1529     * Add the ejbjars of the specified directory.
1530     * @param dir the directory from which the ejbjars are loaded.
1531     * @throws ServiceException if the argument is not a directory
1532     */

1533    private void addEjbjarsFrom(File JavaDoc dir) throws ServiceException {
1534
1535        try {
1536            if (dir.isDirectory()) {
1537                File JavaDoc[] files = dir.listFiles();
1538                for (int i = 0; i < files.length; i++) {
1539                    if (files[i].getPath().toLowerCase().endsWith(".jar")) {
1540                        ejbNames.add(files[i].getCanonicalPath());
1541                    } else if (files[i].isDirectory()) {
1542                        addEjbjarsFrom(files[i]);
1543                    }
1544                }
1545            } else {
1546                String JavaDoc err = "Cannot load dir: '" + dir.getPath();
1547                err += "' is not a directory";
1548                servlog.log(BasicLevel.ERROR, err);
1549                throw new ServiceException(err);
1550            }
1551        } catch (IOException JavaDoc e) {
1552            String JavaDoc err = "Invalid file name '" + dir.getPath();
1553            servlog.log(BasicLevel.ERROR, err);
1554            throw new ServiceException(err, e);
1555        }
1556    }
1557
1558    /**
1559     * Test if the specified filename is already deployed or not
1560     * @param fileName the name of the jar file.
1561     * @return true if the jar is deployed, else false.
1562     */

1563    public boolean isJarLoaded(String JavaDoc fileName) {
1564        return (getContainer(fileName) != null);
1565    }
1566
1567    /**
1568     * Return the list of all loaded EJB container.
1569     * @return The list of deployed EJB container
1570     */

1571    public List JavaDoc getDeployedJars() {
1572        ArrayList JavaDoc al = new ArrayList JavaDoc();
1573        Container oContainer;
1574        for (Enumeration JavaDoc jars = containers.elements(); jars.hasMoreElements();) {
1575            oContainer = (Container) jars.nextElement();
1576            try {
1577                al.add((new File JavaDoc(oContainer.getExternalFileName())).toURL().getPath());
1578            } catch (Exception JavaDoc e) {
1579                // none
1580
}
1581        }
1582        return al;
1583    }
1584
1585    /**
1586     * Return the list of installed EJB container ready to deploy.
1587     * @return The list of deployable EJB container
1588     * @throws Exception when cannot get installed jars list
1589     */

1590    public List JavaDoc getDeployableJars() throws Exception JavaDoc {
1591        List JavaDoc al = getInstalledJars();
1592        al.removeAll(getDeployedJars());
1593        return al;
1594    }
1595
1596    /**
1597     * Return the list of "autoload" directories for EJB containers.
1598     * @return The list of all "autoload" directories
1599     */

1600    public List JavaDoc getAutoloadDirectories() {
1601        ArrayList JavaDoc al = new ArrayList JavaDoc();
1602        for (int i = 0; i < autoloadDirectories.size(); i++) {
1603            try {
1604                al.add((new File JavaDoc(autoloadDirectories.get(i).toString())).toURL().getPath());
1605            } catch (Exception JavaDoc e) {
1606                // none
1607
}
1608        }
1609        return al;
1610    }
1611
1612    /**
1613     * Return the Ejbjars directory.
1614     * @return The Ejbjars directory
1615     */

1616    public String JavaDoc getEjbjarsDirectory() {
1617        String JavaDoc sRet;
1618        try {
1619            sRet = (new File JavaDoc(EJBJARS_DIR)).toURL().getPath();
1620        } catch (Exception JavaDoc e) {
1621            sRet = null;
1622        }
1623        return sRet;
1624    }
1625
1626    /**
1627     * Build the EJBModule name.
1628     * @param pUrl The URL of Jar file
1629     * @return The EJBModule name
1630     */

1631    public static String JavaDoc buildEJBModuleName(URL JavaDoc pUrl) {
1632        String JavaDoc sName;
1633        try {
1634            sName = new File JavaDoc(pUrl.getFile()).getName();
1635            if ("file".equals(pUrl.getProtocol())) {
1636                sName = buildEJBModuleName(sName);
1637            }
1638        } catch (NullPointerException JavaDoc e) {
1639            sName = null;
1640        }
1641        return sName;
1642    }
1643
1644    /**
1645     * Build the EJBModule name.
1646     * @param pFilename The name of Jar file
1647     * @return The EJBModule name
1648     */

1649    public static String JavaDoc buildEJBModuleName(String JavaDoc pFilename) {
1650        String JavaDoc sName;
1651        try {
1652            sName = new File JavaDoc(pFilename).getName();
1653            int iPos = sName.lastIndexOf('.');
1654            if (iPos > -1) {
1655                sName = sName.substring(0, iPos);
1656            }
1657        } catch (NullPointerException JavaDoc e) {
1658            sName = null;
1659        }
1660        return sName;
1661    }
1662
1663    /**
1664     * Check if current carol protocol choose is include into those choose during generation
1665     * @param listProtocolGenerated (string with comma separator)
1666     * @param listCurrentProtocol (string with comma separator)
1667     * @return false if we have find at least one current protocol not in those generated
1668     */

1669    private static boolean checkCurrentProtocolIncludeIntoGenerated(String JavaDoc listProtocolGenerated, String JavaDoc listCurrentProtocol) {
1670        boolean find = true;
1671        int i = 0;
1672
1673        if (listProtocolGenerated == null)
1674            return false;
1675
1676        Vector JavaDoc listGenerate = new Vector JavaDoc();
1677        Vector JavaDoc listCurrent = new Vector JavaDoc();
1678
1679        StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(listProtocolGenerated, ",");
1680        while (st.hasMoreTokens()) {
1681            listGenerate.add(st.nextToken());
1682        }
1683
1684        st = new StringTokenizer JavaDoc(listCurrentProtocol, ",");
1685        while (st.hasMoreTokens()) {
1686            listCurrent.add(st.nextToken());
1687        }
1688
1689        while (i < listCurrent.size() && find) {
1690            if (!listGenerate.contains(listCurrent.get(i)))
1691                   find = false;
1692            i++;
1693        }
1694
1695        return find;
1696    }
1697
1698    /**
1699     * get the attibut value in manifest file
1700     * @param jarName : the jar file containg manifest
1701     * @param attributName : the attribut name
1702     * @return the value corresponding to the attributName if it's exist null otherwise
1703     */

1704    private static String JavaDoc getAttributInManifest(String JavaDoc jarName, String JavaDoc attributName) {
1705        try {
1706            File JavaDoc jarFile = new File JavaDoc(jarName);
1707            JarFile JavaDoc jar = new JarFile JavaDoc(jarFile);
1708            Manifest JavaDoc man = jar.getManifest();
1709            Attributes JavaDoc atts = man.getMainAttributes();
1710            return atts.getValue(attributName);
1711        } catch (Exception JavaDoc e) {
1712            return null;
1713        }
1714    }
1715
1716    /**
1717     * Check that GenIC have been applied on the given ejb-jar file
1718     * If it was not done, it run GenIC against the file.
1719     * @param fileName given EJB-JAR file.
1720     */

1721    public void checkGenIC(String JavaDoc fileName) {
1722        // get Carol configuration to intialize Genic Arguments
1723
ProtocolConfiguration[] listCurrentProtocol = ConfigurationRepository.getConfigurations();
1724
1725        String JavaDoc[] genicArgsString = new String JavaDoc[2];
1726        genicArgsString[0] = "-protocols";
1727        String JavaDoc listProtocols = "";
1728        for (int i = 0; i < listCurrentProtocol.length; i++) {
1729            listProtocols = listProtocols + listCurrentProtocol[i].getName();
1730            if (i != (listCurrentProtocol.length - 1))
1731                listProtocols = listProtocols + ",";
1732        }
1733        genicArgsString[1] = listProtocols;
1734        String JavaDoc jonasVersionGenic = getAttributInManifest(fileName, "Genic-Jonas-Version");
1735        String JavaDoc listProtocolGenerated = getAttributInManifest(fileName, "Genic-Jonas-protocols");
1736
1737        boolean isCurrentProtocolIncludeIntoGenerated = checkCurrentProtocolIncludeIntoGenerated(listProtocolGenerated, listProtocols);
1738
1739        if ((jonasVersionGenic == null) || !jonasVersionGenic.equals(Version.NUMBER)
1740                || !isCurrentProtocolIncludeIntoGenerated) {
1741            // Print a little explaination before calling Genic
1742
if (jonasVersionGenic == null)
1743                servlog.log(BasicLevel.INFO, "JOnAS version is not find into " + fileName + " manifest file. Try to generate container classes...");
1744            else if (!jonasVersionGenic.equals(Version.NUMBER))
1745                servlog.log(BasicLevel.INFO, "JOnAS version find into " + fileName + " manifest file :" + jonasVersionGenic + " is different for the current JOnAS version : " + Version.NUMBER + ". Try to generate container classes...");
1746            else if (!isCurrentProtocolIncludeIntoGenerated)
1747                servlog.log(BasicLevel.INFO, "Current Carol protocol is not include into those find into" + fileName + " manifest file. Try to generate container classes...");
1748
1749            Object JavaDoc[] param = {fileName, genicArgsString};
1750            String JavaDoc[] signature = {"java.lang.String", "[Ljava.lang.String;"};
1751            // invoke method on the MBeanServer
1752
try {
1753                ObjectName JavaDoc j2eeServerON = J2eeObjectName.J2EEServer(this.getDomainName(), this.getJonasServerName());
1754                mbeanServer.invoke(j2eeServerON, "deployLocalFile", param, signature);
1755
1756            } catch (Exception JavaDoc e) {
1757                servlog.log(BasicLevel.WARN, "createContainer: " + fileName + " can't create generated classes", e);
1758            }
1759        }
1760    }
1761}
Popular Tags