KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > spi > conf > ConfFileInitialContext


1 /*
2  * Enhydra Java Application Server Project
3  *
4  * The contents of this file are subject to the Enhydra Public License
5  * Version 1.1 (the "License"); you may not use this file except in
6  * compliance with the License. You may obtain a copy of the License on
7  * the Enhydra web site ( http://www.enhydra.org/ ).
8  *
9  * Software distributed under the License is distributed on an "AS IS"
10  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
11  * the License for the specific terms governing rights and limitations
12  * under the License.
13  *
14  * The Initial Developer of the Enhydra Application Server is Lutris
15  * Technologies, Inc. The Enhydra Application Server and portions created
16  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
17  * All Rights Reserved.
18  *
19  * Contributor(s):
20  *
21  * $Id: ConfFileInitialContext.java,v 1.1 2005/02/24 11:12:42 slobodan Exp $
22  */

23
24 package org.enhydra.spi.conf;
25
26 import java.rmi.Remote JavaDoc;
27 import java.util.Enumeration JavaDoc;
28 import java.util.Hashtable JavaDoc;
29 import java.util.Collection JavaDoc;
30 import java.util.Iterator JavaDoc;
31 import java.io.File JavaDoc;
32 import java.io.FileInputStream JavaDoc;
33
34 import javax.naming.Binding JavaDoc;
35 import javax.naming.CompositeName JavaDoc;
36 import javax.naming.Context JavaDoc;
37 import javax.naming.InvalidNameException JavaDoc;
38 import javax.naming.Name JavaDoc;
39 import javax.naming.NameAlreadyBoundException JavaDoc;
40 import javax.naming.NameClassPair JavaDoc;
41 import javax.naming.NameNotFoundException JavaDoc;
42 import javax.naming.NameParser JavaDoc;
43 import javax.naming.NamingEnumeration JavaDoc;
44 import javax.naming.NamingException JavaDoc;
45 import javax.naming.NotContextException JavaDoc;
46 import javax.naming.OperationNotSupportedException JavaDoc;
47 import javax.naming.Reference JavaDoc;
48 import javax.naming.Referenceable JavaDoc;
49 import javax.naming.spi.ObjectFactory JavaDoc;
50
51 import org.objectweb.carol.util.configuration.TraceCarol;
52 import org.enhydra.spi.conf.util.ConfigToContextParser;
53
54 /*
55  * Class <code>ConfFileInitialContext</code> is the CAROL LMI JNDI SPI Context for local context.
56  * This context is accessible only in local jvm, this is a singleton (the close
57  * method do nothing). This cotext bind and return Local Java Refferences. It also
58  * reads Enhydra application's configuration file (&lt;app_name&gt;.conf) and puts
59  * application parameters into java:comp/env/ context of Application's JNDI context.
60  *
61  * @author
62  * @version 1.0, 25/01/2004
63  */

64 public class ConfFileInitialContext implements Context JavaDoc {
65
66     /**
67      * ConfFile Environment
68      */

69     private static Hashtable JavaDoc fileEnv = new Hashtable JavaDoc();
70
71     /**
72      * ConfFile bindings
73      */

74     private static Hashtable JavaDoc bindings = new Hashtable JavaDoc();
75
76     /**
77      * Application's java:comp/env/ context.
78      */

79     private static Context JavaDoc envContext = null;
80
81     /**
82      * Path to application's configuration file (other than web.xml), if exists.
83      */

84     private String JavaDoc filePath = null;
85
86     /**
87      * True if the file is parsed, otherwise false.
88      */

89     private boolean isFileParsed = false;
90
91     /**
92      * ConfFile Name Parser
93      */

94     private static NameParser JavaDoc fileParser = new ConfFileNameParser();
95
96     public final static String JavaDoc FILE_JNDI_ABS_PATH_NAME = "fileJndiAbsPathName";
97     public final static String JavaDoc CONTEXT_FOR_ENV_BIND = "contextForEnvToBind";
98
99     /**
100      * Resolve a Remote Object:
101      * If this object is a reference return the reference
102      *
103      * @param o the object to resolve
104      * @param name the name of this object
105      * @return a <code>Referenceable</code> if o is a Reference
106      * and the inititial object o if else
107      */

108     private Object JavaDoc resolveObject(Object JavaDoc o, Name JavaDoc name) {
109    try {
110        if (o instanceof Reference JavaDoc) {
111       // build of the Referenceable object with is Reference
112
Reference JavaDoc objRef = (Reference JavaDoc)o;
113       ObjectFactory JavaDoc objFact = (ObjectFactory JavaDoc)(Thread.currentThread().getContextClassLoader().loadClass(objRef.getFactoryClassName())).newInstance();
114       return objFact.getObjectInstance(objRef,name,this,this.getEnvironment());
115        } else {
116       return o;
117        }
118    } catch (Exception JavaDoc e) {
119        TraceCarol.error("ConfFileInitialContext.resolveObject()", e);
120        return o;
121    }
122     }
123
124     /**
125      * Encode an Object :
126      * If the object is a referenceable bind this reference
127      *
128      * @param o the object to encode
129      * @return a <code>Remote Object</code> if o is a ressource
130      * o if else
131      * @throws NamingException If naming exception occures.
132      */

133     private Object JavaDoc encodeObject(Object JavaDoc o) throws NamingException JavaDoc {
134    try {
135        if ((!(o instanceof Remote JavaDoc)) && (o instanceof Referenceable JavaDoc)) {
136             return ((Referenceable JavaDoc)o).getReference();
137        } else if ((!(o instanceof Remote JavaDoc)) && (o instanceof Reference JavaDoc)) {
138           return (Reference JavaDoc)o;
139        } else {
140            return o;
141        }
142    } catch (Exception JavaDoc e) {
143        throw new NamingException JavaDoc("" +e);
144    }
145     }
146
147    /**
148      * Constructor,
149      * load communication framework
150      * and instaciate initial contexts.
151      * @throws NamingException If naming exception occures.
152      */

153     public ConfFileInitialContext () throws NamingException JavaDoc {
154        if (TraceCarol.isDebugJndiCarol()) {
155             TraceCarol.debugJndiCarol("ConfFileInitialContext.ConfFileInitialContext()");
156         }
157         // System.err.println("Parameters set to default!");
158
envContext = null;
159         filePath = null;
160         isFileParsed = false;
161     }
162
163     /**
164      * Constructor,
165      * load communication framework
166      * and instaciate initial contexts.
167      * @param ev JNDI environment.
168      * @throws NamingException If naming exception occures.
169      */

170     public ConfFileInitialContext (Hashtable JavaDoc ev) throws NamingException JavaDoc {
171        if (TraceCarol.isDebugJndiCarol()) {
172             TraceCarol.debugJndiCarol("ConfFileInitialContext.ConfFileInitialContext(Hashtable env)");
173         }
174         if (ev != null) {
175            fileEnv = (Hashtable JavaDoc)(ev.clone());
176         }
177         //System.err.println("Parameters set to default!!!");
178
envContext = null;
179         filePath = null;
180         isFileParsed = false;
181     }
182
183
184     // Inital context wrapper see the Context documentation for this methods
185
public Object JavaDoc lookup(String JavaDoc name) throws NamingException JavaDoc {
186       //System.err.println("Name for lookup: " + name);
187
if (TraceCarol.isDebugJndiCarol()) {
188         TraceCarol.debugJndiCarol("ConfFileInitialContext.lookup(\"" + name +
189                                   "\")");
190       }
191       if ( (name == null) || (name.equals(""))) {
192         return (new ConfFileInitialContext(fileEnv));
193       }
194       Object JavaDoc o = bindings.get(name);
195       if (o != null) {
196         return resolveObject(o, new CompositeName JavaDoc(name));
197       }
198       else {
199         throw new NameNotFoundException JavaDoc(name + " not found");
200    }
201     }
202
203     public Object JavaDoc lookup(Name JavaDoc name) throws NamingException JavaDoc {
204       return lookup(name.toString());
205     }
206
207     public void bind(String JavaDoc name, Object JavaDoc obj) throws NamingException JavaDoc {
208    if (TraceCarol.isDebugJndiCarol()) {
209             TraceCarol.debugJndiCarol("ConfFileInitialContext.bind(\""+name+"\","+simpleClass(obj.getClass().getName())+" object)");
210         }
211         // System.err.println("Key for bind: " + name);
212
if (name.equals("")) {
213             throw new InvalidNameException JavaDoc("Cannot bind empty name");
214         }
215         if (name.equals(FILE_JNDI_ABS_PATH_NAME)) {
216  // if (this.filePath != null) {
217
// System.err.println("File already defined ############################################");
218
// throw new NamingException("File already defined for initial context.");
219
// }
220
// else {
221
this.filePath = (String JavaDoc) obj;
222             if ((this.envContext != null) && (!this.isFileParsed)) {
223 // if (this.envContext != null) {
224
parseConfFile(this.filePath);
225               this.isFileParsed = true;
226             }
227          }
228         else {
229           if (name.equals(CONTEXT_FOR_ENV_BIND)) {
230  // if (this.envContext != null) {
231
// System.err.println("envCtx already defined ############################################");
232
// throw new NamingException(
233
// "java:comp/env context already defined for initial context.");
234
// }
235
// else {
236
this.envContext = (Context JavaDoc) obj;
237 // if ((this.filePath != null) && (!this.isFileParsed)) {
238
if (this.filePath != null) {
239               parseConfFile(this.filePath);
240               this.isFileParsed = true;
241             }
242 // else
243
// throw new NamingException("application file already parsed.");
244
}
245           else {
246             if (bindings.get(name) != null) {
247               throw new NameAlreadyBoundException JavaDoc("Use rebind to override");
248             }
249             bindings.put(name, encodeObject(obj));
250           }
251         }
252     }
253
254     public void bind(Name JavaDoc name, Object JavaDoc obj) throws NamingException JavaDoc {
255    bind(name.toString(), obj);
256     }
257
258     public void rebind(String JavaDoc name, Object JavaDoc obj) throws NamingException JavaDoc {
259    if (TraceCarol.isDebugJndiCarol()) {
260             TraceCarol.debugJndiCarol("ConfFileInitialContext.rebind(\""+name+"\","+simpleClass(obj.getClass().getName())+" object)");
261    }
262    // System.err.println("Key for rebind: " + name);
263
if (name.equals("")) {
264        throw new InvalidNameException JavaDoc("Cannot bind empty name");
265    }
266         if (name.equals(FILE_JNDI_ABS_PATH_NAME)) {
267  // if (this.filePath != null) {
268
// System.err.println("File already defined ############################################");
269
// throw new NamingException("File already defined for initial .");
270
// }
271
this.filePath = (String JavaDoc) obj;
272 // if ((this.envContext != null) && (!this.isFileParsed)) {
273
if (this.envContext != null){
274            parseConfFile(this.filePath);
275            this.isFileParsed = true;
276          }
277        }
278        else {
279          if (name.equals(CONTEXT_FOR_ENV_BIND)) {
280 // if (this.envContext != null) {
281
// System.err.println("envCtx already defined ############################################");
282
// throw new NamingException(
283
// "java:comp/env context already defined for initial context.");
284
// }
285
this.envContext = (Context JavaDoc) obj;
286 // if ((this.filePath != null) && (!this.isFileParsed)) {
287
if (this.filePath != null) {
288              parseConfFile(this.filePath);
289              this.isFileParsed = true;
290           }
291 // else
292
// throw new NamingException("application file already parsed.");
293
}
294          else {
295            bindings.put(name, encodeObject(obj));
296          }
297        }
298     }
299
300     public void rebind(Name JavaDoc name, Object JavaDoc obj) throws NamingException JavaDoc {
301         rebind(name.toString(), obj);
302     }
303
304     public void unbind(String JavaDoc name) throws NamingException JavaDoc {
305    if (TraceCarol.isDebugJndiCarol()) {
306             TraceCarol.debugJndiCarol("ConfFileInitialContext.unbind(\""+name+"\")");
307         }
308         if (name.equals("")) {
309             throw new InvalidNameException JavaDoc("Cannot unbind empty name");
310         }
311         bindings.remove(name);
312     }
313
314     public void unbind(Name JavaDoc name) throws NamingException JavaDoc {
315         unbind(name.toString());
316     }
317     public void rename(String JavaDoc oldName, String JavaDoc newName) throws NamingException JavaDoc {
318    if (TraceCarol.isDebugJndiCarol()) {
319             TraceCarol.debugJndiCarol("ConfFileInitialContext.rename(\""+oldName+"\",\""+newName+"\")");
320         }
321         if (oldName.equals("") || newName.equals("")) throw new InvalidNameException JavaDoc("Cannot rename empty name");
322         if (bindings.get(newName) != null) throw new NameAlreadyBoundException JavaDoc(newName + " is already bound");
323
324         Object JavaDoc oldb = bindings.remove(oldName);
325         if (oldb == null) throw new NameNotFoundException JavaDoc(oldName + " not bound");
326         bindings.put(newName, oldb);
327     }
328
329     public void rename(Name JavaDoc oldname, Name JavaDoc newname) throws NamingException JavaDoc {
330         rename(oldname.toString(), newname.toString());
331     }
332
333     public NamingEnumeration JavaDoc list(String JavaDoc name) throws NamingException JavaDoc {
334    if (TraceCarol.isDebugJndiCarol()) {
335             TraceCarol.debugJndiCarol("ConfFileInitialContext.list(\""+name+"\")");
336         }
337         //System.err.println("Name for list: " + name);
338
if (name.equals("")) {
339             return new ConfFileNames(bindings.keys());
340         }
341
342         Object JavaDoc target = lookup(name);
343         if (target instanceof Context JavaDoc) {
344             return ((Context JavaDoc)target).list("");
345         }
346         throw new NotContextException JavaDoc(name + " cannot be listed");
347     }
348
349     public NamingEnumeration JavaDoc list(Name JavaDoc name) throws NamingException JavaDoc {
350         return list(name.toString());
351     }
352
353     public NamingEnumeration JavaDoc listBindings(String JavaDoc name) throws NamingException JavaDoc {
354    if (TraceCarol.isDebugJndiCarol()) {
355             TraceCarol.debugJndiCarol("ConfFileInitialContext.listBindings(\""+name+"\")/rmi name=\"");
356         }
357         if (name.equals("")) {
358             return new ConfFileBindings(bindings.keys());
359         }
360         Object JavaDoc target = lookup(name);
361         if (target instanceof Context JavaDoc) {
362             return ((Context JavaDoc)target).listBindings("");
363         }
364         throw new NotContextException JavaDoc(name + " cannot be listed");
365     }
366
367     public NamingEnumeration JavaDoc listBindings(Name JavaDoc name) throws NamingException JavaDoc {
368    return listBindings(name.toString());
369     }
370
371     public void destroySubcontext(String JavaDoc name) throws NamingException JavaDoc {
372    TraceCarol.error("ConfFileInitialContext.destroySubcontext(\""+name+"\"): Not supported");
373         throw new OperationNotSupportedException JavaDoc("ConfFileInitialContext.destroySubcontext(\""+name+"\"): Not supported");
374     }
375
376     public void destroySubcontext(Name JavaDoc name) throws NamingException JavaDoc {
377    destroySubcontext(name.toString());
378     }
379
380     public Context JavaDoc createSubcontext(String JavaDoc name) throws NamingException JavaDoc {
381    TraceCarol.error("ConfFileInitialContext.createSubcontext(\""+name+"\"): Not supported");
382         throw new OperationNotSupportedException JavaDoc("ConfFileInitialContext.createSubcontext(\""+name+"\"): Not supported");
383     }
384
385     public Context JavaDoc createSubcontext(Name JavaDoc name) throws NamingException JavaDoc {
386         return createSubcontext(name.toString());
387     }
388
389     public Object JavaDoc lookupLink(String JavaDoc name) throws NamingException JavaDoc {
390    if (TraceCarol.isDebugJndiCarol()) {
391             TraceCarol.debugJndiCarol("ConfFileInitialContext.lookupLink(\""+name+"\")");
392         }
393         return lookup(name);
394     }
395
396     public Object JavaDoc lookupLink(Name JavaDoc name) throws NamingException JavaDoc {
397         return lookupLink(name.toString());
398     }
399
400     public NameParser JavaDoc getNameParser(String JavaDoc name) throws NamingException JavaDoc {
401    if (TraceCarol.isDebugJndiCarol()) {
402             TraceCarol.debugJndiCarol("ConfFileInitialContext.getNameParser(\""+name+"\")");
403         }
404         return fileParser;
405     }
406
407     public NameParser JavaDoc getNameParser(Name JavaDoc name) throws NamingException JavaDoc {
408         return getNameParser(name.toString());
409     }
410
411     public String JavaDoc composeName(String JavaDoc name, String JavaDoc prefix) throws NamingException JavaDoc {
412    if (TraceCarol.isDebugJndiCarol()) {
413             TraceCarol.debugJndiCarol("ConfFileInitialContext.composeName("+name+","+prefix+")");
414         }
415         Name JavaDoc result = composeName(new CompositeName JavaDoc(name), new CompositeName JavaDoc(prefix));
416         return result.toString();
417     }
418
419     public Name JavaDoc composeName(Name JavaDoc name, Name JavaDoc prefix) throws NamingException JavaDoc {
420    if (TraceCarol.isDebugJndiCarol()) {
421             TraceCarol.debugJndiCarol("ConfFileInitialContext.composeName("+name+","+prefix+")");
422         }
423         Name JavaDoc result = (Name JavaDoc)(prefix.clone());
424         result.addAll(name);
425         return result;
426     }
427
428     public Object JavaDoc addToEnvironment(String JavaDoc propName, Object JavaDoc propVal) throws NamingException JavaDoc {
429    if (TraceCarol.isDebugJndiCarol()) {
430        TraceCarol.debugJndiCarol("ConfFileInitialContext.addToEnvironment(\""+propName+"\","+simpleClass(propVal.getClass().getName())+" object)");
431        }
432         if (fileEnv == null) {
433             fileEnv = new Hashtable JavaDoc();
434    }
435    return fileEnv.put(propName, propVal);
436     }
437
438     public Object JavaDoc removeFromEnvironment(String JavaDoc propName) throws NamingException JavaDoc {
439    if (TraceCarol.isDebugJndiCarol()) {
440             TraceCarol.debugJndiCarol("ConfFileInitialContext.removeFromEnvironment(\""+propName+"\")");
441         }
442         if (fileEnv == null) return null;
443    return fileEnv.remove(propName);
444     }
445     public Hashtable JavaDoc getEnvironment() throws NamingException JavaDoc {
446    if (TraceCarol.isDebugJndiCarol()) {
447             TraceCarol.debugJndiCarol("ConfFileInitialContext.getEnvironment()");
448         }
449    if (fileEnv == null) {
450        fileEnv = new Hashtable JavaDoc();
451    }
452         return fileEnv;
453     }
454
455     public void close() throws NamingException JavaDoc {
456    if (TraceCarol.isDebugJndiCarol()) {
457             TraceCarol.debugJndiCarol("ConfFileInitialContext.close()");
458         }
459     }
460
461     public String JavaDoc getNameInNamespace() throws NamingException JavaDoc {
462    if (TraceCarol.isDebugJndiCarol()) {
463             TraceCarol.debugJndiCarol("ConfFileInitialContext.getNameInNamespace()");
464         }
465    return "conffileContext";
466     }
467
468     /**
469      * Just the name of the class without the package.
470      * @param c Full class name.
471      * @return Class name without the package.
472      */

473     private String JavaDoc simpleClass(String JavaDoc c) {
474    return c.substring(c.lastIndexOf('.') +1);
475     }
476
477     // Class for enumerating name/class pairs
478
class ConfFileNames implements NamingEnumeration JavaDoc {
479         Enumeration JavaDoc names;
480
481         ConfFileNames (Enumeration JavaDoc names) {
482             this.names = names;
483         }
484
485         public boolean hasMoreElements() {
486             return names.hasMoreElements();
487         }
488
489         public boolean hasMore() throws NamingException JavaDoc {
490             return hasMoreElements();
491         }
492
493         public Object JavaDoc nextElement() {
494             String JavaDoc name = (String JavaDoc)names.nextElement();
495             String JavaDoc className = bindings.get(name).getClass().getName();
496             return new NameClassPair JavaDoc(name, className);
497         }
498
499         public Object JavaDoc next() throws NamingException JavaDoc {
500             return nextElement();
501         }
502
503         public void close() throws NamingException JavaDoc {
504        names=null;
505         }
506     }
507
508     // Class for enumerating bindings
509
class ConfFileBindings implements NamingEnumeration JavaDoc {
510         Enumeration JavaDoc names;
511
512         ConfFileBindings (Enumeration JavaDoc names) {
513             this.names = names;
514         }
515
516         public boolean hasMoreElements() {
517             return names.hasMoreElements();
518         }
519
520         public boolean hasMore() throws NamingException JavaDoc {
521             return hasMoreElements();
522         }
523
524         public Object JavaDoc nextElement() {
525             String JavaDoc name = (String JavaDoc)names.nextElement();
526             return new Binding JavaDoc(name, bindings.get(name));
527         }
528
529         public Object JavaDoc next() throws NamingException JavaDoc {
530             return nextElement();
531         }
532
533    public void close() throws NamingException JavaDoc {
534        names = null;
535    }
536     }
537
538     private void parseConfFile(String JavaDoc path) {
539       //System.out.println("parseConfFile");
540
File JavaDoc file = new File JavaDoc(path); // file.getCanonicalPath());
541
ConfigToContextParser parser = null;
542       try {
543         parser = new ConfigToContextParser(new FileInputStream JavaDoc(file));
544       }
545       catch (Exception JavaDoc e){
546         System.err.println("Error in forming FileInputStream");
547       }
548       int ii = bindings.size();
549       try {
550         parser.process(this.envContext);
551       }
552       catch (Exception JavaDoc e) {
553         System.err.println("Error in processing conf file");
554         e.printStackTrace();
555       }
556     }
557
558 }
559
Popular Tags