KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > alt > config > ConfigurationFactory


1 /**
2  * Redistribution and use of this software and associated documentation
3  * ("Software"), with or without modification, are permitted provided
4  * that the following conditions are met:
5  *
6  * 1. Redistributions of source code must retain copyright
7  * statements and notices. Redistributions must also contain a
8  * copy of this document.
9  *
10  * 2. Redistributions in binary form must reproduce the
11  * above copyright notice, this list of conditions and the
12  * following disclaimer in the documentation and/or other
13  * materials provided with the distribution.
14  *
15  * 3. The name "OpenEJB" must not be used to endorse or promote
16  * products derived from this Software without prior written
17  * permission of The OpenEJB Group. For written permission,
18  * please contact dev@openejb.org.
19  *
20  * 4. Products derived from this Software may not be called "OpenEJB"
21  * nor may "OpenEJB" appear in their names without prior written
22  * permission of The OpenEJB Group. OpenEJB is a registered
23  * trademark of The OpenEJB Group.
24  *
25  * 5. Due credit should be given to the OpenEJB Project
26  * (http://www.openejb.org/).
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE OPENEJB GROUP AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
30  * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
31  * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
32  * THE OPENEJB GROUP OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
33  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
34  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
35  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
36  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
37  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
39  * OF THE POSSIBILITY OF SUCH DAMAGE.
40  *
41  * Copyright 2001 (C) The OpenEJB Group. All Rights Reserved.
42  *
43  * $Id: ConfigurationFactory.java 2487 2006-02-22 22:05:03Z dblevins $
44  */

45 package org.openejb.alt.config;
46
47 import org.openejb.OpenEJBException;
48 import org.openejb.alt.assembler.classic.*;
49 import org.openejb.alt.config.ejb11.ContainerTransaction;
50 import org.openejb.alt.config.ejb11.EjbDeployment;
51 import org.openejb.alt.config.ejb11.EjbJar;
52 import org.openejb.alt.config.ejb11.EjbLocalRef;
53 import org.openejb.alt.config.ejb11.EjbRef;
54 import org.openejb.alt.config.ejb11.EnterpriseBeansItem;
55 import org.openejb.alt.config.ejb11.Entity;
56 import org.openejb.alt.config.ejb11.EnvEntry;
57 import org.openejb.alt.config.ejb11.Method;
58 import org.openejb.alt.config.ejb11.MethodParams;
59 import org.openejb.alt.config.ejb11.MethodPermission;
60 import org.openejb.alt.config.ejb11.OpenejbJar;
61 import org.openejb.alt.config.ejb11.Query;
62 import org.openejb.alt.config.ejb11.QueryMethod;
63 import org.openejb.alt.config.ejb11.ResourceLink;
64 import org.openejb.alt.config.ejb11.ResourceRef;
65 import org.openejb.alt.config.ejb11.SecurityRole;
66 import org.openejb.alt.config.ejb11.SecurityRoleRef;
67 import org.openejb.alt.config.ejb11.Session;
68 import org.openejb.alt.config.sys.ConnectionManager;
69 import org.openejb.alt.config.sys.Connector;
70 import org.openejb.alt.config.sys.Container;
71 import org.openejb.alt.config.sys.Deployments;
72 import org.openejb.alt.config.sys.JndiProvider;
73 import org.openejb.alt.config.sys.Openejb;
74 import org.openejb.alt.config.sys.ProxyFactory;
75 import org.openejb.alt.config.sys.SecurityService;
76 import org.openejb.alt.config.sys.ServiceProvider;
77 import org.openejb.alt.config.sys.ServicesJar;
78 import org.openejb.alt.config.sys.TransactionService;
79 import org.openejb.loader.SystemInstance;
80 import org.openejb.util.Logger;
81 import org.openejb.util.Messages;
82 import org.openejb.util.FileUtils;
83
84 import java.io.File JavaDoc;
85 import java.io.FilenameFilter JavaDoc;
86 import java.net.MalformedURLException JavaDoc;
87 import java.net.URL JavaDoc;
88 import java.net.URLClassLoader JavaDoc;
89 import java.util.ArrayList JavaDoc;
90 import java.util.Arrays JavaDoc;
91 import java.util.Enumeration JavaDoc;
92 import java.util.HashMap JavaDoc;
93 import java.util.Iterator JavaDoc;
94 import java.util.Map JavaDoc;
95 import java.util.Properties JavaDoc;
96 import java.util.Vector JavaDoc;
97 import java.util.List JavaDoc;
98
99 /**
100  * An implementation of the Classic Assembler's OpenEjbConfigurationFactory
101  * interface. This implementation translates the user's config file and
102  * deployed jars into the required InfoObject structure.
103  * <p/>
104  * This class doesn't do any configuring per se. It just
105  * reads in the config information for the assebler.
106  *
107  * @author <a HREF="mailto:david.blevins@visi.com">David Blevins</a>
108  */

109 public class ConfigurationFactory implements OpenEjbConfigurationFactory, ProviderDefaults {
110
111     public static final String JavaDoc DEFAULT_SECURITY_ROLE = "openejb.default.security.role";
112     protected static final Logger logger = Logger.getInstance("OpenEJB.startup", "org.openejb.util.resources");
113     protected static final Messages messages = new Messages("org.openejb.util.resources");
114
115     private AutoDeployer deployer;
116     private Openejb openejb;
117     private DeployedJar[] jars;
118     private ServicesJar openejbDefaults = null;
119
120     private String JavaDoc configLocation = "";
121
122     private Vector JavaDoc deploymentIds = new Vector JavaDoc();
123     private Vector JavaDoc securityRoles = new Vector JavaDoc();
124     private Vector JavaDoc containerIds = new Vector JavaDoc();
125
126     private Vector JavaDoc mthdPermInfos = new Vector JavaDoc();
127     private Vector JavaDoc mthdTranInfos = new Vector JavaDoc();
128     private Vector JavaDoc sRoleInfos = new Vector JavaDoc();
129
130     //------------------------------------------------//
131
//
132
// I n f o O b j e c t s
133
//
134
//------------------------------------------------//
135
public static OpenEjbConfiguration sys;
136
137     private ContainerInfo[] containers;
138     private EntityContainerInfo[] entityContainers;
139     private StatefulSessionContainerInfo[] sfsbContainers;
140     private StatelessSessionContainerInfo[] slsbContainers;
141
142     /**
143      * Hash of container info objects for quick reference
144      */

145     private HashMap JavaDoc containerTable = new HashMap JavaDoc();
146
147     private Properties JavaDoc props;
148
149     public void init(Properties JavaDoc props) throws OpenEJBException {
150         this.props = props;
151
152         configLocation = props.getProperty("openejb.conf.file");
153
154         if (configLocation == null) {
155             configLocation = props.getProperty("openejb.configuration");
156         }
157
158         configLocation = ConfigUtils.searchForConfiguration(configLocation, props);
159         this.props.setProperty("openejb.configuration", configLocation);
160
161     }
162
163     public static void main(String JavaDoc[] args) {
164         try {
165             ConfigurationFactory conf = new ConfigurationFactory();
166             conf.configLocation = args[0];
167             conf.init(null);
168             OpenEjbConfiguration openejb = conf.getOpenEjbConfiguration();
169
170             conf.printConf(openejb);
171         } catch (Exception JavaDoc e) {
172             System.out.println("[OpenEJB] " + e.getMessage());
173             e.printStackTrace();
174         }
175     }
176
177     /**
178      * Read in the configuration information into the
179      * Openejb object
180      * Validate it
181      * <p/>
182      * Read in each deployment object
183      * Validate it
184      * <p/>
185      * Translate the whole thing into Info objects.
186      * Return them.
187      */

188     public OpenEjbConfiguration getOpenEjbConfiguration() throws OpenEJBException {
189
190         // Load configuration
191
// Validate Configuration
192
openejb = ConfigUtils.readConfig(configLocation);
193
194         deployer = new AutoDeployer(openejb);
195
196         // Resolve File Locations
197
// Resolve Classes
198
resolveDependencies(openejb);
199
200         // Load deployments
201
jars = loadDeployments(openejb);
202
203         // Build the base OpenEjbConfiguration
204
sys = new OpenEjbConfiguration();
205         sys.containerSystem = new ContainerSystemInfo();
206         sys.facilities = new FacilitiesInfo();
207
208         initJndiProviders(openejb, sys.facilities);
209         initTransactionService(openejb, sys.facilities);
210         initConnectors(openejb, sys.facilities);
211         initConnectionManagers(openejb, sys.facilities);
212         initProxyFactory(openejb, sys.facilities);
213
214         // Fills the four container info arrays
215
// in this class
216
initContainerInfos(openejb);
217
218         sys.containerSystem.containers = containers;
219         sys.containerSystem.entityContainers = entityContainers;
220         sys.containerSystem.statefulContainers = sfsbContainers;
221         sys.containerSystem.statelessContainers = slsbContainers;
222
223         ArrayList JavaDoc ejbs = new ArrayList JavaDoc();
224         ArrayList JavaDoc ejbJars = new ArrayList JavaDoc();
225         for (int i = 0; i < jars.length; i++) {
226             try {
227                 EjbJarInfo ejbJarInfo = initEjbJarInfo(jars[i]);
228                 if (ejbJarInfo == null){
229                     continue;
230                 }
231                 ejbJars.add(ejbJarInfo);
232                 ejbs.addAll(Arrays.asList(ejbJarInfo.enterpriseBeans));
233             } catch (Exception JavaDoc e) {
234                 e.printStackTrace();
235                 ConfigUtils.logger.i18n.warning("conf.0004", jars[i].jarURI, e.getMessage());
236             }
237         }
238         sys.containerSystem.enterpriseBeans = (EnterpriseBeanInfo[]) ejbs.toArray(new EnterpriseBeanInfo[]{});
239         sys.containerSystem.ejbJars = (EjbJarInfo[]) ejbJars.toArray(new EjbJarInfo[]{});
240
241         // Add the defaults
242
SecurityRoleInfo defaultRole = new SecurityRoleInfo();
243         defaultRole.description = "The role applied to recurity references that are not linked.";
244         defaultRole.roleName = DEFAULT_SECURITY_ROLE;
245         sRoleInfos.add(defaultRole);
246
247         // Collect Arrays
248
sys.containerSystem.securityRoles = new SecurityRoleInfo[sRoleInfos.size()];
249         sys.containerSystem.methodPermissions = new MethodPermissionInfo[mthdPermInfos.size()];
250         sys.containerSystem.methodTransactions = new MethodTransactionInfo[mthdTranInfos.size()];
251
252         sRoleInfos.copyInto(sys.containerSystem.securityRoles);
253         mthdPermInfos.copyInto(sys.containerSystem.methodPermissions);
254         mthdTranInfos.copyInto(sys.containerSystem.methodTransactions);
255
256         initSecutityService(openejb, sys.facilities);
257
258         return sys;
259     }
260
261     Vector JavaDoc jndiProviderIds = new Vector JavaDoc();
262
263     /**
264      * Create the JndiContextInfo section of the OpenEJBConfiguration
265      * factory.
266      *
267      * @param openejb
268      * @param facilities
269      * @throws OpenEJBException
270      */

271     private void initJndiProviders(Openejb openejb, FacilitiesInfo facilities)
272             throws OpenEJBException {
273         JndiProvider[] provider = openejb.getJndiProvider();
274
275         if (provider == null || provider.length < 1) return;
276
277         JndiContextInfo[] ctxInfo = new JndiContextInfo[provider.length];
278         facilities.remoteJndiContexts = ctxInfo;
279
280         // Init each provider one by one
281
for (int i = 0; i < provider.length; i++) {
282             provider[i] = (JndiProvider) initService(provider[i], null);
283             ServiceProvider service = ServiceUtils.getServiceProvider(provider[i]);
284             checkType(service, provider[i], "JndiProvider");
285
286             ctxInfo[i] = new JndiContextInfo();
287
288             ctxInfo[i].jndiContextId = provider[i].getId();
289
290             // Verify the uniqueness of the ID
291
if (jndiProviderIds.contains(provider[i].getId())) {
292                 handleException("conf.0103", configLocation, provider[i].getId());
293             }
294
295             jndiProviderIds.add(provider[i].getId());
296
297             // Load the propterties file
298
ctxInfo[i].properties =
299                     ServiceUtils.assemblePropertiesFor("JndiProvider",
300                             provider[i].getId(),
301                             provider[i].getContent(),
302                             configLocation,
303                             service);
304         }
305     }
306
307     private void initSecutityService(Openejb openejb, FacilitiesInfo facilities)
308             throws OpenEJBException {
309         SecurityService ss = openejb.getSecurityService();
310
311         ss = (SecurityService) initService(ss, DEFAULT_SECURITY_SERVICE, SecurityService.class);
312         ServiceProvider ssp = ServiceUtils.getServiceProvider(ss);
313         checkType(ssp, ss, "Security");
314
315         SecurityServiceInfo ssi = new SecurityServiceInfo();
316
317         ssi.codebase = ss.getJar();
318         ssi.description = ssp.getDescription();
319         ssi.displayName = ssp.getDisplayName();
320         ssi.factoryClassName = ssp.getClassName();
321         ssi.serviceName = ss.getId();
322         ssi.properties =
323                 ServiceUtils.assemblePropertiesFor("Security",
324                         ss.getId(),
325                         ss.getContent(),
326                         configLocation,
327                         ssp);
328         SecurityRoleInfo[] roles = sys.containerSystem.securityRoles;
329         RoleMappingInfo[] r = new RoleMappingInfo[roles.length];
330         ssi.roleMappings = r;
331
332         // This is really a workaround, I'm simply giving
333
// the physical role the same name as the logical
334
// role. No security services have been integrated
335
// with OpenEJB yet. The conecpt of having OpenEJB
336
// do the role linking for the security service has
337
// never been put to the test, therefore, we are not
338
// going to worry about role mapping until a valid
339
// security service is integrated. At that time, we
340
// can take the approach that makes the most sense.
341
for (int i = 0; i < r.length; i++) {
342             r[i] = new RoleMappingInfo();
343             r[i].logicalRoleNames = new String JavaDoc[]{roles[i].roleName};
344             r[i].physicalRoleNames = new String JavaDoc[]{roles[i].roleName};
345         }
346
347         facilities.securityService = ssi;
348     }
349
350     private void initTransactionService(Openejb openejb, FacilitiesInfo facilities)
351             throws OpenEJBException {
352         TransactionService ts = openejb.getTransactionService();
353
354         ts =
355                 (TransactionService) initService(ts,
356                         DEFAULT_TRANSACTION_MANAGER,
357                         TransactionService.class);
358         ServiceProvider service = ServiceUtils.getServiceProvider(ts);
359         checkType(service, ts, "Transaction");
360
361         TransactionServiceInfo tsi = new TransactionServiceInfo();
362
363         tsi.codebase = ts.getJar();
364         tsi.description = service.getDescription();
365         tsi.displayName = service.getDisplayName();
366         tsi.factoryClassName = service.getClassName();
367         tsi.serviceName = ts.getId();
368         tsi.properties =
369                 ServiceUtils.assemblePropertiesFor("Transaction",
370                         ts.getId(),
371                         ts.getContent(),
372                         configLocation,
373                         service);
374         facilities.transactionService = tsi;
375     }
376
377     Vector JavaDoc connectorIds = new Vector JavaDoc();
378
379     /**
380      * Create the ConnectorInfo section of the OpenEJBConfiguration
381      * factory.
382      *
383      * @param openejb
384      * @param facilities
385      * @throws OpenEJBException
386      */

387     private void initConnectors(Openejb openejb, FacilitiesInfo facilities)
388             throws OpenEJBException {
389
390         Connector[] conn = openejb.getConnector();
391
392         if (conn == null || conn.length < 1) return;
393
394         ConnectorInfo[] info = new ConnectorInfo[conn.length];
395         facilities.connectors = info;
396
397         // Init each conn one by one
398
for (int i = 0; i < conn.length; i++) {
399
400             conn[i] = (Connector) initService(conn[i], DEFAULT_JDBC_DATABASE, Connector.class);
401             ServiceProvider service = ServiceUtils.getServiceProvider(conn[i]);
402             checkType(service, conn[i], "Connector");
403
404             ManagedConnectionFactoryInfo factory = new ManagedConnectionFactoryInfo();
405
406             info[i] = new ConnectorInfo();
407             info[i].connectorId = conn[i].getId();
408             info[i].connectionManagerId = DEFAULT_LOCAL_TX_CON_MANAGER;
409             info[i].managedConnectionFactory = factory;
410
411             factory.id = conn[i].getId();
412             factory.className = service.getClassName();
413             factory.codebase = conn[i].getJar();
414             factory.properties =
415                     ServiceUtils.assemblePropertiesFor("Connector",
416                             conn[i].getId(),
417                             conn[i].getContent(),
418                             configLocation,
419                             service);
420
421             // Verify the uniqueness of the ID
422
if (connectorIds.contains(conn[i].getId())) {
423                 handleException("conf.0103", configLocation, conn[i].getId());
424             }
425
426             connectorIds.add(conn[i].getId());
427         }
428     }
429
430     private void initConnectionManagers(Openejb openejb, FacilitiesInfo facilities)
431             throws OpenEJBException {
432
433         ConnectionManagerInfo manager = new ConnectionManagerInfo();
434         ConnectionManager cm = openejb.getConnectionManager();
435
436         cm =
437                 (ConnectionManager) initService(cm,
438                         DEFAULT_LOCAL_TX_CON_MANAGER,
439                         ConnectionManager.class);
440
441         ServiceProvider service = ServiceUtils.getServiceProvider(cm);
442
443         checkType(service, cm, "ConnectionManager");
444
445         manager.connectionManagerId = cm.getId();
446         manager.className = service.getClassName();
447         manager.codebase = cm.getJar();
448         manager.properties =
449                 ServiceUtils.assemblePropertiesFor("ConnectionManager",
450                         cm.getId(),
451                         cm.getContent(),
452                         configLocation,
453                         service);
454
455         facilities.connectionManagers = new ConnectionManagerInfo[]{manager};
456     }
457
458     private void initProxyFactory(Openejb openejb, FacilitiesInfo facilities)
459             throws OpenEJBException {
460         String JavaDoc defaultFactory = null;
461         try {
462             String JavaDoc version = System.getProperty("java.vm.version");
463             if (version.startsWith("1.1") || version.startsWith("1.2")) {
464                 defaultFactory = "Default JDK 1.2 ProxyFactory";
465             } else {
466                 defaultFactory = "Default JDK 1.3 ProxyFactory";
467             }
468         } catch (Exception JavaDoc e) {
469             //TODO: Better exception handling
470
throw new RuntimeException JavaDoc("Unable to determine the version of your VM. No ProxyFactory Can be installed");
471         }
472
473         ProxyFactory pf = openejb.getProxyFactory();
474
475         pf = (ProxyFactory) initService(pf, defaultFactory, ProxyFactory.class);
476         ServiceProvider pfp = ServiceUtils.getServiceProvider(pf);
477         checkType(pfp, pf, "Proxy");
478
479         IntraVmServerInfo pfi = new IntraVmServerInfo();
480
481         facilities.intraVmServer = pfi;
482         pfi.proxyFactoryClassName = pfp.getClassName();
483
484         pfi.factoryName = pf.getId();
485         pfi.codebase = pf.getJar();
486         pfi.properties =
487                 ServiceUtils.assemblePropertiesFor("Proxy",
488                         pf.getId(),
489                         pf.getContent(),
490                         configLocation,
491                         pfp);
492     }
493
494     /**
495      * Initializes the four container info arrays.
496      * <p/>
497      * ContainerInfo[] cntrs;
498      * EntityContainerInfo[] entyCntrs;
499      * StatefulSessionContainerInfo stflCntrs;
500      * StatelessSessionContainerInfo stlsCntrs;
501      *
502      * @param conf
503      */

504     private void initContainerInfos(Openejb conf) throws OpenEJBException {
505         Vector JavaDoc e = new Vector JavaDoc();
506         Vector JavaDoc sf = new Vector JavaDoc();
507         Vector JavaDoc sl = new Vector JavaDoc();
508
509         Container[] containers = conf.getContainer();
510
511         for (int i = 0; i < containers.length; i++) {
512
513             Container c = containers[i];
514             ContainerInfo ci = null;
515
516             if (c.getCtype().equals("STATELESS")) {
517                 c = (Container) initService(c, DEFAULT_STATELESS_CONTAINER);
518                 ci = new StatelessSessionContainerInfo();
519                 sl.add(ci);
520             } else if (c.getCtype().equals("STATEFUL")) {
521                 c = (Container) initService(c, DEFAULT_STATEFUL_CONTAINER);
522                 ci = new StatefulSessionContainerInfo();
523                 sf.add(ci);
524             } else if (c.getCtype().equals("BMP_ENTITY")) {
525                 c = (Container) initService(c, DEFAULT_BMP_CONTAINER);
526                 ci = new EntityContainerInfo();
527                 e.add(ci);
528             } else if (c.getCtype().equals("CMP_ENTITY")) {
529                 c = (Container) initService(c, DEFAULT_CMP_CONTAINER);
530                 ci = new EntityContainerInfo();
531                 e.add(ci);
532             } else {
533                 throw new OpenEJBException("Unrecognized contianer type " + c.getCtype());
534             }
535
536             ServiceProvider service = ServiceUtils.getServiceProvider(c);
537             checkType(service, c, "Container");
538
539             ci.ejbeans = new EnterpriseBeanInfo[0];
540             ci.containerName = c.getId();
541             ci.className = service.getClassName();
542             ci.codebase = c.getJar();
543             ci.properties =
544                     ServiceUtils.assemblePropertiesFor("Container",
545                             c.getId(),
546                             c.getContent(),
547                             configLocation,
548                             service);
549
550             //// Check if ID is a Duplicate /////
551
if (containerIds.contains(c.getId())) {
552                 handleException("conf.0101", configLocation, c.getId());
553             }
554
555             containerIds.add(c.getId());
556
557         }
558
559         entityContainers = new EntityContainerInfo[e.size()];
560         e.copyInto(entityContainers);
561
562         sfsbContainers = new StatefulSessionContainerInfo[sf.size()];
563         sf.copyInto(sfsbContainers);
564
565         slsbContainers = new StatelessSessionContainerInfo[sl.size()];
566         sl.copyInto(slsbContainers);
567
568         e.addAll(sf);
569         e.addAll(sl);
570         this.containers = new ContainerInfo[e.size()];
571         e.copyInto(this.containers);
572
573         for (int i = 0; i < this.containers.length; i++) {
574             containerTable.put(this.containers[i].containerName, this.containers[i]);
575         }
576
577     }
578
579     private Map JavaDoc getDeployments(OpenejbJar j) throws OpenEJBException {
580         HashMap JavaDoc map = new HashMap JavaDoc(j.getEjbDeploymentCount());
581         Enumeration JavaDoc enumeration = j.enumerateEjbDeployment();
582
583         while (enumeration.hasMoreElements()) {
584             EjbDeployment d = (EjbDeployment) enumeration.nextElement();
585             map.put(d.getEjbName(), d);
586         }
587
588         return map;
589     }
590
591     /**
592      * Creates and EnterpriseBeanInfo for each bean in the deployed jar
593      * then calls assignBeansToContainers. If there is a problem with
594      * the jar, such as a duplicate deployment id, the jar will be skipped.
595      *
596      * @param jar
597      * @throws OpenEJBException
598      */

599     private EjbJarInfo initEjbJarInfo(DeployedJar jar) throws OpenEJBException {
600
601         int beansDeployed = jar.openejbJar.getEjbDeploymentCount();
602         int beansInEjbJar = jar.ejbJar.getEnterpriseBeans().getEnterpriseBeansItemCount();
603
604         if (beansInEjbJar != beansDeployed) {
605             ConfigUtils.logger.i18n.warning("conf.0008", jar.jarURI, "" + beansInEjbJar, "" + beansDeployed);
606             // Not all ejb in this jar have been deployed.
607
// This jar cannot be loaded into the system and must
608
// be skipped.
609
return null;
610         }
611
612         Map JavaDoc ejbds = getDeployments(jar.openejbJar);
613         Map JavaDoc infos = new HashMap JavaDoc();
614         Map JavaDoc items = new HashMap JavaDoc();
615
616         EnterpriseBeanInfo[] beans = new EnterpriseBeanInfo[ejbds.size()];
617         EjbJarInfo ejbJar = new EjbJarInfo();
618         ejbJar.enterpriseBeans = beans;
619         ejbJar.jarPath = jar.jarURI;
620
621         int i = -1;
622
623         Enumeration JavaDoc bl = jar.ejbJar.getEnterpriseBeans().enumerateEnterpriseBeansItem();
624         while (bl.hasMoreElements()) {
625             EnterpriseBeansItem item = (EnterpriseBeansItem) bl.nextElement();
626             i++;
627
628             if (item.getEntity() == null) {
629                 beans[i] = initSessionBean(item, ejbds);
630             } else {
631                 beans[i] = initEntityBean(item, ejbds);
632             }
633
634             // Check For Duplicate Deployment IDs
635
if (deploymentIds.contains(beans[i].ejbDeploymentId)) {
636                 ConfigUtils.logger.i18n.warning("conf.0100", beans[i].ejbDeploymentId, jar.jarURI, beans[i].ejbName);
637                 // No two deployments can have the same deployment ID
638
// the entire ejb jar is invalid and must be redeployed.
639
// This jar cannot be loaded into the system and must
640
// be skipped.
641
return null;
642             }
643
644             deploymentIds.add(beans[i].ejbDeploymentId);
645
646             beans[i].codebase = jar.jarURI;
647             infos.put(beans[i].ejbName, beans[i]);
648             items.put(beans[i].ejbName, item);
649
650         }
651
652         initJndiReferences(ejbds, infos, items);
653
654         if (jar.ejbJar.getAssemblyDescriptor() != null) {
655             initSecurityRoles(jar, ejbds, infos, items);
656             initMethodPermissions(jar, ejbds, infos, items);
657             initMethodTransactions(jar, ejbds, infos, items);
658
659             // Resolve security role links
660
for (int x = 0; x < beans.length; x++) {
661                 resolveRoleLinks(jar, beans[x], (EnterpriseBeansItem) items.get(beans[x].ejbName));
662             }
663         }
664
665         assignBeansToContainers(beans, ejbds);
666
667         if (!"tomcat-webapp".equals(SystemInstance.get().getProperty("openejb.loader"))){
668             try {
669                 //TODO:2: This is really temporary, jars should have their
670
// own classpaths. We have code for this, but it has a couple
671
// issues in the CMP container that prevent us from relying on it.
672
File JavaDoc base = SystemInstance.get().getBase().getDirectory();
673                 File JavaDoc jarFile = new File JavaDoc(jar.jarURI);
674                 
675                 SystemInstance.get().getClassPath().addJarToPath(jarFile.toURL());
676             } catch (Exception JavaDoc e) {
677                 e.printStackTrace();
678             }
679         }
680         return ejbJar;
681     }
682
683     private void initJndiReferences(Map JavaDoc ejbds, Map JavaDoc infos, Map JavaDoc items) throws OpenEJBException {
684
685         Iterator JavaDoc i = infos.values().iterator();
686         while (i.hasNext()) {
687             EnterpriseBeanInfo bean = (EnterpriseBeanInfo) i.next();
688             EnterpriseBeansItem item = (EnterpriseBeansItem) items.get(bean.ejbName);
689             Enumeration JavaDoc envEntries = null;
690             Enumeration JavaDoc ejbRefs = null;
691             Enumeration JavaDoc ejbLocalRefs = null;
692             Enumeration JavaDoc resourceRefs = null;
693
694             if (item.getEntity() != null) {
695                 envEntries = item.getEntity().enumerateEnvEntry();
696                 ejbRefs = item.getEntity().enumerateEjbRef();
697                 ejbLocalRefs = item.getEntity().enumerateEjbLocalRef();
698                 resourceRefs = item.getEntity().enumerateResourceRef();
699             } else {
700                 envEntries = item.getSession().enumerateEnvEntry();
701                 ejbRefs = item.getSession().enumerateEjbRef();
702                 ejbLocalRefs = item.getSession().enumerateEjbLocalRef();
703                 resourceRefs = item.getSession().enumerateResourceRef();
704             }
705
706             Vector JavaDoc envRef = new Vector JavaDoc();
707             Vector JavaDoc ejbRef = new Vector JavaDoc();
708             Vector JavaDoc ejbLocalRef = new Vector JavaDoc();
709             Vector JavaDoc resRef = new Vector JavaDoc();
710
711             /* Build Environment entries *****************/
712             while (envEntries.hasMoreElements()) {
713                 EnvEntry env = (EnvEntry) envEntries.nextElement();
714                 EnvEntryInfo info = new EnvEntryInfo();
715
716                 info.name = env.getEnvEntryName();
717                 info.type = env.getEnvEntryType();
718                 info.value = env.getEnvEntryValue();
719
720                 envRef.add(info);
721             }
722
723             /* Build Resource References *****************/
724             EjbDeployment dep = (EjbDeployment) ejbds.get(bean.ejbName);
725             Enumeration JavaDoc rl = dep.enumerateResourceLink();
726             Map JavaDoc resLinks = new HashMap JavaDoc();
727             while (rl.hasMoreElements()) {
728                 ResourceLink link = (ResourceLink) rl.nextElement();
729                 resLinks.put(link.getResRefName(), link);
730             }
731
732             /* Build EJB References **********************/
733             while (ejbRefs.hasMoreElements()) {
734                 EjbRef ejb = (EjbRef) ejbRefs.nextElement();
735                 EjbReferenceInfo info = new EjbReferenceInfo();
736
737                 info.homeType = ejb.getHome();
738                 info.referenceName = ejb.getEjbRefName();
739                 info.location = new EjbReferenceLocationInfo();
740
741                 //if the ejb-link is null on the ejb-jar, get it from the openejb-jar
742
String JavaDoc ejbLink;
743                 if (ejb.getEjbLink() == null) {
744                     ejbLink = ((ResourceLink) resLinks.get(ejb.getEjbRefName())).getResId();
745                 } else {
746                     ejbLink = ejb.getEjbLink();
747                 }
748
749                 EnterpriseBeanInfo otherBean = (EnterpriseBeanInfo) infos.get(ejbLink);
750                 if (otherBean == null) {
751                     String JavaDoc msg =
752                             messages.format("config.noBeanFound", ejb.getEjbRefName(), bean.ejbName);
753
754                     logger.fatal(msg);
755                     throw new OpenEJBException(msg);
756                 }
757                 info.location.ejbDeploymentId = otherBean.ejbDeploymentId;
758
759                 ejbRef.add(info);
760             }
761
762
763             /* Build EJB References **********************/
764             while (ejbLocalRefs.hasMoreElements()) {
765                 EjbLocalRef ejb = (EjbLocalRef) ejbLocalRefs.nextElement();
766                 EjbLocalReferenceInfo info = new EjbLocalReferenceInfo();
767
768                 info.homeType = ejb.getLocalHome();
769                 info.referenceName = ejb.getEjbRefName();
770                 info.location = new EjbReferenceLocationInfo();
771
772                 //the ejb-link must be local to the ejb-jar
773
String JavaDoc ejbLink;
774                 if (ejb.getEjbLink() == null) {
775                     ejbLink = null;
776                     //ejbLink = ((ResourceLink) resLinks.get(ejb.getEjbRefName())).getResId();
777
} else {
778                     ejbLink = ejb.getEjbLink();
779                 }
780
781                 EnterpriseBeanInfo otherBean = (EnterpriseBeanInfo) infos.get(ejbLink);
782                 if (otherBean == null) {
783                     String JavaDoc msg =
784                             messages.format("config.noBeanFound", ejb.getEjbRefName(), bean.ejbName);
785
786                     logger.fatal(msg);
787                     throw new OpenEJBException(msg);
788                 }
789                 info.location.ejbDeploymentId = otherBean.ejbDeploymentId;
790
791                 ejbLocalRef.add(info);
792             }
793
794             while (resourceRefs.hasMoreElements()) {
795                 ResourceRef res = (ResourceRef) resourceRefs.nextElement();
796                 ResourceReferenceInfo info = new ResourceReferenceInfo();
797
798                 info.referenceAuth = res.getResAuth();
799                 info.referenceName = res.getResRefName();
800                 info.referenceType = res.getResType();
801
802                 ResourceLink link = (ResourceLink) resLinks.get(res.getResRefName());
803                 info.resourceID = link.getResId();
804
805                 resRef.add(info);
806             }
807
808             /* Assign everything to the EnterpriseBeanInfo *****/
809             JndiEncInfo jndi = new JndiEncInfo();
810             jndi.envEntries = new EnvEntryInfo[envRef.size()];
811             jndi.ejbReferences = new EjbReferenceInfo[ejbRef.size()];
812             jndi.ejbLocalReferences = new EjbLocalReferenceInfo[ejbLocalRef.size()];
813             jndi.resourceRefs = new ResourceReferenceInfo[resRef.size()];
814
815             envRef.copyInto(jndi.envEntries);
816             ejbRef.copyInto(jndi.ejbReferences);
817             resRef.copyInto(jndi.resourceRefs);
818             ejbLocalRef.copyInto(jndi.ejbLocalReferences);
819
820             bean.jndiEnc = jndi;
821
822         }
823
824     }
825
826     private void initMethodTransactions(DeployedJar jar, Map JavaDoc ejbds, Map JavaDoc infos, Map JavaDoc items)
827             throws OpenEJBException {
828
829         ContainerTransaction[] cTx = jar.ejbJar.getAssemblyDescriptor().getContainerTransaction();
830
831         if (cTx == null || cTx.length < 1) return;
832
833         MethodTransactionInfo[] mTxs = new MethodTransactionInfo[cTx.length];
834
835         for (int i = 0; i < mTxs.length; i++) {
836             mTxs[i] = new MethodTransactionInfo();
837
838             mTxs[i].description = cTx[i].getDescription();
839             mTxs[i].transAttribute = cTx[i].getTransAttribute();
840             mTxs[i].methods = getMethodInfos(cTx[i].getMethod(), ejbds);
841         }
842
843         this.mthdTranInfos.addAll(Arrays.asList(mTxs));
844     }
845
846     private void initSecurityRoles(DeployedJar jar, Map JavaDoc ejbds, Map JavaDoc infos, Map JavaDoc items)
847             throws OpenEJBException {
848
849         SecurityRole[] sr = jar.ejbJar.getAssemblyDescriptor().getSecurityRole();
850
851         if (sr == null || sr.length < 1) return;
852
853         SecurityRoleInfo[] roles = new SecurityRoleInfo[sr.length];
854         for (int i = 0; i < roles.length; i++) {
855             roles[i] = new SecurityRoleInfo();
856
857             roles[i].description = sr[i].getDescription();
858             roles[i].roleName = sr[i].getRoleName();
859
860             // Check For Duplicate Container IDs
861
if (securityRoles.contains(sr[i].getRoleName())) {
862                 ConfigUtils.logger.i18n.warning("conf.0102", jar.jarURI, sr[i].getRoleName());
863             } else {
864                 securityRoles.add(sr[i].getRoleName());
865             }
866         }
867
868         this.sRoleInfos.addAll(Arrays.asList(roles));
869     }
870
871     private void initMethodPermissions(DeployedJar jar, Map JavaDoc ejbds, Map JavaDoc infos, Map JavaDoc items)
872             throws OpenEJBException {
873
874         MethodPermission[] mp = jar.ejbJar.getAssemblyDescriptor().getMethodPermission();
875         if (mp == null || mp.length < 1) return;
876
877         MethodPermissionInfo[] perms = new MethodPermissionInfo[mp.length];
878
879         for (int i = 0; i < perms.length; i++) {
880             perms[i] = new MethodPermissionInfo();
881
882             perms[i].description = mp[i].getDescription();
883             perms[i].roleNames = mp[i].getRoleName();
884             perms[i].methods = getMethodInfos(mp[i].getMethod(), ejbds);
885         }
886
887         this.mthdPermInfos.addAll(Arrays.asList(perms));
888     }
889
890     /**
891      * Verify that everything has been linked and
892      * that those links refer to actual declared roles.
893      *
894      * @param bean
895      * @throws OpenEJBException
896      */

897     private void resolveRoleLinks(DeployedJar jar,
898                                   EnterpriseBeanInfo bean,
899                                   EnterpriseBeansItem item)
900             throws OpenEJBException {
901         SecurityRoleRef[] refs = null;
902         if (item.getEntity() != null) {
903             refs = item.getEntity().getSecurityRoleRef();
904         } else {
905             refs = item.getSession().getSecurityRoleRef();
906         }
907
908         if (refs == null || refs.length < 1) return;
909
910         SecurityRoleReferenceInfo[] sr = new SecurityRoleReferenceInfo[refs.length];
911         bean.securityRoleReferences = sr;
912
913         for (int i = 0; i < sr.length; i++) {
914             sr[i] = new SecurityRoleReferenceInfo();
915
916             sr[i].description = refs[i].getDescription();
917             sr[i].roleLink = refs[i].getRoleLink();
918             sr[i].roleName = refs[i].getRoleName();
919
920             if (sr[i].roleLink == null) {
921                 ConfigUtils.logger.i18n.warning("conf.0009", sr[i].roleName, bean.ejbName, jar.jarURI);
922                 sr[i].roleLink = DEFAULT_SECURITY_ROLE;
923             }
924         }
925
926     }
927
928     private MethodInfo[] getMethodInfos(Method[] ms, Map JavaDoc ejbds) {
929         if (ms == null) return null;
930
931         MethodInfo[] mi = new MethodInfo[ms.length];
932         for (int i = 0; i < mi.length; i++) {
933
934             mi[i] = new MethodInfo();
935
936             EjbDeployment d = (EjbDeployment) ejbds.get(ms[i].getEjbName());
937
938             mi[i].description = ms[i].getDescription();
939             mi[i].ejbDeploymentId = d.getDeploymentId();
940             mi[i].methodIntf = ms[i].getMethodIntf();
941             mi[i].methodName = ms[i].getMethodName();
942
943             // get the method parameters
944
MethodParams mp = ms[i].getMethodParams();
945             if (mp != null) {
946                 mi[i].methodParams = mp.getMethodParam();
947             }
948         }
949
950         return mi;
951     }
952
953     private EnterpriseBeanInfo initSessionBean(EnterpriseBeansItem item, Map JavaDoc m)
954             throws OpenEJBException {
955         Session s = item.getSession();
956         EnterpriseBeanInfo bean = null;
957
958         if (s.getSessionType().equals("Stateful"))
959             bean = new StatefulBeanInfo();
960         else
961             bean = new StatelessBeanInfo();
962
963         EjbDeployment d = (EjbDeployment) m.get(s.getEjbName());
964         if (d == null) {
965             throw new OpenEJBException("No deployment information in openejb-jar.xml for bean "
966                     + s.getEjbName()
967                     + ". Please redeploy the jar");
968         }
969         bean.ejbDeploymentId = d.getDeploymentId();
970
971         bean.description = s.getDescription();
972         bean.largeIcon = s.getLargeIcon();
973         bean.smallIcon = s.getSmallIcon();
974         bean.displayName = s.getDisplayName();
975         bean.ejbClass = s.getEjbClass();
976         bean.ejbName = s.getEjbName();
977         bean.home = s.getHome();
978         bean.remote = s.getRemote();
979         bean.localHome = s.getLocalHome();
980         bean.local = s.getLocal();
981         bean.transactionType = s.getTransactionType();
982
983         return bean;
984     }
985
986     private EnterpriseBeanInfo initEntityBean(EnterpriseBeansItem item, Map JavaDoc m)
987             throws OpenEJBException {
988         Entity e = item.getEntity();
989         EntityBeanInfo bean = new EntityBeanInfo();
990
991         EjbDeployment d = (EjbDeployment) m.get(e.getEjbName());
992         if (d == null) {
993             throw new OpenEJBException("No deployment information in openejb-jar.xml for bean "
994                     + e.getEjbName()
995                     + ". Please redeploy the jar");
996         }
997         bean.ejbDeploymentId = d.getDeploymentId();
998
999         bean.description = e.getDescription();
1000        bean.largeIcon = e.getLargeIcon();
1001        bean.smallIcon = e.getSmallIcon();
1002        bean.displayName = e.getDisplayName();
1003        bean.ejbClass = e.getEjbClass();
1004        bean.ejbName = e.getEjbName();
1005        bean.home = e.getHome();
1006        bean.remote = e.getRemote();
1007        bean.localHome = e.getLocalHome();
1008        bean.local = e.getLocal();
1009        bean.transactionType = "Container";
1010
1011        bean.primKeyClass = e.getPrimKeyClass();
1012        bean.primKeyField = e.getPrimkeyField();
1013        bean.persistenceType = e.getPersistenceType();
1014        bean.reentrant = e.getReentrant() + "";
1015
1016        bean.cmpFieldNames = new String JavaDoc[e.getCmpFieldCount()];
1017
1018        for (int i = 0; i < bean.cmpFieldNames.length; i++) {
1019            bean.cmpFieldNames[i] = e.getCmpField(i).getFieldName();
1020        }
1021
1022        if (bean.persistenceType.equals("Container")) {
1023
1024            Query[] q = d.getQuery();
1025            QueryInfo[] qi = new QueryInfo[q.length];
1026
1027            for (int i = 0; i < q.length; i++) {
1028                QueryInfo query = new QueryInfo();
1029                query.description = q[i].getDescription();
1030                query.queryStatement = q[i].getObjectQl().trim();
1031
1032                MethodInfo method = new MethodInfo();
1033                QueryMethod qm = q[i].getQueryMethod();
1034                method.methodName = qm.getMethodName();
1035                method.methodParams = qm.getMethodParams().getMethodParam();
1036
1037                query.method = method;
1038                qi[i] = query;
1039            }
1040            bean.queries = qi;
1041        }
1042        return bean;
1043    }
1044
1045    private void assignBeansToContainers(EnterpriseBeanInfo[] beans, Map JavaDoc ejbds)
1046            throws OpenEJBException {
1047
1048        for (int i = 0; i < beans.length; i++) {
1049            // Get the bean deployment object
1050
EjbDeployment d = (EjbDeployment) ejbds.get(beans[i].ejbName);
1051
1052            // Get the container it was assigned to
1053
ContainerInfo cInfo = (ContainerInfo) containerTable.get(d.getContainerId());
1054            if (cInfo == null) {
1055                //TODO Create container if one is not provided
1056
String JavaDoc msg =
1057                        messages.format("config.noContainerFound", d.getContainerId(), d.getEjbName());
1058
1059                logger.fatal(msg);
1060                throw new OpenEJBException(msg);
1061            }
1062
1063            // Add the bean info object to the cotnainer's bean array
1064
EnterpriseBeanInfo[] oldList = cInfo.ejbeans;
1065            EnterpriseBeanInfo[] newList = new EnterpriseBeanInfo[oldList.length + 1];
1066            System.arraycopy(oldList, 0, newList, 1, oldList.length);
1067            newList[0] = beans[i];
1068            cInfo.ejbeans = newList;
1069        }
1070
1071        // Now create the bean arrays of the specific container
1072
// type.
1073
for (int i = 0; i < entityContainers.length; i++) {
1074            EnterpriseBeanInfo[] b = entityContainers[i].ejbeans;
1075            EntityBeanInfo[] eb = new EntityBeanInfo[b.length];
1076            System.arraycopy(b, 0, eb, 0, b.length);
1077        }
1078
1079    }
1080
1081    /**
1082     * Resolve file locations
1083     * Resolve classes
1084     * TODO: Not integral now, implement later.
1085     */

1086    private void resolveDependencies(Openejb openejb) {
1087    }
1088
1089    /**
1090     * Resolve file locations
1091     * Resolve classes
1092     * TODO: Not integral now, implement later.
1093     */

1094    private void resolveDependencies(EjbJar[] jars) {
1095    }
1096
1097    /**
1098     * Loads a list of jar names that we will attempt
1099     * to deploy.
1100     * If the Deployments element is a directory
1101     * then it will load all the jars from that directory.
1102     * <p/>
1103     * If a jar was listed twice in the config file for some
1104     * reason, it only occur once in the list returned
1105     */

1106    private String JavaDoc[] resolveJarLocations(Deployments[] deploy) {
1107
1108        FileUtils base = SystemInstance.get().getBase();
1109        FileUtils home = SystemInstance.get().getHome();
1110
1111        List JavaDoc jarList = new ArrayList JavaDoc(deploy.length);
1112
1113        String JavaDoc flag = this.props.getProperty("openejb.loadFromBaseAndHome","false").toLowerCase();
1114        boolean loadFromBoth = flag.equals("true") && !base.equals(home);
1115
1116        try {
1117            for (int i = 0; i < deploy.length; i++) {
1118
1119                Deployments d = deploy[i];
1120
1121                loadFrom(d, base, jarList);
1122                if (loadFromBoth) {
1123                    // If openejb.base and openejb.home are both specified
1124
// but are different, we would have already loaded from
1125
// openejb.base. Now load from openejb.home to pick up
1126
// any global beans.
1127
loadFrom(d, home, jarList);
1128                }
1129            }
1130        } catch (SecurityException JavaDoc se) {
1131            //Worthless security exception
1132
// log it and move on
1133
// TODO: Log this
1134
}
1135
1136        return (String JavaDoc[]) jarList.toArray(new String JavaDoc[]{});
1137
1138    }
1139
1140    private void loadFrom(Deployments d, FileUtils path, List JavaDoc jarList) {
1141        ///// Add Jar file /////
1142
if (d.getDir() == null && d.getJar() != null) {
1143            try {
1144                File JavaDoc jar = path.getFile(d.getJar(), false);
1145                if (!jarList.contains(jar.getAbsolutePath())) {
1146                    jarList.add(jar.getAbsolutePath());
1147                }
1148            } catch (Exception JavaDoc ignored) {
1149            }
1150            return;
1151        }
1152
1153        ///// A directory /////
1154
File JavaDoc dir = null;
1155        try {
1156            dir = path.getFile(d.getDir(), false);
1157        } catch (Exception JavaDoc ignored) {
1158        }
1159
1160        // Opps! Not a directory
1161
if (dir == null || !dir.isDirectory()) return;
1162
1163        // Check to see if it's an unpacked ejb-jar
1164
File JavaDoc ejbJarXml = new File JavaDoc(dir, "META-INF" + File.separator + "ejb-jar.xml");
1165        if (ejbJarXml.exists()) {
1166            if (!jarList.contains(dir.getAbsolutePath())) {
1167                jarList.add(dir.getAbsolutePath());
1168            }
1169            return;
1170        }
1171
1172        // Glob all the *.jar files and add them to the list
1173
String JavaDoc[] jarFiles = dir.list(new FilenameFilter JavaDoc() {
1174            public boolean accept(File JavaDoc dir, String JavaDoc name) {
1175                return name.endsWith(".jar");
1176            }
1177        });
1178
1179        if (jarFiles == null) {
1180            return;
1181        }
1182
1183        for (int x = 0; x < jarFiles.length; x++) {
1184            String JavaDoc f = jarFiles[x];
1185            File JavaDoc jar = new File JavaDoc(dir, f);
1186
1187            if (jarList.contains(jar.getAbsolutePath())) continue;
1188            jarList.add(jar.getAbsolutePath());
1189        }
1190    }
1191
1192    /**
1193     * Resolve file locations
1194     * Resolve classes
1195     * TODO: Not integral now, implement later.
1196     */

1197    private DeployedJar[] loadDeployments(Openejb openejb) throws OpenEJBException {
1198
1199        EjbValidator validator = new EjbValidator();
1200
1201        Vector JavaDoc jarsVect = new Vector JavaDoc();
1202
1203        String JavaDoc[] jarsToLoad = resolveJarLocations(openejb.getDeployments());
1204
1205        /*[1] Put all EjbJar & OpenejbJar objects in a vector ***************/
1206        for (int i = 0; i < jarsToLoad.length; i++) {
1207
1208            String JavaDoc jarLocation = jarsToLoad[i];
1209            try {
1210                EjbJarUtils ejbJarUtils = new EjbJarUtils(jarLocation);
1211                EjbJar ejbJar = ejbJarUtils.getEjbJar();
1212
1213                ClassLoader JavaDoc classLoader;
1214
1215                File JavaDoc jarFile = new File JavaDoc(jarLocation);
1216                if (jarFile.isDirectory()){
1217                    try {
1218                        URL JavaDoc[] urls = new URL JavaDoc[]{jarFile.toURL()};
1219                        classLoader = new URLClassLoader JavaDoc(urls, this.getClass().getClassLoader());
1220                    } catch (MalformedURLException JavaDoc e) {
1221                        throw new OpenEJBException(messages.format("cl0001", jarLocation, e.getMessage()));
1222                    }
1223                } else {
1224                    TempCodebase tempCodebase = new TempCodebase(jarLocation);
1225                    classLoader = tempCodebase.getClassLoader();
1226                }
1227
1228                /* If there is no openejb-jar.xml attempt to auto deploy it.
1229                 */

1230                OpenejbJar openejbJar = ejbJarUtils.getOpenejbJar();
1231                if (openejbJar == null) {
1232                    openejbJar = deployer.deploy(ejbJarUtils, jarLocation, classLoader);
1233                }
1234
1235                EjbSet set = validator.validateJar( ejbJarUtils, classLoader);
1236                if (set.hasErrors() || set.hasFailures()) {
1237                    ValidationError[] errors = set.getErrors();
1238                    for (int j = 0; j < errors.length; j++) {
1239                        ValidationError e = errors[j];
1240                        logger.error(e.getPrefix()+" ... "+e.getBean().getEjbName()+":\t"+e.getMessage(2));
1241                    }
1242                    ValidationFailure[] failures = set.getFailures();
1243                    for (int j = 0; j < failures.length; j++) {
1244                        ValidationFailure e = failures[j];
1245                        logger.info(e.getPrefix()+" ... "+e.getBean().getEjbName()+":\t"+e.getMessage(2));
1246                    }
1247                    //System.out.println("[] INVALID "+ jarLocation);
1248
throw new OpenEJBException("Jar failed validation. Use the validation tool for more details");
1249                }
1250
1251                /* Add it to the Vector ***************/
1252                logger.info("Loaded EJBs from "+jarLocation);
1253                jarsVect.add(new DeployedJar(jarLocation, ejbJar, openejbJar));
1254            } catch (OpenEJBException e) {
1255                ConfigUtils.logger.i18n.warning("conf.0004", jarLocation, e.getMessage());
1256            }
1257        }
1258
1259        /*[2] Get a DeployedJar array from the vector ***************/
1260        DeployedJar[] jars = new DeployedJar[jarsVect.size()];
1261        jarsVect.copyInto(jars);
1262        return jars;
1263    }
1264
1265    public Service initService(Service service, String JavaDoc defaultName) throws OpenEJBException {
1266        return initService(service, defaultName, null);
1267    }
1268
1269    /**
1270     * Service loading...
1271     * <p/>
1272     * 1. Try and load by provider id
1273     * 2. Try and load by id of the service
1274     * 3. Load the default provider
1275     *
1276     * @param service
1277     * @param defaultName
1278     * @return Service
1279     * @throws OpenEJBException
1280     */

1281    public Service initService(Service service, String JavaDoc defaultName, Class JavaDoc type)
1282            throws OpenEJBException {
1283
1284        if (service == null) {
1285            try {
1286                service = (Service) type.newInstance();
1287                service.setProvider(defaultName);
1288                service.setId(defaultName);
1289            } catch (Exception JavaDoc e) {
1290                throw new OpenEJBException("Cannot instantiate class " + type);
1291            }
1292        } else if (service.getProvider() == null) {
1293            // If the service.getId() points to a valid
1294
// ServiceProvider, then let's use that...
1295
try {
1296                ServiceUtils.getServiceProvider(service.getId());
1297                service.setProvider(service.getId());
1298            } catch (Exception JavaDoc e) {
1299                // Guess that didn't work, let's use the default...
1300
service.setProvider(defaultName);
1301            }
1302        }
1303
1304        return service;
1305    }
1306
1307    private void checkType(ServiceProvider provider, Service service, String JavaDoc type)
1308            throws OpenEJBException {
1309        if (!provider.getProviderType().equals(type)) {
1310            handleException("conf.4902", service, type);
1311        }
1312    }
1313
1314    String JavaDoc[] tabs = {"", " ", " ", " ", " ", " "};
1315
1316    private void printConf(OpenEjbConfiguration conf) {
1317        out(0, "CONFIGURATION");
1318
1319        out(1, conf.containerSystem.containers.length);
1320        for (int i = 0; i < conf.containerSystem.containers.length; i++) {
1321            out(1, "className ", conf.containerSystem.containers[i].className);
1322            out(1, "codebase ", conf.containerSystem.containers[i].codebase);
1323            out(1, "containerName", conf.containerSystem.containers[i].containerName);
1324            out(1, "containerType", conf.containerSystem.containers[i].containerType);
1325            out(1, "description ", conf.containerSystem.containers[i].description);
1326            out(1, "displayName ", conf.containerSystem.containers[i].displayName);
1327            out(1, "properties ");
1328            conf.containerSystem.containers[i].properties.list(System.out);
1329            out(1, "ejbeans ", conf.containerSystem.containers[i].ejbeans.length);
1330            for (int j = 0; j < conf.containerSystem.containers[i].ejbeans.length; j++) {
1331                EnterpriseBeanInfo bean = conf.containerSystem.containers[i].ejbeans[j];
1332                out(2, "codebase ", bean.codebase);
1333                out(2, "description ", bean.description);
1334                out(2, "displayName ", bean.displayName);
1335                out(2, "ejbClass ", bean.ejbClass);
1336                out(2, "ejbDeploymentId", bean.ejbDeploymentId);
1337                out(2, "ejbName ", bean.ejbName);
1338                out(2, "home ", bean.home);
1339                out(2, "largeIcon ", bean.largeIcon);
1340                out(2, "remote ", bean.remote);
1341                out(2, "smallIcon ", bean.smallIcon);
1342                out(2, "transactionType", bean.transactionType);
1343                out(2, "type ", bean.type);
1344                out(2, "jndiEnc ", bean.jndiEnc);
1345                out(2, "envEntries ", bean.jndiEnc.envEntries.length);
1346                for (int n = 0; n < bean.jndiEnc.envEntries.length; n++) {
1347                    out(3, "--[" + n + "]----------------------");
1348                    out(3, "name ", bean.jndiEnc.envEntries[n].name);
1349                    out(3, "type ", bean.jndiEnc.envEntries[n].type);
1350                    out(3, "value ", bean.jndiEnc.envEntries[n].value);
1351                }
1352                out(2, "ejbReferences ", bean.jndiEnc.ejbReferences.length);
1353                for (int n = 0; n < bean.jndiEnc.ejbReferences.length; n++) {
1354                    out(3, "--[" + n + "]----------------------");
1355                    out(3, "homeType ", bean.jndiEnc.ejbReferences[n].homeType);
1356                    out(3, "referenceName ", bean.jndiEnc.ejbReferences[n].referenceName);
1357                    out(3, "location ", bean.jndiEnc.ejbReferences[n].location);
1358                    out(3, "ejbDeploymentId ", bean.jndiEnc.ejbReferences[n].location.ejbDeploymentId);
1359                    out(3, "jndiContextId ", bean.jndiEnc.ejbReferences[n].location.jndiContextId);
1360                    out(3, "remote ", bean.jndiEnc.ejbReferences[n].location.remote);
1361                    out(3, "remoteRefName ", bean.jndiEnc.ejbReferences[n].location.remoteRefName);
1362                }
1363                out(2, "resourceRefs ", bean.jndiEnc.resourceRefs.length);
1364                for (int n = 0; n < bean.jndiEnc.resourceRefs.length; n++) {
1365                    out(3, "--[" + n + "]----------------------");
1366                    out(3, "referenceAuth ", bean.jndiEnc.resourceRefs[n].referenceAuth);
1367                    out(3, "referenceName ", bean.jndiEnc.resourceRefs[n].referenceName);
1368                    out(3, "referenceType ", bean.jndiEnc.resourceRefs[n].referenceType);
1369                    if (bean.jndiEnc.resourceRefs[n].location != null) {
1370                        out(3, "location ", bean.jndiEnc.resourceRefs[n].location);
1371                        out(3, "jndiContextId ", bean.jndiEnc.resourceRefs[n].location.jndiContextId);
1372                        out(3, "remote ", bean.jndiEnc.resourceRefs[n].location.remote);
1373                        out(3, "remoteRefName ", bean.jndiEnc.resourceRefs[n].location.remoteRefName);
1374                    }
1375                }
1376            }
1377        }
1378
1379        if (conf.containerSystem.securityRoles != null) {
1380            out(0, "--Security Roles------------");
1381            for (int i = 0; i < sys.containerSystem.securityRoles.length; i++) {
1382                out(1, "--[" + i + "]----------------------");
1383                out(1, " ", sys.containerSystem.securityRoles[i]);
1384                out(1, "description ", sys.containerSystem.securityRoles[i].description);
1385                out(1, "roleName ", sys.containerSystem.securityRoles[i].roleName);
1386            }
1387        }
1388
1389        if (conf.containerSystem.methodPermissions != null) {
1390            out(0, "--Method Permissions--------");
1391            for (int i = 0; i < sys.containerSystem.methodPermissions.length; i++) {
1392                out(1, "--[" + i + "]----------------------");
1393                out(1, " ", sys.containerSystem.methodPermissions[i]);
1394                out(1, "description ", sys.containerSystem.methodPermissions[i].description);
1395                out(1, "roleNames ", sys.containerSystem.methodPermissions[i].roleNames);
1396                if (sys.containerSystem.methodPermissions[i].roleNames != null) {
1397                    String JavaDoc[] roleNames = sys.containerSystem.methodPermissions[i].roleNames;
1398                    for (int r = 0; r < roleNames.length; r++) {
1399                        out(1, "roleName[" + r + "] ", roleNames[r]);
1400                    }
1401                }
1402                out(1, "methods ", conf.containerSystem.methodPermissions[i].methods);
1403                if (conf.containerSystem.methodPermissions[i].methods != null) {
1404                    MethodInfo[] mthds = conf.containerSystem.methodPermissions[i].methods;
1405                    for (int j = 0; j < mthds.length; j++) {
1406                        out(2, "description ", mthds[j].description);
1407                        out(2, "ejbDeploymentId", mthds[j].ejbDeploymentId);
1408                        out(2, "methodIntf ", mthds[j].methodIntf);
1409                        out(2, "methodName ", mthds[j].methodName);
1410                        out(2, "methodParams ", mthds[j].methodParams);
1411                        if (mthds[j].methodParams != null) {
1412                            for (int n = 0; n < mthds[j].methodParams.length; n++) {
1413                                out(3, "param[" + n + "]", mthds[j].methodParams[n]);
1414                            }
1415                        }
1416
1417                    }
1418                }
1419            }
1420        }
1421
1422        if (conf.containerSystem.methodTransactions != null) {
1423            out(0, "--Method Transactions-------");
1424            for (int i = 0; i < conf.containerSystem.methodTransactions.length; i++) {
1425
1426                out(1, "--[" + i + "]----------------------");
1427                out(1, " ", conf.containerSystem.methodTransactions[i]);
1428                out(1, "description ", conf.containerSystem.methodTransactions[i].description);
1429                out(1, "transAttribute ", conf.containerSystem.methodTransactions[i].transAttribute);
1430                out(1, "methods ", conf.containerSystem.methodTransactions[i].methods);
1431                if (conf.containerSystem.methodTransactions[i].methods != null) {
1432                    MethodInfo[] mthds = conf.containerSystem.methodTransactions[i].methods;
1433                    for (int j = 0; j < mthds.length; j++) {
1434                        out(2, "description ", mthds[j].description);
1435                        out(2, "ejbDeploymentId", mthds[j].ejbDeploymentId);
1436                        out(2, "methodIntf ", mthds[j].methodIntf);
1437                        out(2, "methodName ", mthds[j].methodName);
1438                        out(2, "methodParams ", mthds[j].methodParams);
1439                        if (mthds[j].methodParams != null) {
1440                            for (int n = 0; n < mthds[j].methodParams.length; n++) {
1441                                out(3, "param[" + n + "]", mthds[j].methodParams[n]);
1442                            }
1443                        }
1444
1445                    }
1446                }
1447            }
1448        }
1449    }
1450
1451    private void out(int t, String JavaDoc m) {
1452        System.out.println(tabs[t] + m);
1453    }
1454
1455    private void out(int t, String JavaDoc m, String JavaDoc n) {
1456        System.out.println(tabs[t] + m + " = " + n);
1457    }
1458
1459    private void out(int t, String JavaDoc m, boolean n) {
1460        System.out.println(tabs[t] + m + " = " + n);
1461    }
1462
1463    private void out(int t, String JavaDoc m, int n) {
1464        System.out.println(tabs[t] + m + " = " + n);
1465    }
1466
1467    private void out(int t, String JavaDoc m, Object JavaDoc n) {
1468        System.out.println(tabs[t] + m + " = " + n);
1469    }
1470
1471    private void out(int t, int m) {
1472        System.out.println(tabs[t] + m);
1473    }
1474
1475    /*------------------------------------------------------*/
1476    /* Methods for easy exception handling */
1477    /*------------------------------------------------------*/
1478    public static void handleException(String JavaDoc errorCode,
1479                                       Object JavaDoc arg0,
1480                                       Object JavaDoc arg1,
1481                                       Object JavaDoc arg2,
1482                                       Object JavaDoc arg3)
1483            throws OpenEJBException {
1484        throw new OpenEJBException(messages.format(errorCode, arg0, arg1, arg2, arg3));
1485    }
1486
1487    public static void handleException(String JavaDoc errorCode, Object JavaDoc arg0, Object JavaDoc arg1, Object JavaDoc arg2)
1488            throws OpenEJBException {
1489        throw new OpenEJBException(messages.format(errorCode, arg0, arg1, arg2));
1490    }
1491
1492    public static void handleException(String JavaDoc errorCode, Object JavaDoc arg0, Object JavaDoc arg1)
1493            throws OpenEJBException {
1494        throw new OpenEJBException(messages.format(errorCode, arg0, arg1));
1495    }
1496
1497    public static void handleException(String JavaDoc errorCode, Object JavaDoc arg0) throws OpenEJBException {
1498        throw new OpenEJBException(messages.format(errorCode, arg0));
1499    }
1500
1501    public static void handleException(String JavaDoc errorCode) throws OpenEJBException {
1502        throw new OpenEJBException(messages.message(errorCode));
1503    }
1504}
1505
1506class DeployedJar {
1507
1508    EjbJar ejbJar;
1509    OpenejbJar openejbJar;
1510    String JavaDoc jarURI;
1511
1512    public DeployedJar(String JavaDoc jar, EjbJar ejbJar, OpenejbJar openejbJar) {
1513        this.ejbJar = ejbJar;
1514        this.openejbJar = openejbJar;
1515        this.jarURI = jar;
1516    }
1517}
1518
Popular Tags