KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openejb > core > ivm > naming > IvmContext


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

45
46
47 package org.openejb.core.ivm.naming;
48
49
50 import java.io.ObjectStreamException JavaDoc;
51 import java.util.Enumeration JavaDoc;
52 import java.util.HashMap JavaDoc;
53 import java.util.HashSet JavaDoc;
54 import java.util.Hashtable JavaDoc;
55 import java.util.Set JavaDoc;
56 import java.util.StringTokenizer JavaDoc;
57 import java.util.Vector JavaDoc;
58
59 import javax.naming.Binding JavaDoc;
60 import javax.naming.CompositeName JavaDoc;
61 import javax.naming.Context JavaDoc;
62 import javax.naming.Name JavaDoc;
63 import javax.naming.NameClassPair JavaDoc;
64 import javax.naming.NameNotFoundException JavaDoc;
65 import javax.naming.NameParser JavaDoc;
66 import javax.naming.NamingEnumeration JavaDoc;
67 import javax.naming.NamingException JavaDoc;
68 import javax.naming.spi.ObjectFactory JavaDoc;
69
70 import org.openejb.core.ThreadContext;
71 import org.openejb.OpenEJB;
72
73 import com.sun.naming.internal.ResourceManager;
74
75 /*
76 * This class wrappers a specific NameNode which is the data model for the JNDI
77 * name space. This class provides javax.naming.Context specific functionality
78 * to the NameNode so that it can be used by beans the JNDI ENC.
79 */

80 public class IvmContext implements Context JavaDoc, java.io.Serializable JavaDoc{
81     Hashtable JavaDoc myEnv;
82     boolean readOnly = false;
83     HashMap JavaDoc fastCache = new HashMap JavaDoc();
84     public NameNode mynode;
85
86     /**
87      * Creates and returns a IvmContext object that is a root context.
88      */

89     public static IvmContext createRootContext() {
90     return new IvmContext(new NameNode(null,new ParsedName("/"),null));
91     }
92
93     public IvmContext(){
94         this(new NameNode(null, new ParsedName("root"), null));
95     }
96     public IvmContext(NameNode node){
97         mynode = node;
98     }
99     public IvmContext(Hashtable JavaDoc environment) throws NamingException{
100         this();
101         if(environment ==null)
102             throw new NamingException("Invalid Argument");
103         else
104             myEnv = (Hashtable JavaDoc)environment.clone();
105
106     }
107     public Object JavaDoc lookup(String JavaDoc compositName) throws NamingException {
108         if (compositName.equals("")) {
109             return this;
110         }
111         
112         // Special case for UserTransaction
113
// This is to give transaction support for non-bean ejb clients using the IntraVm Server
114
if ( compositName.equals("java:comp/UserTransaction") && ThreadContext.getThreadContext().getDeploymentInfo() == null ) {
115             return new org.openejb.core.CoreUserTransaction();
116         }
117
118
119         String JavaDoc compoundName = null;
120         int indx = compositName.indexOf(":");
121         if(indx>-1){
122             /*
123              The ':' character will be in the path if its an absolute path name starting with the schema
124              'java:'. We strip the schema off the path before passing it to the node.resolve method.
125             */

126             compoundName = compositName.substring(indx+1);
127         }else{
128             /*
129               the resolve method always starts with the comparison assuming that the first
130               component of the name is a context of a peer node or the same node, so we have
131               to prepend the current context name to the relative lookup path.
132             */

133         compoundName = mynode.atomicName+'/'+compositName;
134         }
135
136         /*
137            If the object has been resolved in the past from this context and the specified path (name)
138            it will be in the fastCache which is significantly faster then peruse the Node graph.
139            80 ms compared to 300 ms for a full node path search.
140         */

141         Object JavaDoc obj = fastCache.get(compoundName);
142         if(obj==null){
143             // this method will transverse the node graph to locate the bound context or object
144
try{
145             obj = mynode.resolve(new ParsedName(compoundName));
146             }catch(NameNotFoundException JavaDoc nnfe){
147                 obj = federate(compositName);
148             }
149             // cache the lookup path and object for faster resolution next time
150
fastCache.put(compoundName,obj);
151         }
152         if(obj.getClass() == IvmContext.class)
153             ((IvmContext)obj).myEnv = myEnv;
154         else if(obj instanceof Reference){
155             /*
156              EJB references and resource references are wrapped in special
157              org.openejb.core.ivm.naming.Reference types that check to
158              see if the current operation is allowed access to the entry (See EJB 1.1/2.0 Allowed Operations)
159              If the operation is not allowed, a javax.naming.NameNotFoundException is thrown.
160
161              A Reference type can also carry out dynamic resolution of references if necessary.
162             */

163             obj = ((Reference)obj).getObject();
164         }
165         return obj;
166     }
167     protected Object JavaDoc federate(String JavaDoc compositName)throws NamingException{
168         ObjectFactory JavaDoc factories [] = getFederatedFactories();
169         for(int i =0; i < factories.length; i++){
170             try{
171             javax.naming.CompositeName JavaDoc name = new javax.naming.CompositeName JavaDoc(compositName);
172             Object JavaDoc obj = factories[i].getObjectInstance(null, name, null,null);
173
174             if(obj instanceof Context JavaDoc)
175                 return ((Context JavaDoc)obj).lookup(compositName);
176             else if(obj!=null)
177                 return obj;
178             }catch(Exception JavaDoc nnfe){
179                 // do nothing; this is expected
180
}
181         }
182         // if a return never happened then the federated factories didn't contain
183
// anything bound to the name so the exception is thrown.
184
throw new javax.naming.NameNotFoundException JavaDoc("Name \""+compositName+"\" not found.");
185     }
186
187     static ObjectFactory JavaDoc [] federatedFactories = null;
188
189     public static ObjectFactory JavaDoc [] getFederatedFactories( ) throws NamingException{
190         if(federatedFactories == null){
191             Set JavaDoc factories = new HashSet JavaDoc();
192             Hashtable JavaDoc jndiProps = ResourceManager.getInitialEnvironment(null);
193             String JavaDoc pkgs = (String JavaDoc)jndiProps.get(Context.URL_PKG_PREFIXES);
194         if( pkgs == null) {
195         return new ObjectFactory JavaDoc[0];
196         }
197             StringTokenizer JavaDoc parser = new StringTokenizer JavaDoc(pkgs, ":");
198
199             while (parser.hasMoreTokens()) {
200                 String JavaDoc className = parser.nextToken() + ".java.javaURLContextFactory";
201                 if(className.equals("org.openejb.core.ivm.naming.java.javaURLContextFactory"))
202                     continue;
203                 try {
204                     ClassLoader JavaDoc cl = OpenEJB.getContextClassLoader();
205                     Class JavaDoc factoryClass = Class.forName(className, true, cl);
206                     ObjectFactory JavaDoc factoryInstance = (ObjectFactory JavaDoc)factoryClass.newInstance();
207                     factories.add(factoryInstance);
208                 }catch (ClassNotFoundException JavaDoc cnfe){
209                     //do nothing; this is expected
210
}catch (Throwable JavaDoc e) {
211                     NamingException ne =
212                     new NamingException("Federation failed: Cannot instantiate " + className);
213                     ne.setRootCause(e);
214                     throw ne;
215                 }
216             }
217             Object JavaDoc [] temp = factories.toArray();
218             federatedFactories = new ObjectFactory JavaDoc[temp.length];
219             System.arraycopy(temp, 0, federatedFactories, 0, federatedFactories.length);
220         }
221         return federatedFactories;
222     }
223
224
225     public Object JavaDoc lookup(Name JavaDoc compositName) throws NamingException {
226         return lookup(compositName.toString());
227     }
228     /**
229      * WARNING: this function does not provide support for relative names.
230      */

231     public void bind(String JavaDoc name, Object JavaDoc obj) throws NamingException {
232         checkReadOnly();
233         int indx = name.indexOf(":");
234         if(indx>-1){
235             /*
236              The ':' character will be in the path if its an absolute path name starting with the schema
237              'java:'. We strip the schema off the path before passing it to the node.resolve method.
238             */

239             name = name.substring(indx+1);
240         }
241         if(fastCache.containsKey(name))
242             throw new javax.naming.NameAlreadyBoundException JavaDoc();
243         else
244             mynode.bind(new ParsedName(name), obj);
245     }
246     /**
247      * WARNING: this function does not provide support for relative names.
248      */

249     public void bind(Name JavaDoc name, Object JavaDoc obj) throws NamingException {
250         bind(name.toString(), obj);
251     }
252     public void rebind(String JavaDoc name, Object JavaDoc obj) throws NamingException {
253         throw new javax.naming.OperationNotSupportedException JavaDoc();
254     }
255     public void rebind(Name JavaDoc name, Object JavaDoc obj) throws NamingException {
256         rebind(name.toString(), obj);
257     }
258     public void unbind(String JavaDoc name) throws NamingException {
259         throw new javax.naming.OperationNotSupportedException JavaDoc();
260     }
261     public void unbind(Name JavaDoc name) throws NamingException {
262         unbind(name.toString());
263     }
264     public void rename(String JavaDoc oldname, String JavaDoc newname)
265     throws NamingException {
266         throw new javax.naming.OperationNotSupportedException JavaDoc();
267     }
268     public void rename(Name JavaDoc oldname, Name JavaDoc newname)
269     throws NamingException {
270         rename(oldname.toString(), newname.toString());
271     }
272     public NamingEnumeration JavaDoc list(String JavaDoc name)
273     throws NamingException {
274         Object JavaDoc obj = lookup(name);
275         if(obj.getClass() == IvmContext.class)
276             return new MyListEnumeration(((IvmContext)obj).mynode);
277         else {
278             return null; // should be simple enumeration of one element
279
}
280     }
281     public NamingEnumeration JavaDoc list(Name JavaDoc name)
282     throws NamingException {
283         return list(name.toString());
284     }
285     public NamingEnumeration JavaDoc listBindings(String JavaDoc name)
286     throws NamingException {
287         Object JavaDoc obj = lookup(name);
288         if(obj.getClass() == IvmContext.class)
289             return new MyListEnumeration(((IvmContext)obj).mynode);
290         else {
291             return null; // should be simple enumeration of one element
292
}
293     }
294     public NamingEnumeration JavaDoc listBindings(Name JavaDoc name)
295     throws NamingException {
296         return listBindings(name.toString());
297     }
298     public void destroySubcontext(String JavaDoc name) throws NamingException {
299         throw new javax.naming.OperationNotSupportedException JavaDoc();
300     }
301     public void destroySubcontext(Name JavaDoc name) throws NamingException {
302         destroySubcontext(name.toString());
303     }
304     /**
305      * WARNING: this function does not provide support for relative names.
306      */

307     public Context JavaDoc createSubcontext(String JavaDoc name) throws NamingException {
308         checkReadOnly();
309         int indx = name.indexOf(":");
310         if(indx>-1){
311             /*
312           The ':' character will be in the path if its an absolute path name starting with the schema
313           'java:'. We strip the schema off the path before passing it to the node.resolve method.
314             */

315             name = name.substring(indx+1);
316         }
317         if(fastCache.containsKey(name))
318             throw new javax.naming.NameAlreadyBoundException JavaDoc();
319         else
320             return mynode.createSubcontext(new ParsedName(name));
321     }
322     /**
323      * WARNING: this function does not provide support for relative names.
324      */

325     public Context JavaDoc createSubcontext(Name JavaDoc name) throws NamingException {
326         return createSubcontext(name.toString());
327     }
328     public Object JavaDoc lookupLink(String JavaDoc name) throws NamingException {
329         return lookup(name);
330     }
331     public Object JavaDoc lookupLink(Name JavaDoc name) throws NamingException {
332         return lookupLink(name.toString());
333     }
334     public NameParser JavaDoc getNameParser(String JavaDoc name)
335     throws NamingException {
336         throw new javax.naming.OperationNotSupportedException JavaDoc();
337     }
338     public NameParser JavaDoc getNameParser(Name JavaDoc name) throws NamingException {
339         return getNameParser(name.toString());
340     }
341     public String JavaDoc composeName(String JavaDoc name, String JavaDoc prefix)
342     throws NamingException {
343         Name JavaDoc result = composeName(new CompositeName JavaDoc(name),
344         new CompositeName JavaDoc(prefix));
345         return result.toString();
346     }
347     public Name JavaDoc composeName(Name JavaDoc name, Name JavaDoc prefix)
348     throws NamingException {
349         Name JavaDoc result = (Name JavaDoc)(prefix.clone());
350         result.addAll(name);
351         return result;
352     }
353     public Object JavaDoc addToEnvironment(String JavaDoc propName, Object JavaDoc propVal)
354     throws NamingException {
355         if (myEnv == null) {
356             myEnv = new Hashtable JavaDoc(5, 0.75f);
357         }
358         return myEnv.put(propName, propVal);
359     }
360     public Object JavaDoc removeFromEnvironment(String JavaDoc propName)
361     throws NamingException {
362         if (myEnv == null)
363             return null;
364         return myEnv.remove(propName);
365     }
366     public Hashtable JavaDoc getEnvironment() throws NamingException {
367         if (myEnv == null) {
368             // Must return non-null
369
return new Hashtable JavaDoc(3, 0.75f);
370         } else {
371             return (Hashtable JavaDoc)myEnv.clone();
372         }
373     }
374     public String JavaDoc getNameInNamespace() throws NamingException {
375         return "";
376     }
377     public void close() throws NamingException {
378     }
379
380     protected void checkReadOnly( )throws javax.naming.OperationNotSupportedException JavaDoc{
381         if(readOnly)throw new javax.naming.OperationNotSupportedException JavaDoc();
382     }
383
384     // NamingEnumeration implemenations
385

386     protected class MyBindingEnumeration extends MyNamingEnumeration {
387          public MyBindingEnumeration(NameNode parentNode){
388             super(parentNode);
389          }
390          protected void buildEnumeration(Vector JavaDoc vect){
391             for(int i = 0; i < vect.size(); i++){
392                 NameNode node = (NameNode)vect.elementAt(i);
393                 String JavaDoc className = node.getBinding().getClass().getName();
394                 vect.setElementAt(new Binding JavaDoc(node.atomicName,className, node.getBinding()), i);
395             }
396             myEnum = vect.elements();
397          }
398
399     }
400
401     protected class MyListEnumeration extends MyNamingEnumeration {
402          public MyListEnumeration(NameNode parentNode){
403             super(parentNode);
404          }
405          protected void buildEnumeration(Vector JavaDoc vect){
406             for(int i = 0; i < vect.size(); i++){
407                 NameNode node = (NameNode)vect.elementAt(i);
408                 String JavaDoc className = node.getBinding().getClass().getName();
409                 vect.setElementAt(new NameClassPair JavaDoc(node.atomicName,className), i);
410             }
411             myEnum = vect.elements();
412          }
413
414     }
415     protected abstract class MyNamingEnumeration implements javax.naming.NamingEnumeration JavaDoc {
416          Enumeration JavaDoc myEnum;
417
418          public MyNamingEnumeration(NameNode parentNode){
419             Vector JavaDoc vect = new Vector JavaDoc();
420           //System.out.println("[] node "+ parentNode);
421
//System.out.println("[] node.atatomicName "+ parentNode.atomicName);
422
//System.out.println("[] node.atomicHash "+ parentNode.atomicHash);
423
//System.out.println("[] node.grtrTree "+ parentNode.grtrTree);
424
//System.out.println("[] node.lessTree "+ parentNode.lessTree);
425
//System.out.println("[] node.myContext "+ parentNode.myContext);
426
//System.out.println("[] node.myObject "+ parentNode.myObject);
427
//System.out.println("[] node.parent "+ parentNode.parent);
428
//System.out.println("[] node.subTree "+ parentNode.subTree);
429
NameNode node = parentNode.subTree;
430             
431             //<DMB> Not sure about this code
432
if ( node == null ) {
433                 node = parentNode;
434             } else {
435                 vect.addElement(node);
436             }
437             //</DMB> Not sure about this code
438

439             gatherNodes(node,vect);
440
441             buildEnumeration(vect);
442          }
443          abstract protected void buildEnumeration(Vector JavaDoc vect);
444
445          protected void gatherNodes(NameNode node, Vector JavaDoc vect){
446             if(node.lessTree!=null){
447                 vect.addElement(node.lessTree);
448                 gatherNodes(node.lessTree,vect);
449             }
450             if(node.grtrTree!=null){
451                 vect.addElement(node.grtrTree);
452                 gatherNodes(node.grtrTree,vect);
453             }
454          }
455
456          public void close(){
457             myEnum = null;
458          }
459
460          public boolean hasMore() {
461             return hasMoreElements();
462          }
463          public Object JavaDoc next() {
464             return nextElement();
465          }
466          public boolean hasMoreElements(){
467             return myEnum.hasMoreElements();
468          }
469          public Object JavaDoc nextElement() {
470             return myEnum.nextElement();
471          }
472     }
473     
474     protected Object JavaDoc writeReplace() throws ObjectStreamException JavaDoc{
475         if(org.openejb.core.ivm.IntraVmCopyMonitor.isStatefulPassivationOperation()){
476             // if the handle is referenced by a stateful bean that is being passivated by the container, we allow this object to be serialized.
477
return new JndiEncArtifact(this);
478         }
479         // under no other circumstances should this object be serialized
480
throw new java.io.NotSerializableException JavaDoc("IntraVM java.naming.Context objects can not be passed as arguments");
481     }
482     
483     
484     /* for testing only*/
485     public static void main(String JavaDoc str []) throws Exception JavaDoc{
486         String JavaDoc str1 = "root/comp/env/rate/work/doc/lot/pop";
487         String JavaDoc str2 = "root/comp/env/rate/work/doc/lot/price";
488         String JavaDoc str3 = "root/comp/env/rate/work/doc/lot";
489         String JavaDoc str4 = "root/comp/env/rate/work/doc/lot/break/story";
490
491         IvmContext context = new IvmContext();
492         context.bind(str1, new Integer JavaDoc(1));
493         context.bind(str2, new Integer JavaDoc(2));
494         context.bind(str4, new Integer JavaDoc(3));
495 /*
496         Object obj = context.lookup(str1);
497         obj = context.lookup(str2);
498         obj = context.lookup(str1);
499         obj = context.lookup(str3);
500         obj = obj;
501
502         NamingEnumeration ne = context.list(str3);
503         while(ne.hasMore()){
504             NameClassPair ncp = (NameClassPair)ne.nextElement();
505             System.out.println(ncp.getName()+" "+ncp.getClassName());
506         }
507         */

508         
509         Context JavaDoc subcntx = (Context JavaDoc)context.lookup(str3);
510         org.openejb.core.ivm.IntraVmCopyMonitor x = null;
511         java.io.FileOutputStream JavaDoc fos = new java.io.FileOutputStream JavaDoc("x.ser");
512         java.io.ObjectOutputStream JavaDoc oos = new java.io.ObjectOutputStream JavaDoc(fos);
513         org.openejb.core.ivm.IntraVmCopyMonitor.prePassivationOperation();
514         oos.writeObject(subcntx);
515         org.openejb.core.ivm.IntraVmCopyMonitor.postPassivationOperation();
516         oos.flush();
517         oos.close();
518         java.io.FileInputStream JavaDoc fis = new java.io.FileInputStream JavaDoc("x.ser");
519         java.io.ObjectInputStream JavaDoc ois = new java.io.ObjectInputStream JavaDoc(fis);
520         Object JavaDoc newObj = ois.readObject();
521         ois.close();
522     }
523     //*/
524
}
525
Popular Tags