Source Code Cross Referenced for EJBServiceImpl.java in  » J2EE » JOnAS-4.8.6 » org » objectweb » jonas » container » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » J2EE » JOnAS 4.8.6 » org.objectweb.jonas.container 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


0001:        /**
0002:         * JOnAS: Java(TM) Open Application Server
0003:         * Copyright (C) 1999-2005 Bull S.A.
0004:         * Contact: jonas-team@objectweb.org
0005:         *
0006:         * This library is free software; you can redistribute it and/or
0007:         * modify it under the terms of the GNU Lesser General Public
0008:         * License as published by the Free Software Foundation; either
0009:         * version 2.1 of the License, or any later version.
0010:         *
0011:         * This library is distributed in the hope that it will be useful,
0012:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
0013:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
0014:         * Lesser General Public License for more details.
0015:         *
0016:         * You should have received a copy of the GNU Lesser General Public
0017:         * License along with this library; if not, write to the Free Software
0018:         * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
0019:         * USA
0020:         *
0021:         * --------------------------------------------------------------------------
0022:         * $Id: EJBServiceImpl.java 9690 2006-10-06 14:08:25Z benoitf $
0023:         * --------------------------------------------------------------------------
0024:         */package org.objectweb.jonas.container;
0025:
0026:        import java.io.File;
0027:        import java.io.IOException;
0028:        import java.net.MalformedURLException;
0029:        import java.net.URL;
0030:        import java.net.URLClassLoader;
0031:        import java.util.ArrayList;
0032:        import java.util.Enumeration;
0033:        import java.util.HashMap;
0034:        import java.util.HashSet;
0035:        import java.util.Iterator;
0036:        import java.util.List;
0037:        import java.util.Map;
0038:        import java.util.Properties;
0039:        import java.util.Set;
0040:        import java.util.StringTokenizer;
0041:        import java.util.Vector;
0042:        import java.util.jar.Attributes;
0043:        import java.util.jar.JarFile;
0044:        import java.util.jar.Manifest;
0045:
0046:        import javax.management.MBeanException;
0047:        import javax.management.MBeanServer;
0048:        import javax.management.ObjectName;
0049:        import javax.management.OperationsException;
0050:        import javax.management.modelmbean.ModelMBean;
0051:        import javax.naming.Context;
0052:        import javax.naming.InitialContext;
0053:        import javax.naming.NamingException;
0054:
0055:        import org.apache.commons.modeler.ManagedBean;
0056:        import org.apache.commons.modeler.Registry;
0057:        import org.objectweb.carol.util.configuration.ConfigurationRepository;
0058:        import org.objectweb.carol.util.configuration.ProtocolConfiguration;
0059:        import org.objectweb.jonas.common.JModule;
0060:        import org.objectweb.jonas.common.JProp;
0061:        import org.objectweb.jonas.common.Log;
0062:        import org.objectweb.jonas.ear.EarServiceImpl;
0063:        import org.objectweb.jonas.jms.JmsService;
0064:        import org.objectweb.jonas.jmx.J2eeObjectName;
0065:        import org.objectweb.jonas.jmx.JmxService;
0066:        import org.objectweb.jonas.jmx.JonasObjectName;
0067:        import org.objectweb.jonas.jtm.TransactionService;
0068:        import org.objectweb.jonas.management.JonasMBeanTools;
0069:        import org.objectweb.jonas.naming.CompNamingContext;
0070:        import org.objectweb.jonas.naming.NamingManager;
0071:        import org.objectweb.jonas.security.SecurityService;
0072:        import org.objectweb.jonas.server.LoaderManager;
0073:        import org.objectweb.jonas.server.WorkManagerMBean;
0074:        import org.objectweb.jonas.service.AbsServiceImpl;
0075:        import org.objectweb.jonas.service.ServiceException;
0076:        import org.objectweb.jonas.service.ServiceManager;
0077:        import org.objectweb.jonas_ejb.container.BeanFactory;
0078:        import org.objectweb.jonas_ejb.container.Container;
0079:        import org.objectweb.jonas_ejb.container.JContainer;
0080:        import org.objectweb.jonas_ejb.container.JEntityFactory;
0081:        import org.objectweb.jonas_ejb.container.JFactory;
0082:        import org.objectweb.jonas_ejb.container.JSessionFactory;
0083:        import org.objectweb.jonas_ejb.container.JStatelessFactory;
0084:        import org.objectweb.jonas_ejb.container.PermissionManager;
0085:        import org.objectweb.jonas_ejb.deployment.api.BeanDesc;
0086:        import org.objectweb.jonas_ejb.deployment.api.DeploymentDesc;
0087:        import org.objectweb.jonas_ejb.deployment.api.EntityBmpDesc;
0088:        import org.objectweb.jonas_ejb.deployment.api.EntityCmpDesc;
0089:        import org.objectweb.jonas_ejb.deployment.api.SessionStatefulDesc;
0090:        import org.objectweb.jonas_ejb.deployment.api.SessionStatelessDesc;
0091:        import org.objectweb.jonas_ejb.deployment.lib.wrapper.EjbManagerWrapper;
0092:        import org.objectweb.jonas_jms.api.JmsManager;
0093:        import org.objectweb.jonas_lib.JWorkManager;
0094:        import org.objectweb.jonas_lib.deployment.api.DeploymentDescException;
0095:        import org.objectweb.jonas_lib.deployment.work.CleanerException;
0096:        import org.objectweb.jonas_lib.deployment.work.DeployerLog;
0097:        import org.objectweb.jonas_lib.deployment.work.DeployerLogException;
0098:        import org.objectweb.jonas_lib.deployment.work.FileManager;
0099:        import org.objectweb.jonas_lib.deployment.work.JarCleanTask;
0100:        import org.objectweb.jonas_lib.deployment.work.WorkCleaner;
0101:        import org.objectweb.jonas_lib.files.FileUtils;
0102:        import org.objectweb.jonas_lib.files.WsGenChecker;
0103:        import org.objectweb.jonas_lib.loader.EjbJarClassLoader;
0104:        import org.objectweb.jonas_lib.version.Version;
0105:        import org.objectweb.transaction.jta.TransactionManager;
0106:        import org.objectweb.util.monolog.api.BasicLevel;
0107:        import org.objectweb.util.monolog.api.Logger;
0108:
0109:        /**
0110:         * Implementation of the EJB Container Service for jonas. This class works only
0111:         * with jonas_ejb classes.
0112:         * @author Philippe Coq
0113:         * @author Jeff Mesnil (Security)
0114:         * @author Markus Karg (Novell port)
0115:         * @author Christophe Ney (for making easier Enhydra integration)
0116:         * @author Adriana Danes (complete management methods)
0117:         * @author Florent Benoit & Ludovic Bert (Ear service, deployJars, undeployJars)
0118:         * @author Benjamin Bonnet (max thread pool size)
0119:         * @author Michel-Ange Anton (JSR77 MBean : EJBModule)
0120:         * @author Adriana Danes (JSR77)
0121:         */
0122:        public class EJBServiceImpl extends AbsServiceImpl implements 
0123:                EJBService, EJBServiceImplMBean {
0124:
0125:            /** server logger */
0126:            private static Logger servlog = null;
0127:
0128:            /** loader logger */
0129:            private static Logger loaderlog = null;
0130:
0131:            /**
0132:             * Transaction manager reference (tm can be accessed directly from
0133:             * everywhere in the package.)
0134:             */
0135:            private TransactionManager tm = null;
0136:
0137:            /** JMS manager reference */
0138:            private JmsManager jms = null;
0139:
0140:            /** JMX Server */
0141:            private MBeanServer mbeanServer = null;
0142:
0143:            /** Security service reference */
0144:            private SecurityService securityService = null;
0145:
0146:            /**
0147:             * Reference to the cleaner
0148:             */
0149:            private static WorkCleaner workCleaner = null;
0150:
0151:            /**
0152:             * Modeler's MBean definition Registry
0153:             */
0154:            private Registry oRegistry = null;
0155:
0156:            /**
0157:             * List of the ejb names to load when starting the EJB Container Service
0158:             */
0159:            private Vector ejbNames = new Vector();
0160:
0161:            /** We have a Container by ejb-jar file. */
0162:            private Vector containers = new Vector();
0163:
0164:            /**
0165:             * Auto-GenIC is enabled or disabled ?
0166:             */
0167:            public static final String AUTO_GENIC = "jonas.service.ejb.auto-genic";
0168:
0169:            /**
0170:             * Arguments for the Auto-GenIC
0171:             */
0172:            public static final String AUTO_GENIC_ARGS = "jonas.service.ejb.auto-genic.args";
0173:
0174:            // ----------------------------------------------
0175:            // WorkManager thread pool sizes
0176:            // ----------------------------------------------
0177:            /** Min Work Thread property name */
0178:            public static final String MINWORKTHREADS = "jonas.service.ejb.minworkthreads";
0179:
0180:            /** Min Work Thread default value */
0181:            private static final int DEFAULT_MINWORKTHREADS = 3;
0182:
0183:            /** Max Work Thread property name */
0184:            public static final String MAXWORKTHREADS = "jonas.service.ejb.maxworkthreads";
0185:
0186:            /** Max Work Thread default value */
0187:            private static final int DEFAULT_MAXWORKTHREADS = 80;
0188:
0189:            /** Thread Wait Timeout property name */
0190:            public static final String THREADWAITTIMEOUT = "jonas.service.ejb.threadwaittimeout";
0191:
0192:            /** Thread Wait Timeout default value */
0193:            private static final int DEFAULT_THREADWAITTIMEOUT = 60;
0194:
0195:            /** The WorkManager instance */
0196:            private JWorkManager workManager;
0197:
0198:            /**
0199:             * The name of the JONAS_BASE directory.
0200:             */
0201:            protected static final String JONAS_BASE = JProp.getJonasBase();
0202:
0203:            /**
0204:             * The name of the directory containing the ejb-jar files.
0205:             */
0206:            protected static final String EJBJARS_DIR = JONAS_BASE
0207:                    + File.separator + "ejbjars";
0208:
0209:            /**
0210:             * List of autoloaded directories.
0211:             */
0212:            private ArrayList autoloadDirectories = new ArrayList();
0213:
0214:            /** base for properties */
0215:            public static final String JONAS_EJB = "jonas.service.ejb";
0216:
0217:            /** autoloaddir property */
0218:            public static final String AUTOLOADDIR = JONAS_EJB + ".autoloaddir";
0219:
0220:            /** parsing with validation property */
0221:            public static final String PARSINGWITHVALIDATION = JONAS_EJB
0222:                    + ".parsingwithvalidation";
0223:
0224:            /** descriptors property */
0225:            public static final String DESCRIPTORS = JONAS_EJB + ".descriptors";
0226:
0227:            /** EJB service class */
0228:            public static final String CLASS = JONAS_EJB + ".class";
0229:
0230:            /** BeanManaged Management properties */
0231:            public static final String BMP = "Bean-Managed";
0232:
0233:            /** ContainerManaged Management properties */
0234:            public static final String CMP = "Container-Managed";
0235:
0236:            /** applications parent classloader */
0237:            private ClassLoader appsClassLoader = null;
0238:
0239:            /**
0240:             * The name of the working directory.
0241:             */
0242:            private static final String WORK_DIR = JProp.getWorkDir();
0243:
0244:            /**
0245:             * The name of the working ejbjars directory.
0246:             */
0247:            private static final String WORK_EJBJARS_DIR = WORK_DIR
0248:                    + File.separator + "ejbjars";
0249:
0250:            /**
0251:             *
0252:             */
0253:            private static String ejbjarsDir = null;
0254:
0255:            /**
0256:             * Reference on the DeployerLog which is the class that manage the accesses
0257:             * to the log file (to remove the jar).
0258:             */
0259:            private DeployerLog jarDeployerLog = null;
0260:
0261:            /**
0262:             * Auto-GenIC has been enabled or not ?
0263:             */
0264:            private boolean autoGenIC = true;
0265:
0266:            /**
0267:             * List of arguments for the autoGenIC.
0268:             */
0269:            private List autoGenICArgsList = null;
0270:
0271:            // -------------------------------------------------------------------
0272:            // JOnAS Service Implementation
0273:            // -------------------------------------------------------------------
0274:
0275:            /**
0276:             * Init the Service. Configuration information is passed thru a Context
0277:             * object.
0278:             */
0279:            public void doInit(Context ctx) throws ServiceException {
0280:                servlog = Log.getLogger(Log.JONAS_SERVER_PREFIX);
0281:                loaderlog = Log.getLogger(Log.JONAS_LOADER_PREFIX);
0282:
0283:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
0284:                    servlog.log(BasicLevel.DEBUG, "");
0285:                }
0286:
0287:                // get apps ClassLoader
0288:                try {
0289:                    LoaderManager lm = LoaderManager.getInstance();
0290:                    appsClassLoader = lm.getAppsLoader();
0291:                } catch (Exception e) {
0292:                    servlog
0293:                            .log(BasicLevel.ERROR,
0294:                                    "Cannot get the Applications ClassLoader from EJB Container Service");
0295:                    throw new ServiceException(
0296:                            "Cannot get the Applications ClassLoader from EJB Container Service",
0297:                            e);
0298:                }
0299:
0300:                ServiceManager serviceManager = null;
0301:                try {
0302:                    serviceManager = ServiceManager.getInstance();
0303:                } catch (Exception e) {
0304:                    servlog.log(BasicLevel.ERROR,
0305:                            "Cannot initialize the EJB Container Service");
0306:                    throw new ServiceException(
0307:                            "Cannot initialize the EJB Container Service", e);
0308:                }
0309:                // Get the used services
0310:                try {
0311:                    // Get the Transaction Manager via the jtm service
0312:                    TransactionService jtmService = (TransactionService) serviceManager
0313:                            .getTransactionService();
0314:                    tm = jtmService.getTransactionManager();
0315:                } catch (ServiceException e) {
0316:                    servlog.log(BasicLevel.ERROR,
0317:                            "Cannot initialize the EJB Container Service");
0318:                    throw new ServiceException(
0319:                            "Cannot initialize the EJB Container Service", e);
0320:                }
0321:
0322:                try {
0323:                    // Get the Security service
0324:                    securityService = (SecurityService) serviceManager
0325:                            .getSecurityService();
0326:                } catch (ServiceException se) {
0327:                    // The Security service may not be started
0328:                    securityService = null;
0329:                }
0330:
0331:                try {
0332:                    // Get the JMS manager via the JMS service
0333:                    JmsService jmsService = (JmsService) serviceManager
0334:                            .getJmsService();
0335:                    jms = jmsService.getJmsManager();
0336:                } catch (ServiceException e) {
0337:                    // the JMS service may not be started
0338:                    jms = null;
0339:                }
0340:
0341:                try {
0342:                    // Get the JMX Server via JMX Service
0343:                    JmxService jmxService = (JmxService) serviceManager
0344:                            .getJmxService();
0345:                    mbeanServer = jmxService.getJmxServer();
0346:                } catch (ServiceException e) {
0347:                    // the JMX service may not be started
0348:                    mbeanServer = null;
0349:                }
0350:                oRegistry = JonasMBeanTools.getRegistry();
0351:
0352:                // Set the XML parsing mode to no validation
0353:                String parsingMode;
0354:                try {
0355:                    parsingMode = (String) ctx.lookup(PARSINGWITHVALIDATION);
0356:                } catch (NamingException e) {
0357:                    // No problem if there is no value for 'parsingwithvalidation'
0358:                    // (false by default)
0359:                    parsingMode = "false";
0360:                }
0361:                if ("false".equalsIgnoreCase(parsingMode)) {
0362:                    EjbManagerWrapper.setParsingWithValidation(false);
0363:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0364:                        servlog.log(BasicLevel.DEBUG,
0365:                                "XML parsing without validation");
0366:                    }
0367:                } else {
0368:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0369:                        servlog.log(BasicLevel.DEBUG,
0370:                                "XML parsing with validation");
0371:                    }
0372:                }
0373:
0374:                // Init the ejb names to be loaded when starting
0375:                String descsValue;
0376:                try {
0377:                    descsValue = (String) ctx.lookup(DESCRIPTORS);
0378:                } catch (NamingException e) {
0379:                    // No problem if there is no value for 'descriptors' (no ejb to
0380:                    // load)
0381:                    descsValue = null;
0382:                }
0383:                if (descsValue != null) {
0384:                    StringTokenizer st = new StringTokenizer(descsValue, ",");
0385:                    while (st.hasMoreTokens()) {
0386:                        String fileName = st.nextToken().trim();
0387:                        ejbNames.add(fileName);
0388:                    }
0389:                }
0390:
0391:                // Add the jars of the jonas.service.ejb.autoloaddir property
0392:                String dirValue;
0393:                ArrayList autoDirs = new ArrayList();
0394:                try {
0395:                    dirValue = (String) ctx.lookup(AUTOLOADDIR);
0396:                } catch (NamingException e) {
0397:                    // No problem if there is no value for 'autoloaddir'
0398:                    //(no ejb to load)
0399:                    dirValue = null;
0400:                }
0401:                if (dirValue != null) {
0402:                    StringTokenizer st = new StringTokenizer(dirValue, ",");
0403:                    while (st.hasMoreTokens()) {
0404:                        String dirName = st.nextToken().trim();
0405:                        addEjbjars(dirName);
0406:                        autoDirs.add(dirName);
0407:                    }
0408:                }
0409:                // Build autoload directories
0410:                File oFile;
0411:                for (int i = 0; i < autoDirs.size(); i++) {
0412:                    try {
0413:                        oFile = new File(EJBJARS_DIR, autoDirs.get(i)
0414:                                .toString());
0415:                        if (oFile.exists()) {
0416:                            autoloadDirectories.add(oFile.getCanonicalPath());
0417:                        } else {
0418:                            oFile = new File(autoDirs.get(i).toString());
0419:                        }
0420:                    } catch (Exception e) {
0421:                        String err = "Error when trying to verify Ejbjar autoload directory : "
0422:                                + autoDirs.get(i);
0423:                        servlog.log(BasicLevel.ERROR, err, e);
0424:                    }
0425:                }
0426:
0427:                // Create the WorkManager (thread Pool)
0428:                int minWorkThreads;
0429:                try {
0430:                    String plz = (String) ctx.lookup(MINWORKTHREADS);
0431:                    minWorkThreads = (new Integer(plz)).intValue();
0432:                } catch (NamingException e) {
0433:                    // default value will be used.
0434:                    minWorkThreads = DEFAULT_MINWORKTHREADS;
0435:                }
0436:                int maxWorkThreads;
0437:                try {
0438:                    String mxplz = (String) ctx.lookup(MAXWORKTHREADS);
0439:                    maxWorkThreads = (new Integer(mxplz)).intValue();
0440:                } catch (NamingException e) {
0441:                    // default value will be used.
0442:                    maxWorkThreads = DEFAULT_MAXWORKTHREADS;
0443:                }
0444:                int threadWaitTimeout;
0445:                try {
0446:                    String tto = (String) ctx.lookup(THREADWAITTIMEOUT);
0447:                    threadWaitTimeout = (new Integer(tto)).intValue();
0448:                } catch (NamingException e) {
0449:                    // default value will be used.
0450:                    threadWaitTimeout = DEFAULT_THREADWAITTIMEOUT;
0451:                }
0452:                workManager = new JWorkManager(minWorkThreads, maxWorkThreads,
0453:                        tm, threadWaitTimeout);
0454:
0455:                // Auto GenIC ?
0456:                try {
0457:                    String propAutoGenIC = (String) ctx.lookup(AUTO_GENIC);
0458:                    if (propAutoGenIC != null) {
0459:                        autoGenIC = new Boolean(propAutoGenIC).booleanValue();
0460:                    }
0461:                    if (!autoGenIC) {
0462:                        servlog.log(BasicLevel.INFO,
0463:                                "Auto GenIC has been disabled");
0464:                    }
0465:                } catch (NamingException e) {
0466:                    servlog.log(BasicLevel.DEBUG, "Property '" + AUTO_GENIC
0467:                            + "' is missing", e);
0468:                }
0469:
0470:                // Arguments for Auto-GenIC
0471:                autoGenICArgsList = new ArrayList();
0472:                int autoGenICArgInt = 0;
0473:                boolean loopArg = true;
0474:                while (loopArg) {
0475:                    try {
0476:                        String arg = (String) ctx.lookup(AUTO_GENIC_ARGS + "."
0477:                                + autoGenICArgInt);
0478:                        autoGenICArgsList.add(arg);
0479:                    } catch (NamingException e) {
0480:                        loopArg = false;
0481:                    }
0482:                    autoGenICArgInt++;
0483:                }
0484:                if (!autoGenICArgsList.isEmpty()) {
0485:                    servlog.log(BasicLevel.INFO, "Auto GenIC args are set to '"
0486:                            + autoGenICArgsList + "'.");
0487:                }
0488:
0489:                // Create and register the MBean for this WorkManager
0490:                ObjectName mbn;
0491:                try {
0492:                    mbn = JonasObjectName.workManager();
0493:                    ManagedBean oManaged = oRegistry
0494:                            .findManagedBean("WorkManager");
0495:                    ModelMBean oMBean = oManaged
0496:                            .createMBean(new WorkManagerMBean(workManager));
0497:                    mbeanServer.registerMBean(oMBean, mbn);
0498:                } catch (Exception e) {
0499:                    servlog.log(BasicLevel.ERROR, "Cannot create MBean", e);
0500:                }
0501:
0502:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
0503:                    servlog.log(BasicLevel.DEBUG,
0504:                            "EJB Container Service initialized");
0505:                }
0506:            }
0507:
0508:            /**
0509:             * @return Returns the WorkManager instance
0510:             */
0511:            public JWorkManager getWorkManager() {
0512:                return workManager;
0513:            }
0514:
0515:            /**
0516:             * Start the Service Initialization of the service is already done.
0517:             */
0518:            public void doStart() throws ServiceException {
0519:
0520:                ejbjarsDir = WORK_EJBJARS_DIR + File.separator
0521:                        + getJonasServerName();
0522:
0523:                URL ejbjarsUrl = null;
0524:                try {
0525:                    ejbjarsUrl = new File(ejbjarsDir).toURL();
0526:                } catch (MalformedURLException mue) {
0527:                    throw new ServiceException(
0528:                            "Error when trying to get the URL of the jonasroot/apps directory",
0529:                            mue);
0530:                }
0531:
0532:                File fLog = new File(ejbjarsUrl.getFile() + File.separator
0533:                        + getJonasServerName() + ".log");
0534:                if (!fLog.exists()) {
0535:                    try {
0536:                        //create
0537:                        fLog.getParentFile().mkdirs();
0538:                        fLog.createNewFile();
0539:                    } catch (IOException e) {
0540:                        throw new ServiceException("cannot create the log file"
0541:                                + fLog, e);
0542:                    }
0543:                }
0544:
0545:                //get the logger
0546:                try {
0547:                    jarDeployerLog = new DeployerLog(fLog);
0548:                } catch (DeployerLogException e) {
0549:                    throw new ServiceException("Can not get an EarDeployerLog",
0550:                            e);
0551:                }
0552:
0553:                // create the jar deployment work file control task
0554:                JarCleanTask jarCleanTask = new JarCleanTask(jarDeployerLog);
0555:
0556:                //get the cleaner ref
0557:                workCleaner = WorkCleaner.getInstance();
0558:
0559:                // add the jar deployment work file control task
0560:                try {
0561:                    workCleaner.registerTask(jarCleanTask);
0562:                } catch (CleanerException ce) {
0563:                    throw new ServiceException(
0564:                            "Cannot register the JAR clean task", ce);
0565:
0566:                }
0567:
0568:                // force the cleaning immediately
0569:                workCleaner.executeTasks();
0570:
0571:                // Creates all predefined containers
0572:                // 1 container per ejbjar file.
0573:                String fileName = null;
0574:                Context contctx = null;
0575:                for (int i = 0; i < ejbNames.size(); i++) {
0576:                    fileName = (String) ejbNames.elementAt(i);
0577:                    try {
0578:                        contctx = new CompNamingContext(fileName);
0579:                        contctx.rebind("filename", fileName);
0580:                    } catch (NamingException ne) {
0581:                        servlog.log(BasicLevel.WARN,
0582:                                "Cannot create container for " + fileName
0583:                                        + " because of a NamingException : "
0584:                                        + ne.toString());
0585:                    }
0586:
0587:                    try {
0588:                        createContainer(contctx);
0589:                    } catch (Exception e) {
0590:                        servlog.log(BasicLevel.WARN,
0591:                                "Cannot create container for " + fileName, e);
0592:                        // Close naming context
0593:                        try {
0594:                            contctx.close();
0595:                        } catch (NamingException nne) {
0596:                            if (servlog.isLoggable(BasicLevel.DEBUG)) {
0597:                                servlog.log(BasicLevel.DEBUG,
0598:                                        "Cannot close deploy context for "
0599:                                                + fileName, nne);
0600:                            }
0601:                        }
0602:                    }
0603:                }
0604:
0605:                // Register EJBService MBean : EJBServiceImplMBean
0606:                if (mbeanServer != null) {
0607:                    try {
0608:                        mbeanServer.registerMBean(this , JonasObjectName
0609:                                .ejbService());
0610:                    } catch (MBeanException mbe) {
0611:                        // registration failed because a MBeanException
0612:                        servlog
0613:                                .log(BasicLevel.WARN,
0614:                                        "Cannot register the EJB Container Service in the MBean Server.");
0615:                        servlog.log(BasicLevel.WARN,
0616:                                "Regstration failure cause : "
0617:                                        + mbe.getTargetException().toString());
0618:                    } catch (OperationsException me) {
0619:                        // registration failed because a OperationsException JMX
0620:                        // Exception
0621:                        servlog
0622:                                .log(
0623:                                        BasicLevel.WARN,
0624:                                        "Cannot register the EJB Container Service in the MBean Server.",
0625:                                        me);
0626:                    }
0627:                }
0628:            }
0629:
0630:            /**
0631:             * Stop the service: - Remove all JOnAS Containers. - Unbinds all the
0632:             * EJBHome names from JNDI
0633:             */
0634:            public void doStop() {
0635:
0636:                Enumeration lc = containers.elements();
0637:                while (lc.hasMoreElements()) {
0638:                    Container cont = (Container) lc.nextElement();
0639:                    removeContainer(cont);
0640:                }
0641:                if (mbeanServer != null) {
0642:                    try {
0643:                        // unregister EJBService MBean : EJBServiceImplMBean
0644:                        mbeanServer.unregisterMBean(JonasObjectName
0645:                                .ejbService());
0646:                    } catch (Exception e) {
0647:                        servlog.log(BasicLevel.ERROR,
0648:                                "Cannot stop the EJB Container Service", e);
0649:                    }
0650:                }
0651:
0652:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
0653:                    servlog.log(BasicLevel.DEBUG,
0654:                            "EJB Container Service stopped");
0655:                }
0656:            }
0657:
0658:            // -------------------------------------------------------------------
0659:            // EJBService Implementation
0660:            // -------------------------------------------------------------------
0661:
0662:            /**
0663:             * Create a JOnAS Container for all the beans that are described in a .xml
0664:             * file, or belong to .jar file.
0665:             * @return The ObjectName of the MBean associated to the container (i.e. to
0666:             *         the deployed module)
0667:             * @throws Exception if an error occur during the creation of the container.
0668:             */
0669:            public String createContainer(Context ctx) throws Exception {
0670:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
0671:                    servlog.log(BasicLevel.DEBUG, "");
0672:                }
0673:
0674:                // Get the file name
0675:                String fileName = (String) ctx.lookup("filename");
0676:                File f = new File(fileName).getCanonicalFile();
0677:
0678:                boolean isEjbJar = fileName.toLowerCase().endsWith(".jar");
0679:
0680:                // check if the file exists
0681:                // In case of the name is a ejb-jar file name, check also in
0682:                // the JONAS_BASE/ejbjars directory
0683:                try {
0684:                    if (!f.exists() && isEjbJar) {
0685:                        String ejbjarFileName = EJBJARS_DIR + File.separator
0686:                                + fileName;
0687:                        f = new File(ejbjarFileName).getCanonicalFile();
0688:                        if (!f.exists()) {
0689:                            servlog.log(BasicLevel.ERROR, "createContainer: "
0690:                                    + fileName + " not found");
0691:                            throw new NamingException(fileName + " not found");
0692:                        }
0693:                    }
0694:                } catch (IOException e) {
0695:                    String err = "Invalid ejbjar file name '" + fileName;
0696:                    servlog.log(BasicLevel.ERROR, err);
0697:                    throw new Exception(err, e);
0698:                }
0699:                boolean isEjbJarFile = isEjbJar && f.isFile();
0700:                boolean isEjbJarXml = fileName.toLowerCase().endsWith(".xml")
0701:                        && f.isFile();
0702:
0703:                // Force fileName with slash to avoid conflict under Windows (slash and
0704:                // back-slash)
0705:                try {
0706:                    fileName = f.toURL().getPath();
0707:                } catch (MalformedURLException e) {
0708:                    servlog.log(BasicLevel.ERROR, "Invalid ejb-jar file name '"
0709:                            + fileName + "'", e);
0710:                }
0711:
0712:                if (f.isFile()) {
0713:                    if (!isEjbJar && !isEjbJarXml) {
0714:                        throw new ServiceException(
0715:                                "The ejbjar to deploy is not a jar file nor an xml file");
0716:                    }
0717:                }
0718:
0719:                // Check if container already exists
0720:                if (getContainer(fileName) != null) {
0721:                    servlog.log(BasicLevel.ERROR, "createContainer: "
0722:                            + fileName + " already exists");
0723:                    throw new Exception("Container already exists");
0724:                }
0725:
0726:                // In order to avoid lock problem after undeploy
0727:                // the jar file is copied under the working directory before its loading
0728:                // ! only if the ejbjars isn't included in an ear
0729:                boolean isInEar = true;
0730:                try {
0731:                    ctx.lookup("earClassLoader");
0732:                } catch (NamingException ne) {
0733:                    isInEar = false;
0734:                }
0735:
0736:                // if need, call Genic. Only in single ejb-jar mode.
0737:                // In ear case, this has been checked by ear service.
0738:                if (!isInEar && isEjbJar) {
0739:                    checkGenIC(fileName, null);
0740:
0741:                    ObjectName j2eeServer = J2eeObjectName.J2EEServer(this 
0742:                            .getDomainName(), this .getJonasServerName());
0743:                    WsGenChecker wsgc = new WsGenChecker(this .mbeanServer,
0744:                            fileName, j2eeServer);
0745:                    String resultFilename = wsgc.checkWsGen();
0746:
0747:                    if (resultFilename.endsWith(".ear")) {
0748:                        // WsGen has produced a new Application
0749:                        // It has already been deployed by 'ear' service
0750:                        // TODO Should return the EJB Module ObjectName of the ear
0751:                        return J2eeObjectName.getEJBModule(
0752:                                this .getDomainName(),
0753:                                this .getJonasServerName(),
0754:                                buildEJBModuleName(resultFilename),
0755:                                buildEJBModuleName(fileName))
0756:                                .getCanonicalName();
0757:                    }
0758:                }
0759:
0760:                String wkFileName = null;
0761:
0762:                if (!isInEar && isEjbJarFile) {
0763:                    // Get the destination file
0764:                    wkFileName = ejbjarsDir + File.separator
0765:                            + FileManager.fileToTimeStampDir(f.toURL(), ".jar");
0766:
0767:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0768:                        servlog.log(BasicLevel.DEBUG, "filename=" + fileName);
0769:                        servlog.log(BasicLevel.DEBUG, "wkFilename="
0770:                                + wkFileName);
0771:                    }
0772:
0773:                    // copy the file
0774:                    FileUtils.copyFile(fileName, wkFileName);
0775:
0776:                    // add an entry in the log file
0777:                    try {
0778:                        jarDeployerLog.addEntry(f, new File(wkFileName));
0779:                    } catch (DeployerLogException e) {
0780:                        String err = "Error while adding the " + fileName
0781:                                + " entry in the log file";
0782:                        servlog.log(BasicLevel.ERROR, err + " : "
0783:                                + e.getMessage());
0784:                        throw new Exception(err, e);
0785:                    }
0786:
0787:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0788:                        servlog.log(BasicLevel.DEBUG, "Create wk file :"
0789:                                + wkFileName);
0790:                    }
0791:
0792:                } else {
0793:                    // in this case, no needs to copy the file
0794:                    wkFileName = fileName;
0795:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0796:                        servlog.log(BasicLevel.DEBUG, "No needs wk file :"
0797:                                + wkFileName);
0798:                    }
0799:                }
0800:
0801:                // Classloader
0802:                URL[] url = null;
0803:                try {
0804:                    url = new URL[1];
0805:                    url[0] = (new File(wkFileName)).toURL();
0806:                } catch (MalformedURLException e) {
0807:                    servlog.log(BasicLevel.ERROR, "Invalid ejb-jar file name '"
0808:                            + wkFileName + "'", e);
0809:                }
0810:
0811:                // Get the classloaders
0812:                URLClassLoader ejbClassLoader = null;
0813:                URLClassLoader earClassLoader = null;
0814:                try {
0815:                    earClassLoader = (URLClassLoader) ctx
0816:                            .lookup("earClassLoader");
0817:                    ejbClassLoader = (URLClassLoader) ctx
0818:                            .lookup("ejbClassLoader");
0819:                    if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
0820:                        loaderlog.log(BasicLevel.DEBUG, "earClassLoader="
0821:                                + earClassLoader);
0822:                    }
0823:                } catch (NamingException ne) {
0824:                    // no ear classloader => ejb application case (not ear case).
0825:                    if (isEjbJar) {
0826:                        ejbClassLoader = new EjbJarClassLoader(url,
0827:                                appsClassLoader);
0828:                    } else {
0829:                        ejbClassLoader = (URLClassLoader) appsClassLoader;
0830:                    }
0831:                    if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
0832:                        loaderlog.log(BasicLevel.DEBUG, "parent Loader="
0833:                                + appsClassLoader);
0834:                    }
0835:                }
0836:                if (loaderlog.isLoggable(BasicLevel.DEBUG)) {
0837:                    loaderlog.log(BasicLevel.DEBUG, "ejbClassLoader="
0838:                            + ejbClassLoader);
0839:                }
0840:
0841:                // Get the deployment descriptor from file
0842:                DeploymentDesc dd = null;
0843:                try {
0844:                    // ejb-jar file
0845:                    dd = EjbManagerWrapper.getDeploymentDesc(url[0],
0846:                            ejbClassLoader, earClassLoader);
0847:                } catch (DeploymentDescException e) {
0848:                    String err = "Cannot read the deployment descriptors '"
0849:                            + fileName + "'";
0850:                    servlog.log(BasicLevel.ERROR, err);
0851:                    servlog.log(BasicLevel.ERROR, "DeploymentDescException:"
0852:                            + e);
0853:                    throw new ServiceException(err, e);
0854:                }
0855:
0856:                // container name
0857:                String cname = buildEJBModuleName(fileName);
0858:                if (cname == null) {
0859:                    //use displayName
0860:                    cname = "EJB container ";
0861:                    if (dd.getDisplayName() != null) {
0862:                        cname += dd.getDisplayName();
0863:                    }
0864:                }
0865:
0866:                // Create the Container Object
0867:                JContainer cont = new JContainer(cname, fileName, wkFileName,
0868:                        ejbClassLoader);
0869:                cont.setContainerNaming(NamingManager.getInstance());
0870:                cont.setTransactionManager(tm);
0871:                cont.setPrincipalFactory(new PrincipalFactoryImpl());
0872:                cont.setJmsManager(jms);
0873:
0874:                // Set the name of the ear application containing this container
0875:                // in the case of an ear application.
0876:                URL earUrl = null;
0877:                String earFileName;
0878:                try {
0879:                    earUrl = (URL) ctx.lookup("earURL");
0880:                    //earFileName = (String) ctx.lookup("earFileName");
0881:                    earFileName = earUrl.getFile();
0882:                    cont.setEarFileName(earFileName);
0883:                } catch (NamingException ne) {
0884:                    earFileName = null;
0885:                }
0886:
0887:                // unset the security if no security service
0888:                if (securityService == null) {
0889:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
0890:                        servlog
0891:                                .log(BasicLevel.DEBUG,
0892:                                        "EJB Container Service: working without Security Service");
0893:                    }
0894:                    cont.setSecurity(false);
0895:                } else {
0896:                    PermissionManager permissionManager = null;
0897:                    try {
0898:                        permissionManager = new PermissionManager(dd, cont
0899:                                .getContextId());
0900:                        permissionManager.translateEjbDeploymentDescriptor();
0901:                        // if not in ear case, commit the policy configuration, else it
0902:                        // is done
0903:                        // by EAR service after linking all policy configuration objects
0904:                        if (!isInEar) {
0905:                            permissionManager.commit();
0906:                        }
0907:                    } catch (Exception e) {
0908:                        servlog.log(BasicLevel.ERROR,
0909:                                "Can't build permission manager object for the ejbjar '"
0910:                                        + fileName + "'", e);
0911:                    }
0912:                    cont.setPermissionManager(permissionManager);
0913:                }
0914:
0915:                // Give access to the WorkManager
0916:                cont.setWorkManager(workManager);
0917:
0918:                String domainName = getDomainName();
0919:                String serverName = getJonasServerName();
0920:                String j2eeAppName = EarServiceImpl
0921:                        .buildJ2eeApplicationName(earFileName);
0922:                EJBModule ejbModuleMBean = null;
0923:                ObjectName onEjbModule = null;
0924:
0925:                // MBeans to register if the deployment is successful
0926:                Map mbeansToRegister = new HashMap();
0927:
0928:                // EJBModule MBean registering
0929:                if (mbeanServer != null) {
0930:                    // Use the conatiner name (the 'name' constructor parameter of
0931:                    // JContainer class)
0932:                    // as the "name" keyProperty for the J2ee ObjectName construction
0933:                    onEjbModule = J2eeObjectName.getEJBModule(domainName,
0934:                            serverName, j2eeAppName, cname);
0935:
0936:                    ejbModuleMBean = new EJBModule(onEjbModule, cont, fileName,
0937:                            cname, j2eeAppName, earUrl);
0938:                    ejbModuleMBean.setDeploymentDescriptor(dd.getXmlContent());
0939:                    ejbModuleMBean.setJonasDeploymentDescriptor(dd
0940:                            .getJOnASXmlContent());
0941:
0942:                    // Use Jakarta Common Modeler API
0943:                    ManagedBean oManaged = oRegistry
0944:                            .findManagedBean("EJBModule");
0945:                    ModelMBean oMBean = oManaged.createMBean(ejbModuleMBean);
0946:                    mbeansToRegister.put(oMBean, onEjbModule);
0947:                }
0948:
0949:                // Process each bean from the DD
0950:                BeanDesc[] beans = dd.getBeanDesc();
0951:                for (int i = 0; i < beans.length; i++) {
0952:                    BeanFactory bf = cont.addBean(beans[i]);
0953:                    beans[i].setBeanFactory(bf);
0954:                    if (mbeanServer != null) {
0955:                        try {
0956:                            // register MBean for this ejb
0957:                            String beanName = beans[i].getEjbName();
0958:                            if ((beans[i] instanceof  EntityBmpDesc)
0959:                                    || (beans[i] instanceof  EntityCmpDesc)) {
0960:                                JEntityFactory jef = (JEntityFactory) bf;
0961:                                ObjectName onEntityBean = J2eeObjectName
0962:                                        .getEntityBean(domainName, cname,
0963:                                                serverName, j2eeAppName,
0964:                                                beanName);
0965:                                EntityBean entityBeanMBean; // new EntityBean
0966:                                // declaration
0967:                                if (beans[i] instanceof  EntityBmpDesc) {
0968:                                    entityBeanMBean = new EntityBean(
0969:                                            onEntityBean.toString(), jef, BMP);
0970:                                } else {
0971:                                    entityBeanMBean = new EntityBean(
0972:                                            onEntityBean.toString(), jef, CMP);
0973:                                }
0974:                                ManagedBean oManaged = oRegistry
0975:                                        .findManagedBean("EntityBean");
0976:                                ModelMBean oMBean = oManaged
0977:                                        .createMBean(entityBeanMBean);
0978:                                mbeansToRegister.put(oMBean, onEntityBean);
0979:                                // Update the EJBModule
0980:                                ejbModuleMBean.addEjb(onEntityBean.toString());
0981:                            } else if (beans[i] instanceof  SessionStatefulDesc) {
0982:                                JSessionFactory jsf = (JSessionFactory) bf;
0983:                                ObjectName onStatefulSessionBean = J2eeObjectName
0984:                                        .getStatefulSessionBean(domainName,
0985:                                                cname, serverName, j2eeAppName,
0986:                                                beanName);
0987:                                StatefulSessionBean sessionBeanMBean = new StatefulSessionBean(
0988:                                        onStatefulSessionBean.toString(), jsf);
0989:                                ManagedBean oManaged = oRegistry
0990:                                        .findManagedBean("StatefulSessionBean");
0991:                                ModelMBean oMBean = oManaged
0992:                                        .createMBean(sessionBeanMBean);
0993:                                mbeansToRegister.put(oMBean,
0994:                                        onStatefulSessionBean);
0995:                                // Update the EJBModule
0996:                                ejbModuleMBean.addEjb(onStatefulSessionBean
0997:                                        .toString());
0998:                            } else if (beans[i] instanceof  SessionStatelessDesc) {
0999:                                JStatelessFactory jsf = (JStatelessFactory) bf;
1000:                                ObjectName onStatelessSessionBean = J2eeObjectName
1001:                                        .getStatelessSessionBean(domainName,
1002:                                                cname, serverName, j2eeAppName,
1003:                                                beanName);
1004:                                StatelessSessionBean sessionBeanMBean = new StatelessSessionBean(
1005:                                        onStatelessSessionBean.toString(), jsf);
1006:                                ManagedBean oManaged = oRegistry
1007:                                        .findManagedBean("StatelessSessionBean");
1008:                                ModelMBean oMBean = oManaged
1009:                                        .createMBean(sessionBeanMBean);
1010:                                mbeansToRegister.put(oMBean,
1011:                                        onStatelessSessionBean);
1012:                                // Update the EJBModule
1013:                                ejbModuleMBean.addEjb(onStatelessSessionBean
1014:                                        .toString());
1015:                            } else {
1016:                                JFactory jmf = (JFactory) bf;
1017:                                ObjectName onMessageDrivenBean = J2eeObjectName
1018:                                        .getMessageDrivenBean(domainName,
1019:                                                cname, serverName, j2eeAppName,
1020:                                                beanName);
1021:                                MessageDrivenBean messageDrivenBeanMBean = new MessageDrivenBean(
1022:                                        onMessageDrivenBean.toString(), jmf);
1023:                                ManagedBean oManaged = oRegistry
1024:                                        .findManagedBean("MessageDrivenBean");
1025:                                ModelMBean oMBean = oManaged
1026:                                        .createMBean(messageDrivenBeanMBean);
1027:                                mbeansToRegister.put(oMBean,
1028:                                        onMessageDrivenBean);
1029:                                // Update the EJBModule
1030:                                ejbModuleMBean.addEjb(onMessageDrivenBean
1031:                                        .toString());
1032:                            }
1033:                        } catch (Exception e) {
1034:                            servlog.log(BasicLevel.ERROR,
1035:                                    "Cannot create container", e);
1036:                        }
1037:                    }
1038:                }
1039:                // Init now pools of instances, in case min-pool-size have been defined.
1040:                // This must be done once all beans have been deployed.
1041:                for (int i = 0; i < beans.length; i++) {
1042:                    BeanFactory bf = beans[i].getBeanFactory();
1043:                    bf.initInstancePool();
1044:                }
1045:
1046:                // Deployment was successful, add the bean as deployed and create the
1047:                // MBeans
1048:                containers.addElement(cont);
1049:                for (Iterator it = mbeansToRegister.keySet().iterator(); it
1050:                        .hasNext();) {
1051:                    ModelMBean mbean = (ModelMBean) it.next();
1052:                    ObjectName oName = (ObjectName) mbeansToRegister.get(mbean);
1053:                    mbeanServer.registerMBean(mbean, oName);
1054:
1055:                }
1056:
1057:                // Restart Timers. Must be done when containers has been updated.
1058:                for (int i = 0; i < beans.length; i++) {
1059:                    BeanFactory bf = beans[i].getBeanFactory();
1060:                    bf.restartTimers();
1061:                }
1062:
1063:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1064:                    servlog.log(BasicLevel.DEBUG, "created container for "
1065:                            + fileName);
1066:                }
1067:                //return cont;
1068:                return onEjbModule.toString();
1069:            }
1070:
1071:            /**
1072:             * Get the Container by its file name (.xml or .jar)
1073:             * @param fileName given file name on which
1074:             * @return Container
1075:             */
1076:            public Container getContainer(String fileName) {
1077:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1078:                    servlog.log(BasicLevel.DEBUG, fileName);
1079:                }
1080:
1081:                // In case of the name is a ejb-jar file name, check also in
1082:                // the JONAS_BASE/ejbjars directory and JONAS_BASE/ejbjars/autoload
1083:
1084:                String ejbjarFileName = EJBJARS_DIR + File.separator + fileName;
1085:                File f = null;
1086:                String pathEjbJarDirFile;
1087:                String pathFile = "";
1088:                try {
1089:                    f = new File(ejbjarFileName).getCanonicalFile();
1090:                    // Force pathEjbJarDirFile with slash to avoid conflict under
1091:                    // Windows (slash and back-slash)
1092:                    pathEjbJarDirFile = f.toURL().getPath();
1093:                } catch (Exception e) {
1094:                    // If filename was an absolute path, it can throw an exception
1095:                    // The pathFile will be empty
1096:                    pathEjbJarDirFile = "";
1097:                }
1098:                try {
1099:                    f = new File(fileName).getCanonicalFile();
1100:                    // Force pathFile with slash to avoid conflict under Windows (slash
1101:                    // and back-slash)
1102:                    pathFile = f.toURL().getPath();
1103:                } catch (Exception e) {
1104:                    String err = "Error while trying to get canonical file '"
1105:                            + fileName + "'";
1106:                    servlog.log(BasicLevel.ERROR, err);
1107:                    return null;
1108:                }
1109:
1110:                // for each container loaded
1111:                Enumeration lc = containers.elements();
1112:                while (lc.hasMoreElements()) {
1113:                    Container cont = (JContainer) lc.nextElement();
1114:                    String contName = cont.getExternalFileName();
1115:
1116:                    // first, search abs path
1117:                    if (contName.equals(pathFile)) {
1118:                        return cont;
1119:                    } else if (contName.equals(pathEjbJarDirFile)) {
1120:                        // next, search in ejbjar path
1121:                        return cont;
1122:                    } else {
1123:                        // else search in autoloadir
1124:                        List lAlDirs = getAutoloadDirectories();
1125:                        for (int i = 0; i < lAlDirs.size(); i++) {
1126:                            String alDir = (String) lAlDirs.get(i);
1127:
1128:                            String alFileName = alDir + File.separator
1129:                                    + fileName;
1130:                            try {
1131:                                f = new File(alFileName).getCanonicalFile();
1132:                                // Force alFileName with slash to avoid conflict under
1133:                                // Windows (slash and back-slash)
1134:                                alFileName = f.toURL().getPath();
1135:                            } catch (Exception e) {
1136:                                // If filename was an absolute path, it can throw an
1137:                                // exception
1138:                                alFileName = alDir + File.separator + fileName;
1139:                            }
1140:                            if (servlog.isLoggable(BasicLevel.DEBUG)) {
1141:                                servlog.log(BasicLevel.DEBUG, "alFileName= "
1142:                                        + alFileName);
1143:                            }
1144:
1145:                            if (contName.equals(alFileName)) {
1146:                                return cont;
1147:                            }
1148:                        }
1149:                    }
1150:                }
1151:
1152:                // not found
1153:                return null;
1154:            }
1155:
1156:            /**
1157:             * Remove a JOnAS container
1158:             */
1159:            public void removeContainer(Container cont) {
1160:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1161:                    servlog.log(BasicLevel.DEBUG, cont.getName());
1162:                }
1163:
1164:                if (mbeanServer != null) {
1165:                    String moduleName = cont.getName();
1166:                    String earFileName = cont.getEarFileName();
1167:                    String earName = null;
1168:                    if (earFileName != null) {
1169:                        earName = EarServiceImpl
1170:                                .buildJ2eeApplicationName(earFileName);
1171:                    }
1172:                    String domainName = getDomainName();
1173:                    String serverName = getJonasServerName();
1174:                    ObjectName onEjbModule = J2eeObjectName.getEJBModule(
1175:                            domainName, serverName, earName, moduleName);
1176:
1177:                    // try to remove MBeans corresponding to the EJBs in the module
1178:                    ObjectName onEjb = null;
1179:                    try {
1180:                        String[] onEjbs = (String[]) mbeanServer.getAttribute(
1181:                                onEjbModule, "ejbs");
1182:                        for (int i = 0; i < onEjbs.length; i++) {
1183:                            onEjb = new ObjectName(onEjbs[i]);
1184:                            mbeanServer.unregisterMBean(onEjb);
1185:                        }
1186:                    } catch (Exception e) {
1187:                        servlog.log(BasicLevel.ERROR,
1188:                                "Problem when trying to unregsiter MBean "
1189:                                        + onEjb.toString(), e);
1190:                    }
1191:
1192:                    // try to remove MBean corresponding to the module
1193:                    try {
1194:                        mbeanServer.unregisterMBean(onEjbModule);
1195:                        if (servlog.isLoggable(BasicLevel.DEBUG)) {
1196:                            servlog.log(BasicLevel.DEBUG,
1197:                                    "unregistered MBean: "
1198:                                            + onEjbModule.toString());
1199:                        }
1200:                    } catch (Exception e) {
1201:                        servlog.log(BasicLevel.ERROR,
1202:                                "Problem when trying to unregsiter MBean "
1203:                                        + onEjbModule.toString(), e);
1204:                    }
1205:                }
1206:                cont.remove();
1207:                containers.removeElement(cont);
1208:
1209:                // Run the garbage collector
1210:                Runtime.getRuntime().gc();
1211:
1212:            }
1213:
1214:            /**
1215:             * List JOnAS container created by EJB Service
1216:             */
1217:            public Container[] listContainers() {
1218:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1219:                    servlog.log(BasicLevel.DEBUG, "size= " + containers.size());
1220:                }
1221:
1222:                Container[] ret = new Container[containers.size()];
1223:                containers.copyInto(ret);
1224:                return ret;
1225:            }
1226:
1227:            /**
1228:             * Synchronized all entity bean containers
1229:             * @param passivate passivate instances after synchronization.
1230:             */
1231:            public void syncAllEntities(boolean passivate) {
1232:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1233:                    servlog.log(BasicLevel.DEBUG, "");
1234:                }
1235:
1236:                Enumeration lc = containers.elements();
1237:                while (lc.hasMoreElements()) {
1238:                    JContainer cont = (JContainer) lc.nextElement();
1239:                    cont.syncAll(true, passivate);
1240:                }
1241:            }
1242:
1243:            /** ******* MBEan methods ******** */
1244:
1245:            /**
1246:             * MBean method
1247:             * @return Integer Total Number of Container currently in JOnAS
1248:             */
1249:            public Integer getCurrentNumberOfContainer() {
1250:                return new Integer(containers.size());
1251:            }
1252:
1253:            /**
1254:             * MBean method
1255:             * @return Integer Total Number of Bean Type currently in JOnAS
1256:             */
1257:            public Integer getTotalCurrentNumberOfBeanType() {
1258:                int count = 0;
1259:                Enumeration lc = containers.elements();
1260:                while (lc.hasMoreElements()) {
1261:                    JContainer cont = (JContainer) lc.nextElement();
1262:                    count += cont.getBeanNb();
1263:                }
1264:                return new Integer(count);
1265:            }
1266:
1267:            /**
1268:             * MBean method
1269:             * @return Integer Total Number of Bmp Type currently in JOnAS
1270:             */
1271:            public Integer getTotalCurrentNumberOfBMPType() {
1272:                int count = 0;
1273:                Enumeration lc = containers.elements();
1274:                while (lc.hasMoreElements()) {
1275:                    JContainer cont = (JContainer) lc.nextElement();
1276:                    count += cont.getEntityBMPNb();
1277:                }
1278:                return new Integer(count);
1279:            }
1280:
1281:            /**
1282:             * MBean method
1283:             * @return Integer Total Number of Cmp Type currently in JOnAS
1284:             */
1285:            public Integer getTotalCurrentNumberOfCMPType() {
1286:                int count = 0;
1287:                Enumeration lc = containers.elements();
1288:                while (lc.hasMoreElements()) {
1289:                    JContainer cont = (JContainer) lc.nextElement();
1290:                    count += cont.getEntityCMPNb();
1291:                }
1292:                return new Integer(count);
1293:            }
1294:
1295:            /**
1296:             * MBean method
1297:             * @return Integer Total Number of Sbf Type currently in JOnAS
1298:             */
1299:            public Integer getTotalCurrentNumberOfSBFType() {
1300:                int count = 0;
1301:                Enumeration lc = containers.elements();
1302:                while (lc.hasMoreElements()) {
1303:                    JContainer cont = (JContainer) lc.nextElement();
1304:                    count += cont.getStatefulSessionNb();
1305:                }
1306:                return new Integer(count);
1307:            }
1308:
1309:            /**
1310:             * MBean method
1311:             * @return Integer Total Number of Sbl Type currently in JOnAS
1312:             */
1313:            public Integer getTotalCurrentNumberOfSBLType() {
1314:                int count = 0;
1315:                Enumeration lc = containers.elements();
1316:                while (lc.hasMoreElements()) {
1317:                    JContainer cont = (JContainer) lc.nextElement();
1318:                    count += cont.getStatelessSessionNb();
1319:                }
1320:                return new Integer(count);
1321:            }
1322:
1323:            /**
1324:             * MBean method
1325:             * @return Integer Total Number of Mdb Type currently in JOnAS
1326:             */
1327:            public Integer getTotalCurrentNumberOfMDBType() {
1328:                int count = 0;
1329:                Enumeration lc = containers.elements();
1330:                while (lc.hasMoreElements()) {
1331:                    JContainer cont = (JContainer) lc.nextElement();
1332:                    count += cont.getMessageDrivenNb();
1333:                }
1334:                return new Integer(count);
1335:            }
1336:
1337:            public void removeContainer(String fileName) throws Exception {
1338:                removeContainerMBean(fileName);
1339:            }
1340:
1341:            /**
1342:             * MBean method remove a container application
1343:             * @param fileName the Name of this container
1344:             */
1345:            public void removeContainerMBean(String fileName) throws Exception {
1346:                Container cont = null;
1347:                try {
1348:                    cont = getContainer(fileName);
1349:                } catch (Exception e) {
1350:                    String err = "Error while trying to find file '" + fileName
1351:                            + "'";
1352:                    servlog.log(BasicLevel.ERROR, err);
1353:                    throw new Exception(err, e);
1354:                }
1355:
1356:                if (cont != null) {
1357:                    removeContainer(cont, false);
1358:                } else {
1359:                    String err = "Cannot remove the non-existant container '"
1360:                            + fileName + "'";
1361:                    servlog.log(BasicLevel.ERROR, err);
1362:                    throw new Exception(err);
1363:                }
1364:            }
1365:
1366:            public String createContainer(String file) throws Exception {
1367:                return createContainerMBean(file);
1368:            }
1369:
1370:            /**
1371:             * MBean method allowing to create an EJB container for the EJBs contained
1372:             * in a .jar (or .xml) file.
1373:             * @param file Name of the file to be deployed
1374:             * @return The ObjectName of the MBean associated to the container (to the
1375:             *         deployed module)
1376:             */
1377:            public String createContainerMBean(String file) throws Exception {
1378:                String ejbModuleObjectName = null;
1379:                try {
1380:                    Context contctx = new CompNamingContext(file);
1381:                    contctx.rebind("filename", file);
1382:                    ejbModuleObjectName = createContainer(contctx);
1383:                } catch (Exception e) {
1384:                    throw new Exception("Cannot create Container", e);
1385:                }
1386:                return ejbModuleObjectName;
1387:            }
1388:
1389:            /**
1390:             * Test if the specified file is already deployed (if a container is created
1391:             * for this jar).
1392:             * @param fileName the name of the jar file
1393:             * @return true if the jar was deployed, false otherwise
1394:             */
1395:            public Boolean isJarDeployed(String fileName) {
1396:                return new Boolean(isJarLoaded(fileName));
1397:            }
1398:
1399:            /**
1400:             * Test if the specified jar identified with its work name is already
1401:             * deployed (if a container is created for this jar).
1402:             * @param workFileName the internal name of the jar file (working copy)
1403:             * @return true if the jar was deployed, false otherwise
1404:             */
1405:            public boolean isJarDeployedByWorkName(String workFileName) {
1406:                if (servlog.isLoggable(BasicLevel.DEBUG)) {
1407:                    servlog.log(BasicLevel.DEBUG, workFileName);
1408:                }
1409:
1410:                // for each container loaded
1411:                Enumeration lc = containers.elements();
1412:                while (lc.hasMoreElements()) {
1413:                    Container cont = (JContainer) lc.nextElement();
1414:
1415:                    // get name of the container (basename)
1416:                    // cont.getFileName return the internal name (working copy)
1417:                    String contName = new File(cont.getFileName()).getName();
1418:                    if (contName.equals(workFileName)) {
1419:                        return true;
1420:                    }
1421:                }
1422:
1423:                // not found
1424:                return false;
1425:            }
1426:
1427:            // Kind of resources:
1428:            /** DataSource Resource Type */
1429:            static final int DATASOURCE = 1;
1430:
1431:            /** JMS Destination Resource Type */
1432:            static final int JMS_DESTINATION = 2;
1433:
1434:            /** JMS Factory Resource Type */
1435:            static final int JMS_FACTORY = 3;
1436:
1437:            /** Mail Factory Resource Type */
1438:            static final int MAIL_FACTORY = 4;
1439:
1440:            /**
1441:             * This method is used by the getXXXDependence MBean methods. It gathers the
1442:             * ObjectNames of the EJBs using a given resource.
1443:             * @param name the resource name
1444:             * @type the resource type
1445:             * @return the ObjectNames of all the ejb using this resource
1446:             */
1447:            Set getDependence(String name, int type) {
1448:                Set resultObjectName = new HashSet(); // to be returned by this method
1449:                Set resultProperties = new HashSet(); // constructed by the JContainer
1450:                Enumeration lc = containers.elements();
1451:                try {
1452:                    Context ctx = new InitialContext();
1453:                    ctx.lookup(name);
1454:                    ctx.close();
1455:                    // this resource is rebind
1456:                    while (lc.hasMoreElements()) {
1457:                        JContainer cont = (JContainer) lc.nextElement();
1458:                        Set depProps = null; // Dependences described as a set of
1459:                        // Properties objects
1460:                        switch (type) {
1461:
1462:                        case DATASOURCE:
1463:                            depProps = cont.getDataSourceDependence(name);
1464:                            break;
1465:
1466:                        case JMS_DESTINATION:
1467:                            depProps = cont.getJmsDestinationDependence(name);
1468:                            break;
1469:
1470:                        case JMS_FACTORY:
1471:                            depProps = cont
1472:                                    .getJmsConnectionFactoryDependence(name);
1473:                            break;
1474:
1475:                        case MAIL_FACTORY:
1476:                            depProps = cont.getMailFactoryDependence(name);
1477:                            break;
1478:
1479:                        }
1480:                        resultProperties.addAll(depProps);
1481:                        // change string to ObjectName
1482:                        try {
1483:                            resultObjectName = convertToObjectNames(resultProperties);
1484:                        } catch (Exception e) {
1485:                            servlog.log(BasicLevel.ERROR,
1486:                                    "EjbServiceImpl: Object Name Error", e);
1487:                        }
1488:                    }
1489:                } catch (NamingException ne) {
1490:                    // unexisting ds
1491:                    resultObjectName = new HashSet();
1492:                }
1493:                return resultObjectName;
1494:            }
1495:
1496:            /**
1497:             * Converts a Set of properties to ObjectNames
1498:             * @param resultProperties properties to be converted
1499:             * @return Returns a Set of ObjectNames
1500:             */
1501:            private Set convertToObjectNames(Set resultProperties) {
1502:                Set resultObjectName = new HashSet();
1503:                Iterator it = resultProperties.iterator();
1504:                String domainName = getDomainName();
1505:                String serverName = getJonasServerName();
1506:                Properties item = null; // a item in resultProperties
1507:                String ejbType = null;
1508:                String ejbName = null;
1509:                String earFileName = null;
1510:                String moduleName = null;
1511:                String j2eeAppName = null;
1512:                while (it.hasNext()) {
1513:                    item = (Properties) it.next();
1514:                    ObjectName ejbObjectName = null;
1515:                    // See JContainer.beansDependence() method for info about the
1516:                    // Properties object containt
1517:                    ejbType = item.getProperty("type");
1518:                    ejbName = item.getProperty("name");
1519:                    earFileName = item.getProperty("earFileName");
1520:                    //moduleName = buildEJBModuleName(fileName);
1521:                    moduleName = item.getProperty("cname");
1522:                    if (earFileName != null) {
1523:                        j2eeAppName = EarServiceImpl
1524:                                .buildJ2eeApplicationName(earFileName);
1525:                    }
1526:
1527:                    if (ejbType.equals("ejbbmp") || ejbType.equals("ejbcmp")) {
1528:                        ejbObjectName = J2eeObjectName.getEntityBean(
1529:                                domainName, moduleName, serverName,
1530:                                j2eeAppName, ejbName);
1531:                    } else if (ejbType.equals("ejbsbf")) {
1532:                        ejbObjectName = J2eeObjectName.getStatefulSessionBean(
1533:                                domainName, moduleName, serverName,
1534:                                j2eeAppName, ejbName);
1535:                    } else if (ejbType.equals("ejbsbl")) {
1536:                        ejbObjectName = J2eeObjectName.getStatelessSessionBean(
1537:                                domainName, moduleName, serverName,
1538:                                j2eeAppName, ejbName);
1539:                    } else if (ejbType.equals("ejbmdb")) {
1540:                        ejbObjectName = J2eeObjectName.getMessageDrivenBean(
1541:                                domainName, moduleName, serverName,
1542:                                j2eeAppName, ejbName);
1543:                    }
1544:                    if (ejbObjectName != null) {
1545:                        resultObjectName.add(ejbObjectName);
1546:                    }
1547:                }
1548:                return resultObjectName;
1549:            }
1550:
1551:            /**
1552:             * MBean method
1553:             * @return the ObjectName of all the ejbs using this datasource.
1554:             */
1555:            public Set getDataSourceDependence(String dsName) {
1556:                return getDependence(dsName, DATASOURCE);
1557:            }
1558:
1559:            /**
1560:             * Manangement method
1561:             * @return the ObjectName of all the ejb using this destination.
1562:             */
1563:            public Set getJmsDestinationDependence(String destName) {
1564:                return getDependence(destName, JMS_DESTINATION);
1565:            }
1566:
1567:            /**
1568:             * Management method
1569:             * @return the ObjectName of all the ejb using this Connection Factory.
1570:             */
1571:            public Set getJmsConnectionFactoryDependence(String cfName) {
1572:                return getDependence(cfName, JMS_FACTORY);
1573:            }
1574:
1575:            /**
1576:             * Management method
1577:             * @return the ObjectName of all the ejb using a given Mail Factory.
1578:             */
1579:            public Set getMailFactoryDependence(String mfName) {
1580:                return getDependence(mfName, MAIL_FACTORY);
1581:            }
1582:
1583:            /**
1584:             * Return the list of installed EJB containers. The JAR files or the
1585:             * directories with expanded EJB container are searched in
1586:             * JONAS_BASE/ejbjars and all ejbjar directories 'autoload'.
1587:             * @return The list of JAR files or the directories with expanded EJB
1588:             *         container found
1589:             * @throws Exception if the list can't be retrieved
1590:             */
1591:            public List getInstalledJars() throws Exception {
1592:                // get JAR files found in JONAS_BASE/ejbjars
1593:                ArrayList al = JModule.getInstalledContainersInDir(EJBJARS_DIR,
1594:                        JModule.EJBJAR_EXTENSION, JModule.EJBJAR_CHILD_DIR,
1595:                        JModule.EJBJAR_CONFIRM_FILE);
1596:                // get JAR files found in all autoload directories
1597:                for (int i = 0; i < autoloadDirectories.size(); i++) {
1598:                    al.addAll(JModule.getInstalledContainersInDir(
1599:                            autoloadDirectories.get(i).toString(),
1600:                            JModule.EJBJAR_EXTENSION, JModule.EJBJAR_CHILD_DIR,
1601:                            JModule.EJBJAR_CONFIRM_FILE));
1602:                }
1603:                return al;
1604:            }
1605:
1606:            /**
1607:             * Deploy the given ejb-jars of an ear file with the specified parent
1608:             * classloader (ear classloader). (This method is only used for the ear
1609:             * applications, not for the ejb-jar applications).
1610:             * @param ctx the context containing the configuration to deploy the
1611:             *        ejbjars. <BR>This context contains the following parameters :
1612:             *        <BR>- earRootUrl the root of the ear application. <BR>- earURL
1613:             *        filename of the EAR. <BR>- earClassLoader the ear classLoader of
1614:             *        the ear application. <BR>- ejbClassLoader the ejb classLoader for
1615:             *        the ejbjars. <BR>- jarURLs the list of the urls of the ejb-jars
1616:             *        to deploy. <BR>- roleNames the role names of the security-role.
1617:             *        <BR>
1618:             * @throws ServiceException if an error occurs during the deployment.
1619:             */
1620:            public void deployJars(Context ctx) throws ServiceException {
1621:
1622:                // Get the 6 parameters from the context
1623:                // - earRootUrl the root of the ear application.
1624:                // - earClassLoader the ear classLoader of the ear application.
1625:                // - ejbClassLoader the ejb classLoader for the ejbjars.
1626:                // - jarURLs the list of the urls of the ejb-jars to deploy.
1627:                // - roleNames the role names of the security-role
1628:                URL earRootUrl = null;
1629:                URL earUrl = null;
1630:                ClassLoader earClassLoader = null;
1631:                ClassLoader ejbClassLoader = null;
1632:                URL[] jarURLs = null;
1633:                String[] roleNames = null;
1634:                try {
1635:                    earRootUrl = (URL) ctx.lookup("earRootUrl");
1636:                    earUrl = (URL) ctx.lookup("earUrl");
1637:                    earClassLoader = (ClassLoader) ctx.lookup("earClassLoader");
1638:                    ejbClassLoader = (ClassLoader) ctx.lookup("ejbClassLoader");
1639:                    jarURLs = (URL[]) ctx.lookup("jarURLs");
1640:                    roleNames = (String[]) ctx.lookup("roleNames");
1641:                } catch (NamingException e) {
1642:                    String err = "Error while getting parameter from context param :"
1643:                            + e.getMessage();
1644:                    servlog.log(BasicLevel.ERROR, err);
1645:                    throw new ServiceException(err, e);
1646:                }
1647:
1648:                // Deploy all the ejb-jars of the ear application.
1649:                for (int i = 0; i < jarURLs.length; i++) {
1650:
1651:                    // Get the name of an ejb-jar to deploy.
1652:                    String fileName = jarURLs[i].getFile();
1653:                    if (servlog.isLoggable(BasicLevel.DEBUG)) {
1654:                        servlog.log(BasicLevel.DEBUG, "Deploy '" + fileName
1655:                                + "' for the ear service.");
1656:                    }
1657:
1658:                    // The context to give for the creation of the container
1659:                    // associated to the ejb-jar.
1660:                    Context contctx = null;
1661:                    try {
1662:                        contctx = new CompNamingContext(fileName);
1663:                        contctx.rebind("filename", fileName);
1664:                        contctx.rebind("earClassLoader", earClassLoader);
1665:                        contctx.rebind("ejbClassLoader", ejbClassLoader);
1666:                        contctx.rebind("earRoot", earRootUrl.getFile());
1667:                        //contctx.rebind("earFileName", earUrl.getFile());
1668:                        contctx.rebind("earURL", earUrl);
1669:                        contctx.rebind("roleNames", roleNames);
1670:                        createContainer(contctx);
1671:                    } catch (Exception e) {
1672:                        // An ejb-jar is corrupted so undeploy all the deployed jar
1673:                        // of the ear application.
1674:                        servlog.log(BasicLevel.ERROR, "Error when deploying '"
1675:                                + fileName + "'", e);
1676:                        servlog.log(BasicLevel.ERROR,
1677:                                "Undeploy ejb-jar of the ear application");
1678:
1679:                        for (int j = 0; j <= i; j++) {
1680:                            Container cont = getContainer(jarURLs[j].getFile());
1681:                            if (cont != null) {
1682:                                removeContainer(cont, true);
1683:                            } else {
1684:                                servlog.log(BasicLevel.ERROR,
1685:                                        "Cannot remove the non-existant container '"
1686:                                                + fileName + "'");
1687:                            }
1688:                        }
1689:                        throw new ServiceException(
1690:                                "Error during the deployment", e);
1691:                    }
1692:                }
1693:                //return ejbClassLoader;
1694:            }
1695:
1696:            /**
1697:             * Undeploy the given ejb-jars of an ear file. (This method is only used for
1698:             * the ear applications, not for the ejb-jar applications).
1699:             * @param urls the list of the urls of the ejb-jars to undeploy.
1700:             */
1701:            public void unDeployJars(URL[] urls) {
1702:                for (int i = 0; i < urls.length; i++) {
1703:                    String fileName = urls[i].getFile();
1704:                    Container cont = getContainer(urls[i].getFile());
1705:                    if (cont != null) {
1706:                        removeContainer(cont, true);
1707:                    } else {
1708:                        servlog.log(BasicLevel.ERROR,
1709:                                "Cannot remove the non-existant container '"
1710:                                        + fileName + "'");
1711:                    }
1712:                }
1713:            }
1714:
1715:            /**
1716:             * Remove the specified container.
1717:             * @param cont the container to remove.
1718:             * @param isEarCase true if only if the removeContainer method is called in
1719:             *        the ear case, false otherwise.
1720:             */
1721:            public void removeContainer(Container cont, boolean isEarCase) {
1722:                if (isEarCase == (cont.getEarFileName() != null)) {
1723:                    removeContainer(cont);
1724:                } else {
1725:                    String err = "Cannot remove container '"
1726:                            + cont.getName()
1727:                            + "' it is in an ear application. You must undeploy the ear associated.";
1728:                    servlog.log(BasicLevel.ERROR, err);
1729:                }
1730:            }
1731:
1732:            /**
1733:             * Make a cleanup of the cache of deployment descriptor. This method must be
1734:             * invoked after the ear deployment by the EAR service. the deployment of an
1735:             * ear by .
1736:             * @param earClassLoader the ClassLoader of the ear application to remove
1737:             *        from the cache.
1738:             */
1739:            public void removeCache(ClassLoader earClassLoader) {
1740:                EjbManagerWrapper.removeCache(earClassLoader);
1741:            }
1742:
1743:            /**
1744:             * Add recursively the ejbjars of the specified directory. If the dir has a
1745:             * relative path, this path is relative from where the Application Server is
1746:             * launched. If the dir is not found it will be searched in
1747:             * $JONAS_BASE/ejbjars/ directory.
1748:             * @param dirPath the path to the directory containing the ejbjars to load.
1749:             */
1750:            private void addEjbjars(String dirPath) {
1751:                boolean found = false;
1752:
1753:                // Look the directory relative to the $JONAS_BASE/ejbjars directory
1754:                File dir = new File(EJBJARS_DIR + File.separator + dirPath);
1755:                found = dir.isDirectory();
1756:
1757:                if (found) {
1758:                    addEjbjarsFrom(dir);
1759:                } else {
1760:                    String err = "Warning: Cannot load dir: '" + dirPath + "' ";
1761:                    err += "is not a directory or directory doesn't exist";
1762:                    servlog.log(BasicLevel.WARN, err);
1763:                }
1764:            }
1765:
1766:            /**
1767:             * Add the ejbjars of the specified directory.
1768:             * @param dir the directory from which the ejbjars are loaded.
1769:             * @throws ServiceException if the argument is not a directory
1770:             */
1771:            private void addEjbjarsFrom(File dir) throws ServiceException {
1772:
1773:                try {
1774:                    if (dir.isDirectory()) {
1775:                        File[] files = dir.listFiles();
1776:                        for (int i = 0; i < files.length; i++) {
1777:                            if (files[i].getPath().toLowerCase().endsWith(
1778:                                    ".jar")) {
1779:                                ejbNames.add(files[i].getCanonicalPath());
1780:                            } else if (files[i].isDirectory()) {
1781:                                addEjbjarsFrom(files[i]);
1782:                            }
1783:                        }
1784:                    } else {
1785:                        String err = "Cannot load dir: '" + dir.getPath();
1786:                        err += "' is not a directory";
1787:                        servlog.log(BasicLevel.ERROR, err);
1788:                        throw new ServiceException(err);
1789:                    }
1790:                } catch (IOException e) {
1791:                    String err = "Invalid file name '" + dir.getPath();
1792:                    servlog.log(BasicLevel.ERROR, err);
1793:                    throw new ServiceException(err, e);
1794:                }
1795:            }
1796:
1797:            /**
1798:             * Test if the specified filename is already deployed or not
1799:             * @param fileName the name of the jar file.
1800:             * @return true if the jar is deployed, else false.
1801:             */
1802:            public boolean isJarLoaded(String fileName) {
1803:                return (getContainer(fileName) != null);
1804:            }
1805:
1806:            /**
1807:             * Return the list of all loaded EJB container.
1808:             * @return The list of deployed EJB container
1809:             */
1810:            public List getDeployedJars() {
1811:                ArrayList al = new ArrayList();
1812:                Container oContainer;
1813:                for (Enumeration jars = containers.elements(); jars
1814:                        .hasMoreElements();) {
1815:                    oContainer = (Container) jars.nextElement();
1816:                    try {
1817:                        al.add((new File(oContainer.getExternalFileName()))
1818:                                .toURL().getPath());
1819:                    } catch (Exception e) {
1820:                        // none
1821:                    }
1822:                }
1823:                return al;
1824:            }
1825:
1826:            /**
1827:             * Return the list of installed EJB container ready to deploy.
1828:             * @return The list of deployable EJB container
1829:             * @throws Exception when cannot get installed jars list
1830:             */
1831:            public List getDeployableJars() throws Exception {
1832:                List al = getInstalledJars();
1833:                al.removeAll(getDeployedJars());
1834:                return al;
1835:            }
1836:
1837:            /**
1838:             * Return the list of "autoload" directories for EJB containers.
1839:             * @return The list of all "autoload" directories
1840:             */
1841:            public List getAutoloadDirectories() {
1842:                ArrayList al = new ArrayList();
1843:                for (int i = 0; i < autoloadDirectories.size(); i++) {
1844:                    try {
1845:                        al
1846:                                .add((new File(autoloadDirectories.get(i)
1847:                                        .toString())).toURL().getPath());
1848:                    } catch (Exception e) {
1849:                        // none
1850:                    }
1851:                }
1852:                return al;
1853:            }
1854:
1855:            /**
1856:             * Return the Ejbjars directory.
1857:             * @return The Ejbjars directory
1858:             */
1859:            public String getEjbjarsDirectory() {
1860:                String sRet;
1861:                try {
1862:                    sRet = (new File(EJBJARS_DIR)).toURL().getPath();
1863:                } catch (Exception e) {
1864:                    sRet = null;
1865:                }
1866:                return sRet;
1867:            }
1868:
1869:            /**
1870:             * Build the EJBModule name.
1871:             * @param pUrl The URL of Jar file
1872:             * @return The EJBModule name
1873:             */
1874:            public static String buildEJBModuleName(URL pUrl) {
1875:                String sName;
1876:                try {
1877:                    sName = new File(pUrl.getFile()).getName();
1878:                    if ("file".equals(pUrl.getProtocol())) {
1879:                        sName = buildEJBModuleName(sName);
1880:                    }
1881:                } catch (NullPointerException e) {
1882:                    sName = null;
1883:                }
1884:                return sName;
1885:            }
1886:
1887:            /**
1888:             * Build the EJBModule name.
1889:             * @param pFilename The name of Jar file
1890:             * @return The EJBModule name
1891:             */
1892:            public static String buildEJBModuleName(String pFilename) {
1893:                String sName;
1894:                try {
1895:                    sName = new File(pFilename).getName();
1896:                    int iPos = sName.lastIndexOf('.');
1897:                    if (iPos > -1) {
1898:                        sName = sName.substring(0, iPos);
1899:                    }
1900:                } catch (NullPointerException e) {
1901:                    sName = null;
1902:                }
1903:                return sName;
1904:            }
1905:
1906:            /**
1907:             * Check if current carol protocol choose is include into those choose during generation
1908:             * @param listProtocolGenerated (string with comma separator)
1909:             * @param listCurrentProtocol (string with comma separator)
1910:             * @return true if we have find at least one current protocol not in those generated
1911:             */
1912:            private static boolean checkCurrentProtocolIncludeIntoGenerated(
1913:                    String listProtocolGenerated, String listCurrentProtocol) {
1914:                Protocols generated = new Protocols(listProtocolGenerated);
1915:                Protocols current = new Protocols(listCurrentProtocol);
1916:                return generated.isSupported(current);
1917:            }
1918:
1919:            /**
1920:             * get the attibut value in manifest file
1921:             * @param jarName : the jar file containg manifest
1922:             * @param attributName : the attribut name
1923:             * @return the value corresponding to the attributName if it's exist null otherwise
1924:             */
1925:            private static String getAttributeInManifest(String jarName,
1926:                    String attributName) {
1927:                try {
1928:                    File jarFile = new File(jarName);
1929:                    JarFile jar = new JarFile(jarFile);
1930:                    Manifest man = jar.getManifest();
1931:                    Attributes atts = man.getMainAttributes();
1932:                    return atts.getValue(attributName);
1933:                } catch (Exception e) {
1934:                    servlog.log(BasicLevel.ERROR, "Cannot read Manifest: " + e);
1935:                    return null;
1936:                }
1937:            }
1938:
1939:            /**
1940:             * Check that GenIC have been applied on the given ejb-jar file
1941:             * If it was not done, it run GenIC against the file.
1942:             * @param fileName given EJB-JAR file.
1943:             * @param urls Array of URLs used as CLASSPATH during EJB compilation
1944:             */
1945:            public void checkGenIC(String fileName, URL[] urls) {
1946:                // Detect if auto genIC is disabled or not in jonas.properties file.
1947:                if (!autoGenIC) {
1948:                    return;
1949:                }
1950:
1951:                // get Carol configuration to intialize Genic Arguments
1952:                ProtocolConfiguration[] listCurrentProtocol = ConfigurationRepository
1953:                        .getConfigurations();
1954:
1955:                String[] genicArgsString = null;
1956:
1957:                // Extra args are stored in autoGenICArgsList
1958:
1959:                int argIndex = 0;
1960:                // append classpath
1961:                if (urls != null && urls.length > 0) {
1962:                    // we have a CP to use
1963:                    genicArgsString = new String[4 + autoGenICArgsList.size()];
1964:
1965:                    StringBuffer classpath = new StringBuffer();
1966:                    for (int i = 0; i < urls.length; i++) {
1967:                        classpath.append(urls[i].getPath());
1968:                        if (i != (urls.length - 1)) {
1969:                            classpath.append(File.pathSeparator);
1970:                        }
1971:                    }
1972:
1973:                    genicArgsString[argIndex++] = "-classpath";
1974:                    genicArgsString[argIndex++] = classpath.toString();
1975:                } else {
1976:                    // no CP
1977:                    genicArgsString = new String[2 + autoGenICArgsList.size()];
1978:                }
1979:
1980:                genicArgsString[argIndex++] = "-protocols";
1981:                String listProtocols = "";
1982:                for (int i = 0; i < listCurrentProtocol.length; i++) {
1983:                    listProtocols = listProtocols
1984:                            + listCurrentProtocol[i].getName();
1985:                    if (i != (listCurrentProtocol.length - 1)) {
1986:                        listProtocols = listProtocols + ",";
1987:                    }
1988:                }
1989:                genicArgsString[argIndex++] = listProtocols;
1990:
1991:                // Add the extra args
1992:                Iterator itExtraArg = autoGenICArgsList.iterator();
1993:                while (itExtraArg.hasNext()) {
1994:                    genicArgsString[argIndex++] = (String) itExtraArg.next();
1995:                }
1996:
1997:                String jonasVersionGenic = getAttributeInManifest(fileName,
1998:                        "Genic-Jonas-Version");
1999:                String listProtocolGenerated = getAttributeInManifest(fileName,
2000:                        "Genic-Jonas-protocols");
2001:
2002:                boolean isCurrentProtocolIncludeIntoGenerated = checkCurrentProtocolIncludeIntoGenerated(
2003:                        listProtocolGenerated, listProtocols);
2004:
2005:                if ((jonasVersionGenic == null)
2006:                        || !jonasVersionGenic.equals(Version.getNumber())
2007:                        || !isCurrentProtocolIncludeIntoGenerated) {
2008:                    // Print a little explaination before calling Genic
2009:                    if (jonasVersionGenic == null) {
2010:                        servlog
2011:                                .log(
2012:                                        BasicLevel.INFO,
2013:                                        "JOnAS version was not found in the '"
2014:                                                + fileName
2015:                                                + "' manifest file. Auto-generating container classes...");
2016:                    } else if (!jonasVersionGenic.equals(Version.getNumber())) {
2017:                        servlog
2018:                                .log(
2019:                                        BasicLevel.INFO,
2020:                                        "JOnAS version found in the '"
2021:                                                + fileName
2022:                                                + "' manifest file :"
2023:                                                + jonasVersionGenic
2024:                                                + " is different of the current JOnAS version : "
2025:                                                + Version.getNumber()
2026:                                                + ". Auto-generating container classes...");
2027:                    } else if (!isCurrentProtocolIncludeIntoGenerated) {
2028:                        servlog
2029:                                .log(
2030:                                        BasicLevel.INFO,
2031:                                        "Current Carol protocol is not included in the protocols found in the '"
2032:                                                + fileName
2033:                                                + "' manifest file. Auto-generating container classes...");
2034:                    }
2035:
2036:                    Object[] param = { fileName, genicArgsString };
2037:                    String[] signature = { "java.lang.String",
2038:                            "[Ljava.lang.String;" };
2039:                    //  invoke method on the MBeanServer
2040:                    try {
2041:                        ObjectName j2eeServerON = J2eeObjectName
2042:                                .J2EEServer(this .getDomainName(), this 
2043:                                        .getJonasServerName());
2044:                        mbeanServer.invoke(j2eeServerON, "deployLocalFile",
2045:                                param, signature);
2046:
2047:                    } catch (Exception e) {
2048:                        servlog.log(BasicLevel.WARN, "createContainer: "
2049:                                + fileName + " can't create generated classes",
2050:                                e);
2051:                    }
2052:                }
2053:            }
2054:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.