KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jnp > interfaces > NamingContext


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.jnp.interfaces;
23
24 import java.io.BufferedInputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.ObjectInputStream JavaDoc;
27 import java.lang.ref.WeakReference JavaDoc;
28 import java.lang.reflect.Constructor JavaDoc;
29 import java.lang.reflect.InvocationTargetException JavaDoc;
30 import java.net.DatagramPacket JavaDoc;
31 import java.net.InetAddress JavaDoc;
32 import java.net.MulticastSocket JavaDoc;
33 import java.net.Socket JavaDoc;
34 import java.net.InetSocketAddress JavaDoc;
35 import java.rmi.ConnectException JavaDoc;
36 import java.rmi.MarshalledObject JavaDoc;
37 import java.util.ArrayList JavaDoc;
38 import java.util.Arrays JavaDoc;
39 import java.util.Collection JavaDoc;
40 import java.util.Enumeration JavaDoc;
41 import java.util.HashMap JavaDoc;
42 import java.util.Hashtable JavaDoc;
43 import java.util.Iterator JavaDoc;
44 import java.util.StringTokenizer JavaDoc;
45 import javax.naming.Binding JavaDoc;
46 import javax.naming.CannotProceedException JavaDoc;
47 import javax.naming.CommunicationException JavaDoc;
48 import javax.naming.ConfigurationException JavaDoc;
49 import javax.naming.Context JavaDoc;
50 import javax.naming.InitialContext JavaDoc;
51 import javax.naming.InvalidNameException JavaDoc;
52 import javax.naming.LinkRef JavaDoc;
53 import javax.naming.Name JavaDoc;
54 import javax.naming.NameParser JavaDoc;
55 import javax.naming.NamingEnumeration JavaDoc;
56 import javax.naming.NamingException JavaDoc;
57 import javax.naming.NotContextException JavaDoc;
58 import javax.naming.ContextNotEmptyException JavaDoc;
59 import javax.naming.OperationNotSupportedException JavaDoc;
60 import javax.naming.Reference JavaDoc;
61 import javax.naming.Referenceable JavaDoc;
62 import javax.naming.ServiceUnavailableException JavaDoc;
63 import javax.naming.event.EventContext JavaDoc;
64 import javax.naming.event.NamingListener JavaDoc;
65 import javax.naming.spi.NamingManager JavaDoc;
66 import javax.naming.spi.ResolveResult JavaDoc;
67 import javax.net.SocketFactory;
68
69 import org.jboss.logging.Logger;
70
71 /**
72  * This class provides the jnp provider Context implementation. It is a Context
73  * interface wrapper for a RMI Naming instance that is obtained from either the
74  * local server instance or by locating the server given by the
75  * Context.PROVIDER_URL value.
76  *
77  * This class also serves as the jnp url resolution context. jnp style urls
78  * passed to the
79  * @author oberg
80  * @author scott.stark@jboss.org
81  * @version $Revision: 58348 $
82  */

83 public class NamingContext
84    implements EventContext JavaDoc, java.io.Serializable JavaDoc
85 {
86    // Constants -----------------------------------------------------
87
/**
88     * @since 1.7
89     */

90    static final long serialVersionUID = 8906455608484282128L;
91    /**
92     * The javax.net.SocketFactory impl to use for the bootstrap socket
93     */

94    public static final String JavaDoc JNP_SOCKET_FACTORY = "jnp.socketFactory";
95    /**
96     * The local address to bind the connected bootstrap socket to
97     */

98    public static final String JavaDoc JNP_LOCAL_ADDRESS = "jnp.localAddress";
99    /**
100     * The local port to bind the connected bootstrap socket to
101     */

102    public static final String JavaDoc JNP_LOCAL_PORT = "jnp.localPort";
103    /**
104     * A flag to disable the broadcast discovery queries
105     */

106    public static final String JavaDoc JNP_DISABLE_DISCOVERY = "jnp.disableDiscovery";
107    /**
108     * The cluster partition discovery should be restricted to
109     */

110    public static final String JavaDoc JNP_PARTITION_NAME = "jnp.partitionName";
111    /**
112     * The multicast IP/address to which the discovery query is sent
113     */

114    public static final String JavaDoc JNP_DISCOVERY_GROUP = "jnp.discoveryGroup";
115    /**
116     * The port to which the discovery query is sent
117     */

118    public static final String JavaDoc JNP_DISCOVERY_PORT = "jnp.discoveryPort";
119
120    /** The time-to-live for the multicast discovery packets */
121    public static final String JavaDoc JNP_DISCOVERY_TTL = "jnp.discoveryTTL";
122
123    /**
124     * The time in MS to wait for a discovery query response
125     */

126    public static final String JavaDoc JNP_DISCOVERY_TIMEOUT = "jnp.discoveryTimeout";
127    /**
128     * An internal property added by parseNameForScheme if the input name uses a
129     * url prefix that was removed during cannonicalization. This is needed to
130     * avoid modification of the incoming Name.
131     */

132    public static final String JavaDoc JNP_PARSED_NAME = "jnp.parsedName";
133    /**
134     * A flag indicating the style of names passed to NamingManager method.
135     * True for api expected relative names, false for absolute names as used
136     * historically by the jboss naming implementation.
137     */

138    public static final String JavaDoc JNP_USE_RELATIVE_NAME = "jnp.useRelativeName";
139    /**
140     * An integer that controls the number of connection retry attempts will
141     * be made on the initial connection to the naming server. This only applies
142     * to ConnectException failures. A value <= 1 means that only one attempt
143     * will be made.
144     */

145    public static final String JavaDoc JNP_MAX_RETRIES = "jnp.maxRetries";
146
147    /**
148     * The default discovery multicast information
149     */

150    public final static String JavaDoc DEFAULT_DISCOVERY_GROUP_ADDRESS = "230.0.0.4";
151    public final static int DEFAULT_DISCOVERY_GROUP_PORT = 1102;
152    public final static int DEFAULT_DISCOVERY_TIMEOUT = 5000;
153
154    /**
155     * An obsolete constant replaced by the JNP_MAX_RETRIES value
156     */

157    public static int MAX_RETRIES = 1;
158    /**
159     * The JBoss logging interface
160     */

161    private static Logger log = Logger.getLogger(NamingContext.class);
162
163    // Static --------------------------------------------------------
164

165    public static Hashtable JavaDoc haServers = new Hashtable JavaDoc();
166
167    public static void setHANamingServerForPartition(String JavaDoc partitionName, Naming haServer)
168    {
169       haServers.put(partitionName, haServer);
170    }
171
172    public static void removeHANamingServerForPartition(String JavaDoc partitionName)
173    {
174       haServers.remove(partitionName);
175    }
176
177    public static Naming getHANamingServerForPartition(String JavaDoc partitionName)
178    {
179       return (Naming) haServers.get(partitionName);
180    }
181
182    public static Naming localServer;
183
184    // Attributes ----------------------------------------------------
185
Naming naming;
186    Hashtable JavaDoc env;
187    Name JavaDoc prefix;
188
189    NameParser JavaDoc parser = new NamingParser();
190    
191    // Static --------------------------------------------------------
192

193    // Cache of naming server stubs
194
// This is a critical optimization in the case where new InitialContext
195
// is performed often. The server stub will be shared between all those
196
// calls, which will improve performance.
197
// Weak references are used so if no contexts use a particular server
198
// it will be removed from the cache.
199
static HashMap JavaDoc cachedServers = new HashMap JavaDoc();
200
201    static void addServer(String JavaDoc name, Naming server)
202    {
203       // Add server to map
204
synchronized (NamingContext.class)
205       {
206          cachedServers.put(name, new WeakReference JavaDoc(server));
207       }
208    }
209
210    static Naming getServer(String JavaDoc host, int port, Hashtable JavaDoc serverEnv)
211       throws NamingException JavaDoc
212    {
213       // Check the server cache for a host:port entry
214
String JavaDoc hostKey = host + ":" + port;
215       WeakReference JavaDoc ref = (WeakReference JavaDoc) cachedServers.get(hostKey);
216       Naming server;
217       if (ref != null)
218       {
219          server = (Naming) ref.get();
220          if (server != null)
221          {
222             return server;
223          }
224       }
225
226       // Server not found; add it to cache
227
try
228       {
229          SocketFactory factory = loadSocketFactory(serverEnv);
230          Socket JavaDoc s;
231
232          try
233          {
234             InetAddress JavaDoc localAddr = null;
235             int localPort = 0;
236             String JavaDoc localAddrStr = (String JavaDoc) serverEnv.get(JNP_LOCAL_ADDRESS);
237             String JavaDoc localPortStr = (String JavaDoc) serverEnv.get(JNP_LOCAL_PORT);
238             if (localAddrStr != null)
239                localAddr = InetAddress.getByName(localAddrStr);
240             if (localPortStr != null)
241                localPort = Integer.parseInt(localPortStr);
242             s = factory.createSocket(host, port, localAddr, localPort);
243          }
244          catch (IOException JavaDoc e)
245          {
246             NamingException JavaDoc ex = new ServiceUnavailableException JavaDoc("Failed to connect to server " + hostKey);
247             ex.setRootCause(e);
248             throw ex;
249          }
250
251          // Get stub from naming server
252
BufferedInputStream JavaDoc bis = new BufferedInputStream JavaDoc(s.getInputStream());
253          ObjectInputStream JavaDoc in = new ObjectInputStream JavaDoc(bis);
254          MarshalledObject JavaDoc stub = (MarshalledObject JavaDoc) in.readObject();
255          server = (Naming) stub.get();
256          s.close();
257
258          // Add it to cache
259
addServer(hostKey, server);
260          serverEnv.put("hostKey", hostKey);
261
262          return server;
263       }
264       catch (IOException JavaDoc e)
265       {
266          NamingException JavaDoc ex = new CommunicationException JavaDoc("Failed to retrieve stub from server " + hostKey);
267          ex.setRootCause(e);
268          throw ex;
269       }
270       catch (Exception JavaDoc e)
271       {
272          NamingException JavaDoc ex = new CommunicationException JavaDoc("Failed to connect to server " + hostKey);
273          ex.setRootCause(e);
274          throw ex;
275       }
276    }
277
278    /**
279     * Create a SocketFactory based on the JNP_SOCKET_FACTORY property in the
280     * given env. If JNP_SOCKET_FACTORY is not specified default to the
281     * TimedSocketFactory.
282     */

283    static SocketFactory loadSocketFactory(Hashtable JavaDoc serverEnv)
284       throws ClassNotFoundException JavaDoc, IllegalAccessException JavaDoc,
285       InstantiationException JavaDoc, InvocationTargetException JavaDoc
286    {
287       SocketFactory factory = null;
288
289       // Get the socket factory classname
290
String JavaDoc socketFactoryName = (String JavaDoc) serverEnv.get(JNP_SOCKET_FACTORY);
291       if (socketFactoryName == null ||
292          socketFactoryName.equals(TimedSocketFactory.class.getName()))
293       {
294          factory = new TimedSocketFactory(serverEnv);
295          return factory;
296       }
297
298       /* Create the socket factory. Look for a ctor that accepts a
299        Hashtable and if not found use the default ctor.
300        */

301       ClassLoader JavaDoc loader = Thread.currentThread().getContextClassLoader();
302       Class JavaDoc factoryClass = loader.loadClass(socketFactoryName);
303       try
304       {
305          Class JavaDoc[] ctorSig = {Hashtable JavaDoc.class};
306          Constructor JavaDoc ctor = factoryClass.getConstructor(ctorSig);
307          Object JavaDoc[] ctorArgs = {serverEnv};
308          factory = (SocketFactory) ctor.newInstance(ctorArgs);
309       }
310       catch (NoSuchMethodException JavaDoc e)
311       {
312          // Use the default ctor
313
factory = (SocketFactory) factoryClass.newInstance();
314       }
315       return factory;
316    }
317
318    static void removeServer(Hashtable JavaDoc serverEnv)
319    {
320       String JavaDoc host = "localhost";
321       int port = 1099;
322       
323       // Locate naming service
324
if (serverEnv.get(Context.PROVIDER_URL) != null)
325       {
326          String JavaDoc providerURL = (String JavaDoc) serverEnv.get(Context.PROVIDER_URL);
327
328          StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(providerURL, ", ");
329          while (tokenizer.hasMoreElements())
330          {
331             String JavaDoc url = tokenizer.nextToken();
332
333             try
334             {
335                // Parse the url into a host:port form, stripping any protocol
336
Name JavaDoc urlAsName = new NamingParser().parse(url);
337                String JavaDoc server = parseNameForScheme(urlAsName, null);
338                if (server != null)
339                   url = server;
340                int colon = url.indexOf(':');
341                if (colon < 0)
342                {
343                   host = url.trim();
344                }
345                else
346                {
347                   host = url.substring(0, colon).trim();
348                   try
349                   {
350                      port = Integer.parseInt(url.substring(colon + 1).trim());
351                   }
352                   catch (Exception JavaDoc ex)
353                   {
354                      // Use default;
355
}
356                }
357
358                // Remove server from map
359
synchronized (NamingContext.class)
360                {
361                   cachedServers.remove(host + ":" + port);
362                }
363             }
364             catch (NamingException JavaDoc ignored)
365             {
366             }
367          }
368          Object JavaDoc hostKey = serverEnv.remove("hostKey");
369          if (hostKey != null)
370          {
371             synchronized (NamingContext.class)
372             {
373                cachedServers.remove(hostKey);
374             }
375          }
376       }
377       else
378       {
379          // Don't do anything for local server
380
}
381    }
382
383    /**
384     * Called to remove any url scheme atoms and extract the naming service
385     * hostname:port information.
386     * @param n the name component to the parsed. After returning n will have all
387     * scheme related atoms removed.
388     * @return the naming service hostname:port information string if name
389     * contained the host information.
390     */

391    static String JavaDoc parseNameForScheme(Name JavaDoc n, Hashtable JavaDoc nameEnv)
392       throws InvalidNameException JavaDoc
393    {
394       String JavaDoc serverInfo = null;
395       if (n.size() > 0)
396       {
397          String JavaDoc scheme = n.get(0);
398          int schemeLength = 0;
399          if (scheme.startsWith("java:"))
400             schemeLength = 5;
401          else if (scheme.startsWith("jnp:"))
402             schemeLength = 4;
403          else if (scheme.startsWith("jnps:"))
404             schemeLength = 5;
405          else if (scheme.startsWith("jnp-http:"))
406             schemeLength = 9;
407          else if (scheme.startsWith("jnp-https:"))
408             schemeLength = 10;
409          if (schemeLength > 0)
410          {
411             // Make a copy of the name to avoid
412
n = (Name JavaDoc) n.clone();
413             String JavaDoc suffix = scheme.substring(schemeLength);
414             if (suffix.length() == 0)
415             {
416                // Scheme was "url:/..."
417
n.remove(0);
418                if (n.size() > 1 && n.get(0).equals(""))
419                {
420                   // Scheme was "url://hostname:port/..."
421
// Get hostname:port value for the naming server
422
serverInfo = n.get(1);
423                   n.remove(0);
424                   n.remove(0);
425                   // If n is a empty atom remove it or else a '/' will result
426
if (n.size() == 1 && n.get(0).length() == 0)
427                      n.remove(0);
428                }
429             }
430             else
431             {
432                // Scheme was "url:foo" -> reinsert "foo"
433
n.remove(0);
434                n.add(0, suffix);
435             }
436             if (nameEnv != null)
437                nameEnv.put(JNP_PARSED_NAME, n);
438          }
439       }
440       return serverInfo;
441    }
442
443    public static void setLocal(Naming server)
444    {
445       localServer = server;
446    }
447
448    // Constructors --------------------------------------------------
449
public NamingContext(Hashtable JavaDoc e, Name JavaDoc baseName, Naming server)
450       throws NamingException JavaDoc
451    {
452       if (baseName == null)
453          this.prefix = parser.parse("");
454       else
455          this.prefix = baseName;
456
457       if (e != null)
458          this.env = (Hashtable JavaDoc) e.clone();
459       else
460          this.env = new Hashtable JavaDoc();
461
462       this.naming = server;
463    }
464
465    // Public --------------------------------------------------------
466
public Naming getNaming()
467    {
468       return this.naming;
469    }
470
471    public void setNaming(Naming server)
472    {
473       this.naming = server;
474    }
475
476    // Context implementation ----------------------------------------
477
public void rebind(String JavaDoc name, Object JavaDoc obj)
478       throws NamingException JavaDoc
479    {
480       rebind(getNameParser(name).parse(name), obj);
481    }
482
483    public void rebind(Name JavaDoc name, Object JavaDoc obj)
484       throws NamingException JavaDoc
485    {
486       Hashtable JavaDoc refEnv = getEnv(name);
487       checkRef(refEnv);
488       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
489       if (parsedName != null)
490          name = parsedName;
491
492       // Allow state factories to change the stored object
493
obj = getStateToBind(obj, name, refEnv);
494
495       try
496       {
497          String JavaDoc className;
498          
499          // Referenceable
500
if (obj instanceof Referenceable JavaDoc)
501             obj = ((Referenceable JavaDoc) obj).getReference();
502
503          if (!(obj instanceof Reference JavaDoc))
504          {
505             className = obj.getClass().getName();
506             // Normal object - serialize using a MarshalledValuePair
507
obj = new MarshalledValuePair(obj);
508          }
509          else
510          {
511             className = ((Reference JavaDoc) obj).getClassName();
512          }
513          naming.rebind(getAbsoluteName(name), obj, className);
514       }
515       catch (CannotProceedException JavaDoc cpe)
516       {
517          cpe.setEnvironment(refEnv);
518          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
519          cctx.rebind(cpe.getRemainingName(), obj);
520       }
521       catch (IOException JavaDoc e)
522       {
523          naming = null;
524          removeServer(refEnv);
525          NamingException JavaDoc ex = new CommunicationException JavaDoc();
526          ex.setRootCause(e);
527          throw ex;
528       }
529    }
530
531    public void bind(String JavaDoc name, Object JavaDoc obj)
532       throws NamingException JavaDoc
533    {
534       bind(getNameParser(name).parse(name), obj);
535    }
536
537    public void bind(Name JavaDoc name, Object JavaDoc obj)
538       throws NamingException JavaDoc
539    {
540       Hashtable JavaDoc refEnv = getEnv(name);
541       checkRef(refEnv);
542       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
543       if (parsedName != null)
544          name = parsedName;
545
546       // Allow state factories to change the stored object
547
obj = getStateToBind(obj, name, refEnv);
548
549       try
550       {
551          String JavaDoc className;
552          
553          // Referenceable
554
if (obj instanceof Referenceable JavaDoc)
555             obj = ((Referenceable JavaDoc) obj).getReference();
556
557          if (!(obj instanceof Reference JavaDoc))
558          {
559             className = obj.getClass().getName();
560             
561             // Normal object - serialize using a MarshalledValuePair
562
obj = new MarshalledValuePair(obj);
563          }
564          else
565          {
566             className = ((Reference JavaDoc) obj).getClassName();
567          }
568          name = getAbsoluteName(name);
569          naming.bind(name, obj, className);
570       }
571       catch (CannotProceedException JavaDoc cpe)
572       {
573          cpe.setEnvironment(refEnv);
574          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
575          cctx.bind(cpe.getRemainingName(), obj);
576       }
577       catch (IOException JavaDoc e)
578       {
579          naming = null;
580          removeServer(refEnv);
581          NamingException JavaDoc ex = new CommunicationException JavaDoc();
582          ex.setRootCause(e);
583          throw ex;
584       }
585    }
586
587    public Object JavaDoc lookup(String JavaDoc name)
588       throws NamingException JavaDoc
589    {
590       return lookup(getNameParser(name).parse(name));
591    }
592
593    public Object JavaDoc lookup(Name JavaDoc name)
594       throws NamingException JavaDoc
595    {
596       Hashtable JavaDoc refEnv = getEnv(name);
597       checkRef(refEnv);
598       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
599       if (parsedName != null)
600          name = parsedName;
601
602       // Empty?
603
if (name.isEmpty())
604          return new NamingContext(refEnv, prefix, naming);
605
606       try
607       {
608          int maxTries = 1;
609          try
610          {
611             String JavaDoc n = (String JavaDoc) refEnv.get(JNP_MAX_RETRIES);
612             if( n != null )
613                maxTries = Integer.parseInt(n);
614             if( maxTries <= 0 )
615                maxTries = 1;
616          }
617          catch(Exception JavaDoc e)
618          {
619             log.debug("Failed to get JNP_MAX_RETRIES, using 1", e);
620          }
621          Name JavaDoc n = getAbsoluteName(name);
622          Object JavaDoc res = null;
623          boolean trace = log.isTraceEnabled();
624          for (int i = 0; i < maxTries; i++)
625          {
626             try
627             {
628                res = naming.lookup(n);
629                break;
630             }
631             catch (ConnectException JavaDoc ce)
632             {
633                int retries = maxTries - i - 1;
634                if( trace )
635                   log.trace("Connect failed, retry count: "+retries, ce);
636                // We may overload server so sleep and retry
637
if (retries > 0)
638                {
639                   try
640                   {
641                      Thread.sleep(1);
642                   }
643                   catch (InterruptedException JavaDoc ignored)
644                   {
645                   }
646                   continue;
647                }
648                // Throw the exception to flush the bad server
649
throw ce;
650             }
651          }
652          if (res instanceof MarshalledValuePair)
653          {
654             MarshalledValuePair mvp = (MarshalledValuePair) res;
655             Object JavaDoc storedObj = mvp.get();
656             return getObjectInstanceWrapFailure(storedObj, name, refEnv);
657          }
658          else if (res instanceof MarshalledObject JavaDoc)
659          {
660             MarshalledObject JavaDoc mo = (MarshalledObject JavaDoc) res;
661             return mo.get();
662          }
663          else if (res instanceof Context JavaDoc)
664          {
665             // Add env
666
Enumeration JavaDoc keys = refEnv.keys();
667             while (keys.hasMoreElements())
668             {
669                String JavaDoc key = (String JavaDoc) keys.nextElement();
670                ((Context JavaDoc) res).addToEnvironment(key, refEnv.get(key));
671             }
672             return res;
673          }
674          else if (res instanceof ResolveResult JavaDoc)
675          {
676             // Dereference partial result
677
ResolveResult JavaDoc rr = (ResolveResult JavaDoc) res;
678             Object JavaDoc resolveRes = rr.getResolvedObj();
679             Object JavaDoc context;
680             Object JavaDoc instanceID;
681
682             if (resolveRes instanceof LinkRef JavaDoc)
683             {
684                context = resolveLink(resolveRes, null);
685                instanceID = ((LinkRef JavaDoc) resolveRes).getLinkName();
686             }
687             else
688             {
689                context = getObjectInstanceWrapFailure(resolveRes, name, refEnv);
690                instanceID = context;
691             }
692
693             if ((context instanceof Context JavaDoc) == false)
694             {
695                throw new NotContextException JavaDoc(instanceID + " is not a Context");
696             }
697             Context JavaDoc ncontext = (Context JavaDoc) context;
698             return ncontext.lookup(rr.getRemainingName());
699          }
700          else if (res instanceof LinkRef JavaDoc)
701          {
702             // Dereference link
703
res = resolveLink(res, refEnv);
704          }
705          else if (res instanceof Reference JavaDoc)
706          {
707             // Dereference object
708
res = getObjectInstanceWrapFailure(res, name, refEnv);
709             if (res instanceof LinkRef JavaDoc)
710                res = resolveLink(res, refEnv);
711          }
712
713          return res;
714       }
715       catch (CannotProceedException JavaDoc cpe)
716       {
717          cpe.setEnvironment(refEnv);
718          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
719          return cctx.lookup(cpe.getRemainingName());
720       }
721       catch (IOException JavaDoc e)
722       {
723          naming = null;
724          removeServer(refEnv);
725          NamingException JavaDoc ex = new CommunicationException JavaDoc();
726          ex.setRootCause(e);
727          throw ex;
728       }
729       catch (ClassNotFoundException JavaDoc e)
730       {
731          NamingException JavaDoc ex = new CommunicationException JavaDoc();
732          ex.setRootCause(e);
733          throw ex;
734       }
735    }
736
737    public void unbind(String JavaDoc name)
738       throws NamingException JavaDoc
739    {
740       unbind(getNameParser(name).parse(name));
741    }
742
743
744    public void unbind(Name JavaDoc name)
745       throws NamingException JavaDoc
746    {
747       Hashtable JavaDoc refEnv = getEnv(name);
748       checkRef(refEnv);
749       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
750       if (parsedName != null)
751          name = parsedName;
752
753       try
754       {
755          naming.unbind(getAbsoluteName(name));
756       }
757       catch (CannotProceedException JavaDoc cpe)
758       {
759          cpe.setEnvironment(refEnv);
760          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
761          cctx.unbind(cpe.getRemainingName());
762       }
763       catch (IOException JavaDoc e)
764       {
765          naming = null;
766          removeServer(refEnv);
767          NamingException JavaDoc ex = new CommunicationException JavaDoc();
768          ex.setRootCause(e);
769          throw ex;
770       }
771    }
772
773    public void rename(String JavaDoc oldname, String JavaDoc newname)
774       throws NamingException JavaDoc
775    {
776       rename(getNameParser(oldname).parse(oldname), getNameParser(newname).parse(newname));
777    }
778
779    public void rename(Name JavaDoc oldName, Name JavaDoc newName)
780       throws NamingException JavaDoc
781    {
782       bind(newName, lookup(oldName));
783       unbind(oldName);
784    }
785
786    public NamingEnumeration JavaDoc list(String JavaDoc name)
787       throws NamingException JavaDoc
788    {
789       return list(getNameParser(name).parse(name));
790    }
791
792    public NamingEnumeration JavaDoc list(Name JavaDoc name)
793       throws NamingException JavaDoc
794    {
795       Hashtable JavaDoc refEnv = getEnv(name);
796       checkRef(refEnv);
797       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
798       if (parsedName != null)
799          name = parsedName;
800
801       try
802       {
803          return new NamingEnumerationImpl(naming.list(getAbsoluteName(name)));
804       }
805       catch (CannotProceedException JavaDoc cpe)
806       {
807          cpe.setEnvironment(refEnv);
808          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
809          return cctx.list(cpe.getRemainingName());
810       }
811       catch (IOException JavaDoc e)
812       {
813          naming = null;
814          removeServer(refEnv);
815          NamingException JavaDoc ex = new CommunicationException JavaDoc();
816          ex.setRootCause(e);
817          throw ex;
818       }
819    }
820
821    public NamingEnumeration JavaDoc listBindings(String JavaDoc name)
822       throws NamingException JavaDoc
823    {
824       return listBindings(getNameParser(name).parse(name));
825    }
826
827    public NamingEnumeration JavaDoc listBindings(Name JavaDoc name)
828       throws NamingException JavaDoc
829    {
830       Hashtable JavaDoc refEnv = getEnv(name);
831       checkRef(refEnv);
832       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
833       if (parsedName != null)
834          name = parsedName;
835
836       try
837       {
838          // Get list
839
Collection JavaDoc bindings = naming.listBindings(getAbsoluteName(name));
840          Collection JavaDoc realBindings = new ArrayList JavaDoc(bindings.size());
841          
842          // Convert marshalled objects
843
Iterator JavaDoc i = bindings.iterator();
844          while (i.hasNext())
845          {
846             Binding JavaDoc binding = (Binding JavaDoc) i.next();
847             Object JavaDoc obj = binding.getObject();
848             if (obj instanceof MarshalledValuePair)
849             {
850                try
851                {
852                   obj = ((MarshalledValuePair) obj).get();
853                }
854                catch (ClassNotFoundException JavaDoc e)
855                {
856                   NamingException JavaDoc ex = new CommunicationException JavaDoc();
857                   ex.setRootCause(e);
858                   throw ex;
859                }
860             }
861             else if (obj instanceof MarshalledObject JavaDoc)
862             {
863                try
864                {
865                   obj = ((MarshalledObject JavaDoc) obj).get();
866                }
867                catch (ClassNotFoundException JavaDoc e)
868                {
869                   NamingException JavaDoc ex = new CommunicationException JavaDoc();
870                   ex.setRootCause(e);
871                   throw ex;
872                }
873             }
874             realBindings.add(new Binding JavaDoc(binding.getName(), binding.getClassName(), obj));
875          }
876          
877          // Return transformed list of bindings
878
return new NamingEnumerationImpl(realBindings);
879       }
880       catch (CannotProceedException JavaDoc cpe)
881       {
882          cpe.setEnvironment(refEnv);
883          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
884          return cctx.listBindings(cpe.getRemainingName());
885       }
886       catch (IOException JavaDoc e)
887       {
888          naming = null;
889          removeServer(refEnv);
890          NamingException JavaDoc ex = new CommunicationException JavaDoc();
891          ex.setRootCause(e);
892          throw ex;
893       }
894    }
895
896    public String JavaDoc composeName(String JavaDoc name, String JavaDoc prefix)
897       throws NamingException JavaDoc
898    {
899       Name JavaDoc result = composeName(parser.parse(name),
900          parser.parse(prefix));
901       return result.toString();
902    }
903
904    public Name JavaDoc composeName(Name JavaDoc name, Name JavaDoc prefix)
905       throws NamingException JavaDoc
906    {
907       Name JavaDoc result = (Name JavaDoc) (prefix.clone());
908       result.addAll(name);
909       return result;
910    }
911
912    public NameParser JavaDoc getNameParser(String JavaDoc name)
913       throws NamingException JavaDoc
914    {
915       return parser;
916    }
917
918    public NameParser JavaDoc getNameParser(Name JavaDoc name)
919       throws NamingException JavaDoc
920    {
921       return getNameParser(name.toString());
922    }
923
924    public Context JavaDoc createSubcontext(String JavaDoc name)
925       throws NamingException JavaDoc
926    {
927       return createSubcontext(getNameParser(name).parse(name));
928    }
929
930    public Context JavaDoc createSubcontext(Name JavaDoc name)
931       throws NamingException JavaDoc
932    {
933       if (name.size() == 0)
934          throw new InvalidNameException JavaDoc("Cannot pass an empty name to createSubcontext");
935
936       Hashtable JavaDoc refEnv = getEnv(name);
937       checkRef(refEnv);
938       Name JavaDoc parsedName = (Name JavaDoc) refEnv.get(JNP_PARSED_NAME);
939       if (parsedName != null)
940          name = parsedName;
941
942       try
943       {
944          name = getAbsoluteName(name);
945          return naming.createSubcontext(name);
946       }
947       catch (CannotProceedException JavaDoc cpe)
948       {
949          cpe.setEnvironment(refEnv);
950          Context JavaDoc cctx = NamingManager.getContinuationContext(cpe);
951          return cctx.createSubcontext(cpe.getRemainingName());
952       }
953       catch (IOException JavaDoc e)
954       {
955          naming = null;
956          removeServer(refEnv);
957          NamingException JavaDoc ex = new CommunicationException JavaDoc();
958          ex.setRootCause(e);
959          throw ex;
960       }
961    }
962
963    public Object JavaDoc addToEnvironment(String JavaDoc propName, Object JavaDoc propVal)
964       throws NamingException JavaDoc
965    {
966       Object JavaDoc old = env.get(propName);
967       env.put(propName, propVal);
968       return old;
969    }
970
971    public Object JavaDoc removeFromEnvironment(String JavaDoc propName)
972       throws NamingException JavaDoc
973    {
974       return env.remove(propName);
975    }
976
977    public Hashtable JavaDoc getEnvironment()
978       throws NamingException JavaDoc
979    {
980       return env;
981    }
982
983    public void close()
984       throws NamingException JavaDoc
985    {
986       env = null;
987       naming = null;
988    }
989
990    public String JavaDoc getNameInNamespace()
991       throws NamingException JavaDoc
992    {
993       return prefix.toString();
994    }
995
996    public void destroySubcontext(String JavaDoc name)
997       throws NamingException JavaDoc
998    {
999       destroySubcontext(getNameParser(name).parse(name));
1000   }
1001
1002   public void destroySubcontext(Name JavaDoc name)
1003      throws NamingException JavaDoc
1004   {
1005      if (!list(name).hasMore())
1006      {
1007         unbind(name);
1008      }
1009      else
1010         throw new ContextNotEmptyException JavaDoc();
1011   }
1012
1013   public Object JavaDoc lookupLink(String JavaDoc name)
1014      throws NamingException JavaDoc
1015   {
1016      return lookupLink(getNameParser(name).parse(name));
1017   }
1018
1019   /**
1020    * Lookup the object referred to by name but don't dereferrence the final
1021    * component. This really just involves returning the raw value returned by
1022    * the Naming.lookup() method.
1023    * @return the raw object bound under name.
1024    */

1025   public Object JavaDoc lookupLink(Name JavaDoc name)
1026      throws NamingException JavaDoc
1027   {
1028      if (name.isEmpty())
1029         return lookup(name);
1030
1031      Object JavaDoc link = null;
1032      try
1033      {
1034         Name JavaDoc n = getAbsoluteName(name);
1035         link = naming.lookup(n);
1036         if (!(link instanceof LinkRef JavaDoc) && link instanceof Reference JavaDoc)
1037            link = getObjectInstance(link, name, null);
1038         ;
1039      }
1040      catch (IOException JavaDoc e)
1041      {
1042         naming = null;
1043         removeServer(env);
1044         NamingException JavaDoc ex = new CommunicationException JavaDoc();
1045         ex.setRootCause(e);
1046         throw ex;
1047      }
1048      catch (Exception JavaDoc e)
1049      {
1050         NamingException JavaDoc ex = new NamingException JavaDoc("Could not lookup link");
1051         ex.setRemainingName(name);
1052         ex.setRootCause(e);
1053         throw ex;
1054      }
1055      return link;
1056   }
1057
1058   // Begin EventContext methods
1059
public void addNamingListener(Name JavaDoc target, int scope, NamingListener JavaDoc l)
1060      throws NamingException JavaDoc
1061   {
1062      // TODO Auto-generated method stub
1063
throw new UnsupportedOperationException JavaDoc("This is not supported currently");
1064   }
1065
1066   public void addNamingListener(String JavaDoc target, int scope, NamingListener JavaDoc l)
1067      throws NamingException JavaDoc
1068   {
1069      // TODO Auto-generated method stub
1070
throw new UnsupportedOperationException JavaDoc("This is not supported currently");
1071   }
1072
1073   public void removeNamingListener(NamingListener JavaDoc l)
1074      throws NamingException JavaDoc
1075   {
1076      // TODO Auto-generated method stub
1077
throw new UnsupportedOperationException JavaDoc("This is not supported currently");
1078   }
1079
1080   public boolean targetMustExist()
1081      throws NamingException JavaDoc
1082   {
1083      // TODO Auto-generated method stub
1084
return false;
1085   }
1086   // End EventContext methods
1087

1088   protected Object JavaDoc resolveLink(Object JavaDoc res, Hashtable JavaDoc refEnv)
1089      throws NamingException JavaDoc
1090   {
1091      Object JavaDoc linkResult = null;
1092      try
1093      {
1094         LinkRef JavaDoc link = (LinkRef JavaDoc) res;
1095         String JavaDoc ref = link.getLinkName();
1096         if (ref.startsWith("./"))
1097            linkResult = lookup(ref.substring(2));
1098         else if (refEnv != null)
1099            linkResult = new InitialContext JavaDoc(refEnv).lookup(ref);
1100         else
1101            linkResult = new InitialContext JavaDoc().lookup(ref);
1102      }
1103      catch (Exception JavaDoc e)
1104      {
1105         NamingException JavaDoc ex = new NamingException JavaDoc("Could not dereference object");
1106         ex.setRootCause(e);
1107         throw ex;
1108      }
1109      return linkResult;
1110   }
1111
1112   // Private -------------------------------------------------------
1113

1114   /**
1115    * Determine the form of the name to pass to the NamingManager operations.
1116    * This is supposed to be a context relative name according to the javaodcs
1117    * for NamingManager, but historically the absolute name of the target
1118    * context has been passed in.
1119    *
1120    * @param env - the env of NamingContext that op was called on
1121    * @return true if the legacy and technically incorrect absolute name should
1122    * be used, false if the context relative name should be used.
1123    */

1124   private boolean useAbsoluteName(Hashtable JavaDoc env)
1125   {
1126      if (env == null)
1127         return true;
1128      String JavaDoc useRelativeName = (String JavaDoc) env.get(JNP_USE_RELATIVE_NAME);
1129      return Boolean.valueOf(useRelativeName) == Boolean.FALSE;
1130   }
1131
1132   /**
1133    * Use the NamingManager.getStateToBind to obtain the actual object to bind
1134    * into jndi.
1135    * @param obj - the value passed to bind/rebind
1136    * @param name - the name passed to bind/rebind
1137    * @param env - the env of NamingContext that bind/rebind was called on
1138    * @return the object to bind to the naming server
1139    * @throws NamingException
1140    */

1141   private Object JavaDoc getStateToBind(Object JavaDoc obj, Name JavaDoc name, Hashtable JavaDoc env)
1142      throws NamingException JavaDoc
1143   {
1144      if (useAbsoluteName(env))
1145         name = getAbsoluteName(name);
1146      return NamingManager.getStateToBind(obj, name, this, env);
1147   }
1148
1149   /**
1150    * Use the NamingManager.getObjectInstance to resolve the raw object obtained
1151    * from the naming server.
1152    * @param obj - raw value obtained from the naming server
1153    * @param name - the name passed to the lookup op
1154    * @param env - the env of NamingContext that the op was called on
1155    * @return the fully resolved object
1156    * @throws Exception
1157    */

1158   private Object JavaDoc getObjectInstance(Object JavaDoc obj, Name JavaDoc name, Hashtable JavaDoc env)
1159      throws Exception JavaDoc
1160   {
1161      if (useAbsoluteName(env))
1162         name = getAbsoluteName(name);
1163      return NamingManager.getObjectInstance(obj, name, this, env);
1164   }
1165
1166   /**
1167    * Resolve the final object and wrap any non-NamingException errors in a
1168    * NamingException with the cause passed as the root cause.
1169    * @param obj - raw value obtained from the naming server
1170    * @param name - the name passed to the lookup op
1171    * @param env - the env of NamingContext that the op was called on
1172    * @return the fully resolved object
1173    * @throws NamingException
1174    */

1175   private Object JavaDoc getObjectInstanceWrapFailure(Object JavaDoc obj, Name JavaDoc name, Hashtable JavaDoc env)
1176      throws NamingException JavaDoc
1177   {
1178      try
1179      {
1180         return getObjectInstance(obj, name, env);
1181      }
1182      catch (NamingException JavaDoc e)
1183      {
1184         throw e;
1185      }
1186      catch (Exception JavaDoc e)
1187      {
1188         NamingException JavaDoc ex = new NamingException JavaDoc("Could not dereference object");
1189         ex.setRootCause(e);
1190         throw ex;
1191      }
1192   }
1193
1194   /**
1195    * This methods sends a broadcast message on the network and asks and HA-JNDI
1196    * server to sent it the HA-JNDI stub
1197    */

1198   private Naming discoverServer(Hashtable JavaDoc serverEnv) throws NamingException JavaDoc
1199   {
1200      boolean trace = log.isTraceEnabled();
1201      // Check if discovery should be done
1202
String JavaDoc disableDiscovery = (String JavaDoc) serverEnv.get(JNP_DISABLE_DISCOVERY);
1203      if (Boolean.valueOf(disableDiscovery) == Boolean.TRUE)
1204      {
1205         if (trace)
1206            log.trace("Skipping discovery due to disable flag");
1207         return null;
1208      }
1209      
1210      // we first try to discover the server locally
1211
//
1212
String JavaDoc partitionName = (String JavaDoc) serverEnv.get(JNP_PARTITION_NAME);
1213      Naming server = null;
1214      if (partitionName != null)
1215      {
1216         server = getHANamingServerForPartition(partitionName);
1217         if (server != null)
1218            return server;
1219      }
1220      
1221      // We next broadcast a HelloWorld datagram (multicast)
1222
// Any listening server will answer with its IP address:port in another datagram
1223
// we will then use this to make a standard "lookup"
1224
//
1225
MulticastSocket JavaDoc s = null;
1226      InetAddress JavaDoc iaGroup = null;
1227      try
1228      {
1229         String JavaDoc group = DEFAULT_DISCOVERY_GROUP_ADDRESS;
1230         int port = DEFAULT_DISCOVERY_GROUP_PORT;
1231         int timeout = DEFAULT_DISCOVERY_TIMEOUT;
1232         int ttl = 16;
1233
1234         String JavaDoc discoveryGroup = (String JavaDoc) serverEnv.get(JNP_DISCOVERY_GROUP);
1235         if (discoveryGroup != null)
1236            group = discoveryGroup;
1237
1238         String JavaDoc discoveryTTL = (String JavaDoc) serverEnv.get(JNP_DISCOVERY_TTL);
1239         if(discoveryTTL != null)
1240            ttl = Integer.parseInt(discoveryTTL);
1241
1242         String JavaDoc discoveryTimeout = (String JavaDoc) serverEnv.get(JNP_DISCOVERY_TIMEOUT);
1243         if (discoveryTimeout == null)
1244         {
1245            // Check the old property name
1246
discoveryTimeout = (String JavaDoc) serverEnv.get("DISCOVERY_TIMEOUT");
1247         }
1248         if (discoveryTimeout != null && !discoveryTimeout.equals(""))
1249            timeout = Integer.parseInt(discoveryTimeout);
1250
1251         String JavaDoc discoveryGroupPort = (String JavaDoc) serverEnv.get(JNP_DISCOVERY_PORT);
1252         if (discoveryGroupPort == null)
1253         {
1254            // Check the old property name
1255
discoveryGroupPort = (String JavaDoc) serverEnv.get("DISCOVERY_GROUP");
1256         }
1257         if (discoveryGroupPort != null && !discoveryGroupPort.equals(""))
1258         {
1259            int colon = discoveryGroupPort.indexOf(':');
1260            if (colon < 0)
1261            {
1262               // No group given, just the port
1263
try
1264               {
1265                  port = Integer.parseInt(discoveryGroupPort);
1266               }
1267               catch (Exception JavaDoc ex)
1268               {
1269                  log.warn("Failed to parse port: " + discoveryGroupPort, ex);
1270               }
1271            }
1272            else
1273            {
1274               // The old group:port syntax was given
1275
group = discoveryGroupPort.substring(0, colon);
1276               String JavaDoc portStr = discoveryGroupPort.substring(colon + 1);
1277               try
1278               {
1279                  port = Integer.parseInt(portStr);
1280               }
1281               catch (Exception JavaDoc ex)
1282               {
1283                  log.warn("Failed to parse port: " + portStr, ex);
1284               }
1285            }
1286         }
1287
1288         iaGroup = InetAddress.getByName(group);
1289         String JavaDoc localAddrStr = (String JavaDoc) serverEnv.get(JNP_LOCAL_ADDRESS);
1290         String JavaDoc localPortStr = (String JavaDoc) serverEnv.get(JNP_LOCAL_PORT);
1291         int localPort = 0;
1292         if (localPortStr != null)
1293            localPort = Integer.parseInt(localPortStr);
1294         if (localAddrStr != null)
1295         {
1296            InetSocketAddress JavaDoc localAddr = new InetSocketAddress JavaDoc(localAddrStr, localPort);
1297            s = new MulticastSocket JavaDoc(localAddr);
1298         }
1299         else
1300         {
1301            s = new MulticastSocket JavaDoc(localPort);
1302         }
1303         s.setSoTimeout(timeout);
1304         s.setTimeToLive(ttl);
1305         if(log.isTraceEnabled())
1306            log.trace("TTL on multicast discovery socket is " + ttl);
1307         s.joinGroup(iaGroup);
1308         if (trace)
1309            log.trace("MulticastSocket: " + s);
1310         DatagramPacket JavaDoc packet;
1311         // Send a request optionally restricted to a cluster partition
1312
StringBuffer JavaDoc data = new StringBuffer JavaDoc("GET_ADDRESS");
1313         if (partitionName != null)
1314            data.append(":" + partitionName);
1315         byte[] buf = data.toString().getBytes();
1316         packet = new DatagramPacket JavaDoc(buf, buf.length, iaGroup, port);
1317         if (trace)
1318            log.trace("Sending discovery packet(" + data + ") to: " + iaGroup + ":" + port);
1319         s.send(packet);
1320         // Look for a reply
1321
// IP address + port number = 128.128.128.128:65535 => (12+3) + 1 + (5) = 21
1322

1323         buf = new byte[50];
1324         packet = new DatagramPacket JavaDoc(buf, buf.length);
1325         s.receive(packet);
1326         String JavaDoc myServer = new String JavaDoc(packet.getData()).trim();
1327         if (trace)
1328            log.trace("Received answer packet: " + myServer);
1329         while (myServer != null && myServer.startsWith("GET_ADDRESS"))
1330         {
1331            Arrays.fill(buf, (byte) 0);
1332            packet.setLength(buf.length);
1333            s.receive(packet);
1334            byte[] reply = packet.getData();
1335            myServer = new String JavaDoc(reply).trim();
1336            if (trace)
1337               log.trace("Received answer packet: " + myServer);
1338         }
1339         String JavaDoc serverHost;
1340         int serverPort;
1341
1342         int colon = myServer.indexOf(':');
1343         if (colon >= 0)
1344         {
1345            serverHost = myServer.substring(0, colon);
1346            serverPort = Integer.valueOf(myServer.substring(colon + 1)).intValue();
1347            server = getServer(serverHost, serverPort, serverEnv);
1348         }
1349         return server;
1350      }
1351      catch (IOException JavaDoc e)
1352      {
1353         if (trace)
1354            log.trace("Discovery failed", e);
1355         NamingException JavaDoc ex = new CommunicationException JavaDoc(e.getMessage());
1356         ex.setRootCause(e);
1357         throw ex;
1358      }
1359      finally
1360      {
1361         try
1362         {
1363            if (s != null)
1364               s.leaveGroup(iaGroup);
1365         }
1366         catch (Exception JavaDoc ignore)
1367         {
1368         }
1369         try
1370         {
1371            if (s != null)
1372               s.close();
1373         }
1374         catch (Exception JavaDoc ignore)
1375         {
1376         }
1377      }
1378   }
1379
1380   private void checkRef(Hashtable JavaDoc refEnv)
1381      throws NamingException JavaDoc
1382   {
1383      if (naming == null)
1384      {
1385         String JavaDoc host = "localhost";
1386         int port = 1099;
1387         Exception JavaDoc serverEx = null;
1388         
1389         // Locate first available naming service
1390
String JavaDoc urls = (String JavaDoc) refEnv.get(Context.PROVIDER_URL);
1391         if (urls != null && urls.length() > 0)
1392         {
1393            StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(urls, ",");
1394
1395            while (naming == null && tokenizer.hasMoreElements())
1396            {
1397               String JavaDoc url = tokenizer.nextToken();
1398               // Parse the url into a host:port form, stripping any protocol
1399
Name JavaDoc urlAsName = getNameParser("").parse(url);
1400               String JavaDoc server = parseNameForScheme(urlAsName, null);
1401               if (server != null)
1402                  url = server;
1403               int colon = url.indexOf(':');
1404               if (colon < 0)
1405               {
1406                  host = url;
1407               }
1408               else
1409               {
1410                  host = url.substring(0, colon).trim();
1411                  try
1412                  {
1413                     port = Integer.parseInt(url.substring(colon + 1).trim());
1414                  }
1415                  catch (Exception JavaDoc ex)
1416                  {
1417                     // Use default;
1418
}
1419               }
1420               try
1421               {
1422                  // Get server from cache
1423
naming = getServer(host, port, refEnv);
1424               }
1425               catch (Exception JavaDoc e)
1426               {
1427                  serverEx = e;
1428                  log.debug("Failed to connect to " + host + ":" + port, e);
1429               }
1430            }
1431
1432            // If there is still no
1433
Exception JavaDoc discoveryFailure = null;
1434            if (naming == null)
1435            {
1436               try
1437               {
1438                  naming = discoverServer(refEnv);
1439               }
1440               catch (Exception JavaDoc e)
1441               {
1442                  discoveryFailure = e;
1443                  if (serverEx == null)
1444                     serverEx = e;
1445               }
1446               if (naming == null)
1447               {
1448                  StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(50);
1449                  buffer.append("Could not obtain connection to any of these urls: ").append(urls);
1450                  if (discoveryFailure != null)
1451                     buffer.append(" and discovery failed with error: ").append(discoveryFailure);
1452                  CommunicationException JavaDoc ce = new CommunicationException JavaDoc(buffer.toString());
1453                  ce.setRootCause(serverEx);
1454                  throw ce;
1455               }
1456            }
1457         }
1458         else
1459         {
1460            // If we are in a clustering scenario, the client code may request a context
1461
// for a *specific* HA-JNDI service (i.e. linked to a *specific* partition)
1462
// EVEN if the lookup is done inside a JBoss VM. For example, a JBoss service
1463
// may do a lookup on a HA-JNDI service running on another host *without*
1464
// explicitly providing a PROVIDER_URL but simply by providing a JNP_PARTITON_NAME
1465
// parameter so that dynamic discovery can be used
1466
//
1467
String JavaDoc jnpPartitionName = (String JavaDoc) refEnv.get(JNP_PARTITION_NAME);
1468            if (jnpPartitionName != null)
1469            {
1470               // the client is requesting for a specific partition name
1471
//
1472
naming = discoverServer(refEnv);
1473               if (naming == null)
1474                  throw new ConfigurationException JavaDoc
1475                     ("No valid context could be build for jnp.partitionName=" + jnpPartitionName);
1476            }
1477            else
1478            {
1479               // Use server in same JVM
1480
naming = localServer;
1481
1482               if (naming == null)
1483               {
1484                  naming = discoverServer(refEnv);
1485                  if (naming == null)
1486                  // Local, but no local JNDI provider found!
1487
throw new ConfigurationException JavaDoc("No valid Context.PROVIDER_URL was found");
1488               }
1489            }
1490         }
1491      }
1492   }
1493
1494   private Name JavaDoc getAbsoluteName(Name JavaDoc n)
1495      throws NamingException JavaDoc
1496   {
1497      if (n.isEmpty())
1498         return composeName(n, prefix);
1499      else if (n.get(0).toString().equals("")) // Absolute name
1500
return n.getSuffix(1);
1501      else // Add prefix
1502
return composeName(n, prefix);
1503   }
1504
1505   private Hashtable JavaDoc getEnv(Name JavaDoc n)
1506      throws InvalidNameException JavaDoc
1507   {
1508      Hashtable JavaDoc nameEnv = env;
1509      env.remove(JNP_PARSED_NAME);
1510      String JavaDoc serverInfo = parseNameForScheme(n, nameEnv);
1511      if (serverInfo != null)
1512      {
1513         // Set hostname:port value for the naming server
1514
nameEnv = (Hashtable JavaDoc) env.clone();
1515         nameEnv.put(Context.PROVIDER_URL, serverInfo);
1516      }
1517      return nameEnv;
1518   }
1519
1520   // Inner classes -------------------------------------------------
1521
}
1522
Popular Tags