KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > proxy > ejb > IORFactory


1 /*
2 * JBoss, Home of Professional Open Source
3 * Copyright 2005, JBoss Inc., and individual contributors as indicated
4 * by the @authors tag. See the copyright.txt in the distribution for a
5 * full listing of individual contributors.
6 *
7 * This is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU Lesser General Public License as
9 * published by the Free Software Foundation; either version 2.1 of
10 * the License, or (at your option) any later version.
11 *
12 * This software is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with this software; if not, write to the Free
19 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21 */

22 package org.jboss.proxy.ejb;
23
24
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collection JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.Map JavaDoc;
30 import javax.ejb.EJBHome JavaDoc;
31 import javax.ejb.EJBMetaData JavaDoc;
32 import javax.ejb.EJBObject JavaDoc;
33 import javax.management.ObjectName JavaDoc;
34 import javax.naming.Context JavaDoc;
35 import javax.naming.InitialContext JavaDoc;
36 import javax.naming.NamingException JavaDoc;
37 import javax.naming.Reference JavaDoc;
38 import javax.naming.StringRefAddr JavaDoc;
39 import javax.rmi.CORBA.Stub JavaDoc;
40 import javax.rmi.PortableRemoteObject JavaDoc;
41
42 import org.jacorb.ssl.SSLPolicyValue;
43 import org.jacorb.ssl.SSLPolicyValueHelper;
44 import org.jacorb.ssl.SSL_POLICY_TYPE;
45 import org.jboss.ejb.Container;
46 import org.jboss.ejb.EJBProxyFactory;
47 import org.jboss.ejb.EJBProxyFactoryContainer;
48 import org.jboss.ejb.EntityContainer;
49 import org.jboss.ejb.StatefulSessionContainer;
50 import org.jboss.ejb.StatelessSessionContainer;
51 import org.jboss.iiop.CorbaNamingService;
52 import org.jboss.iiop.CorbaORBService;
53 import org.jboss.iiop.codebase.CodebasePolicy;
54 import org.jboss.iiop.csiv2.CSIv2Policy;
55 import org.jboss.iiop.rmi.AttributeAnalysis;
56 import org.jboss.iiop.rmi.InterfaceAnalysis;
57 import org.jboss.iiop.rmi.OperationAnalysis;
58 import org.jboss.iiop.rmi.ir.InterfaceRepository;
59 import org.jboss.iiop.rmi.marshal.strategy.SkeletonStrategy;
60 import org.jboss.invocation.Invocation;
61 import org.jboss.invocation.iiop.ReferenceFactory;
62 import org.jboss.invocation.iiop.ServantRegistries;
63 import org.jboss.invocation.iiop.ServantRegistry;
64 import org.jboss.invocation.iiop.ServantRegistryKind;
65 import org.jboss.invocation.iiop.ServantWithMBeanServer;
66 import org.jboss.logging.Logger;
67 import org.jboss.metadata.EntityMetaData;
68 import org.jboss.metadata.InvokerProxyBindingMetaData;
69 import org.jboss.metadata.IorSecurityConfigMetaData;
70 import org.jboss.metadata.MetaData;
71 import org.jboss.metadata.SessionMetaData;
72 import org.jboss.naming.Util;
73 import org.jboss.system.Registry;
74 import org.jboss.web.WebClassLoader;
75 import org.omg.CORBA.Any JavaDoc;
76 import org.omg.CORBA.InterfaceDef JavaDoc;
77 import org.omg.CORBA.InterfaceDefHelper;
78 import org.omg.CORBA.ORB JavaDoc;
79 import org.omg.CORBA.Policy JavaDoc;
80 import org.omg.CORBA.Repository JavaDoc;
81 import org.omg.CosNaming.NameComponent JavaDoc;
82 import org.omg.CosNaming.NamingContext JavaDoc;
83 import org.omg.CosNaming.NamingContextExt JavaDoc;
84 import org.omg.CosNaming.NamingContextExtHelper JavaDoc;
85 import org.omg.CosNaming.NamingContextHelper JavaDoc;
86 import org.omg.CosNaming.NamingContextPackage.CannotProceed JavaDoc;
87 import org.omg.CosNaming.NamingContextPackage.InvalidName JavaDoc;
88 import org.omg.CosNaming.NamingContextPackage.NotFound JavaDoc;
89 import org.omg.PortableServer.Current JavaDoc;
90 import org.omg.PortableServer.CurrentHelper JavaDoc;
91 import org.omg.PortableServer.POA JavaDoc;
92 import org.w3c.dom.Element JavaDoc;
93
94 /**
95  * This is an IIOP "proxy factory" for <code>EJBHome</code>s and
96  * <code>EJBObject</code>s. Rather than creating Java proxies (as the JRMP
97  * proxy factory does), this factory creates CORBA IORs.
98  *<p>
99  * An <code>IORFactory</code> is associated to a given enterprise bean. It
100  * registers with the IIOP invoker two CORBA servants: an
101  * <code>EjbHomeCorbaServant</code> for the bean's
102  * <code>EJBHome</code> and an <code>EjbObjectCorbaServant</code> for the
103  * bean's <code>EJBObject</code>s.
104  *
105  * @version $Revision: 37459 $
106  */

107 public class IORFactory
108    implements EJBProxyFactory
109 {
110
111    // Constants --------------------------------------------------------------
112

113    private static final Logger staticLogger =
114                            Logger.getLogger(IORFactory.class);
115
116    // Attributes -------------------------------------------------------------
117

118    /**
119     * A reference for the ORB.
120     */

121    private ORB JavaDoc orb;
122
123    /**
124     * This <code>IORFactory</code>'s container.
125     */

126    private Container container;
127
128    /**
129     * <code>JNDI</code> name of the enterprise bean in the container.
130     */

131    private String JavaDoc jndiName;
132
133    /**
134     * True if the <code>EJBHome</code> should be bound to a JNP/JNDI context
135     * in addition to being bound to a CORBA naming context.
136     */

137    private boolean useJNPContext;
138
139    /**
140     * The JNP/JNDI name the <code>EJBHome</code> should be bound to.
141     */

142    private String JavaDoc jnpName;
143
144    /**
145     * <code>EJBMetaData</code> the enterprise bean in the container.
146     */

147    private EJBMetaDataImplIIOP ejbMetaData;
148
149    /**
150     * Mapping from bean methods to <code>SkeletonStrategy</code> instances.
151     */

152    private Map JavaDoc beanMethodMap;
153
154    /**
155     * Mapping from home methods to <code>SkeletonStrategy</code> instances.
156     */

157    private Map JavaDoc homeMethodMap;
158
159    /**
160     * CORBA repository ids of the RMI-IDL interfaces implemented by the bean
161     * (<code>EJBObject</code> instance).
162     */

163    private String JavaDoc[] beanRepositoryIds;
164
165    /**
166     * CORBA repository ids of the RMI-IDL interfaces implemented by the bean's
167     * home (<code>EJBHome</code> instance).
168     */

169    private String JavaDoc[] homeRepositoryIds;
170
171    /**
172     * <code>ServantRegistry</code> for the container's <code>EJBHome</code>.
173     */

174    private ServantRegistry homeServantRegistry;
175
176    /**
177     * <code>ServantRegistry</code> for the container's <code>EJBObject</code>s.
178     */

179    private ServantRegistry beanServantRegistry;
180
181    /**
182     * <code>ReferenceFactory</code> for the container's <code>EJBHome</code>.
183     */

184    private ReferenceFactory homeReferenceFactory;
185
186    /**
187     * <code>ReferenceFactory</code> for <code>EJBObject</code>s.
188     */

189    private ReferenceFactory beanReferenceFactory;
190
191    /**
192     * Thread-local <code>Current</code> object from which we get the target oid
193     * in an incoming IIOP request.
194     */

195    private Current JavaDoc poaCurrent;
196
197    /**
198     * The container's <code>CodebasePolicy</code>.
199     */

200    private Policy codebasePolicy;
201
202    /**
203     * The container's <code>CSIv2Policy</code>.
204     */

205    private Policy csiv2Policy;
206    
207    /**
208     * The container's <code>SSLPolicy</code>.
209     */

210    private Policy sslPolicy;
211    
212    /**
213     * The container's <code>EJBHome</code>.
214     */

215    private EJBHome JavaDoc ejbHome;
216
217    /**
218     * Invoker metadata, which includes the invoker JMX name.
219     */

220    private InvokerProxyBindingMetaData invokerMetaData;
221
222    /**
223     * A reference to the invoker, used for servant registration.
224     */

225    private ServantRegistries servantRegistries;
226
227    /**
228     * The enterprise bean's interface repository implementation, or null
229     * if the enterprise bean does not have its own interface repository.
230     */

231    private InterfaceRepository iri;
232
233    /**
234     * POA for the enterprise bean's interface repository.
235     */

236    private POA JavaDoc irPoa;
237
238    /**
239     * This <code>IORFactory</code>'s logger. Initialized with a
240     * per-class logger. Once the enterprise bean's JNDI name is known, the
241     * per-class logger will be replaced by a per-instance logger whose name
242     * includes the JNDI name.
243     */

244    private Logger logger = staticLogger;
245
246    // Implementation of the interface ContainerPlugin -------------------------
247

248    public void setContainer(Container container)
249    {
250       this.container = container;
251       if (container != null) {
252          String JavaDoc loggerName = IORFactory.class.getName() + '.'
253                                    + container.getBeanMetaData().getJndiName();
254          logger = Logger.getLogger(loggerName);
255       }
256    }
257
258    public void create() throws Exception JavaDoc
259    {
260       // Get orb and irPoa references
261
try {
262          orb = (ORB JavaDoc)new InitialContext JavaDoc().lookup("java:/"
263                                                 + CorbaORBService.ORB_NAME);
264       }
265       catch (NamingException JavaDoc e) {
266          throw new Exception JavaDoc("Cannot lookup java:/"
267                              + CorbaORBService.ORB_NAME + ": " + e);
268       }
269       try {
270          irPoa = (POA JavaDoc)new InitialContext JavaDoc().lookup("java:/"
271                                                 + CorbaORBService.IR_POA_NAME);
272       }
273       catch (NamingException JavaDoc e) {
274          throw new Exception JavaDoc("Cannot lookup java:/"
275                              + CorbaORBService.IR_POA_NAME + ": " + e);
276       }
277
278       // Should create a CORBA interface repository?
279
Element JavaDoc proxyFactoryConfig = invokerMetaData.getProxyFactoryConfig();
280       boolean interfaceRepositorySupported =
281          MetaData.getOptionalChildBooleanContent(
282                          proxyFactoryConfig, "interface-repository-supported");
283
284       if (interfaceRepositorySupported) {
285          // Create a CORBA interface repository for the enterprise bean
286
iri = new InterfaceRepository(orb, irPoa, jndiName);
287          
288          // Add bean interface info to the interface repository
289
iri.mapClass(((EJBProxyFactoryContainer)container).getRemoteClass());
290          iri.mapClass(((EJBProxyFactoryContainer)container).getHomeClass());
291          iri.finishBuild();
292          
293          logger.info("CORBA interface repository for " + jndiName + ": "
294                      + orb.object_to_string(iri.getReference()));
295       }
296
297       // Create bean method mappings for container invoker
298
logger.debug("Bean methods:");
299
300       InterfaceAnalysis interfaceAnalysis =
301             InterfaceAnalysis.getInterfaceAnalysis(
302                   ((EJBProxyFactoryContainer)container).getRemoteClass());
303
304       beanMethodMap = new HashMap JavaDoc();
305
306       AttributeAnalysis[] attrs = interfaceAnalysis.getAttributes();
307       for (int i = 0; i < attrs.length; i++) {
308          OperationAnalysis op = attrs[i].getAccessorAnalysis();
309
310          logger.debug(" " + op.getJavaName()
311                       + "\n " + op.getIDLName());
312          beanMethodMap.put(op.getIDLName(),
313                            new SkeletonStrategy(op.getMethod()));
314          op = attrs[i].getMutatorAnalysis();
315          if (op != null) {
316             logger.debug(" " + op.getJavaName()
317                          + "\n " + op.getIDLName());
318             beanMethodMap.put(op.getIDLName(),
319                               new SkeletonStrategy(op.getMethod()));
320          }
321       }
322
323       OperationAnalysis[] ops = interfaceAnalysis.getOperations();
324       for (int i = 0; i < ops.length; i++) {
325          logger.debug(" " + ops[i].getJavaName()
326                       + "\n " + ops[i].getIDLName());
327          beanMethodMap.put(ops[i].getIDLName(),
328                            new SkeletonStrategy(ops[i].getMethod()));
329       }
330
331       // Initialize repository ids of remote interface
332
beanRepositoryIds = interfaceAnalysis.getAllTypeIds();
333
334       // Create home method mappings for container invoker
335
logger.debug("Home methods:");
336
337       interfaceAnalysis =
338             InterfaceAnalysis.getInterfaceAnalysis(
339                   ((EJBProxyFactoryContainer)container).getHomeClass());
340
341       homeMethodMap = new HashMap JavaDoc();
342
343       attrs = interfaceAnalysis.getAttributes();
344       for (int i = 0; i < attrs.length; i++) {
345          OperationAnalysis op = attrs[i].getAccessorAnalysis();
346
347          logger.debug(" " + op.getJavaName()
348                       + "\n " + op.getIDLName());
349          homeMethodMap.put(op.getIDLName(),
350                            new SkeletonStrategy(op.getMethod()));
351          op = attrs[i].getMutatorAnalysis();
352          if (op != null) {
353             logger.debug(" " + op.getJavaName()
354                          + "\n " + op.getIDLName());
355             homeMethodMap.put(op.getIDLName(),
356                               new SkeletonStrategy(op.getMethod()));
357          }
358       }
359
360       ops = interfaceAnalysis.getOperations();
361       for (int i = 0; i < ops.length; i++) {
362          logger.debug(" " + ops[i].getJavaName()
363                       + "\n " + ops[i].getIDLName());
364          homeMethodMap.put(ops[i].getIDLName(),
365                            new SkeletonStrategy(ops[i].getMethod()));
366       }
367
368       // Initialize repository ids of home interface
369
homeRepositoryIds = interfaceAnalysis.getAllTypeIds();
370
371       // Create codebasePolicy containing the container's codebase string
372
logger.debug("container classloader: " + container.getClassLoader()
373                    + "\ncontainer parent classloader: "
374                    + container.getClassLoader().getParent());
375       WebClassLoader wcl = (WebClassLoader)container.getWebClassLoader();
376       String JavaDoc codebaseString;
377       if (wcl != null && (codebaseString = wcl.getCodebaseString()) != null)
378       {
379          Any JavaDoc codebase = orb.create_any();
380          codebase.insert_string(codebaseString);
381          codebasePolicy = orb.create_policy(CodebasePolicy.TYPE, codebase);
382          logger.debug("codebasePolicy: " + codebasePolicy);
383       }
384       else
385       {
386          logger.debug("Not setting codebase policy, codebase is null");
387       }
388
389       // Create csiv2Policy for both home and remote containing
390
// IorSecurityConfigMetadata
391
Any JavaDoc secPolicy = orb.create_any();
392       IorSecurityConfigMetaData iorSecurityConfigMetaData =
393          container.getBeanMetaData().getIorSecurityConfigMetaData();
394       secPolicy.insert_Value(iorSecurityConfigMetaData);
395       csiv2Policy = orb.create_policy(CSIv2Policy.TYPE, secPolicy);
396
397       // Create SSLPolicy
398
// (SSL_REQUIRED ensures home and remote IORs
399
// will have port 0 in the primary address)
400
boolean sslRequired = false;
401       if (iorSecurityConfigMetaData != null) {
402          IorSecurityConfigMetaData.TransportConfig tc =
403             iorSecurityConfigMetaData.getTransportConfig();
404          sslRequired =
405             tc.getIntegrity() ==
406                IorSecurityConfigMetaData.TransportConfig.INTEGRITY_REQUIRED
407             || tc.getConfidentiality() ==
408                IorSecurityConfigMetaData.TransportConfig.CONFIDENTIALITY_REQUIRED
409             || tc.getEstablishTrustInClient() ==
410                IorSecurityConfigMetaData.TransportConfig.ESTABLISH_TRUST_IN_CLIENT_REQUIRED;
411       }
412       Any JavaDoc sslPolicyValue = orb.create_any();
413       SSLPolicyValueHelper.insert(
414             sslPolicyValue,
415             (sslRequired) ? SSLPolicyValue.SSL_REQUIRED
416                           : SSLPolicyValue.SSL_NOT_REQUIRED);
417       sslPolicy = orb.create_policy(SSL_POLICY_TYPE.value, sslPolicyValue);
418       logger.debug("container's SSL policy: " + sslPolicy);
419       
420       // Get the POACurrent object
421
poaCurrent = CurrentHelper.narrow(
422                   orb.resolve_initial_references("POACurrent"));
423    }
424
425    public void start() throws Exception JavaDoc
426    {
427       // Lookup the invoker in the object registry. This typically cannot
428
// be done until our start method as the invokers may need to be started
429
// themselves.
430
ObjectName JavaDoc oname = new ObjectName JavaDoc(invokerMetaData.getInvokerMBean());
431       servantRegistries = (ServantRegistries)Registry.lookup(oname);
432       if (servantRegistries == null)
433          throw new Exception JavaDoc("invoker is null: " + oname);
434
435       Policy[] policies = null;
436       if (codebasePolicy == null)
437          policies = new Policy[] { sslPolicy, csiv2Policy };
438       else
439          policies = new Policy[] { codebasePolicy, sslPolicy, csiv2Policy };
440
441
442       // Read POA usage model from proxy factory config.
443
ServantRegistryKind registryWithTransientPOA;
444       ServantRegistryKind registryWithPersistentPOA;
445       Element JavaDoc proxyFactoryConfig = invokerMetaData.getProxyFactoryConfig();
446       String JavaDoc poaUsageModel =
447          MetaData.getOptionalChildContent(proxyFactoryConfig, "poa");
448       if (poaUsageModel == null || poaUsageModel.equals("shared")) {
449          registryWithTransientPOA = ServantRegistryKind.SHARED_TRANSIENT_POA;
450          registryWithPersistentPOA = ServantRegistryKind.SHARED_PERSISTENT_POA;
451       }
452       else if (poaUsageModel.equals("per-servant")) {
453          registryWithTransientPOA =
454             ServantRegistryKind.TRANSIENT_POA_PER_SERVANT;
455          registryWithPersistentPOA =
456             ServantRegistryKind.PERSISTENT_POA_PER_SERVANT;
457       }
458       else {
459          throw new Exception JavaDoc("invalid poa element in proxy factory config: "
460                              + poaUsageModel);
461       }
462
463       // If there is an interface repository, then get
464
// the homeInterfaceDef from the IR
465
InterfaceDef JavaDoc homeInterfaceDef = null;
466       if (iri != null) {
467             Repository ir = iri.getReference();
468             homeInterfaceDef =
469                InterfaceDefHelper.narrow(ir.lookup_id(homeRepositoryIds[0]));
470       }
471
472       // Instantiate home servant, bind it to the servant registry, and
473
// create CORBA reference to the EJBHome.
474
homeServantRegistry =
475             servantRegistries.getServantRegistry(registryWithPersistentPOA);
476
477
478       String JavaDoc homeServantLoggerName =
479          EjbHomeCorbaServant.class.getName() + '.'+ jndiName;
480
481       ServantWithMBeanServer homeServant =
482          new EjbHomeCorbaServant(container.getJmxName(),
483                                  container.getClassLoader(),
484                                  homeMethodMap,
485                                  homeRepositoryIds,
486                                  homeInterfaceDef,
487                                  Logger.getLogger(homeServantLoggerName));
488
489       homeReferenceFactory = homeServantRegistry.bind(homeServantName(jndiName), homeServant, policies);
490
491       org.omg.CORBA.Object JavaDoc corbaRef =
492          homeReferenceFactory.createReference(homeRepositoryIds[0]);
493       ((EjbHomeCorbaServant)homeServant).setHomeHandle(
494                                              new HomeHandleImplIIOP(corbaRef));
495       ejbHome = (EJBHome JavaDoc)PortableRemoteObject.narrow(corbaRef, EJBHome JavaDoc.class);
496
497       // Initialize beanPOA and create metadata depending on the kind of bean
498
if (container.getBeanMetaData() instanceof EntityMetaData) {
499
500          // This is an entity bean (lifespan: persistent)
501
beanServantRegistry =
502             servantRegistries.getServantRegistry(registryWithPersistentPOA);
503
504          Class JavaDoc pkClass;
505          EntityMetaData metaData = (EntityMetaData)container.getBeanMetaData();
506          String JavaDoc pkClassName = metaData.getPrimaryKeyClass();
507          try {
508             if (pkClassName != null)
509                pkClass = container.getClassLoader().loadClass(pkClassName);
510             else
511                pkClass = container.getClassLoader().loadClass(
512                      metaData.getEjbClass()).getField(
513                            metaData.getPrimKeyField()).getClass();
514          }
515          catch (NoSuchFieldException JavaDoc e) {
516             logger.error("Unable to identify Bean's Primary Key class! "
517                          + "Did you specify a primary key class and/or field? "
518                          + "Does that field exist?");
519             throw new Exception JavaDoc("Primary Key Problem");
520          }
521          catch (NullPointerException JavaDoc e) {
522             logger.error("Unable to identify Bean's Primary Key class! "
523                          + "Did you specify a primary key class and/or field? "
524                          + "Does that field exist?");
525             throw new Exception JavaDoc("Primary Key Problem");
526          }
527
528          ejbMetaData = new EJBMetaDataImplIIOP(
529                ((EJBProxyFactoryContainer)container).getRemoteClass(),
530                ((EJBProxyFactoryContainer)container).getHomeClass(),
531                pkClass,
532                false, // Session
533
false, // Stateless
534
ejbHome);
535       }
536       else {
537
538          // This is a session bean (lifespan: transient)
539
beanServantRegistry =
540             servantRegistries.getServantRegistry(registryWithTransientPOA);
541
542          if (((SessionMetaData)container.getBeanMetaData()).isStateless()) {
543
544             // Stateless session bean
545
ejbMetaData = new EJBMetaDataImplIIOP(
546                   ((EJBProxyFactoryContainer)container).getRemoteClass(),
547                   ((EJBProxyFactoryContainer)container).getHomeClass(),
548                   null, // No PK
549
true, // Session
550
true, // Stateless
551
ejbHome);
552
553          }
554          else {
555
556             // Stateful session bean
557
ejbMetaData = new EJBMetaDataImplIIOP(
558                   ((EJBProxyFactoryContainer)container).getRemoteClass(),
559                   ((EJBProxyFactoryContainer)container).getHomeClass(),
560                   null, // No PK
561
true, // Session
562
false, // Stateless
563
ejbHome);
564          }
565       }
566
567       // If there is an interface repository, then get
568
// the beanInterfaceDef from the IR
569
InterfaceDef JavaDoc beanInterfaceDef = null;
570       if (iri != null) {
571             Repository ir = iri.getReference();
572             beanInterfaceDef =
573                InterfaceDefHelper.narrow(ir.lookup_id(beanRepositoryIds[0]));
574       }
575
576       String JavaDoc beanServantLoggerName =
577          EjbObjectCorbaServant.class.getName() + '.'+ jndiName;
578
579       ServantWithMBeanServer beanServant =
580          new EjbObjectCorbaServant(container.getJmxName(),
581                                    container.getClassLoader(),
582                                    poaCurrent,
583                                    beanMethodMap,
584                                    beanRepositoryIds,
585                                    beanInterfaceDef,
586                                    Logger.getLogger(beanServantLoggerName));
587
588       beanReferenceFactory = beanServantRegistry.bind(beanServantName(jndiName), beanServant, policies);
589
590       // Just for testing
591
logger.info("EJBHome reference for " + jndiName + ":\n"
592                   + orb.object_to_string((org.omg.CORBA.Object JavaDoc)ejbHome));
593
594       // Get JNP usage info from proxy factory config.
595
useJNPContext = MetaData.getOptionalChildBooleanContent(
596                            proxyFactoryConfig, "register-ejbs-in-jnp-context");
597
598       Context JavaDoc initialContext = new InitialContext JavaDoc();
599
600       if (useJNPContext) {
601          String JavaDoc jnpContext =
602             MetaData.getOptionalChildContent(proxyFactoryConfig,
603                                              "jnp-context");
604          if (jnpContext != null && !jnpContext.equals("")) {
605             jnpName = jnpContext + "/" + jndiName;
606          }
607          else {
608             jnpName = jndiName;
609          }
610
611          try {
612             // Bind the bean home in the JNDI initial context
613
Util.rebind(initialContext,
614                         jnpName,
615                         new Reference JavaDoc(
616                               "javax.ejb.EJBHome",
617                               new StringRefAddr JavaDoc("IOR",
618                                        orb.object_to_string(
619                                                (org.omg.CORBA.Object JavaDoc)ejbHome)),
620                               IIOPHomeFactory.class.getName(),
621                               null));
622             logger.info("Home IOR for " + container.getBeanMetaData().getEjbName()
623                         + " bound to " + jnpName + " in JNP naming service");
624          }
625          catch (NamingException JavaDoc e) {
626             throw new Exception JavaDoc("Cannot bind EJBHome in JNDI:\n" + e);
627          }
628       }
629
630       NamingContextExt JavaDoc corbaContext = null;
631       try {
632          // Obtain local (in-VM) CORBA naming context
633
corbaContext = NamingContextExtHelper.narrow((org.omg.CORBA.Object JavaDoc)
634                initialContext.lookup("java:/" +
635                                      CorbaNamingService.NAMING_NAME));
636       }
637       catch (NamingException JavaDoc e) {
638          throw new Exception JavaDoc("Cannot lookup java:/" +
639                              CorbaNamingService.NAMING_NAME + ":\n" + e);
640       }
641
642       try {
643          // Register bean home in local CORBA naming context
644
rebind(corbaContext, jndiName, (org.omg.CORBA.Object JavaDoc)ejbHome);
645          logger.info("Home IOR for " + container.getBeanMetaData().getEjbName()
646                      + " bound to " + jndiName + " in CORBA naming service");
647       }
648       catch (Exception JavaDoc e) {
649          logger.error("Cannot bind EJBHome in CORBA naming service:", e);
650          throw new Exception JavaDoc("Cannot bind EJBHome in CORBA naming service:\n"
651                              + e);
652       }
653
654    }
655
656    public void stop()
657    {
658       try {
659          // Get initial JNP/JNDI context
660
Context JavaDoc initialContext = new InitialContext JavaDoc();
661
662          if (useJNPContext) {
663             // Unbind bean home from the JNDI initial context
664
try {
665                initialContext.unbind(jnpName);
666             }
667             catch (NamingException JavaDoc namingException) {
668                logger.error("Cannot unbind EJBHome from JNDI", namingException);
669             }
670          }
671
672          // Get local (in-VM) CORBA naming context
673
NamingContextExt JavaDoc corbaContext =
674                NamingContextExtHelper.narrow((org.omg.CORBA.Object JavaDoc)
675                      initialContext.lookup("java:/"
676                                    + CorbaNamingService.NAMING_NAME));
677
678          // Unregister bean home from local CORBA naming context
679
try {
680             NameComponent JavaDoc[] name = corbaContext.to_name(jndiName);
681             corbaContext.unbind(name);
682          }
683          catch (InvalidName JavaDoc invalidName) {
684             logger.error("Cannot unregister EJBHome from CORBA naming service",
685                          invalidName);
686          }
687          catch (NotFound JavaDoc notFound) {
688             logger.error("Cannot unregister EJBHome from CORBA naming service",
689                          notFound);
690          }
691          catch (CannotProceed JavaDoc cannotProceed) {
692             logger.error("Cannot unregister EJBHome from CORBA naming service",
693                          cannotProceed);
694          }
695       }
696       catch (NamingException JavaDoc namingException) {
697          logger.error("Unexpected error in JNDI lookup", namingException);
698       }
699
700       // Deactivate the home servant and the bean servant
701
try {
702          homeServantRegistry.unbind(homeServantName(jndiName));
703       }
704       catch (Exception JavaDoc e) {
705          logger.error("Cannot deactivate home servant", e);
706       }
707       try {
708          beanServantRegistry.unbind(beanServantName(jndiName));
709       }
710       catch (Exception JavaDoc e) {
711          logger.error("Cannot deactivate bean servant", e);
712       }
713
714       if (iri != null) {
715          // Deactivate the interface repository
716
iri.shutdown();
717       }
718    }
719
720    public void destroy()
721    {
722    }
723
724    // Implementation of the interface EJBProxyFactory -------------------------
725

726    public void setInvokerMetaData(InvokerProxyBindingMetaData imd)
727    {
728       invokerMetaData = imd;
729    }
730
731    public void setInvokerBinding(String JavaDoc binding)
732    {
733       jndiName = binding;
734    }
735
736    public boolean isIdentical(Container container, Invocation mi)
737    {
738       EJBObject JavaDoc other = (EJBObject JavaDoc) mi.getArguments()[0];
739       if (other == null)
740          return false;
741       EJBObject JavaDoc me;
742       if (container instanceof StatelessSessionContainer)
743          me = (EJBObject JavaDoc) getStatelessSessionEJBObject();
744       else if (container instanceof StatefulSessionContainer)
745          me = (EJBObject JavaDoc) getStatefulSessionEJBObject(mi.getId());
746       else if (container instanceof EntityContainer)
747          me = (EJBObject JavaDoc) getEntityEJBObject(mi.getId());
748       else
749          return false;
750       
751       Stub JavaDoc meStub = (Stub JavaDoc) me;
752       Stub JavaDoc otherStub = (Stub JavaDoc) other;
753       return meStub._is_equivalent(otherStub);
754    }
755
756    public EJBMetaData JavaDoc getEJBMetaData()
757    {
758       return ejbMetaData;
759    }
760
761    public Object JavaDoc getEJBHome()
762    {
763       return ejbHome;
764    }
765
766    public Object JavaDoc getStatelessSessionEJBObject()
767    {
768       try {
769          return (EJBObject JavaDoc)PortableRemoteObject.narrow(
770                beanReferenceFactory.createReference(beanRepositoryIds[0]),
771                EJBObject JavaDoc.class);
772       }
773       catch (Exception JavaDoc e) {
774          throw new RuntimeException JavaDoc("Unable to create reference to EJBObject\n"
775                                     + e);
776       }
777    }
778
779    public Object JavaDoc getStatefulSessionEJBObject(Object JavaDoc id)
780    {
781       try {
782          return (EJBObject JavaDoc)PortableRemoteObject.narrow(
783                beanReferenceFactory.createReferenceWithId(
784                                                    id,
785                                                    beanRepositoryIds[0]),
786                EJBObject JavaDoc.class);
787       }
788       catch (Exception JavaDoc e) {
789          throw new RuntimeException JavaDoc("Unable to create reference to EJBObject\n"
790                                     + e);
791       }
792    }
793
794    public Object JavaDoc getEntityEJBObject(Object JavaDoc id)
795    {
796       if (logger.isTraceEnabled()) {
797          logger.trace("getEntityEJBObject(), id class is "
798                       + id.getClass().getName());
799       }
800       try {
801          Object JavaDoc ejbObject = (id == null ? null :
802             (EJBObject JavaDoc)PortableRemoteObject.narrow(
803                beanReferenceFactory.createReferenceWithId(id, beanRepositoryIds[0]),
804                EJBObject JavaDoc.class));
805          return ejbObject;
806       }
807       catch (Exception JavaDoc e) {
808          throw new RuntimeException JavaDoc("Unable to create reference to EJBObject\n"
809                                     + e);
810       }
811    }
812
813    public Collection JavaDoc getEntityCollection(Collection JavaDoc ids)
814    {
815       if (logger.isTraceEnabled()) {
816          logger.trace("entering getEntityCollection()");
817       }
818       Collection JavaDoc collection = new ArrayList JavaDoc(ids.size());
819       Iterator JavaDoc idEnum = ids.iterator();
820       while(idEnum.hasNext()) {
821          collection.add(getEntityEJBObject(idEnum.next()));
822       }
823       if (logger.isTraceEnabled()) {
824          logger.trace("leaving getEntityCollection()");
825       }
826       return collection;
827    }
828
829    // Static methods ----------------------------------------------------------
830

831    /**
832     * Returns the CORBA repository id of a given the RMI-IDL interface.
833     */

834    public static String JavaDoc rmiRepositoryId(Class JavaDoc clz)
835    {
836       return "RMI:" + clz.getName() + ":0000000000000000";
837    }
838
839    /**
840     * (Re)binds an object to a name in a given CORBA naming context, creating
841     * any non-existent intermediate contexts along the way.
842     */

843    public static void rebind(NamingContextExt JavaDoc ctx,
844                              String JavaDoc strName, org.omg.CORBA.Object JavaDoc obj)
845           throws Exception JavaDoc
846    {
847       NameComponent JavaDoc[] name = ctx.to_name(strName);
848       NamingContext JavaDoc intermediateCtx = ctx;
849
850       for (int i = 0; i < name.length - 1; i++ ) {
851          NameComponent JavaDoc[] relativeName = new NameComponent JavaDoc[] { name[i] };
852          try {
853             intermediateCtx = NamingContextHelper.narrow(
854                   intermediateCtx.resolve(relativeName));
855          }
856          catch (NotFound JavaDoc e) {
857             intermediateCtx = intermediateCtx.bind_new_context(relativeName);
858          }
859       }
860       intermediateCtx.rebind(new NameComponent JavaDoc[] { name[name.length - 1] },
861                              obj);
862    }
863
864    /**
865     * Returns the name of a home servant for an EJB with the given jndiName.
866     * The home servant will be bound to this name in a ServantRegistry.
867     */

868    private static String JavaDoc homeServantName(String JavaDoc jndiName)
869    {
870       return "EJBHome/" + jndiName;
871    }
872
873    /**
874     * Returns the name of a bean servant for an EJB with the given jndiName.
875     * The bean servant will be bound to this name in a ServantRegistry.
876     */

877    private static String JavaDoc beanServantName(String JavaDoc jndiName)
878    {
879       return "EJBObject/" + jndiName;
880    }
881
882 }
883
Popular Tags