KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > util > JNDIAdapter


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: JNDIAdapter.java,v 1.1 2005/07/13 11:09:06 slobodan Exp $
22  */

23
24 package org.enhydra.util;
25
26 import java.util.Hashtable JavaDoc;
27 import java.util.StringTokenizer JavaDoc;
28 import java.util.Vector JavaDoc;
29
30 import javax.naming.Context JavaDoc;
31 import javax.naming.InitialContext JavaDoc;
32 import javax.naming.NameClassPair JavaDoc;
33 import javax.naming.NamingEnumeration JavaDoc;
34 import javax.naming.NamingException JavaDoc;
35
36 import com.lutris.util.KeywordValueException;
37
38 /**
39  * This class is used for reading configuration parameters using JNDI. It
40  * coresponds between InitialContext object and application's Config and
41  * ConfigFile object.
42  *
43  * @author Tanja Jovanovic
44  * @version 1.0
45  */

46 public class JNDIAdapter {
47
48 /**
49  * Passed as the "count" argument to getInts, getLongs(), etc. to
50  * indicate that all available elements are to be retrieved.
51  */

52  private static final int GET_ALL = -1;
53
54 /**
55  * Context
56  */

57  private Context JavaDoc context = null;
58  private Context JavaDoc envCtx = null;
59
60  /**
61   * Absolute path to application configuration file.
62   */

63  public final static String JavaDoc FILE_JNDI_ABS_PATH_NAME = "fileJndiAbsPathName";
64
65  /**
66   * Application component Context environment.
67   */

68  public final static String JavaDoc CONTEXT_FOR_ENV_BIND = "contextForEnvToBind";
69
70
71 /**
72  * Default constructor for empty adapter.
73  */

74   public JNDIAdapter() {
75     try {
76       context = new InitialContext JavaDoc();
77     }
78     catch (NamingException JavaDoc ex){
79 // System.err.println("Error in creating initial context");
80
context = null;
81     }
82
83     try {
84       envCtx = (Context JavaDoc)context.lookup("java:comp/env");
85     }
86     catch (NamingException JavaDoc ex){
87 // System.err.println("Error in creating J2EE environment of initial context");
88
envCtx = null;
89
90    }
91 // try {
92
// for (NamingEnumeration e = envCtx.list(""); e.hasMore();) {
93
// String str = (String)e.next();
94
// System.err.println("elem= "+str);
95
// } // for
96
// }
97
// catch (NamingException ex){
98
// System.err.println("Error in creating initial context 2");
99
// ex.printStackTrace();
100
// }
101

102  /*
103     Context ccc = null;
104      try {
105       ccc = (Context)context.lookup("java:comp/env");
106       if (ccc != null)
107         System.err.println("ccc pronadjen= " + ccc.getClass().toString());
108       else
109         System.err.println("ccc nije pronadjen!!!");
110     }
111     catch (NamingException ex){
112       System.err.println("Error in creating initial context 2");
113       ex.printStackTrace();
114     }
115
116      try {
117       NamingEnumeration ne = ccc.listBindings("");
118       if (ne.hasMore())
119         System.err.println("hasMore" );
120       else
121         System.err.println("not hasMore ");
122     }
123     catch (NamingException ex){
124       System.err.println("Error in creating initial context 2");
125       ex.printStackTrace();
126     }
127 */

128
129 /*
130      Context ccc = null;
131      try {
132       ccc = (Context)context.lookup("java:comp/env");
133       if (ccc != null)
134         System.err.println("ccc pronadjen= " + ccc.getClass().toString());
135       else
136         System.err.println("ccc nije pronadjen!!!");
137     }
138     catch (NamingException ex){
139       System.err.println("Error in creating initial context 2");
140       ex.printStackTrace();
141     }
142
143     if (ccc != null){
144       try {
145         Object ppp = ccc.lookup("probaTest");
146         if (ppp != null)
147           System.err.println("ppp pronadjen= " + ppp.toString());
148         else
149           System.err.println("ppp nije pronadjen!!!");
150       }
151       catch (NamingException ex){
152         System.err.println("Error in creating initial context 4");
153         ex.printStackTrace();
154       }
155     }
156
157      try {
158       Object o = context.lookup("java:comp/env/probaTest");
159       if (o != null)
160         System.err.println("obj2 pronadjen= " + o.toString());
161       else
162         System.err.println("obj2 nije pronadjen!!!");
163     }
164     catch (NamingException ex){
165       System.err.println("Error in creating initial context 3");
166     }
167 */

168
169 /*
170     try {
171       Object o = context.lookup("vrati_se");
172       if (o != null)
173         System.err.println("vrati_se pronadjen!!! " + o.toString());
174       else
175         System.err.println("vrati_se nije pronadjen!!!");
176     }
177     catch (NamingException ex){
178       System.err.println("Error in creating initial context 2");
179     }
180     try {
181       Object o = context.lookup("tanja");
182       if (o != null)
183         System.err.println("tanja pronadjena!!! " + o.toString());
184       else
185         System.err.println("tanja nije pronadjena!!!");
186     }
187     catch (NamingException ex){
188       System.err.println("Error in creating initial context 3");
189     }
190 */

191   }
192
193   /**
194    * Constructor with defined file. This is used if file other than web.xml is
195    * used for reading Application's parameters with JNDI.
196    *
197    * @param fileAbsolutePath absolute file path.
198    * @param factoryClass InitialContextFactory class used for creating
199    * application InitialContext.
200    */

201   public JNDIAdapter(String JavaDoc fileAbsolutePath, String JavaDoc factoryClass) {
202     boolean toCompileFile = false;
203     try {
204       if ((factoryClass != null) && (!factoryClass.equals(""))) {
205         Hashtable JavaDoc env = new Hashtable JavaDoc();
206         env.put(Context.INITIAL_CONTEXT_FACTORY, factoryClass);
207         context = new InitialContext JavaDoc(env);
208         toCompileFile = true;
209       }
210       else {
211         System.err.println("Warning: InitialContextFactory class not defined. Default will be used.");
212         context = new InitialContext JavaDoc();
213       }
214     }
215     catch (NamingException JavaDoc ex){
216 // System.err.println("Error in creating initial context");
217
context = null;
218     }
219     try {
220       envCtx = (Context JavaDoc)context.lookup("java:comp/env");
221     }
222     catch (NamingException JavaDoc ex){
223 // System.err.println("Error in creating J2EE environment of initial context");
224
envCtx = null;
225     }
226
227     try {
228       if (toCompileFile){
229         context.rebind(CONTEXT_FOR_ENV_BIND, envCtx);
230         context.rebind(FILE_JNDI_ABS_PATH_NAME, fileAbsolutePath);
231       }
232     }
233     catch (Exception JavaDoc ex){
234        System.err.println("Error in creating JNDIAdapter(String)");
235        //ex.printStackTrace();
236
}
237
238   }
239
240   /**
241    * Returns <code>true</code> if the specified key is found,
242    * <code>false</code> otherwise.
243    * @param key The key whose existence is to be tested.
244    * @return <code>true</code> if the key was found, otherwise <code>false</code>.
245    */

246   public boolean containsKey(String JavaDoc key) {
247     try {
248       if (envCtx.lookup(key) != null)
249         return true;
250     }
251     catch (Exception JavaDoc ex){ }
252
253     try {
254       if (envCtx.lookup(key+"[]") != null)
255         return true;
256       else
257         return false;
258     }
259     catch (Exception JavaDoc ex){
260         return false;
261     }
262   }
263
264     /**
265      * Get the keywords in the table. This is only the keywords at the top
266      * level, its doesn't recurse.
267      *
268      * @return An string array of the keywords.
269      */

270     public synchronized String JavaDoc[] keys() {
271       Vector JavaDoc keyList = null;
272       try {
273         if (context != null) {
274             NamingEnumeration JavaDoc enumeration = envCtx.list("");
275           if ((enumeration != null) && (enumeration.hasMore())) {
276             keyList = new Vector JavaDoc ();
277             String JavaDoc toAdd = null;
278             for (NamingEnumeration JavaDoc en = enumeration; en.hasMore();) {
279                toAdd = ((NameClassPair JavaDoc)en.next()).getName();
280                keyList.addElement(toAdd);
281             } // for
282
}
283         }
284  // else
285
// System.err.println("enumeration == null");
286
}
287       catch (NamingException JavaDoc ex){
288         System.err.println("Error in keys() method");
289         //ex.printStackTrace();
290
keyList = null;
291       }
292
293       String JavaDoc [] keyStrings = null;
294       if (keyList != null) {
295         keyStrings = new String JavaDoc [keyList.size()];
296         for (int idx = 0; idx < keyList.size (); idx++) {
297             keyStrings [idx] = (String JavaDoc) keyList.elementAt (idx);
298         }
299       }
300       return keyStrings;
301     }
302
303     /**
304      * Recursively get the keywords for the entire table. This returns the
305      * full keyword of all leaf values.
306      *
307      * @return An string array of the keywords.
308      */

309     public synchronized String JavaDoc [] leafKeys() {
310       NamingEnumeration JavaDoc keyEnum = null;
311       Vector JavaDoc keyList = new Vector JavaDoc ();
312       try {
313           keyEnum = envCtx.list("");
314       }
315       catch (NamingException JavaDoc ex){
316           System.err.println("Error in leafKeys() method");
317           //ex.printStackTrace();
318
keyEnum = null;
319       }
320       try {
321         if ((keyEnum != null) && (keyEnum.hasMore())) {
322           while (keyEnum.hasMore()) {
323              String JavaDoc key = ((NameClassPair JavaDoc)keyEnum.next()).getName();
324               Object JavaDoc value = envCtx.lookup(key);
325              if (implementsContextInterface(value)) {
326                  String JavaDoc[] subKeys = leafKeysInternal((Context JavaDoc)value);
327                     for (int idx = 0; idx < subKeys.length; idx++) {
328                         keyList.addElement( key+"/"+subKeys[idx]);
329                     }
330                 } else {
331                     keyList.addElement(key);
332                 }
333           }
334           }
335       }
336       catch (NamingException JavaDoc ex){
337           System.err.println("Error occured in leafKeys() method");
338           //ex.printStackTrace();
339
keyList = null;
340       }
341       if (keyList != null){
342         String JavaDoc [] keyStrings = new String JavaDoc[keyList.size()];
343         for (int idx = 0; idx < keyList.size(); idx++) {
344            keyStrings [idx] = (String JavaDoc)keyList.elementAt(idx);
345         }
346         return keyStrings;
347       }
348       return null;
349     }
350
351     private synchronized String JavaDoc [] leafKeysInternal(Context JavaDoc con) {
352       NamingEnumeration JavaDoc keyEnum = null;
353       Vector JavaDoc keyList = new Vector JavaDoc ();
354       try {
355         keyEnum = con.list("");
356       }
357       catch (NamingException JavaDoc ex){
358           System.err.println("Error in leafKeys() method");
359           //ex.printStackTrace();
360
keyEnum = null;
361       }
362       try {
363         if ((keyEnum != null) && (keyEnum.hasMore())) {
364           while (keyEnum.hasMore()) {
365              String JavaDoc key = ((NameClassPair JavaDoc)keyEnum.next()).getName();
366              Object JavaDoc value = con.lookup(key);
367
368              if (implementsContextInterface(value)) {
369
370                  String JavaDoc[] subKeys = leafKeysInternal((Context JavaDoc)value);
371                     for (int idx = 0; idx < subKeys.length; idx++) {
372                         keyList.addElement( key + "/" + subKeys[idx]);
373                     }
374                 } else {
375                     keyList.addElement(key);
376                 }
377           }
378           }
379       }
380       catch (NamingException JavaDoc ex){
381           System.err.println("Error occured in leafKeys() method");
382           //ex.printStackTrace();
383
keyList = null;
384       }
385       if (keyList != null){
386         String JavaDoc [] keyStrings = new String JavaDoc[keyList.size()];
387         for (int idx = 0; idx < keyList.size(); idx++) {
388            keyStrings [idx] = (String JavaDoc)keyList.elementAt(idx);
389         }
390         return keyStrings;
391       }
392       return null;
393     }
394
395     /**
396      * Get the value of a field as an object.
397      *
398      * @param keyword The keyword of the field. This can be a simple keyword
399      * or a recursive, dot-seperated keyword path.
400      * @return The object value or null if its not found.
401      * @exception KeywordValueException If the keyword is not syntactically
402      * legal or is a non-leaf element of the keyword is not a section.
403      */

404     public synchronized Object JavaDoc get(String JavaDoc keyword)
405                                       throws NamingException JavaDoc {
406       Object JavaDoc obj = null;
407       try {
408           obj = envCtx.lookup(keyword);
409       }
410       catch (Exception JavaDoc ex ){
411         obj = null;
412       }
413       if (obj != null)
414         return obj;
415       else {
416          return envCtx.lookup(keyword + "[]");
417        }
418     }
419
420     /**
421      * Get the value of a field as an object, return a default if it
422      * does not exist.
423      *
424      * @param keyword The keyword of the field. This can be a simple keyword
425      * or a recursive, dot-seperated keyword path.
426      * @param defaultValue The default value to return it the keyword does not
427      * exist.
428      * @return The object value or <CODE>defaultValue</CODE> if its not found.
429      * @exception KeywordValueException If the keyword is not syntactically
430      * legal or is a non-leaf element of the keyword is not a section.
431      */

432     public synchronized Object JavaDoc get(String JavaDoc keyword, Object JavaDoc defaultValue)
433                           throws NamingException JavaDoc {
434         Object JavaDoc value = null;
435         try {
436           value = get(keyword);
437         }
438         catch (Exception JavaDoc e){
439           value = null;
440         }
441         if (value == null) {
442             return defaultValue;
443         }
444         return value;
445     }
446
447     public synchronized Object JavaDoc getResource(String JavaDoc jndiName)
448                           throws NamingException JavaDoc {
449       Object JavaDoc obj = null;
450       try {
451          obj = context.lookup(jndiName);
452       }
453       catch (Exception JavaDoc ex ){
454         obj = null;
455 // ex.printStackTrace();
456
}
457       if (obj == null) {
458         try {
459            obj = envCtx.lookup(jndiName);
460         }
461         catch (Exception JavaDoc ex ){
462            obj = null;
463 // ex.printStackTrace();
464
}
465       }
466     return obj;
467     }
468
469     /**
470      * Sets the value of a field with the defined key.
471      *
472      * @param keyword The keyword of the field.
473      * @param value The new field value.
474      */

475     public synchronized void set(String JavaDoc keyword, String JavaDoc value) {
476         if (envCtx != null) {
477           try {
478             envCtx.rebind(keyword, value);
479           }
480           catch (NamingException JavaDoc ex){
481             //ex.printStackTrace();
482
}
483         }
484         else {
485 // should not happen
486
// TODO create envContext
487
}
488     }
489
490     /**
491      * Removes field with the defined key.
492      *
493      * @param keyword The keyword of the field.
494      */

495     public synchronized void remove(String JavaDoc keyword) {
496       if (envCtx != null) {
497         try {
498           envCtx.unbind(keyword);
499         }
500         catch (NamingException JavaDoc ex){
501           //System.err.println("Unbind error in remove method of JNDIApadter");
502
}
503       }
504     }
505
506     /**
507      * Converts to a string.
508      *
509      * @return Generate a string representation of this object.
510      */

511 /*
512     public synchronized String toString () {
513 // TODO
514 // return hashTable.toString();
515           return null;
516
517     }
518 */

519
520     /**
521      * Checks whether the object obj implements interface <code>javax.naming.Context</code>.
522      *
523      * @param obj Object for wich is checked whether is implementation of
524      * <code>javax.naming.Context</code> interface.
525      * @return true if object obj implements interface <code>javax.naming.Context</code>,
526      * otherwise false.
527      */

528     private static boolean implementsContextInterface(Object JavaDoc obj) {
529       Class JavaDoc[] interfaces = obj.getClass().getInterfaces();
530       int length = interfaces.length;
531       int i = 0;
532       while (i<length){
533         if (interfaces[i].getName().equals("javax.naming.Context"))
534           return true;
535         i++;
536       }
537       return false;
538     }
539
540     /**
541      * From Context String (delimiters are <code>/</code> signs) makes Config
542      * String (delimiters are <code>.</code> signs).
543      *
544      * @param oldString Context String
545      * @return Transformed Config String.
546      */

547     public static String JavaDoc makeConfigString (String JavaDoc oldString) {
548       if (oldString == null)
549         return null;
550       String JavaDoc newString = null;
551       newString = oldString.replaceAll("/", ".");
552       return newString;
553     }
554
555     /**
556      * From Config String (delimiters are <code>.</code> signs) makes Context
557      * String (delimiters are <code>/</code> signs).
558      *
559      * @param oldString Config String
560      * @return Transformed Context String.
561      */

562     public static String JavaDoc makeContextString (String JavaDoc oldString) {
563       if (oldString == null)
564         return null;
565       String JavaDoc newString = null;
566       int len = oldString.length();
567       if (len >0)
568         newString = new String JavaDoc("");
569       for (int i=0; i<len; i++){
570         char ch = oldString.charAt(i);
571         if (ch == '.') {
572           newString = newString + "/";
573         }
574         else {
575           newString = newString + ch;
576         }
577       }
578       return newString;
579     }
580
581     /**
582      * From String array makes String in which are String array elements
583      * separated with <code>,</code> sign.
584      *
585      * @param strings String array.
586      * @return Transformed String.
587      */

588     public static String JavaDoc makeStringFromStrings (String JavaDoc[] strings) {
589       if (strings == null)
590         return null;
591       String JavaDoc newString = null;
592       int len = strings.length;
593       if (len >0)
594         newString = strings[0].trim();
595       if (len > 1) {
596         for (int i=1; i<len; i++){
597            String JavaDoc str = strings[i].trim();
598            newString = newString + "," + str;
599         }
600       }
601       return newString;
602     }
603
604    /**
605     * Returns <code>true</code> if key has indicator that the field is array
606     * (the key ends with "[]")
607     *
608     * @param key The keyword of the field.
609     * @return <code>true</code> if key has indicator that the field is array,
610     * otherwise false.
611     */

612     public static boolean isArray(String JavaDoc key) {
613       int len = key.length();
614       if (len < 3)
615         return false;
616       if (key.substring(len-2).equals("[]"))
617         return true;
618       else
619         return false;
620     }
621
622   /**
623     * Removes array indicator (the key ends with "[]") if exists.
624     *
625     * @param key The keyword of the field.
626     * @return Keyword without "[]".
627     */

628     public String JavaDoc removeArrayMark (String JavaDoc key) {
629       if (isArray(key)) {
630         int len = key.length();
631         return key.substring(0, len-2);
632       }
633       else
634         return null;
635     }
636
637     /**
638      * Get the value of a field as String array.
639      *
640      * @param key The keyword of the field. This can be a simple keyword
641      * or a recursive, dot-seperated keyword path.
642      * @return The object value as String[] or null if its not found.
643      */

644     public String JavaDoc[] getStrings (String JavaDoc key) {
645       try {
646         Object JavaDoc returnObject = get(key);
647         if (returnObject.getClass().isArray()) {
648           return (String JavaDoc[])returnObject;
649         }
650         String JavaDoc oldValue = (String JavaDoc)returnObject;
651         StringTokenizer JavaDoc tok = new StringTokenizer JavaDoc(oldValue, new String JavaDoc(","));
652         String JavaDoc[] newValue = new String JavaDoc[tok.countTokens()];
653         int i = 0;
654         while (tok.hasMoreTokens()) {
655           newValue[i] = tok.nextToken().trim();
656           i++;
657         }
658         return newValue;
659       }
660       catch (Exception JavaDoc e){
661         //e.printStackTrace();
662
System.err.println("Error in getStrings() method of JNDIAdapter.");
663         return null;
664       }
665     }
666
667
668
669
670 }
671
Popular Tags