Source Code Cross Referenced for ClientContainer.java in  » J2EE » JOnAS-4.8.6 » org » objectweb » jonas » client » 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.client 
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 1any 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: ClientContainer.java 8083 2006-03-06 10:26:40Z sauthieg $
0023:         * --------------------------------------------------------------------------
0024:         */package org.objectweb.jonas.client;
0025:
0026:        import java.io.File;
0027:        import java.io.IOException;
0028:        import java.lang.reflect.InvocationTargetException;
0029:        import java.lang.reflect.Method;
0030:        import java.net.MalformedURLException;
0031:        import java.net.URL;
0032:        import java.net.URLClassLoader;
0033:        import java.util.ArrayList;
0034:        import java.util.Iterator;
0035:        import java.util.List;
0036:        import java.util.Map;
0037:        import java.util.StringTokenizer;
0038:        import java.util.jar.Attributes;
0039:        import java.util.jar.JarFile;
0040:        import java.util.jar.Manifest;
0041:
0042:        import javax.naming.Context;
0043:        import javax.naming.LinkRef;
0044:        import javax.naming.NamingException;
0045:        import javax.naming.Reference;
0046:        import javax.naming.StringRefAddr;
0047:        import javax.security.auth.callback.CallbackHandler;
0048:        import javax.security.auth.login.LoginContext;
0049:
0050:        import org.objectweb.carol.util.configuration.CarolDefaultValues;
0051:        import org.objectweb.carol.util.configuration.ConfigurationRepository;
0052:
0053:        import org.objectweb.jonas_client.deployment.api.ClientContainerDeploymentDesc;
0054:        import org.objectweb.jonas_client.deployment.api.ClientContainerDeploymentDescException;
0055:        import org.objectweb.jonas_client.deployment.lib.ClientDeploymentDescManager;
0056:
0057:        import org.objectweb.jonas_ear.deployment.api.EarDeploymentDesc;
0058:        import org.objectweb.jonas_ear.deployment.api.EarDeploymentDescException;
0059:        import org.objectweb.jonas_ear.deployment.lib.EarDeploymentDescManager;
0060:        import org.objectweb.jonas_ear.deployment.xml.Web;
0061:
0062:        import org.objectweb.jonas_ejb.deployment.lib.EjbDeploymentDescManager;
0063:
0064:        import org.objectweb.jonas_lib.deployment.api.EjbRefDesc;
0065:        import org.objectweb.jonas_lib.deployment.api.EnvEntryDesc;
0066:        import org.objectweb.jonas_lib.deployment.api.MessageDestinationRefDesc;
0067:        import org.objectweb.jonas_lib.deployment.api.ResourceEnvRefDesc;
0068:        import org.objectweb.jonas_lib.deployment.api.ResourceRefDesc;
0069:        import org.objectweb.jonas_lib.deployment.work.EarFileManager;
0070:        import org.objectweb.jonas_lib.files.FileUtils;
0071:        import org.objectweb.jonas_lib.naming.ContainerNaming;
0072:        import org.objectweb.jonas_lib.version.Version;
0073:
0074:        import org.objectweb.jonas_web.deployment.lib.WebDeploymentDescManager;
0075:
0076:        import org.objectweb.jonas_ws.deployment.api.ServiceRefDesc;
0077:        import org.objectweb.jonas_ws.wsgen.WsGen;
0078:
0079:        import org.objectweb.jonas.common.Log;
0080:        import org.objectweb.jonas.ear.lib.EarClassPathManager;
0081:        import org.objectweb.jonas.ear.lib.EarClassPathManagerException;
0082:        import org.objectweb.jonas.ear.lib.JarList;
0083:        import org.objectweb.jonas.ear.lib.JarListException;
0084:        import org.objectweb.jonas.naming.NamingManager;
0085:        import org.objectweb.jonas.security.auth.callback.NoInputCallbackHandler;
0086:        import org.objectweb.jonas.security.jacc.JPolicyUserRoleMapping;
0087:        import org.objectweb.jonas.ws.ClientJServiceFactoryFinder;
0088:        import org.objectweb.jonas.ws.JServiceFactory;
0089:
0090:        import org.objectweb.util.monolog.api.BasicLevel;
0091:        import org.objectweb.util.monolog.api.Logger;
0092:
0093:        /**
0094:         * Defines the class use for the client container This class analyze the ear or
0095:         * the jar client and launch the client
0096:         * @author Florent Benoit
0097:         */
0098:        public class ClientContainer {
0099:
0100:            /**
0101:             * Name of the carol file
0102:             */
0103:            private static final String CAROL_FILE = "carol.properties";
0104:
0105:            /**
0106:             * Main class to use to launch the application client
0107:             */
0108:            private String mainClass = null;
0109:
0110:            /**
0111:             * Temporary directory
0112:             */
0113:            private String tmpDir = null;
0114:
0115:            /**
0116:             * Jar client to use (if many)
0117:             */
0118:            private String jarClient = null;
0119:
0120:            /**
0121:             * Classpath for the application client
0122:             */
0123:            private String classpath = null;
0124:
0125:            /**
0126:             * trace.properties file to use instead of the default file.
0127:             */
0128:            private String clientTraceFile = null;
0129:
0130:            /**
0131:             * Reference on the NamingManager.
0132:             */
0133:            private ContainerNaming naming;
0134:
0135:            /**
0136:             * carol.properties file to use instead of the default file.
0137:             */
0138:            private String carolFile = null;
0139:
0140:            /**
0141:             * Arguments used by the client
0142:             */
0143:            private String[] args = null;
0144:
0145:            /**
0146:             * Class loader of the EAR
0147:             */
0148:            private URLClassLoader earClassLoader = null;
0149:
0150:            /**
0151:             * Extra Arguments
0152:             */
0153:            private ArrayList appArgs = null;
0154:
0155:            /**
0156:             * URLs resolved in the case of the extension mechanism in the Ear case
0157:             */
0158:            private URL[] extensionsURLs = null;
0159:
0160:            /**
0161:             * Logger to use
0162:             */
0163:            private Logger logger = null;
0164:
0165:            /**
0166:             * true if the user want to auto generate web services artifacts
0167:             */
0168:            private boolean applyWsGen = true;
0169:
0170:            /**
0171:             * Constructor for a Client container
0172:             * @param args the arguments of the instance of the client container
0173:             */
0174:            private ClientContainer(String[] args) {
0175:                this .args = args;
0176:
0177:                appArgs = new ArrayList();
0178:            }
0179:
0180:            /**
0181:             * Call the Log class to instanciate the client container logger
0182:             */
0183:            private void initLogger() {
0184:                // Allow tracing ejb/jms code
0185:                Log.configure(clientTraceFile);
0186:                // init the logger
0187:                this .logger = Log.getLogger(Log.JONAS_CLIENT_PREFIX);
0188:            }
0189:
0190:            /**
0191:             * Main method of the Client container
0192:             * @param args the arguments of the client container
0193:             */
0194:            public static void main(String[] args) {
0195:                // Retrieve command line parameters
0196:                ClientContainer cc = new ClientContainer(args);
0197:
0198:                try {
0199:                    cc.start();
0200:                } catch (InvocationTargetException ite) {
0201:                    Throwable t = ite.getTargetException();
0202:                    String message = t.getMessage();
0203:                    if (t instanceof  Error) {
0204:                        System.err.println("There was the following error : "
0205:                                + message);
0206:                    } else if (t instanceof  Exception) {
0207:                        System.err
0208:                                .println("There was the following exception : "
0209:                                        + message);
0210:                    }
0211:                    t.printStackTrace(System.err);
0212:                } catch (Exception e) {
0213:                    System.err.println("There was the following exception : "
0214:                            + e.getMessage());
0215:                    e.printStackTrace();
0216:                    System.exit(-1);
0217:                }
0218:            }
0219:
0220:            /**
0221:             * Start the client container
0222:             * @throws Exception if it fails
0223:             */
0224:            private void start() throws Exception {
0225:                analyzeArgs();
0226:
0227:                // Use the specified traceclient.properties
0228:                if (clientTraceFile != null) {
0229:                    File tClient = new File(clientTraceFile);
0230:
0231:                    if (!tClient.exists()) {
0232:                        throw new ClientContainerException("The file '"
0233:                                + clientTraceFile + "' was not found.");
0234:                    }
0235:
0236:                    if (!tClient.isFile()) {
0237:                        throw new ClientContainerException("The file '"
0238:                                + clientTraceFile
0239:                                + "' is not a valid file. Maybe a directory ?");
0240:                    }
0241:
0242:                    // Configure log
0243:                    System.setProperty("jonas.client.trace.file",
0244:                            clientTraceFile);
0245:                    Log.reset();
0246:                } else {
0247:                    clientTraceFile = "traceclient";
0248:                }
0249:
0250:                initLogger();
0251:
0252:                // Get the filename
0253:                String userArg = null;
0254:                String fileName = null;
0255:                boolean fileMode = true;
0256:
0257:                try {
0258:                    userArg = (String) appArgs.get(0);
0259:                } catch (IndexOutOfBoundsException ioobe) {
0260:                    usage();
0261:                    throw new ClientContainerException(
0262:                            "You haven't specify a jar, an ear file or class name as argument. See the Usage.");
0263:                }
0264:
0265:                String className = null;
0266:                // Test if this is an ear or a jar file else it must be a class name
0267:                if (!(userArg.toLowerCase().endsWith(".jar") || userArg
0268:                        .toLowerCase().endsWith(".ear"))) {
0269:                    className = userArg;
0270:                    fileMode = false;
0271:                } else {
0272:                    fileMode = true;
0273:                    fileName = userArg;
0274:                }
0275:
0276:                // WsGen
0277:                if (applyWsGen && fileMode) {
0278:                    try {
0279:                        File argFile = new File(fileName);
0280:
0281:                        if (!argFile.exists()) {
0282:                            throw new ClientContainerException(
0283:                                    "The specified file '" + fileName
0284:                                            + "' doesn't exists.");
0285:                        }
0286:                        Manifest manifest = new JarFile(argFile).getManifest();
0287:
0288:                        if (manifest == null) {
0289:                            throw new ClientContainerException(
0290:                                    "No manifest was found inside the file"
0291:                                            + argFile);
0292:                        }
0293:
0294:                        // Extract attributes
0295:                        Attributes attributes = manifest.getMainAttributes();
0296:
0297:                        if (attributes == null) {
0298:                            throw new ClientContainerException(
0299:                                    "No attributes were found in the manifest of the file '"
0300:                                            + argFile + "'.");
0301:                        }
0302:                        String archiveVersion = attributes
0303:                                .getValue("WsGen-JOnAS-Version");
0304:                        if (!Version.getNumber().equals(archiveVersion)) {
0305:                            this .logger
0306:                                    .log(BasicLevel.DEBUG,
0307:                                            "Archive was not compiled with the latest WsGen. Regenerating ...");
0308:                            // different versions, re-generate Stuff
0309:                            WsGen wsgen = new WsGen();
0310:                            String[] args = { "-d",
0311:                                    System.getProperty("java.io.tmpdir"),
0312:                                    argFile.getPath() };
0313:                            String resultJarFile = wsgen.execute(args);
0314:
0315:                            if (!resultJarFile.equals(argFile.getPath())) {
0316:                                // WsGen changed the archive
0317:                                FileUtils.copyFile(resultJarFile, argFile
0318:                                        .getPath());
0319:                                FileUtils.delete(resultJarFile);
0320:                            }
0321:                        }
0322:
0323:                    } catch (Exception e) {
0324:                        throw new ClientContainerException(
0325:                                "Cannot apply WsGen on the client archive : "
0326:                                        + userArg, e);
0327:                    }
0328:                }
0329:
0330:                // Build file and test if it exists
0331:                File clientJarFile = null;
0332:                if (fileMode) {
0333:                    File argFile = new File(fileName);
0334:
0335:                    // Unpack and analyze EAR file if it is an ear
0336:                    if (fileName.toLowerCase().endsWith(".ear")) {
0337:                        clientJarFile = extractAndAnalyzeEar(argFile);
0338:                    } else {
0339:                        //Client jar is the given file
0340:                        clientJarFile = argFile;
0341:                    }
0342:                }
0343:
0344:                // Carol initialisation (property)
0345:                System.setProperty("javax.rmi.CORBA.PortableRemoteObjectClass",
0346:                        "org.objectweb.carol.rmi.multi.MultiPRODelegate");
0347:                System
0348:                        .setProperty("java.naming.factory.initial",
0349:                                "org.objectweb.carol.jndi.spi.MultiOrbInitialContextFactory");
0350:                System
0351:                        .setProperty(
0352:                                "org.omg.PortableInterceptor.ORBInitializerClass.org.objectweb.jotm.ots.OTSORBInitializer",
0353:                                "");
0354:                System
0355:                        .setProperty(
0356:                                "org.omg.PortableInterceptor.ORBInitializerClass.org.objectweb.jonas.security.interceptors.iiop.SecurityInitializer",
0357:                                "");
0358:                System.setProperty("org.omg.CORBA.ORBClass",
0359:                        "org.jacorb.orb.ORB");
0360:                System.setProperty("org.omg.CORBA.ORBSingletonClass",
0361:                        "org.jacorb.orb.ORBSingleton");
0362:                System
0363:                        .setProperty(
0364:                                "org.omg.PortableInterceptor.ORBInitializerClass.standard_init",
0365:                                "org.jacorb.orb.standardInterceptors.IORInterceptorInitializer");
0366:                System.setProperty("javax.rmi.CORBA.UtilClass",
0367:                        "org.objectweb.carol.util.delegate.UtilDelegateImpl");
0368:
0369:                // Build a classloader for the initialisation of carol
0370:                // Priority
0371:                //    1/ file as argument
0372:                //    2/ file in the jar client
0373:                //    3/ file in client.jar
0374:                URL urlCarolFile = null;
0375:
0376:                if (carolFile != null) {
0377:                    File fCarol = new File(carolFile);
0378:
0379:                    if (!fCarol.exists()) {
0380:                        throw new ClientContainerException("The file '"
0381:                                + carolFile + "' was not found.");
0382:                    }
0383:
0384:                    if (!fCarol.isFile()) {
0385:                        throw new ClientContainerException("The file '"
0386:                                + carolFile
0387:                                + "' is not a valid file. Maybe a directory ?");
0388:                    }
0389:
0390:                    if (!fCarol.getName().equals(CAROL_FILE)) {
0391:                        throw new ClientContainerException("The file '"
0392:                                + carolFile + "' must be named '" + CAROL_FILE
0393:                                + "'.");
0394:                    }
0395:
0396:                    try {
0397:                        urlCarolFile = fCarol.toURL();
0398:                        if (logger.isLoggable(BasicLevel.DEBUG)) {
0399:                            logger
0400:                                    .log(BasicLevel.DEBUG,
0401:                                            "Using carol.properties file specified by the user on command line");
0402:                        }
0403:                    } catch (MalformedURLException mue) {
0404:                        throw new ClientContainerException(
0405:                                "Error when building an URL for the file '"
0406:                                        + fCarol + "'.", mue);
0407:                    }
0408:                }
0409:
0410:                // carol.properties file in client jar, use it if this is the case ?
0411:                if (urlCarolFile == null && fileMode) {
0412:                    URL tmpUrl = null;
0413:                    try {
0414:                        tmpUrl = clientJarFile.toURL();
0415:                    } catch (MalformedURLException mue) {
0416:                        throw new ClientContainerException(
0417:                                "Error when building an URL for the file '"
0418:                                        + clientJarFile + "'.", mue);
0419:                    }
0420:                    // Build classloader with null parent CL, to see if it is in the file.
0421:                    ClassLoader tmpCl = new URLClassLoader(
0422:                            new URL[] { tmpUrl }, null);
0423:
0424:                    urlCarolFile = tmpCl
0425:                            .getResource(CarolDefaultValues.CAROL_CONFIGURATION_FILE);
0426:                    if (urlCarolFile != null) {
0427:                        if (logger.isLoggable(BasicLevel.DEBUG)) {
0428:                            logger.log(BasicLevel.DEBUG,
0429:                                    "Using carol.properties file of the '"
0430:                                            + clientJarFile + "' file.");
0431:                        }
0432:                    }
0433:                }
0434:
0435:                if (urlCarolFile != null) {
0436:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0437:                        logger.log(BasicLevel.DEBUG, "Init carol with URL '"
0438:                                + urlCarolFile + "'.");
0439:                    }
0440:                    ConfigurationRepository.init(urlCarolFile);
0441:                } else {
0442:                    ConfigurationRepository.init();
0443:                }
0444:                // Add Csiv2 Interceptors
0445:                ConfigurationRepository.addInterceptors("iiop",
0446:                        "org.objectweb.jonas.security.iiop.Csiv2Initializer");
0447:
0448:                // Carol configuration is done
0449:                // Extract Main-Class to use in the jar from the manifest
0450:                if (fileMode) {
0451:                    Manifest manifest = new JarFile(clientJarFile)
0452:                            .getManifest();
0453:
0454:                    if (manifest == null) {
0455:                        throw new ClientContainerException(
0456:                                "No manifest was found inside the file"
0457:                                        + clientJarFile);
0458:                    }
0459:
0460:                    // Extract attributes
0461:                    Attributes attributes = manifest.getMainAttributes();
0462:
0463:                    if (attributes == null) {
0464:                        throw new ClientContainerException(
0465:                                "No attributes were found in the manifest of the file '"
0466:                                        + clientJarFile + "'.");
0467:                    }
0468:                    mainClass = attributes.getValue(Attributes.Name.MAIN_CLASS);
0469:                } else {
0470:                    mainClass = className;
0471:                }
0472:
0473:                // Invoke the client if there is no need of XML parsing
0474:                if (!fileMode) {
0475:                    ClassLoader clientCL = new URLClassLoader(
0476:                            getUserClasspathUrls());
0477:                    Thread.currentThread().setContextClassLoader(clientCL);
0478:                    invokeClient();
0479:                    return;
0480:                }
0481:
0482:                if (mainClass == null || mainClass.length() == 0) {
0483:                    throw new ClientContainerException(
0484:                            "No main class was found inside the Manifest  of the file '"
0485:                                    + clientJarFile
0486:                                    + "'. This attribute is required to launch the application client.");
0487:                }
0488:
0489:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0490:                    logger.log(BasicLevel.DEBUG, "Using Main-Class :"
0491:                            + mainClass);
0492:                }
0493:
0494:                // Convert file to URL
0495:                URL clientJarURL = null;
0496:
0497:                try {
0498:                    clientJarURL = clientJarFile.toURL();
0499:                } catch (MalformedURLException mue) {
0500:                    throw new ClientContainerException(
0501:                            "Error when building an URL with the file '"
0502:                                    + clientJarFile + "'.", mue);
0503:                }
0504:
0505:                // Build the urls for the classloader
0506:                URL[] urlsClient = null;
0507:
0508:                // URLs for the classloader
0509:                if (extensionsURLs != null) {
0510:                    // There were URLs with the extension mechanism in the EAR
0511:                    urlsClient = new URL[extensionsURLs.length + 1];
0512:
0513:                    for (int i = 0; i < extensionsURLs.length; i++) {
0514:                        urlsClient[i] = extensionsURLs[i];
0515:
0516:                        if (logger.isLoggable(BasicLevel.DEBUG)) {
0517:                            logger.log(BasicLevel.DEBUG, "Adding "
0518:                                    + extensionsURLs[i]
0519:                                    + " to the urls of the client");
0520:                        }
0521:                    }
0522:
0523:                    urlsClient[extensionsURLs.length] = clientJarURL;
0524:                } else {
0525:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0526:                        logger.log(BasicLevel.DEBUG,
0527:                                "Only one url for urls of client");
0528:                    }
0529:
0530:                    // No extension or jar case.
0531:                    urlsClient = new URL[1];
0532:                    urlsClient[0] = clientJarURL;
0533:                }
0534:
0535:                // Build classloader
0536:                URLClassLoader clientClassloader = new URLClassLoader(
0537:                        urlsClient, Thread.currentThread()
0538:                                .getContextClassLoader());
0539:                Thread.currentThread().setContextClassLoader(clientClassloader);
0540:
0541:                // Get the deployment descriptor from file
0542:                ClientContainerDeploymentDesc clientDD = null;
0543:                if (extensionsURLs != null) {
0544:                    EjbDeploymentDescManager.getInstance()
0545:                            .addClassLoaderUrlMapping(clientClassloader,
0546:                                    extensionsURLs);
0547:                }
0548:
0549:                try {
0550:                    clientDD = ClientDeploymentDescManager.getInstance()
0551:                            .getDeploymentDesc(clientJarURL, clientClassloader,
0552:                                    earClassLoader);
0553:                } catch (ClientContainerDeploymentDescException e) {
0554:                    String err = "Cannot read the deployment descriptors '"
0555:                            + clientJarURL + "'";
0556:                    error(err);
0557:                    throw new ClientContainerException(err, e);
0558:                }
0559:
0560:                // Populate the java:comp/env (ENC) environment.
0561:                try {
0562:                    setClientEnvironment(clientDD);
0563:                } catch (Exception e) {
0564:                    //populating environment failed.
0565:                    String err = "Error when populating ";
0566:                    error(err);
0567:                    throw new ClientContainerException(err, e);
0568:                }
0569:
0570:                // JAAS
0571:                String jaasFile = clientDD.getJaasFile();
0572:                String jaasEntry = clientDD.getJaasEntry();
0573:                String username = clientDD.getUsername();
0574:                String password = clientDD.getPassword();
0575:
0576:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0577:                    logger.log(BasicLevel.DEBUG, "Using jaas file = "
0578:                            + jaasFile);
0579:                }
0580:
0581:                String jaasConfigFile = null;
0582:
0583:                if (jaasFile != null) {
0584:                    // Use JAAS
0585:                    jaasConfigFile = "jar:" + clientJarURL.toExternalForm()
0586:                            + "!/" + jaasFile;
0587:                    System.setProperty("java.security.auth.login.config",
0588:                            jaasConfigFile);
0589:                }
0590:
0591:                CallbackHandler ch = null;
0592:
0593:                if ((username != null) && (password != null)) {
0594:                    ch = new NoInputCallbackHandler(username, password);
0595:                    info("Using the login/password specified in the jonas-client.xml file with a specific CallbackHandler");
0596:                } else {
0597:                    // Is there a callbackHandler specified ?
0598:                    String ddCallbackHandler = clientDD.getCallbackHandler();
0599:
0600:                    if (ddCallbackHandler != null) {
0601:                        if (logger.isLoggable(BasicLevel.DEBUG)) {
0602:                            logger.log(BasicLevel.DEBUG, "Using '"
0603:                                    + ddCallbackHandler
0604:                                    + "' class as CallbackHandler.");
0605:                        }
0606:
0607:                        Class clazz = null;
0608:
0609:                        //try to invoke this class
0610:                        try {
0611:                            clazz = clientClassloader
0612:                                    .loadClass(ddCallbackHandler);
0613:                        } catch (Exception e) {
0614:                            throw new ClientContainerException(
0615:                                    "There was an error while trying to instantiate the class '"
0616:                                            + ddCallbackHandler
0617:                                            + "' which is specified in the application.xml as CallbackHandler class",
0618:                                    e);
0619:                        }
0620:
0621:                        try {
0622:                            ch = (CallbackHandler) clazz.newInstance();
0623:                        } catch (Exception e) {
0624:                            throw new ClientContainerException(
0625:                                    "Error while triyng to cast the class '"
0626:                                            + ddCallbackHandler
0627:                                            + "' to CallbackHandler interface, maybe the specified class doesn't implement this interface.",
0628:                                    e);
0629:                        }
0630:                    }
0631:                }
0632:
0633:                // Use JAAS
0634:                if (ch != null) {
0635:                    if (jaasFile == null) {
0636:                        throw new ClientContainerException(
0637:                                "You have defined that you want use a CallbackHandler but you haven't specify the jaas file to use for the JAAS configuration.");
0638:                    }
0639:
0640:                    if (jaasEntry == null) {
0641:                        throw new ClientContainerException(
0642:                                "You have defined that you want use a CallbackHandler but you haven't specify the jaas entry to use from the jaas config file.");
0643:                    }
0644:
0645:                    info("Using JAAS loginContext '" + jaasEntry
0646:                            + "' from the file '" + jaasConfigFile + "'.");
0647:
0648:                    try {
0649:                        LoginContext lc = new LoginContext(jaasEntry, ch);
0650:                        lc.login();
0651:                    } catch (Exception e) {
0652:                        String err = "Can not use the JAAS authentication";
0653:                        error(err);
0654:                        throw new ClientContainerException(err, e);
0655:                    }
0656:                }
0657:
0658:                // Start client
0659:                invokeClient();
0660:
0661:            }
0662:
0663:            /**
0664:             * Start the client on its main class with the thread class loader
0665:             * @throws ClassNotFoundException if class is not found
0666:             * @throws NoSuchMethodException if method (main) is not found
0667:             * @throws IllegalAccessException if access is illegal
0668:             * @throws InvocationTargetException if invocation failed
0669:             */
0670:            private void invokeClient() throws ClassNotFoundException,
0671:                    NoSuchMethodException, IllegalAccessException,
0672:                    InvocationTargetException {
0673:                ClassLoader clientClassloader = Thread.currentThread()
0674:                        .getContextClassLoader();
0675:
0676:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0677:                    if (clientClassloader instanceof  URLClassLoader) {
0678:                        URLClassLoader urlClassLoader = (URLClassLoader) clientClassloader;
0679:                        URL[] urls = urlClassLoader.getURLs();
0680:                        logger.log(BasicLevel.DEBUG,
0681:                                "URLs of the classloader :");
0682:                        for (int u = 0; u < urls.length; u++) {
0683:                            logger.log(BasicLevel.DEBUG, "URL[" + u + "] = "
0684:                                    + urls[u]);
0685:                        }
0686:                    }
0687:                }
0688:
0689:                // Invoke client
0690:                // Launch the "class_to_run" by using our classloader.
0691:                Class clazz = clientClassloader.loadClass(mainClass);
0692:                Class[] argList = new Class[] { args.getClass() };
0693:                Method meth = clazz.getMethod("main", argList);
0694:
0695:                // Remove name of the file from arguments
0696:                String[] newArgs = new String[appArgs.size() - 1];
0697:                String txtArgs = "";
0698:
0699:                for (int i = 0; i < newArgs.length; i++) {
0700:                    newArgs[i] = (String) appArgs.get(i + 1);
0701:                    txtArgs += (newArgs[i] + " ");
0702:                }
0703:
0704:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0705:                    logger.log(BasicLevel.DEBUG,
0706:                            "Starting the application client with the arguments '"
0707:                                    + txtArgs + "'.");
0708:                }
0709:
0710:                info("Starting client...");
0711:
0712:                meth.invoke(null, new Object[] { newArgs });
0713:
0714:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0715:                    logger.log(BasicLevel.DEBUG, "End of main method");
0716:                }
0717:
0718:            }
0719:
0720:            /**
0721:             * Set the environment of this client
0722:             * @param clientDD deployment descriptor used for build the environment
0723:             * @throws NamingException if the creation of the environment fails
0724:             */
0725:            private void setClientEnvironment(
0726:                    ClientContainerDeploymentDesc clientDD)
0727:                    throws NamingException {
0728:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0729:                    logger.log(BasicLevel.DEBUG, "");
0730:                }
0731:
0732:                //Init the naming manager
0733:                try {
0734:                    naming = NamingManager.getInstance();
0735:                } catch (NamingException e) {
0736:                    throw new ClientContainerException(
0737:                            "Error when getting the reference to the Naming manager",
0738:                            e);
0739:                }
0740:
0741:                Context javaCtx = naming
0742:                        .createEnvironmentContext("ClientContainer");
0743:                naming.setClientContainerComponentContext(javaCtx);
0744:
0745:                Context envCtx = javaCtx.createSubcontext("comp/env");
0746:
0747:                // Bean Environment
0748:                EnvEntryDesc[] envt = clientDD.getEnvEntryDesc();
0749:
0750:                for (int i = 0; i < envt.length; i++) {
0751:                    // get information in descriptor
0752:                    String name = envt[i].getName();
0753:                    Object obj = envt[i].getValue();
0754:
0755:                    // register object in JNDI
0756:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0757:                        logger.log(BasicLevel.DEBUG, "Binding object " + name
0758:                                + " -> " + obj);
0759:                    }
0760:
0761:                    envCtx.rebind(name, obj);
0762:                }
0763:
0764:                // Resource References
0765:                ResourceRefDesc[] resref = clientDD.getResourceRefDesc();
0766:
0767:                for (int i = 0; i < resref.length; i++) {
0768:                    // get information in descriptor
0769:                    String name = resref[i].getName();
0770:                    String resname = resref[i].getJndiName();
0771:                    String type = resref[i].getTypeName();
0772:
0773:                    // build the LinkRef that will be registered:
0774:                    // FactoryClassName = null, size = 1, refAddr = resname.
0775:                    // register object in JNDI
0776:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0777:                        logger.log(BasicLevel.DEBUG, "Linking resource " + name
0778:                                + " -> " + resname);
0779:                    }
0780:
0781:                    if (type.equalsIgnoreCase("java.net.URL")) {
0782:                        // Specify the factory to use with the right URL
0783:                        Reference ref = new Reference(
0784:                                "java.net.URL",
0785:                                "org.objectweb.jonas_lib.naming.factory.URLFactory",
0786:                                null);
0787:                        StringRefAddr refAddr = new StringRefAddr("url",
0788:                                resname);
0789:                        ref.add(refAddr);
0790:                        envCtx.rebind(name, ref);
0791:                    } else {
0792:                        LinkRef lref = new LinkRef(resname);
0793:                        envCtx.rebind(name, lref);
0794:                    }
0795:                }
0796:
0797:                // Resource Environment References
0798:                ResourceEnvRefDesc[] resEnvref = clientDD
0799:                        .getResourceEnvRefDesc();
0800:
0801:                for (int i = 0; i < resEnvref.length; i++) {
0802:                    // get information in descriptor
0803:                    String name = resEnvref[i].getName();
0804:                    String resname = resEnvref[i].getJndiName();
0805:                    LinkRef lref = new LinkRef(resname);
0806:
0807:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0808:                        logger.log(BasicLevel.DEBUG,
0809:                                "Linking resource environment " + name + " -> "
0810:                                        + resname);
0811:                    }
0812:
0813:                    envCtx.rebind(name, lref);
0814:                }
0815:
0816:                // EJB References
0817:                EjbRefDesc[] ejbref = clientDD.getEjbRefDesc();
0818:
0819:                for (int i = 0; i < ejbref.length; i++) {
0820:                    // get information in descriptor
0821:                    String name = ejbref[i].getEjbRefName();
0822:                    String ejbname = null;
0823:                    ejbname = ejbref[i].getJndiName();
0824:
0825:                    LinkRef lref = new LinkRef(ejbname);
0826:
0827:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0828:                        logger.log(BasicLevel.DEBUG, "Linking ejb " + name
0829:                                + " -> " + ejbname);
0830:                    }
0831:
0832:                    envCtx.rebind(name, lref);
0833:                }
0834:
0835:                // ServiceRef
0836:                ServiceRefDesc[] serviceRefs = clientDD.getServiceRefDesc();
0837:                if (serviceRefs.length != 0) {
0838:
0839:                    // get the current ClassLoader
0840:                    ClassLoader loader = Thread.currentThread()
0841:                            .getContextClassLoader();
0842:
0843:                    // get the JServiceFactory
0844:                    JServiceFactory factory = ClientJServiceFactoryFinder
0845:                            .getJOnASServiceFactory();
0846:
0847:                    for (int i = 0; i < serviceRefs.length; i++) {
0848:                        // Create the Service from the ServiceRef description
0849:                        String refname = serviceRefs[i].getServiceRefName();
0850:
0851:                        Reference ref = factory.getServiceReference(
0852:                                serviceRefs[i], loader);
0853:                        envCtx.rebind(refname, ref);
0854:
0855:                        if (logger.isLoggable(BasicLevel.DEBUG)) {
0856:                            logger.log(BasicLevel.DEBUG,
0857:                                    "Adding service-ref 'java:comp/env/"
0858:                                            + refname + "'");
0859:                        }
0860:                    }
0861:                }
0862:
0863:                // MessageDestination References
0864:                MessageDestinationRefDesc[] mdref = clientDD
0865:                        .getMessageDestinationRefDesc();
0866:
0867:                for (int i = 0; i < mdref.length; i++) {
0868:                    // get information in descriptor
0869:                    String name = mdref[i].getMessageDestinationRefName();
0870:                    String mdname = null;
0871:                    mdname = mdref[i].getJndiName();
0872:
0873:                    LinkRef lref = new LinkRef(mdname);
0874:
0875:                    if (logger.isLoggable(BasicLevel.DEBUG)) {
0876:                        logger.log(BasicLevel.DEBUG,
0877:                                "Linking message-destination-ref " + name
0878:                                        + " -> " + mdname);
0879:                    }
0880:
0881:                    envCtx.rebind(name, lref);
0882:                }
0883:            }
0884:
0885:            /**
0886:             * Analyze arguments and extract parameters for the client container
0887:             * @throws Exception if there is an error when analyzing arguments
0888:             */
0889:            private void analyzeArgs() throws Exception {
0890:                for (int argn = 0; argn < args.length; argn++) {
0891:                    String arg = args[argn];
0892:
0893:                    try {
0894:                        if (arg.equals("-tmpDir")) {
0895:                            tmpDir = args[++argn];
0896:
0897:                            continue;
0898:                        }
0899:
0900:                        if (arg.equals("-jarClient")) {
0901:                            jarClient = args[++argn];
0902:
0903:                            continue;
0904:                        }
0905:
0906:                        if (arg.equals("-traceFile")) {
0907:                            clientTraceFile = args[++argn];
0908:
0909:                            continue;
0910:                        }
0911:
0912:                        if (arg.equals("-carolFile")) {
0913:                            carolFile = args[++argn];
0914:
0915:                            continue;
0916:                        }
0917:
0918:                        if (arg.equals("-cp")) {
0919:                            classpath = args[++argn];
0920:                            continue;
0921:                        }
0922:
0923:                        if (arg.equals("-nowsgen")) {
0924:                            applyWsGen = false;
0925:                            continue;
0926:                        }
0927:
0928:                        if (arg.equals("--help") || arg.equals("-help")
0929:                                || arg.equals("-h") || arg.equals("-?")) {
0930:                            usage();
0931:                            System.exit(1);
0932:                        }
0933:
0934:                        // Add argument to the application arguments
0935:                        appArgs.add(arg);
0936:                    } catch (ArrayIndexOutOfBoundsException aioobe) {
0937:                        // The next argument is not in the array
0938:                        throw new ClientContainerException(
0939:                                "A required parameter was missing after the argument"
0940:                                        + arg);
0941:                    }
0942:                }
0943:            }
0944:
0945:            /**
0946:             * Print the usage of this client
0947:             */
0948:            private void usage() {
0949:                System.out.println("Usage of this client :");
0950:                System.out
0951:                        .println("-------------------------------------------------------------------");
0952:                System.out
0953:                        .println("java -jar client.jar <client.jar|app.ear|className> [options]");
0954:                System.out
0955:                        .println("-------------------------------------------------------------------");
0956:                System.out
0957:                        .println(" -jarClient   : Specify the client jar to use of the ear if many.");
0958:                System.out
0959:                        .println(" -traceFile   : Specify the configuration file to use for the traces\n"
0960:                                + "                of this client instead of the default file\n"
0961:                                + "                (traceclient.properties) present in client.jar.");
0962:                System.out
0963:                        .println(" -carolFile   : Specify the carol.properties file to use instead of \n"
0964:                                + "                the default carol.properties file of the client.jar");
0965:                System.out
0966:                        .println(" -tmpDir      : Specify the temp directory where unpack the ear.");
0967:                System.out
0968:                        .println(" -cp          : Specify the classpath to use for the jar client.");
0969:                System.out
0970:                        .println(" -nowsgen     : Specify if the Container shouldn't use Automated WsGen.");
0971:                System.out
0972:                        .println("-------------------------------------------------------------------");
0973:                System.out.println("  --help  : Display this help.");
0974:                System.out.println("  -help   : Display this help.");
0975:                System.out.println("  -h      : Display this help.");
0976:                System.out.println("  -?      : Display this help.");
0977:                System.out
0978:                        .println("-------------------------------------------------------------------");
0979:            }
0980:
0981:            /**
0982:             * Extract the client of an ear and analyze ear too
0983:             * @param earFile ear to be analyzed
0984:             * @return the file of the client which was extracted
0985:             * @throws Exception if the analyze and/or extract fails
0986:             */
0987:            private File extractAndAnalyzeEar(File earFile) throws Exception {
0988:                if (logger.isLoggable(BasicLevel.DEBUG)) {
0989:                    logger.log(BasicLevel.DEBUG, "");
0990:                }
0991:
0992:                URL earUrl = null;
0993:
0994:                try {
0995:                    earUrl = earFile.toURL();
0996:                } catch (MalformedURLException mue) {
0997:                    throw new ClientContainerException(
0998:                            "Can not build an url with the filename '"
0999:                                    + earFile + "'.", mue);
1000:                }
1001:
1002:                // Create classLoader
1003:                URL[] arrURL = new URL[1];
1004:                arrURL[0] = earUrl;
1005:
1006:                // parent classloader is the current classloader
1007:                ClassLoader currentLoader = Thread.currentThread()
1008:                        .getContextClassLoader();
1009:                URLClassLoader loaderCls = new URLClassLoader(arrURL,
1010:                        currentLoader);
1011:
1012:                EarDeploymentDesc earDD = null;
1013:
1014:                if (logger.isLoggable(BasicLevel.DEBUG)) {
1015:                    logger.log(BasicLevel.DEBUG,
1016:                            "Getting the deployment descriptor of the file"
1017:                                    + earFile.getPath());
1018:                }
1019:
1020:                try {
1021:                    earDD = EarDeploymentDescManager.getDeploymentDesc(earFile
1022:                            .getPath(), loaderCls);
1023:                } catch (EarDeploymentDescException e) {
1024:                    String err = "Error in the Deployment descriptor '"
1025:                            + earFile + "'";
1026:                    throw new ClientContainerException(err, e);
1027:                }
1028:
1029:                Map userToRoleMapping = earDD.getUserToRoleMapping();
1030:                // Do user-to-role mapping
1031:                if (userToRoleMapping != null) {
1032:                    for (Iterator itMapping = userToRoleMapping.keySet()
1033:                            .iterator(); itMapping.hasNext();) {
1034:                        String principalName = (String) itMapping.next();
1035:                        List roles = (List) userToRoleMapping
1036:                                .get(principalName);
1037:                        String[] roleNames = (String[]) roles
1038:                                .toArray(new String[roles.size()]);
1039:                        JPolicyUserRoleMapping.addGlobalUserToRoleMapping(
1040:                                principalName, roleNames);
1041:                    }
1042:                }
1043:
1044:                // Get the tags from the Deployment descriptor
1045:                String[] ejbTags = earDD.getEjbTags();
1046:                Web[] webTags = earDD.getWebTags();
1047:                String[] clientTags = earDD.getClientTags();
1048:                String[] altDDEjbs = earDD.getAltDDEjbs();
1049:                String[] altDDWebs = earDD.getAltDDWebs();
1050:                String[] altDDClients = earDD.getAltDDClients();
1051:
1052:                // Check if all modules are inside the EAR file
1053:                // no relatives mode like ../../file1.jar
1054:                File fEar = null;
1055:                File tmpFile = null;
1056:
1057:                try {
1058:                    fEar = earFile.getCanonicalFile();
1059:                } catch (IOException ioe) {
1060:                    String err = "Error : Can not get canonical file for the file '"
1061:                            + earFile + "'.";
1062:                    throw new ClientContainerException(err, ioe);
1063:                }
1064:
1065:                try {
1066:                    for (int i = 0; i < ejbTags.length; i++) {
1067:                        tmpFile = new File(fEar, ejbTags[i]);
1068:                        tmpFile = tmpFile.getCanonicalFile();
1069:                        if (!tmpFile.getPath().startsWith(fEar.getPath())) {
1070:                            String err = "Error : The ejb-jar file "
1071:                                    + ejbTags[i]
1072:                                    + " is not inside the ear file " + fEar;
1073:                            throw new ClientContainerException(err);
1074:                        }
1075:                    }
1076:
1077:                    for (int i = 0; i < webTags.length; i++) {
1078:                        tmpFile = new File(fEar, webTags[i].getWebUri());
1079:                        tmpFile = tmpFile.getCanonicalFile();
1080:                        if (!tmpFile.getPath().startsWith(fEar.getPath())) {
1081:                            String err = "Error : The webapp file "
1082:                                    + webTags[i]
1083:                                    + " is not inside the ear file " + fEar;
1084:                            throw new ClientContainerException(err);
1085:                        }
1086:                    }
1087:
1088:                    for (int i = 0; i < clientTags.length; i++) {
1089:                        tmpFile = new File(fEar, clientTags[i]);
1090:                        tmpFile = tmpFile.getCanonicalFile();
1091:
1092:                        if (!tmpFile.getPath().startsWith(fEar.getPath())) {
1093:                            String err = "Error : The client jar file "
1094:                                    + clientTags[i]
1095:                                    + " is not inside the ear file " + fEar;
1096:                            throw new ClientContainerException(err);
1097:                        }
1098:                    }
1099:                } catch (IOException ioe) {
1100:                    String err = "Error while trying to get the canonical file of "
1101:                            + tmpFile;
1102:                    throw new ClientContainerException(err, ioe);
1103:                }
1104:
1105:                //Changing array into JarList
1106:                JarList ejbsList = new JarList(ejbTags);
1107:                JarList websList = new JarList(webTags);
1108:                JarList clientsList = new JarList(clientTags);
1109:
1110:                // Temporary directory
1111:                String tempDir = null;
1112:
1113:                if (tmpDir != null) {
1114:                    // use specific directory
1115:                    tempDir = tmpDir;
1116:                    info("Use your specified temp directory '" + tempDir + "'.");
1117:                } else {
1118:                    // use default
1119:                    tempDir = System.getProperty("java.io.tmpdir");
1120:                }
1121:
1122:                if (logger.isLoggable(BasicLevel.DEBUG)) {
1123:                    logger.log(BasicLevel.DEBUG, "Using temp directory '"
1124:                            + tempDir + "'.");
1125:                }
1126:
1127:                // Can we write to ?
1128:                File tmpFileDir = new File(tempDir);
1129:
1130:                if (!tmpFileDir.exists() || !tmpFileDir.isDirectory()) {
1131:                    throw new ClientContainerException("The temp directory '"
1132:                            + tempDir
1133:                            + "' doesn't exist or is not a directory.");
1134:                }
1135:
1136:                if (!tmpFileDir.canWrite()) {
1137:                    throw new ClientContainerException(
1138:                            "Can not write to the temporary directory '"
1139:                                    + tempDir + "'.");
1140:                }
1141:
1142:                // Unpack the ear file and get the unpacked dir
1143:                URL dirUnpackURL = null;
1144:
1145:                try {
1146:                    dirUnpackURL = EarFileManager.unpackEar(earUrl, tmpFileDir
1147:                            .toURL(), false);
1148:                } catch (Exception e) {
1149:                    String err = "Error while unpacking the file '" + earUrl
1150:                            + "'";
1151:                    throw new ClientContainerException(err, e);
1152:                }
1153:
1154:                // Ear is unpacked, now analyze manifest Class-path:
1155:                EarClassPathManager earCPManager = null;
1156:
1157:                try {
1158:                    earCPManager = new EarClassPathManager(clientsList,
1159:                            dirUnpackURL);
1160:                } catch (EarClassPathManagerException e) {
1161:                    String err = "Error while creating the Ear class path manager of the ear : '"
1162:                            + earUrl + "'";
1163:                    error(err + " : " + e.getMessage());
1164:                    throw new ClientContainerException(err, e);
1165:                }
1166:
1167:                URL[] classpathURLs = null;
1168:
1169:                //Get the urls of the ear class path manager
1170:                try {
1171:                    classpathURLs = earCPManager.getResolvedClassPath();
1172:                } catch (EarClassPathManagerException e) {
1173:                    String err = "Error while trying to resolve the classpath of the ejbjars and wars of the ear : '"
1174:                            + earUrl + "'";
1175:                    error(err + " : " + e.getMessage());
1176:                    throw new ClientContainerException(err, e);
1177:                }
1178:
1179:                if (logger.isLoggable(BasicLevel.DEBUG)) {
1180:                    logger.log(BasicLevel.DEBUG, "EAR : ejbs = " + ejbsList);
1181:                    logger.log(BasicLevel.DEBUG, "EAR : clientUrls = "
1182:                            + clientsList);
1183:                }
1184:
1185:                currentLoader = Thread.currentThread().getContextClassLoader();
1186:                earClassLoader = new URLClassLoader(new URL[0], currentLoader);
1187:
1188:                //Extract the urls of the jarList
1189:                URL[] jarUrls = null;
1190:                URL[] warUrls = null;
1191:                URL[] clientUrls = null;
1192:
1193:                try {
1194:                    jarUrls = ejbsList.getURLs(dirUnpackURL.toExternalForm());
1195:                    warUrls = websList.getURLs(dirUnpackURL.toExternalForm());
1196:                    clientUrls = clientsList.getURLs(dirUnpackURL
1197:                            .toExternalForm());
1198:                } catch (JarListException e) {
1199:                    String err = "Error while geting the Urls from jarlist of the ear : '"
1200:                            + earUrl + "'";
1201:                    throw new ClientContainerException(err, e);
1202:                }
1203:
1204:                //Fill Alt-DD for Ejbs and Clients
1205:                String altdd = null;
1206:                File fAltDD = null;
1207:
1208:                //Transorm the array altDDWebs into an array with the absolute URL to
1209:                // the file
1210:                URL[] clientsAltDDs = new URL[altDDClients.length];
1211:
1212:                for (int i = 0; i < altDDClients.length; i++) {
1213:                    if (altDDClients[i] != null) {
1214:                        altdd = altDDClients[i];
1215:
1216:                        if (altdd != null) {
1217:                            try {
1218:                                fAltDD = new File(new URL(dirUnpackURL
1219:                                        .toExternalForm()
1220:                                        + File.separator + altdd).getFile());
1221:                                clientsAltDDs[i] = fAltDD.getCanonicalFile()
1222:                                        .toURL();
1223:                            } catch (MalformedURLException e) {
1224:                                String err = "Can't build URL for alt-dd '"
1225:                                        + altdd;
1226:                                error(err + "': " + e.getMessage());
1227:                                throw new ClientContainerException(err, e);
1228:                            } catch (IOException ioe) {
1229:                                String err = "Can't get canonicalFile() for the file '"
1230:                                        + fAltDD;
1231:                                error(err + "': " + ioe.getMessage());
1232:                                throw new ClientContainerException(err, ioe);
1233:                            }
1234:                        }
1235:                    }
1236:                }
1237:
1238:                URL[] ejbsAltDDs = new URL[altDDEjbs.length];
1239:
1240:                for (int i = 0; i < altDDEjbs.length; i++) {
1241:                    if (altDDEjbs[i] != null) {
1242:                        altdd = altDDEjbs[i];
1243:
1244:                        if (altdd != null) {
1245:                            try {
1246:                                fAltDD = new File(new URL(dirUnpackURL
1247:                                        .toExternalForm()
1248:                                        + File.separator + altdd).getFile());
1249:                                ejbsAltDDs[i] = fAltDD.getCanonicalFile()
1250:                                        .toURL();
1251:                            } catch (MalformedURLException e) {
1252:                                String err = "Can't build URL for alt-dd '"
1253:                                        + altdd;
1254:                                error(err + "': " + e.getMessage());
1255:                                throw new ClientContainerException(err, e);
1256:                            } catch (IOException ioe) {
1257:                                String err = "Can't get canonicalFile() for the file '"
1258:                                        + fAltDD;
1259:                                error(err + "': " + ioe.getMessage());
1260:                                throw new ClientContainerException(err, ioe);
1261:                            }
1262:                        }
1263:                    }
1264:                }
1265:
1266:                URL[] websAltDDs = new URL[altDDWebs.length];
1267:
1268:                for (int i = 0; i < altDDWebs.length; i++) {
1269:                    if (altDDWebs[i] != null) {
1270:                        altdd = altDDWebs[i];
1271:
1272:                        if (altdd != null) {
1273:                            try {
1274:                                fAltDD = new File(new URL(dirUnpackURL
1275:                                        .toExternalForm()
1276:                                        + File.separator + altdd).getFile());
1277:                                websAltDDs[i] = fAltDD.getCanonicalFile()
1278:                                        .toURL();
1279:                            } catch (MalformedURLException e) {
1280:                                String err = "Can't build URL for alt-dd '"
1281:                                        + altdd;
1282:                                error(err + "': " + e.getMessage());
1283:                                throw new ClientContainerException(err, e);
1284:                            } catch (IOException ioe) {
1285:                                String err = "Can't get canonicalFile() for the file '"
1286:                                        + fAltDD;
1287:                                error(err + "': " + ioe.getMessage());
1288:                                throw new ClientContainerException(err, ioe);
1289:                            }
1290:                        }
1291:                    }
1292:                }
1293:
1294:                EjbDeploymentDescManager.getInstance()
1295:                        .setAvailableEjbJarsAndAltDDs(earClassLoader, jarUrls,
1296:                                ejbsAltDDs);
1297:                WebDeploymentDescManager.getInstance().setAltDD(earClassLoader,
1298:                        warUrls, websAltDDs);
1299:                ClientDeploymentDescManager.getInstance().setAltDD(
1300:                        earClassLoader, clientUrls, clientsAltDDs);
1301:
1302:                // Construct the ejb classloader for all the ejb-jars of the same
1303:                // ear application. Because there is one ejb classloader for all
1304:                // the ejb-jars of the same ear application.
1305:                URL[] userURLs = getUserClasspathUrls();
1306:                extensionsURLs = new URL[jarUrls.length + classpathURLs.length
1307:                        + userURLs.length];
1308:
1309:                System.arraycopy(jarUrls, 0, extensionsURLs, 0, jarUrls.length);
1310:                System.arraycopy(classpathURLs, 0, extensionsURLs,
1311:                        jarUrls.length, classpathURLs.length);
1312:                System.arraycopy(userURLs, 0, extensionsURLs, jarUrls.length
1313:                        + classpathURLs.length, userURLs.length);
1314:
1315:                if (logger.isLoggable(BasicLevel.DEBUG)) {
1316:                    logger.log(BasicLevel.DEBUG, "Extensions urls :");
1317:
1318:                    for (int ii = 0; ii < extensionsURLs.length; ii++) {
1319:                        logger.log(BasicLevel.DEBUG, "url[" + ii + "] = "
1320:                                + extensionsURLs[ii]);
1321:                    }
1322:                }
1323:
1324:                // Choose the jar client
1325:                if (clientUrls.length == 0) {
1326:                    throw new ClientContainerException(
1327:                            "No java client was found in the application.xml file of the Ear '"
1328:                                    + earUrl + "'.");
1329:                }
1330:
1331:                File fClient = null;
1332:
1333:                // User has specify an application client to execute
1334:                // Search it
1335:                if (jarClient != null) {
1336:                    int f = 0;
1337:                    File ff = null;
1338:                    boolean found = false;
1339:
1340:                    while (f < clientUrls.length && !found) {
1341:                        ff = new File(clientUrls[f].getFile());
1342:
1343:                        if (ff.getPath().endsWith(jarClient)) {
1344:                            found = true;
1345:                            fClient = ff;
1346:
1347:                            if (logger.isLoggable(BasicLevel.DEBUG)) {
1348:                                logger.log(BasicLevel.DEBUG,
1349:                                        "Found a matching client with the name "
1350:                                                + ff);
1351:                            }
1352:                        }
1353:
1354:                        f++;
1355:                    }
1356:
1357:                    if (!found) {
1358:                        throw new ClientContainerException(
1359:                                "No client with the name '" + jarClient
1360:                                        + "' was found in this Ear file");
1361:                    }
1362:                } else {
1363:                    // Take first
1364:                    fClient = new File(clientUrls[0].getFile());
1365:
1366:                    // Warning if many
1367:                    if (clientUrls.length > 1) {
1368:                        warn("There are "
1369:                                + clientUrls.length
1370:                                + " clients in this ear, choosing the first one : "
1371:                                + fClient.getName());
1372:                    }
1373:                }
1374:
1375:                info("Use the application client '" + fClient
1376:                        + "' of the Ear '" + earUrl + "'.");
1377:
1378:                return fClient;
1379:            }
1380:
1381:            /**
1382:             * Gets the URL of user classpath (can be empty
1383:             * @return URL of user classpath (-cp arg)
1384:             */
1385:            private URL[] getUserClasspathUrls() {
1386:                if (classpath == null) {
1387:                    return new URL[0];
1388:                }
1389:                String sep = File.pathSeparator;
1390:                List clUser = new ArrayList();
1391:                StringTokenizer tokenizer = new StringTokenizer(classpath, sep);
1392:                while (tokenizer.hasMoreTokens()) {
1393:                    File file = new File(tokenizer.nextToken());
1394:                    try {
1395:                        clUser.add(file.toURL());
1396:                    } catch (MalformedURLException mue) {
1397:                        logger.log(BasicLevel.WARN,
1398:                                "Cannot transform to URL the file : '" + file
1399:                                        + "'", mue);
1400:                    }
1401:                }
1402:                return (URL[]) clUser.toArray(new URL[0]);
1403:            }
1404:
1405:            /**
1406:             * Display an info message with the logger
1407:             * @param s the message
1408:             */
1409:            private void info(String s) {
1410:                logger.log(BasicLevel.INFO, s);
1411:            }
1412:
1413:            /**
1414:             * Display an error message with the logger
1415:             * @param s the message
1416:             */
1417:            private void error(String s) {
1418:                logger.log(BasicLevel.ERROR, s);
1419:            }
1420:
1421:            /**
1422:             * Display a warn message with the logger
1423:             * @param s the message
1424:             */
1425:            private void warn(String s) {
1426:                logger.log(BasicLevel.WARN, s);
1427:            }
1428:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.