KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > naming > NamingManagerImpl


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.naming;
25
26 import java.util.*;
27 import java.net.*;
28 import java.io.*;
29 import javax.jms.ConnectionFactory JavaDoc;
30 import javax.jms.QueueConnectionFactory JavaDoc;
31 import javax.jms.TopicConnectionFactory JavaDoc;
32 import java.rmi.RemoteException JavaDoc;
33 import javax.rmi.PortableRemoteObject JavaDoc;
34 import javax.naming.*;
35 import java.security.PrivilegedActionException JavaDoc;
36
37 import java.lang.reflect.Method JavaDoc;
38 import java.lang.reflect.Proxy JavaDoc;
39 import java.lang.reflect.InvocationHandler JavaDoc;
40
41 import javax.xml.namespace.QName JavaDoc;
42 import javax.xml.rpc.ServiceFactory JavaDoc;
43 import javax.xml.rpc.Service JavaDoc;
44 import javax.xml.rpc.handler.HandlerChain JavaDoc;
45 import javax.xml.rpc.handler.HandlerInfo JavaDoc;
46 import javax.xml.ws.BindingProvider;
47 import javax.xml.ws.soap.SOAPBinding;
48
49 import org.omg.CORBA.ORB JavaDoc;
50
51 import com.sun.enterprise.*;
52 import com.sun.enterprise.util.*;
53 import com.sun.enterprise.deployment.*;
54 import com.sun.enterprise.webservice.WsUtil;
55 import com.sun.enterprise.webservice.ServiceInvocationHandler;
56 import com.sun.enterprise.webservice.JAXWSServiceDelegate;
57 import com.sun.enterprise.distributedtx.UserTransactionImpl;
58 import com.sun.enterprise.naming.java.*;
59 import com.sun.enterprise.log.Log;
60
61 import com.sun.ejb.Container;
62 import com.sun.ejb.EJBUtils;
63
64 import java.util.logging.*;
65 import com.sun.logging.*;
66
67 /**
68  * This is the manager that handles all naming operations including
69  * publishObject as well as binding environment props, resource and
70  * ejb references in the namespace.
71  */

72 public final class NamingManagerImpl implements NamingManager
73 {
74
75     static Logger _logger=LogDomains.getLogger(LogDomains.JNDI_LOGGER);
76
77     public static final String JavaDoc IIOPOBJECT_FACTORY =
78         "com.sun.enterprise.naming.factory.IIOPObjectFactory";
79
80     public static final String JavaDoc JAVA_COMP_STRING = "java:comp/env/";
81
82     private static final String JavaDoc CONTEXT_SEPARATOR = "/";
83     private static final String JavaDoc ID_SEPARATOR = "_";
84
85     // J2EE Component type
86
private static final int UNKNOWN_COMPONENT = 0;
87     private static final int EJB_COMPONENT = 1;
88     private static final int WEB_COMPONENT = 2;
89     private static final int APP_CLIENT_COMPONENT = 3;
90
91     private static LocalStringManagerImpl localStrings =
92     new LocalStringManagerImpl(NamingManagerImpl.class);
93   
94     private InitialContext initialContext;
95     private InitialContext cosContext;
96
97     private InvocationManager im = null;
98     private Switch theSwitch = null;
99     private NameParser nameParser = new SerialNameParser();
100
101     // This is synchronized.
102
private Hashtable namespaces;
103
104     public static final String JavaDoc EIS_STRING = "/eis/";
105
106     private static final String JavaDoc CORBANAME = "corbaname:";
107  
108     public NamingManagerImpl() throws NamingException
109     {
110         this( new InitialContext() );
111     }
112
113     /**
114      * Create the naming manager. Creates a new initial context.
115      */

116     public NamingManagerImpl(InitialContext ic) throws NamingException
117     {
118         initialContext = ic;
119     namespaces = new Hashtable();
120
121         theSwitch = Switch.getSwitch();
122         im = theSwitch.getInvocationManager();
123     }
124
125     /**
126      * Get the initial naming context.
127      */

128     public Context getInitialContext()
129     {
130         return initialContext;
131     }
132
133
134     public NameParser getNameParser()
135     {
136     return nameParser;
137     }
138
139     /**
140      * Get cosContext which is the root of the COSNaming namespace.
141      * Setting java.naming.corba.orb is necessary to prevent the
142      * COSNaming context from creating its own ORB instance.
143      */

144
145     private InitialContext getCosContext() throws NamingException {
146     if (cosContext == null) {
147         Hashtable cosNamingEnv = new Hashtable ();
148         cosNamingEnv.put("java.naming.factory.initial",
149                  "com.sun.jndi.cosnaming.CNCtxFactory");
150         ORB JavaDoc orb = ORBManager.getORB();
151         cosNamingEnv.put("java.naming.corba.orb", orb);
152         cosContext = new InitialContext(cosNamingEnv);
153     }
154     return cosContext;
155
156     }
157     /**
158      * Publish a name in the naming service.
159      * @param the Name that the object is bound as.
160      * @param the Object that needs to be bound.
161      * @param rebind flag
162      * @exception NamingException if there is a naming exception.
163      */

164     public void publishObject(String JavaDoc name, Object JavaDoc obj, boolean rebind)
165         throws NamingException
166     {
167         Name JavaDoc nameobj = new CompositeName(name);
168         publishObject(nameobj, obj, rebind);
169     }
170
171     /**
172      * Publish a name in the naming service.
173      * @param the Name that the object is bound as.
174      * @param the Object that needs to be bound.
175      * @param rebind flag
176      * @exception NamingException if there is a naming exception.
177      */

178     public void publishObject(Name JavaDoc name, Object JavaDoc obj, boolean rebind)
179     throws NamingException
180     {
181     
182         if(_logger.isLoggable(Level.FINE)) {
183             _logger.log(Level.FINE,"Publish object " + obj + " using name " + name);
184     }
185     
186         Object JavaDoc serialObj = obj;
187     
188         if ( isCOSNamingObj( obj ) ) {
189         
190             // Create any COS naming sub-contexts in name
191
// that don't already exist.
192
createSubContexts( name, getCosContext() );
193         
194             if( rebind ) {
195                 getCosContext().rebind(name, obj);
196             }
197             else {
198                 getCosContext().bind(name, obj);
199             }
200
201             // Bind a reference to it in the SerialContext using
202
// the same name. This is needed to allow standalone clients
203
// to lookup the object using the same JNDI name.
204
// It is also used from bindObjects while populating ejb-refs in
205
// the java:comp namespace.
206
serialObj = new Reference("reference",
207                                       new StringRefAddr("url", name.toString()),
208                                       IIOPOBJECT_FACTORY, null);
209         } // End if -- CORBA object
210

211         if( rebind ) {
212             initialContext.rebind(name, serialObj);
213         }
214         else {
215             initialContext.bind(name, serialObj);
216         }
217     }
218
219     /**
220      * Remove an object from the naming service.
221      * @param the Name that the object is bound as.
222      * @exception Exception
223      */

224     public void unpublishObject(String JavaDoc name) throws NamingException
225     {
226
227         Object JavaDoc obj = initialContext.lookup(name);
228
229         if ( isCOSNamingObj( obj ) ) {
230             getCosContext().unbind(name);
231         }
232
233         initialContext.unbind(name);
234
235         // XXX Clean up sub-contexts???
236
}
237
238
239     /**
240      * Remove an object from the naming service.
241      * @param the Name that the object is bound as.
242      * @exception Exception
243      */

244     public void unpublishObject(Name JavaDoc name) throws NamingException
245     {
246         this.unpublishObject(name.toString());
247     }
248
249     /**
250      * Create any sub-contexts in name that don't already exist.
251      * @param the Name containing sub-contexts to create
252      * @param context in which sub-contexts should be created
253      * @exception Exception
254      */

255     private void createSubContexts(Name JavaDoc name, Context rootCtx) throws NamingException {
256
257         int numSubContexts = name.size() - 1;
258         Context currentCtx = rootCtx;
259         if(_logger.isLoggable(Level.FINE)) {
260             _logger.log(Level.FINE,"Creating sub contexts for " + name);
261         }
262
263         for(int subCtxIndex = 0; subCtxIndex < numSubContexts; subCtxIndex++) {
264             String JavaDoc subCtxName = name.get(subCtxIndex);
265             try {
266
267                 Object JavaDoc obj = currentCtx.lookup(subCtxName);
268
269                 if( obj == null ) {
270                     // @@@ thought it should throw NameNotFound when
271
// context doesn't exist...
272
if( _logger.isLoggable(Level.FINE)) {
273                         _logger.log(Level.FINE,"name == null");
274                     }
275                     // Doesn't exist so create it.
276
Context newCtx = currentCtx.createSubcontext(subCtxName);
277                     currentCtx = newCtx;
278                 }
279                 else if( obj instanceof Context ) {
280                     // OK -- no need to create it.
281
currentCtx = (Context) obj;
282                 }
283                 else {
284                     // Context name clashes with existing object.
285
throw new NameAlreadyBoundException(subCtxName);
286                 }
287             }
288             catch(NameNotFoundException e) {
289                 _logger.log(Level.FINE,"name not found", e);
290
291                 // Doesn't exist so create it.
292
Context newCtx = currentCtx.createSubcontext(subCtxName);
293                 currentCtx = newCtx;
294             }
295         } // End for -- each sub-context
296

297         return;
298     }
299
300     /**
301      * This method enumerates the env properties, ejb and resource
302      * references etc for a J2EE component and binds them in the component's
303      * java:comp namespace.
304      * This method is synchronized to avoid any possibility of concurrent
305      * deployment-time calls.
306      */

307     public synchronized String JavaDoc bindObjects(JndiNameEnvironment env)
308     throws NamingException
309     {
310         String JavaDoc componentId = getMangledIdName(env);
311       
312     // Note: HashMap is not synchronized. The namespace is populated
313
// at deployment time by a single thread, and then on there are
314
// no structural modifications (i.e. no keys added/removed).
315
// So the namespace doesnt need to be synchronized.
316
HashMap namespace = new HashMap();
317     namespaces.put(componentId, namespace);
318
319     // put entries for java:, java:comp and java:comp/env
320
namespace.put("java:", new javaURLContext("java:", null));
321     namespace.put("java:comp", new javaURLContext("java:comp", null));
322     namespace.put("java:comp/env", new javaURLContext("java:comp/env", null));
323
324     for (Iterator itr = env.getEnvironmentProperties().iterator();
325              itr.hasNext();) {
326             
327
328         EnvironmentProperty next = (EnvironmentProperty) itr.next();
329             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
330
331             // Skip any env-entries that have not been assigned a value.
332
if( !next.hasAValue() ) {
333                 continue;
334             }
335
336         Object JavaDoc valueObject = next.getValueObject();
337
338
339         if (_logger.isLoggable(Level.FINE)) {
340             _logger.log(Level.FINE,localStrings.getLocalString("naming.bind",
341                       "Binding name:{0}" , new Object JavaDoc[] {logicalJndiName}));
342             }
343
344             if (namespace.put(logicalJndiName, valueObject) != null) {
345             _logger.log(Level.WARNING,
346                     localStrings.getLocalString("naming.alreadyexists",
347                      "Reference name [{0}] already exists in {1}",
348                       new Object JavaDoc[] {next.getName(), getApplicationName(env)}));
349             }
350
351         bindIntermediateContexts(namespace, logicalJndiName);
352     }
353
354         //JmsDestinationReferenceDescriptor actually represents all Admin objects.
355
for (Iterator itr = env.getJmsDestinationReferenceDescriptors().iterator();
356              itr.hasNext();) {
357         JmsDestinationReferenceDescriptor next =
358                 (JmsDestinationReferenceDescriptor) itr.next();
359             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
360
361             String JavaDoc destinationName = next.getJndiName();
362             Object JavaDoc destinationObject = null;
363             if (next.isEJBContext()) {
364                 // Need to delay ejb context lookup until runtime
365
destinationObject =
366                     new J2EEEnvWrapper(next, J2EEEnvWrapper.EJB_CONTEXT);
367             } else {
368                 try {
369                     destinationObject = initialContext.lookup(destinationName);
370                 }
371                 catch(NamingException ne) {
372
373                     _logger.log(Level.SEVERE,
374                      "enterprise_naming.notfound_jmsdestination", destinationName);
375                     _logger.log(Level.SEVERE, ne.getClass().getName(), ne);
376                 // For embedded resource adapters, admin object can be
377
// created after deployment. Doesnt throw exception,
378
// because deployment/should succeed.
379
destinationObject = null;
380                 }
381
382                 if (destinationObject == null) {
383                 destinationObject = new J2EEEnvWrapper (destinationName,
384                             J2EEEnvWrapper.MUTABLE_RESOURCE_REF);
385             }
386             }
387
388             if( destinationObject instanceof javax.jms.Queue JavaDoc ) {
389                 if( !next.getRefType().equals("javax.jms.Queue") ) {
390                     throw new InvalidNameException(localStrings.getLocalString("naming.destinationRefTypeMismatch", "", new Object JavaDoc[] {next.getName(), next.getRefType()}));
391                 }
392             } else if( destinationObject instanceof javax.jms.Topic JavaDoc ) {
393                 if( !next.getRefType().equals("javax.jms.Topic") ) {
394                     throw new InvalidNameException(localStrings.getLocalString("naming.destinationRefTypeMismatch", "", new Object JavaDoc[] {next.getName(), next.getRefType()}));
395                 }
396             }
397             
398         if (_logger.isLoggable(Level.FINE)) {
399               _logger.log(Level.FINE,localStrings.getLocalString("naming.bind",
400                       "Binding name:{0}" , new Object JavaDoc[] {logicalJndiName}));
401             }
402
403             if ( namespace.put(logicalJndiName, destinationObject) != null) {
404             _logger.log(Level.WARNING,
405                      localStrings.getLocalString("naming.alreadyexists",
406                      "Reference name [{0}] already exists in {1}",
407                       new Object JavaDoc[] {next.getName(), getApplicationName(env)}));
408             }
409
410         bindIntermediateContexts(namespace, logicalJndiName);
411     }
412
413     for (Iterator itr = env.getEjbReferenceDescriptors().iterator();
414              itr.hasNext();) {
415         EjbReferenceDescriptor next = (EjbReferenceDescriptor) itr.next();
416         String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
417             
418         if (_logger.isLoggable(Level.FINE)) {
419               _logger.log(Level.FINE,localStrings.getLocalString
420                                ("naming.bind", "Binding name:{0}",
421                                 new Object JavaDoc[] {logicalJndiName}));
422             }
423
424         Object JavaDoc home = null;
425         if ( next.isLocal() ) { // an ejb-local-ref
426
// Create EJB_LOCAL_REF wrapper. Actual ejb local ref
427
// lookup resolution is done lazily.
428
home = new J2EEEnvWrapper(next,J2EEEnvWrapper.EJBLOCAL_REF);
429
430         }
431         else { // an ejb-ref
432
home = new J2EEEnvWrapper(next, J2EEEnvWrapper.EJB_REF);
433
434         // We dont do a COSNaming lookup here because COSNaming lookup
435
// internally calls "is_a" on the EJB which causes problems
436
// if the EJB requires authentication.
437
}
438
439             if (namespace.put(logicalJndiName, home) != null) {
440             _logger.log(Level.WARNING,
441                     localStrings.getLocalString("naming.alreadyexists",
442                      "Reference name [{0}] already exists in {1}",
443                       new Object JavaDoc[] {next.getName(), getApplicationName(env)}));
444             }
445
446         bindIntermediateContexts(namespace, logicalJndiName);
447     }
448         
449         for (Iterator itr = env.getMessageDestinationReferenceDescriptors().
450                  iterator(); itr.hasNext();) {
451             MessageDestinationReferenceDescriptor next =
452                 (MessageDestinationReferenceDescriptor) itr.next();
453             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
454
455             String JavaDoc destinationName = null;
456             // when this message ref is linked to a logical destination
457
if( next.isLinkedToMessageDestination() ) {
458                 destinationName =
459                     next.getMessageDestination().getJndiName();
460             // when this message ref is to a physical destination
461
} else {
462                 destinationName = next.getJndiName();
463             }
464             
465             // if this message reference has been resolved
466
if (destinationName != null) {
467         _logger.fine("NamingManagerImpl : destinationName = "+ destinationName );
468                 try {
469                     Object JavaDoc adminObject =
470                         initialContext.lookup(destinationName);
471             _logger.fine("NamingManagerImpl : binding " + logicalJndiName + " to " +adminObject);
472
473                     _logger.log(Level.INFO, localStrings.getLocalString(
474                         "naming.bind", "Binding name:`{0}`",
475                         new Object JavaDoc[] {logicalJndiName}));
476                     namespace.put(logicalJndiName, adminObject);
477                     bindIntermediateContexts(namespace, logicalJndiName);
478                 } catch(Exception JavaDoc e) {
479                     String JavaDoc msg = localStrings.getLocalString
480                         ("naming.invalidDestination",
481                          "Invalid Destination:`{0} for {1}`",
482                          new Object JavaDoc[] {destinationName, logicalJndiName});
483                     _logger.log(Level.SEVERE, "naming.invalidDestination",
484                 new Object JavaDoc[] {destinationName, logicalJndiName});
485                     NamingException ne = new NamingException();
486                     ne.initCause(e);
487                     throw ne;
488                 }
489             } else {
490                 String JavaDoc msg =
491                     localStrings.getLocalString("naming.unresolvedmsgdestref",
492                         "Message Destination Reference {0} has not been" +
493                         " resolved",
494                         new Object JavaDoc[] { logicalJndiName });
495                 _logger.log(Level.SEVERE, "naming.unresolvedmsgdestref",
496                 new Object JavaDoc[] {logicalJndiName});
497                 throw new NamingException(msg);
498            }
499         }
500         
501         for (Iterator itr = env.getResourceReferenceDescriptors().iterator();
502         itr.hasNext();) {
503             ResourceReferenceDescriptor next =
504             (ResourceReferenceDescriptor) itr.next();
505             
506             next.checkType();
507             
508             String JavaDoc logicalResRef = next.getName(); // "MyAccountBean"
509
String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
510             
511             if (_logger.isLoggable(Level.FINE)) {
512                 _logger.log(Level.FINE,localStrings.
513                 getLocalString("naming.bind", "Binding name:{0}",
514                 new Object JavaDoc[] {logicalJndiName}));
515             }
516             
517             String JavaDoc resJndi = next.getJndiName();
518
519             if(resJndi == null || resJndi.equals("")) {
520                 throw new InvalidNameException
521                     ("Real JNDI name cannot be " +
522                     "empty for " + logicalResRef);
523             }
524             
525             Object JavaDoc obj = null;
526             
527             if (next.isMailResource()) {
528                 obj = new J2EEEnvWrapper(resJndi, J2EEEnvWrapper.MAIL_REF);
529             }
530             else if (next.isURLResource()) {
531                 String JavaDoc url = next.getJndiName();
532                 try {
533                     obj = new java.net.URL JavaDoc(url);
534                 }
535                 catch(MalformedURLException e) {
536                     throw new InvalidNameException
537                     (localStrings.getLocalString("naming.malformedURL",
538                     "Malformed URL:'{0}'",
539                     new Object JavaDoc[] {url}));
540                 }
541                 obj = new J2EEEnvWrapper(obj, J2EEEnvWrapper.MUTABLE);
542             }
543             
544             //IMPORTANT!!! this needs to be before the test for JDBC as
545
//a connector could have a type of javax.sql.DataSource
546
//else if (next.isResourceConnectionFactory()) {
547
else if (isConnector(logicalJndiName)) {
548                 obj = new J2EEEnvWrapper(resJndi,
549                 J2EEEnvWrapper.RESOURCE_ADAPTER_REF);
550             }
551             
552             // adding check for jdbc resource
553
// IMPORTANT!!! this needs to be after the test for connectors as
554
// a connector could have a type of javax.sql.DataSource
555
else if (next.isJDBCResource()) {
556
557                 try {
558                     Object JavaDoc res = initialContext.lookup(resJndi);
559                     obj = new J2EEEnvWrapper(res, J2EEEnvWrapper.JDBC_REF);
560                 } catch( NamingException ne ) {
561                     String JavaDoc msg = localStrings.getLocalString
562                     ("naming.unresolved.warning", "",
563                     new Object JavaDoc[] {logicalJndiName, resJndi});
564                     _logger.log(Level.FINE,msg);
565                 }
566                 if ( obj == null ) { // perhaps the resource is not yet deployed
567
obj = new J2EEEnvWrapper(resJndi,
568                     J2EEEnvWrapper.MUTABLE_RESOURCE_REF);
569                 }
570             }
571
572         else if (next.isORB()) {
573         _logger.fine(" we have an ORB resource " + next);
574         
575         // Need to delay ejb context lookup until runtime
576
obj = new J2EEEnvWrapper(next, J2EEEnvWrapper.ORB_RESOURCE);
577         }
578
579             else if(next.isWebServiceContext()) {
580                 Object JavaDoc wsc = new com.sun.enterprise.webservice.WebServiceContextImpl();
581                 obj = new J2EEEnvWrapper(wsc, J2EEEnvWrapper.WEBSERVICE_CONTEXT);
582             }
583
584             else {
585                 try {
586                     // Find the actual object to which this reference is mapped
587
Object JavaDoc res = initialContext.lookup(resJndi);
588                     obj = new J2EEEnvWrapper(res, J2EEEnvWrapper.MUTABLE);
589                 }
590                 catch( NamingException ne ) {
591                     String JavaDoc msg = localStrings.getLocalString
592                     ("naming.unresolved.warning", "",
593                     new Object JavaDoc[] {logicalJndiName, resJndi});
594                     _logger.log(Level.FINE,msg);
595                     // TN - allow unresolved reference at deployment time
596
}
597                 if ( obj == null ) { // perhaps the resource is not yet deployed
598
obj = new J2EEEnvWrapper(resJndi,
599                     J2EEEnvWrapper.MUTABLE_RESOURCE_REF);
600                 }
601             }
602             
603             // Add the resource to the component's local java:comp namespace
604
if ( namespace.put(logicalJndiName, obj) != null) {
605                 _logger.log(Level.WARNING,
606                 localStrings.getLocalString("naming.alreadyexists",
607                 "Reference name [{0}] already exists in {1}",
608                 new Object JavaDoc[] {next.getName(), getApplicationName(env)}));
609             }
610
611             bindIntermediateContexts(namespace, logicalJndiName);
612         }
613         
614         for (Iterator itr = env.getServiceReferenceDescriptors().iterator();
615              itr.hasNext();) {
616         ServiceReferenceDescriptor next =
617                 (ServiceReferenceDescriptor) itr.next();
618
619             if(next.getMappedName() != null) {
620                 next.setName(next.getMappedName());
621             }
622             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
623
624             // Delay creation of service ref until access time
625
// to avoid classloading difficulties. (E.g. Setting
626
// up service-ref for web component requires classes
627
// that could be in .war or in .war's library jar.
628
// Better to let context classloader handle it later...)
629
Object JavaDoc serviceRefObject =
630                 new J2EEEnvWrapper(next, J2EEEnvWrapper.SERVICE_REF);
631                                                          
632         _logger.log(Level.INFO, "naming.bind",
633         new Object JavaDoc[] {logicalJndiName});
634         namespace.put(logicalJndiName, serviceRefObject);
635         bindIntermediateContexts(namespace, logicalJndiName);
636     }
637
638         for (EntityManagerFactoryReferenceDescriptor next :
639                  env.getEntityManagerFactoryReferenceDescriptors()) {
640
641             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
642
643             // Delay creation of actual object until lookup time.
644
Object JavaDoc factoryRefObject =
645                 new J2EEEnvWrapper(next,
646                                    J2EEEnvWrapper.ENTITY_MANAGER_FACTORY_REF);
647                                                          
648         _logger.log(Level.INFO, "naming.bind",
649         new Object JavaDoc[] {logicalJndiName});
650         namespace.put(logicalJndiName, factoryRefObject);
651         bindIntermediateContexts(namespace, logicalJndiName);
652     }
653
654         for (EntityManagerReferenceDescriptor next :
655                  env.getEntityManagerReferenceDescriptors()) {
656
657             String JavaDoc logicalJndiName = descriptorToLogicalJndiName(next);
658
659             // Delay creation of actual object until lookup time.
660
Object JavaDoc entityManagerRefObject =
661                 new J2EEEnvWrapper(next, J2EEEnvWrapper.ENTITY_MANAGER_REF);
662                                                          
663         _logger.log(Level.INFO, "naming.bind",
664         new Object JavaDoc[] {logicalJndiName});
665         namespace.put(logicalJndiName, entityManagerRefObject);
666         bindIntermediateContexts(namespace, logicalJndiName);
667     }
668
669     return componentId;
670     }
671
672     private void bindIntermediateContexts(HashMap namespace, String JavaDoc name)
673     throws NamingException
674     {
675     // for each component of name, put an entry into namespace
676
name = name.substring("java:comp/".length());
677     StringTokenizer toks = new StringTokenizer(name, "/", false);
678     String JavaDoc partialName="java:comp";
679     while ( toks.hasMoreTokens() ) {
680         String JavaDoc tok = toks.nextToken();
681         partialName = partialName + "/" + tok;
682         if ( namespace.get(partialName) == null ) {
683         
684         namespace.put(partialName, new javaURLContext(partialName, null));
685         }
686         }
687     }
688
689
690     /**
691      * This method enumerates the env properties, ejb and resource
692      * references and unbinds them from the java:comp namespace.
693      */

694     public void unbindObjects(JndiNameEnvironment env) throws NamingException
695     {
696         String JavaDoc componentId = getMangledIdName(env);
697     namespaces.remove(componentId); // remove local namespace cache
698
}
699
700     
701     /**
702      * Recreate a context for java:comp/env or one of its sub-contexts given
703      * the context name.
704      */

705     public Context restoreJavaCompEnvContext(String JavaDoc contextName)
706         throws NamingException
707     {
708         if( !contextName.startsWith("java:" ) ) {
709             throw new NamingException("Invalid context name [" + contextName
710                + "]. Name must start with java:");
711         }
712
713         return new javaURLContext(contextName, null);
714     }
715
716     public Object JavaDoc lookup(String JavaDoc name) throws NamingException
717     {
718         return lookup(name, null);
719     }
720
721     /**
722      * This method is called from SerialContext class.
723      * The serialContext instance that was created by the appclient's
724      * Main class is passed so that stickiness is preserved.
725      * Called from javaURLContext.lookup, for java:comp names.
726     */

727     public Object JavaDoc lookup(String JavaDoc name, SerialContext serialContext)
728     throws NamingException {
729     _logger.fine("serialcontext in NamingManagerImpl.." + serialContext);
730     Context ic = null;
731     
732     if (serialContext != null) {
733         ic = serialContext;
734     } else {
735         ic = initialContext;
736     }
737     
738         //initialContext is used as ic in case of PE while
739
//serialContext is used as ic in case of EE/SE
740
if (_logger.isLoggable(Level.FINE))
741         _logger.log(Level.FINE,"NamingManagerImpl : looking up name : " + name);
742     
743     // Get the component id and namespace to lookup
744
String JavaDoc componentId = getComponentId();
745     
746     HashMap namespace = (HashMap)namespaces.get(componentId);
747     
748     Object JavaDoc obj = namespace.get(name);
749     
750     if ( obj == null )
751         throw new NameNotFoundException("No object bound to name " + name);
752     
753     if ( obj instanceof J2EEEnvWrapper ) {
754         J2EEEnvWrapper wr = (J2EEEnvWrapper)obj;
755         switch ( wr.type ) {
756         case J2EEEnvWrapper.MUTABLE:
757         // XXX is this copy necessary ?
758

759         obj= NamingUtils.makeCopyOfObject(wr.object);
760         break;
761         
762         case J2EEEnvWrapper.JDBC_REF:
763         obj = wr.object;
764         break;
765         
766         case J2EEEnvWrapper.MAIL_REF:
767         
768         // MailConfiguration config = (MailConfiguration)wr.object;
769
String JavaDoc resJndi = (String JavaDoc)wr.object;
770         MailConfiguration config =
771             (MailConfiguration)ic.lookup(resJndi);
772         
773         // Note: javax.mail.Session is not serializable,
774
// but we need to get a new instance on every lookup.
775
javax.mail.Session JavaDoc s = javax.mail.Session.getInstance(
776                                       config.getMailProperties(), null);
777         s.setDebugOut(new PrintStream(new MailLogOutputStream()));
778         s.setDebug(true);
779         obj = s;
780         break;
781         
782         case J2EEEnvWrapper.ORB_RESOURCE:
783         
784         ResourceReferenceDescriptor resRef =
785             (ResourceReferenceDescriptor) wr.object;
786         if (resRef.getSharingScope().equals(
787                ResourceReferenceDescriptor.RESOURCE_SHAREABLE)) {
788             //jndi name is java:comp/ORB
789
_logger.fine("ORB resource is shareable" + resRef.getJndiName());
790             obj = ic.lookup(resRef.getJndiName());
791         } else {
792             //init a new ORB with empty args and an empty Properties obj
793
obj = ORB.init(new String JavaDoc[]{}, new Properties());
794             _logger.fine("ORB resource is unshareable" + obj);
795         }
796         break;
797         
798         case J2EEEnvWrapper.EJB_REF:
799         // Lookup the target bean's EJBHome ref using JNDI name.
800
// If the string is a "corbaname:...." URL
801
// the lookup happens thru the corbanameURL context,
802
// else it happens thru the COSNaming context.
803

804         // if ic is equal to initialContext then we are in
805
//PE environment
806
// else we should use sticky serialContext's private
807
//field cosContext which is an IC pointing to that
808
//specific orb's CosNaming Service.
809

810         /* MEJB lookup involved one more level of indirection
811          * hence, the following check.
812          * if name starts with corbaname: then use the
813          * initialcontext pointing to CosNaming Service
814          * (sticky or local)
815          * else use sticky SerialContext or InitialContext
816          * that is set in NamingManagerImpl()
817          */

818         EjbReferenceDescriptor remoteEjbRef =
819             (EjbReferenceDescriptor) wr.object;
820         
821         // Get actual jndi-name from ejb module.
822
String JavaDoc remoteJndiName =
823             EJBUtils.getRemoteEjbJndiName(remoteEjbRef);
824         
825         if( _logger.isLoggable(Level.FINE) ) {
826             _logger.fine("EJB_REF..." + remoteEjbRef);
827         }
828         
829         if (remoteJndiName.startsWith(CORBANAME)) {
830             ORB JavaDoc orb = ORBManager.getORB();
831             obj = (Object JavaDoc) orb.string_to_object(remoteJndiName);
832         } else {
833             obj = ic.lookup(remoteJndiName);
834         }
835         
836         obj = EJBUtils.resolveEjbRefObject(remoteEjbRef, obj);
837         
838         //if serialContext is null, no loadbalancing is
839
//happening. So cache the ref obj. else dont,
840
//inorder to do load balancing
841
if (serialContext == null) {
842             if( EJBUtils.isEjbRefCacheable(remoteEjbRef) ) {
843             namespace.put(name, obj);
844             }
845         }
846         
847         break;
848         
849         case J2EEEnvWrapper.EJBLOCAL_REF:
850         
851         EjbReferenceDescriptor localEjbRef =
852             (EjbReferenceDescriptor) wr.object;
853         
854         // @@@ revisit api
855
obj = EJBUtils.resolveEjbRefObject(localEjbRef, null);
856         
857         // No need to check load-balancing when determining whether
858
// to cache ejb-local-ref object b/c ejb local-refs are
859
// only available to components running within the server.
860
// However, still need to check with ejb module to determine
861
// whether the ref itself is cacheable.
862
if( EJBUtils.isEjbRefCacheable(localEjbRef) ) {
863             namespace.put(name, obj);
864         }
865         
866         break;
867         
868         case J2EEEnvWrapper.EJB_CONTEXT:
869         
870         JmsDestinationReferenceDescriptor jmsRef =
871             (JmsDestinationReferenceDescriptor) wr.object;
872         
873         // Get current ejb context. This should never be cached
874
// within the namespace.
875
obj = Switch.getSwitch().getContainerFactory().
876                     getEJBContextObject(jmsRef.getRefType());
877             
878         
879         break;
880         
881         case J2EEEnvWrapper.MUTABLE_RESOURCE_REF:
882         
883         // lookup resource using JNDI name
884

885         obj = ic.lookup((String JavaDoc)wr.object);
886                 
887         // replace wr with a MUTABLE wrapper for future lookups.
888
// Note: this is not a structural modification,
889
// so no synchronization needed.
890
wr = new J2EEEnvWrapper(obj, J2EEEnvWrapper.MUTABLE);
891         
892         //if serialContext is null, no loadbalancing is
893
//happening. So cache the ref obj. else dont,
894
//in order to do load balancing
895
if (serialContext == null) {
896             namespace.put(name, wr);
897         }
898         break;
899         
900         case J2EEEnvWrapper.RESOURCE_ADAPTER:
901         
902         obj=wr.object;
903         
904         break;
905         
906         case J2EEEnvWrapper.RESOURCE_ADAPTER_REF:
907         
908         // lookup resource using JNDI name
909

910         obj = ic.lookup((String JavaDoc)wr.object);
911         
912         break;
913         
914         case J2EEEnvWrapper.SERVICE_REF :
915         ServiceReferenceDescriptor desc =
916             (ServiceReferenceDescriptor) wr.object;
917         obj = getClientServiceObject(desc);
918         // Replace wrapper with actual service ref object
919
namespace.put(name, obj);
920         break;
921         
922         case J2EEEnvWrapper.ENTITY_MANAGER_FACTORY_REF :
923         EntityManagerFactoryReferenceDescriptor emfRefDesc =
924             (EntityManagerFactoryReferenceDescriptor) wr.object;
925         obj = new EntityManagerFactoryWrapper(emfRefDesc);
926         
927         // Do not cache resulting object so that each lookup
928
// will create a new wrapper object.
929

930         break;
931         
932         case J2EEEnvWrapper.ENTITY_MANAGER_REF :
933         EntityManagerReferenceDescriptor emRefDesc =
934             (EntityManagerReferenceDescriptor) wr.object;
935         obj = new EntityManagerWrapper(emRefDesc);
936         
937         // Do not cache resulting object so that each lookup
938
// will create a new wrapper object.
939

940         break;
941
942             case J2EEEnvWrapper.WEBSERVICE_CONTEXT :
943                 // lookup resource using JNDI name; if not present
944
obj = wr.object;
945                 break;
946         }
947     }
948     if (obj instanceof com.sun.enterprise.naming.java.javaURLContext) {
949         if (serialContext != null) {
950             //in EE mode
951
return ((com.sun.enterprise.naming.java.javaURLContext)obj).addStickyContext(serialContext);
952         }
953     }
954     return obj;
955     }
956     
957     private void resolvePortComponentLinks(ServiceReferenceDescriptor desc)
958         throws Exception JavaDoc {
959             
960         // Resolve port component links to target endpoint address.
961
// We can't assume web service client is running in same VM
962
// as endpoint in the intra-app case because of app clients.
963
//
964
// Also set port-qname based on linked port's qname if not
965
// already set.
966
for(Iterator iter = desc.getPortsInfo().iterator(); iter.hasNext();) {
967             ServiceRefPortInfo portInfo = (ServiceRefPortInfo) iter.next();
968
969             if( portInfo.isLinkedToPortComponent() ) {
970                 WebServiceEndpoint linkedPortComponent =
971                     portInfo.getPortComponentLink();
972                 
973                 // XXX-JD we could at this point try to figure out the
974
// endpoint-address from the ejb wsdl file but it is a
975
// little complicated so I will leave it for post Beta2
976
if( !(portInfo.hasWsdlPort()) ) {
977                     portInfo.setWsdlPort(linkedPortComponent.getWsdlPort());
978                 }
979             }
980         }
981     }
982     
983     private Object JavaDoc initiateInstance(Class JavaDoc svcClass, ServiceReferenceDescriptor desc)
984                                                     throws Exception JavaDoc {
985         
986         java.lang.reflect.Constructor JavaDoc cons = svcClass.getConstructor(new Class JavaDoc[]{java.net.URL JavaDoc.class,
987                                     javax.xml.namespace.QName JavaDoc.class});
988         com.sun.enterprise.webservice.ServiceRefDescUtil descUtil =
989            new com.sun.enterprise.webservice.ServiceRefDescUtil();
990         descUtil.preServiceCreate(desc);
991         WsUtil wsu = new WsUtil();
992         URL wsdlFile = wsu.privilegedGetServiceRefWsdl(desc);
993         // Check if there is a catalog for this web service client
994
// If so resolve the catalog entry
995
String JavaDoc genXmlDir;
996         if(desc.getBundleDescriptor().getApplication() != null) {
997             genXmlDir = desc.getBundleDescriptor().getApplication().getGeneratedXMLDirectory();
998            if(!desc.getBundleDescriptor().getApplication().isVirtual()) {
999                 String JavaDoc subDirName = desc.getBundleDescriptor().getModuleDescriptor().getArchiveUri();
1000                genXmlDir += (File.separator+subDirName.replaceAll("\\.", "_"));
1001            }
1002        } else {
1003            // this is the case of an appclient being run as class file from command line
1004
genXmlDir = desc.getBundleDescriptor().getModuleDescriptor().getArchiveUri();
1005        }
1006        File catalogFile = new File(genXmlDir,
1007                desc.getBundleDescriptor().getDeploymentDescriptorDir() +
1008                    File.separator + "jax-ws-catalog.xml");
1009        if(catalogFile.exists()) {
1010            wsdlFile = wsu.resolveCatalog(catalogFile, desc.getWsdlFileUri(), null);
1011        }
1012        Object JavaDoc obj =
1013           cons.newInstance(wsdlFile, desc.getServiceName());
1014        descUtil.postServiceCreate();
1015        return obj;
1016        
1017    }
1018    
1019    private Object JavaDoc getClientServiceObject(ServiceReferenceDescriptor desc)
1020      throws NamingException {
1021
1022        Class JavaDoc serviceInterfaceClass = null;
1023        Object JavaDoc returnObj = null;
1024        WsUtil wsUtil = new WsUtil();
1025
1026        try {
1027
1028            ClassLoader JavaDoc cl = Thread.currentThread().getContextClassLoader();
1029            
1030            serviceInterfaceClass = cl.loadClass(desc.getServiceInterface());
1031
1032            resolvePortComponentLinks(desc);
1033
1034            Service JavaDoc serviceDelegate = null;
1035            javax.xml.ws.Service jaxwsDelegate = null;
1036            Object JavaDoc injValue = null;
1037
1038            if( desc.hasGeneratedServiceInterface() || desc.hasWsdlFile() ) {
1039
1040                String JavaDoc serviceImplName = desc.getServiceImplClassName();
1041                if(serviceImplName != null) {
1042                    Class JavaDoc serviceImplClass = cl.loadClass(serviceImplName);
1043                    serviceDelegate = (Service JavaDoc) serviceImplClass.newInstance();
1044                } else {
1045                    // The target is probably a post JAXRPC-1.1- based service;
1046
// If Service Interface class is set, check if it is indeed a subclass of Service
1047
// initiateInstance should not be called if the user has given javax.xml.ws.Service itself
1048
// as the interface through DD
1049
if(javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass) &&
1050                        !javax.xml.ws.Service.class.equals(serviceInterfaceClass)) {
1051                        // OK - the interface class is indeed the generated service class; get an instance
1052
injValue = initiateInstance(serviceInterfaceClass, desc);
1053                    } else {
1054                        // First try failed; Try to get the Service class type from injected field name
1055
// and from there try to get an instance of the service class
1056

1057                        // I assume the at all inejction target are expecting the SAME service
1058
// interface, therefore I take the first one.
1059
if (desc.isInjectable()) {
1060                            
1061                            InjectionTarget target = desc.getInjectionTargets().iterator().next();
1062                            Class JavaDoc serviceType = null;
1063                            if (target.isFieldInjectable()) {
1064                                java.lang.reflect.Field JavaDoc f = target.getField();
1065                                if(f == null) {
1066                                    String JavaDoc fName = target.getFieldName();
1067                                    Class JavaDoc targetClass = cl.loadClass(target.getClassName());
1068                                    try {
1069                                        f = targetClass.getDeclaredField(target.getFieldName());
1070                                    } catch(java.lang.NoSuchFieldException JavaDoc nsfe) {}// ignoring exception
1071
}
1072                                serviceType = f.getType();
1073                            }
1074                            if (target.isMethodInjectable()) {
1075                                Method JavaDoc m = target.getMethod();
1076                                if(m == null) {
1077                                    String JavaDoc mName = target.getMethodName();
1078                                    Class JavaDoc targetClass = cl.loadClass(target.getClassName());
1079                                    try {
1080                                        m = targetClass.getDeclaredMethod(target.getMethodName());
1081                                    } catch(java.lang.NoSuchMethodException JavaDoc nsfe) {}// ignoring exception
1082
}
1083                                if (m.getParameterTypes().length==1) {
1084                                    serviceType = m.getParameterTypes()[0];
1085                                }
1086                            }
1087                            if (serviceType!=null){
1088                                Class JavaDoc loadedSvcClass = cl.loadClass(serviceType.getCanonicalName());
1089                                injValue = initiateInstance(loadedSvcClass, desc);
1090                            }
1091                        }
1092                    }
1093                    // Unable to get hold of generated service class -> try the Service.create avenue to get a Service
1094
if(injValue == null) {
1095                        // Here create the service with WSDL (overridden wsdl if wsdl-override is present)
1096
// so that JAXWS runtime uses this wsdl @ runtime
1097
javax.xml.ws.Service svc =
1098                            javax.xml.ws.Service.create((new WsUtil()).privilegedGetServiceRefWsdl(desc),
1099                                desc.getServiceName());
1100                        jaxwsDelegate = new JAXWSServiceDelegate(desc, svc, cl);
1101                    }
1102                }
1103                    
1104                if( desc.hasHandlers() ) {
1105                    // We need the service's ports to configure the
1106
// handler chain (since service-ref handler chain can
1107
// optionally specify handler-port association)
1108
// so create a configured service and call getPorts
1109
Service JavaDoc configuredService =
1110                        wsUtil.createConfiguredService(desc);
1111                    Iterator ports = configuredService.getPorts();
1112                    wsUtil.configureHandlerChain
1113                        (desc, serviceDelegate, ports, cl);
1114                }
1115                
1116                // check if this is a post 1.1 web service
1117
if(javax.xml.ws.Service.class.isAssignableFrom(serviceInterfaceClass)) {
1118                    // This is a JAXWS based webservice client;
1119
// process handlers and mtom setting
1120
// moved test for handlers into wsUtil, in case
1121
// we have to add system handler
1122

1123            javax.xml.ws.Service service =
1124            (injValue != null ?
1125             (javax.xml.ws.Service) injValue : jaxwsDelegate);
1126
1127            if (service != null) {
1128                        // Now configure client side handlers
1129
wsUtil.configureJAXWSClientHandlers(service, desc);
1130            }
1131                    // the requested resource is not the service but one of its port.
1132
if (injValue!=null && desc.getInjectionTargetType()!=null) {
1133                        Class JavaDoc requestedPortType = service.getClass().getClassLoader().loadClass(desc.getInjectionTargetType());
1134                        injValue = service.getPort(requestedPortType);
1135                    }
1136                    
1137                }
1138
1139            } else {
1140                // Generic service interface / no WSDL
1141
QName JavaDoc serviceName = desc.getServiceName();
1142                if( serviceName == null ) {
1143                    // ServiceFactory API requires a service-name.
1144
// However, 109 does not allow getServiceName() to be
1145
// called, so it's ok to use a dummy value.
1146
serviceName = new QName JavaDoc("urn:noservice", "servicename");
1147                }
1148                ServiceFactory JavaDoc serviceFac = ServiceFactory.newInstance();
1149                serviceDelegate = serviceFac.createService(serviceName);
1150            }
1151
1152            // Create a proxy for the service object.
1153
// Get a proxy only in jaxrpc case because in jaxws the service class is not
1154
// an interface any more
1155
InvocationHandler JavaDoc handler = null;
1156            if(serviceDelegate != null) {
1157                handler = new ServiceInvocationHandler(desc, serviceDelegate, cl);
1158                returnObj = Proxy.newProxyInstance
1159                    (cl, new Class JavaDoc[] { serviceInterfaceClass }, handler);
1160            } else if(jaxwsDelegate != null) {
1161                returnObj = jaxwsDelegate;
1162            } else if(injValue != null) {
1163                returnObj = injValue;
1164            }
1165        } catch(PrivilegedActionException JavaDoc pae) {
1166            _logger.log(Level.WARNING, "", pae);
1167            NamingException ne = new NamingException();
1168            ne.initCause(pae.getCause());
1169            throw ne;
1170        } catch(Exception JavaDoc e) {
1171            _logger.log(Level.WARNING, "", e);
1172            NamingException ne = new NamingException();
1173            ne.initCause(e);
1174            throw ne;
1175        }
1176        return returnObj;
1177    }
1178    
1179
1180
1181    public NamingEnumeration list(String JavaDoc name) throws NamingException
1182    {
1183    ArrayList list = listNames(name);
1184    return new NamePairsEnum(this, list.iterator());
1185    }
1186
1187    public NamingEnumeration listBindings(String JavaDoc name) throws NamingException
1188    {
1189    ArrayList list = listNames(name);
1190    return new BindingsEnum(this, list.iterator());
1191    }
1192
1193    private ArrayList listNames(String JavaDoc name) throws NamingException
1194    {
1195    // Get the component id and namespace to lookup
1196
String JavaDoc componentId = getComponentId();
1197    HashMap namespace = (HashMap)namespaces.get(componentId);
1198
1199    Object JavaDoc obj = namespace.get(name);
1200
1201    if ( obj == null )
1202        throw new NameNotFoundException("No object bound to name " + name);
1203
1204    if ( !(obj instanceof javaURLContext) )
1205        throw new NotContextException(name + " cannot be listed");
1206
1207    // This iterates over all names in entire component namespace,
1208
// so its a little inefficient. The alternative is to store
1209
// a list of bindings in each javaURLContext instance.
1210
ArrayList list = new ArrayList();
1211    Iterator itr = namespace.keySet().iterator();
1212    if ( !name.endsWith("/") )
1213        name = name + "/";
1214    while ( itr.hasNext() ) {
1215        String JavaDoc key = (String JavaDoc)itr.next();
1216        // Check if key begins with name and has only 1 component extra
1217
// (i.e. no more slashes)
1218
if ( key.startsWith(name)
1219         && key.indexOf('/', name.length()) == -1 )
1220        list.add(key);
1221    }
1222    return list;
1223    }
1224
1225
1226    /**
1227     * Get the component id from the Invocation Manager.
1228     * @return the component id as a string.
1229     */

1230    private String JavaDoc getComponentId() throws NamingException
1231    {
1232        String JavaDoc id = null;
1233
1234        ComponentInvocation ci = im.getCurrentInvocation();
1235        if (ci == null) {
1236            throw new NamingException("invocation exception ");
1237        }
1238
1239        try {
1240            Object JavaDoc containerContext = ci.getContainerContext();
1241
1242            if(containerContext == null) {
1243                throw new NamingException("No container context");
1244            }
1245        if ( containerContext instanceof Container )
1246        return ((Container)containerContext).getComponentId();
1247
1248        JndiNameEnvironment desc = (JndiNameEnvironment)
1249                theSwitch.getDescriptorFor(containerContext);
1250        id = getMangledIdName(desc);
1251
1252        } catch(InvocationException e) {
1253            NamingException ine = new NamingException("invocation exception");
1254            ine.initCause(e);
1255            throw ine;
1256        }
1257        return id;
1258    }
1259
1260
1261    /**
1262     * Generate the name of an environment property in the java:comp/env
1263     * namespace. This is the lookup string used by a component to access
1264     * its environment.
1265     */

1266    private String JavaDoc descriptorToLogicalJndiName(Descriptor descriptor) {
1267        return JAVA_COMP_STRING + descriptor.getName();
1268    }
1269
1270    private int getComponentType(JndiNameEnvironment env) {
1271        int componentType = UNKNOWN_COMPONENT;
1272        if(env instanceof EjbDescriptor) {
1273            componentType = EJB_COMPONENT;
1274        } else if (env instanceof WebBundleDescriptor) {
1275            componentType = WEB_COMPONENT;
1276        } else if (env instanceof ApplicationClientDescriptor) {
1277            componentType = APP_CLIENT_COMPONENT;
1278        } else {
1279            throw new IllegalArgumentException JavaDoc("Unknown component type" +
1280                                               env);
1281        }
1282        return componentType;
1283    }
1284
1285    /**
1286     * Generate a unique id name for each J2EE component.
1287     */

1288    private String JavaDoc getMangledIdName(JndiNameEnvironment env) {
1289    String JavaDoc id = null;
1290        int componentType = getComponentType(env);
1291
1292        switch(componentType) {
1293        case EJB_COMPONENT :
1294            // EJB component
1295
EjbDescriptor ejbEnv = (EjbDescriptor) env;
1296
1297            if(_logger.isLoggable(Level.FINE)) {
1298                _logger.log(Level.FINE,
1299                            "Application:" + ejbEnv.getApplication());
1300            }
1301            
1302            // Make jndi name flat so it won't result in the creation of
1303
// a bunch of sub-contexts.
1304
String JavaDoc flattedJndiName = ejbEnv.getJndiName().replace('/', '.');
1305
1306            EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor();
1307        id = ejbEnv.getApplication().getName() + ID_SEPARATOR +
1308                ejbBundle.getModuleDescriptor().getArchiveUri()
1309                + ID_SEPARATOR +
1310                ejbEnv.getName() + ID_SEPARATOR + flattedJndiName +
1311                ejbEnv.getUniqueId();
1312
1313            break;
1314
1315        case WEB_COMPONENT :
1316            WebBundleDescriptor webEnv = (WebBundleDescriptor) env;
1317        id = webEnv.getApplication().getName() + ID_SEPARATOR +
1318                webEnv.getContextRoot();
1319            break;
1320
1321        case APP_CLIENT_COMPONENT :
1322            ApplicationClientDescriptor appEnv =
1323        (ApplicationClientDescriptor) env;
1324        id = "client" + ID_SEPARATOR + appEnv.getName() +
1325                ID_SEPARATOR + appEnv.getMainClassName();
1326            break;
1327        }
1328
1329        if(_logger.isLoggable(Level.FINE)) {
1330            _logger.log(Level.FINE, "Component Id: " + id);
1331        }
1332        return id;
1333    }
1334    
1335    private boolean isCOSNamingObj(Object JavaDoc obj) {
1336        return ((obj instanceof java.rmi.Remote JavaDoc) ||
1337                (obj instanceof org.omg.CORBA.Object JavaDoc));
1338    }
1339
1340    private String JavaDoc getApplicationName(JndiNameEnvironment env) {
1341        String JavaDoc appName = "";
1342        int componentType = getComponentType(env);
1343        String JavaDoc moduleName = "";
1344
1345        switch(componentType) {
1346        case EJB_COMPONENT :
1347            // EJB component
1348
EjbDescriptor ejbEnv = (EjbDescriptor) env;
1349            EjbBundleDescriptor ejbBundle = ejbEnv.getEjbBundleDescriptor();
1350        appName = "ejb ["+
1351                ejbEnv.getApplication().getRegistrationName();
1352            moduleName = ejbEnv.getName();
1353            if (moduleName == null || moduleName.equals("")) {
1354                appName = appName+"]";
1355            }
1356            else {
1357                appName = appName+":"+ejbEnv.getName()+"]";
1358            }
1359            break;
1360        case WEB_COMPONENT :
1361            WebBundleDescriptor webEnv = (WebBundleDescriptor) env;
1362        appName = "web module ["+
1363                webEnv.getApplication().getRegistrationName();
1364            moduleName = webEnv.getContextRoot();
1365            if (moduleName == null || moduleName.equals("")) {
1366                appName = appName+"]";
1367            }
1368            else {
1369                appName = appName+":"+webEnv.getContextRoot()+"]";
1370            }
1371            break;
1372        case APP_CLIENT_COMPONENT :
1373            ApplicationClientDescriptor appEnv =
1374        (ApplicationClientDescriptor) env;
1375        appName = "client ["+appEnv.getName() +
1376                ":" + appEnv.getMainClassName()+"]";
1377            break;
1378        }
1379        return appName;
1380    }
1381
1382
1383    private boolean isConnector(String JavaDoc logicalJndiName){
1384        return (logicalJndiName.indexOf(EIS_STRING)!=-1);
1385    }
1386}
1387    
1388
1389// Class for enumerating name/class pairs
1390
class NamePairsEnum implements NamingEnumeration {
1391    NamingManagerImpl nm;
1392    Iterator names;
1393
1394    NamePairsEnum(NamingManagerImpl nm, Iterator names) {
1395    this.nm = nm;
1396    this.names = names;
1397    }
1398
1399    public boolean hasMoreElements() {
1400    return names.hasNext();
1401    }
1402
1403    public boolean hasMore() throws NamingException {
1404    return hasMoreElements();
1405    }
1406
1407    public Object JavaDoc nextElement() {
1408    if(names.hasNext()) {
1409        try {
1410        String JavaDoc name = (String JavaDoc)names.next();
1411        String JavaDoc className = nm.lookup(name).getClass().getName();
1412        return new NameClassPair(name, className);
1413        } catch ( Exception JavaDoc ex ) {
1414        throw new RuntimeException JavaDoc("Exception during lookup: "+ex);
1415        }
1416    }
1417    else
1418        return null;
1419    }
1420
1421    public Object JavaDoc next() throws NamingException {
1422    return nextElement();
1423    }
1424
1425    // New API for JNDI 1.2
1426
public void close() throws NamingException {
1427    throw new OperationNotSupportedException("close() not implemented");
1428    }
1429}
1430
1431// Class for enumerating bindings
1432
class BindingsEnum implements NamingEnumeration {
1433    NamingManagerImpl nm;
1434    Iterator names;
1435
1436    BindingsEnum(NamingManagerImpl nm, Iterator names) {
1437    this.nm = nm;
1438    this.names = names;
1439    }
1440
1441    public boolean hasMoreElements() {
1442    return names.hasNext();
1443    }
1444
1445    public boolean hasMore() throws NamingException {
1446    return hasMoreElements();
1447    }
1448
1449    public Object JavaDoc nextElement() {
1450    if( names.hasNext() ) {
1451        try {
1452        String JavaDoc name = (String JavaDoc)names.next();
1453        return new Binding(name, nm.lookup(name));
1454        } catch ( Exception JavaDoc ex ) {
1455        throw new RuntimeException JavaDoc("Exception during lookup: "+ex);
1456        }
1457    }
1458    else
1459        return null;
1460    }
1461
1462    public Object JavaDoc next() throws NamingException {
1463    return nextElement();
1464    }
1465
1466    // New API for JNDI 1.2
1467
public void close() throws NamingException {
1468    throw new OperationNotSupportedException("close() not implemented");
1469    }
1470}
1471
1472// Class for storing references to EJBHome names
1473
class J2EEEnvWrapper {
1474    static final int MUTABLE = 1;
1475    static final int MAIL_REF = 2;
1476    static final int EJB_REF = 3;
1477    static final int EJBLOCAL_REF = 4;
1478    static final int MUTABLE_RESOURCE_REF = 5;
1479
1480    static final int RESOURCE_ADAPTER = 6;
1481
1482    static final int RESOURCE_ADAPTER_REF = 7;
1483
1484    static final int JDBC_REF = 8;
1485
1486    static final int SERVICE_REF = 9;
1487
1488    static final int EJB_CONTEXT = 10;
1489
1490    static final int ENTITY_MANAGER_FACTORY_REF = 11;
1491
1492    static final int ENTITY_MANAGER_REF = 12;
1493
1494    static final int ORB_RESOURCE = 13;
1495    
1496    static final int WEBSERVICE_CONTEXT = 14;
1497    
1498    int type;
1499    Object JavaDoc object;
1500 
1501    J2EEEnvWrapper(Object JavaDoc object, int type) {
1502    this.object = object;
1503    this.type = type;
1504    }
1505}
1506
Popular Tags