KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > configuration > JNDIConfiguration


1 package net.myvietnam.mvncore.configuration;
2 /* ====================================================================
3  * The Apache Software License, Version 1.1
4  *
5  * Copyright (c) 1999-2003 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution, if
21  * any, must include the following acknowledgement:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgement may appear in the software itself,
25  * if and wherever such third-party acknowledgements normally appear.
26  *
27  * 4. The names "The Jakarta Project", "Commons", and "Apache Software
28  * Foundation" must not be used to endorse or promote products derived
29  * from this software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache"
33  * nor may "Apache" appear in their names without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 import java.util.ArrayList JavaDoc;
56 import java.util.Iterator JavaDoc;
57 import java.util.List JavaDoc;
58 import java.util.NoSuchElementException JavaDoc;
59 import java.util.Properties JavaDoc;
60 import java.util.Vector JavaDoc;
61 import javax.naming.Binding JavaDoc;
62 import javax.naming.Context JavaDoc;
63 import javax.naming.InitialContext JavaDoc;
64 import javax.naming.NamingEnumeration JavaDoc;
65 import javax.naming.NamingException JavaDoc;
66 import org.apache.commons.lang.StringUtils;
67 import org.apache.commons.logging.Log;
68 import org.apache.commons.logging.LogFactory;
69 /**
70  * This Configuration class allows you to interface with a JNDI datasource.
71  *
72  * @author <a HREF="mailto:epugh@upstate.com">Eric Pugh</a>
73  * @version $Id: JNDIConfiguration.java,v 1.3 2004/10/06 09:12:30 minhnn Exp $
74  */

75 public class JNDIConfiguration
76     extends BaseConfiguration
77     implements Configuration
78 {
79     private static Log log = LogFactory.getLog(JNDIConfiguration.class);
80     private String JavaDoc prefix;
81     private Context JavaDoc envCtx;
82     private List JavaDoc clearedProperties = new ArrayList JavaDoc();
83     /**
84      * Creates an empty JNDIConfiguration object which can then
85      * be added some other Configuration files
86      */

87     public JNDIConfiguration()
88     {
89     }
90     /**
91      * JNDIConfigurations can not be added to
92      *
93      * @param key The Key to add the property to.
94      * @param token The Value to add.
95      */

96     public void addProperty(String JavaDoc key, Object JavaDoc token)
97     {
98         throw new Error JavaDoc("This operation is not supported");
99     }
100     /**
101      * This method recursive traverse the JNDI tree, looking for Context objects.
102      * When it finds them, it traverses them as well. Otherwise it just adds the
103      * values to the list of keys found.
104      * @param keys All the keys that have been found.
105      * @param enum An enumeration of all the elements found at a specific context
106      * @param key What key we are building on.
107      * @throws NamingException If JNDI has an issue.
108      */

109     private void recursiveGetKeys(
110         List JavaDoc keys,
111         NamingEnumeration JavaDoc enumeration,
112         String JavaDoc key)
113         throws NamingException JavaDoc
114     {
115         while (enumeration.hasMoreElements())
116         {
117             Binding JavaDoc binding = (Binding JavaDoc) enumeration.next();
118             StringBuffer JavaDoc newKey = new StringBuffer JavaDoc();
119             newKey.append(key);
120             if (newKey.length() > 0)
121             {
122                 newKey.append(".");
123             }
124             newKey.append(binding.getName());
125             if (binding.getObject() instanceof Context JavaDoc)
126             {
127                 Context JavaDoc c = (Context JavaDoc) binding.getObject();
128                 NamingEnumeration JavaDoc enum2 = c.listBindings("");
129                 recursiveGetKeys(keys, enum2, newKey.toString());
130             }
131             else
132             {
133                 if (!keys.contains(newKey.toString()))
134                 {
135                     keys.add(newKey.toString());
136                 }
137             }
138         }
139     }
140     /**
141      * Get the list of the keys contained in the configuration
142      * repository.
143      *
144      * @return An Iterator.
145      */

146     public Iterator JavaDoc getKeys()
147     {
148         return getKeys("");
149     }
150     /**
151      * Get the list of the keys contained in the configuration
152      * repository that match a passed in beginning pattern.
153      *
154      * @param key the key pattern to match on.
155      * @return An Iterator.
156      */

157     public Iterator JavaDoc getKeys(String JavaDoc key)
158     {
159         List JavaDoc keys = new ArrayList JavaDoc();
160         try
161         {
162             String JavaDoc[] splitKeys = StringUtils.split(key, ".");
163             for (int i = 0; i < splitKeys.length; i++)
164             {
165                 keys.add(splitKeys[i]);
166             }
167             Context JavaDoc context = null;
168             if (keys.size() == 0)
169             {
170                 context = getContext();
171             }
172             else
173             {
174                 context =
175                     getStartingContextPoint(
176                         keys,
177                         getContext().listBindings(""));
178             }
179             if (context != null)
180             {
181                 NamingEnumeration JavaDoc enumeration = context.listBindings("");
182                 recursiveGetKeys(keys, enumeration, key);
183             }
184         }
185         catch (NamingException JavaDoc ne)
186         {
187             log.warn(ne);
188         }
189         return keys.iterator();
190     }
191     /**
192      * Because JNDI is based on a tree configuration, we need to filter down the
193      * tree, till we find the Context specified by the key to start from.
194      * Otherwise return null.
195      *
196      * @param The key (or name) of the Context we are looking to start from.
197      * @return The context at that key's location in the JNDI tree, or null if not found
198      * @throws NamingException if JNDI has an issue
199      */

200     private Context JavaDoc getStartingContextPoint(List JavaDoc keys, NamingEnumeration JavaDoc enumeration)
201         throws NamingException JavaDoc
202     {
203         String JavaDoc keyToSearchFor = (String JavaDoc) keys.get(0);
204         log.debug("Key to search for is " + keyToSearchFor);
205         while (enumeration.hasMoreElements())
206         {
207             Binding JavaDoc binding = (Binding JavaDoc) enumeration.next();
208             log.debug(
209                 "Binding for name: "
210                     + binding.getName()
211                     + ", object:"
212                     + binding.getObject()
213                     + ", class:"
214                     + binding.getClassName());
215             if (binding.getObject() instanceof Context JavaDoc
216                 && binding.getName().equals(keyToSearchFor))
217             {
218                 keys.remove(0);
219                 Context JavaDoc c = (Context JavaDoc) binding.getObject();
220                 if (keys.size() > 0)
221                 {
222                     return getStartingContextPoint(keys, c.listBindings(""));
223                 }
224                 else
225                 {
226                     return c;
227                 }
228             }
229         }
230         return null;
231     }
232     /**
233      * Get a list of properties associated with the given
234      * configuration key.
235      *
236      * @param key The configuration key.
237      * @return The associated properties if key is found.
238      * @throws ClassCastException is thrown if the key maps to an
239      * object that is not a String/Vector.
240      * @throws IllegalArgumentException if one of the tokens is
241      * malformed (does not contain an equals sign).
242      * @see #getProperties(String, Properties)
243      */

244     public Properties JavaDoc getProperties(String JavaDoc key)
245     {
246         throw new Error JavaDoc("This operation is not supported");
247     }
248     public boolean isEmpty()
249     {
250         try
251         {
252             NamingEnumeration JavaDoc enumeration = getContext().listBindings("");
253             return !enumeration.hasMore();
254         }
255         catch (NamingException JavaDoc ne)
256         {
257             log.warn(ne);
258             return true;
259         }
260     }
261     /**
262      * Gets a property from the configuration.
263      *
264      * @param key property to retrieve
265      * @return value as object. Will return user value if exists,
266      * if not then default value if exists, otherwise null
267      */

268     public Object JavaDoc getProperty(String JavaDoc key)
269     {
270         throw new Error JavaDoc("This operation is not supported");
271     }
272     /**
273      * Set a property, this will replace any previously
274      * set values. Set values is implicitly a call
275      * to clearProperty(key), addProperty(key,value).
276      *
277      * @param key
278      * @param value
279      */

280     public void setProperty(String JavaDoc key, Object JavaDoc value)
281     {
282         throw new Error JavaDoc("This operation is not supported");
283     }
284     /**
285      * Clear a property in the configuration. Just marks it as cleared,
286      * doesn't change the underlying JNDI data source.
287      *
288      * @param key the key to remove along with corresponding value.
289      */

290     public void clearProperty(String JavaDoc key)
291     {
292         if (!clearedProperties.contains(key))
293         {
294             clearedProperties.add(key);
295         }
296     }
297     /**
298      * check if the configuration contains the key, or the key
299      * has been removed.
300      */

301     public boolean containsKey(String JavaDoc key)
302     {
303         if (clearedProperties.contains(key))
304         {
305             return false;
306         }
307         key = StringUtils.replace(key, ".", "/");
308         try
309         {
310             // throws a NamingException if JNDI doesn't contain the key.
311
getContext().lookup(key);
312             return true;
313         }
314         catch (javax.naming.NamingException JavaDoc ne)
315         {
316             return false;
317         }
318     }
319     /**
320      * Create an ExtendedProperties object that is a subset
321      * of this one. Take into account duplicate keys
322      * by using the setProperty() in ExtendedProperties.
323      *
324      * @param prefix
325      */

326     public Configuration subset(String JavaDoc prefix)
327     {
328         BaseConfiguration c = new BaseConfiguration();
329         Iterator JavaDoc keys = this.getKeys();
330         boolean validSubset = false;
331         while (keys.hasNext())
332         {
333             Object JavaDoc key = keys.next();
334             if (key instanceof String JavaDoc && ((String JavaDoc) key).startsWith(prefix))
335             {
336                 if (!validSubset)
337                 {
338                     validSubset = true;
339                 }
340                 String JavaDoc newKey = null;
341                 /*
342                  * Check to make sure that c.subset(prefix) doesn't blow up when
343                  * there is only a single property with the key prefix. This is
344                  * not a useful subset but it is a valid subset.
345                  */

346                 if (((String JavaDoc) key).length() == prefix.length())
347                 {
348                     newKey = prefix;
349                 }
350                 else
351                 {
352                     newKey = ((String JavaDoc) key).substring(prefix.length() + 1);
353                 }
354                 /*
355                  * use addPropertyDirect() - this will plug the data as is into
356                  * the Map, but will also do the right thing re key accounting
357                  */

358                 Object JavaDoc value = getValueFromJNDI(key.toString());
359                 if (value instanceof String JavaDoc)
360                 {
361                     c.addPropertyDirect(newKey, interpolate((String JavaDoc) value));
362                 }
363                 else
364                 {
365                     c.addPropertyDirect(newKey, value);
366                 }
367             }
368         }
369         if (validSubset)
370         {
371             return c;
372         }
373         else
374         {
375             return null;
376         }
377     }
378
379     /**
380      * Get a boolean associated with the given configuration key.
381      *
382      * @param key The configuration key.
383      * @param defaultValue The default value.
384      * @return The associated boolean if key is found and has valid
385      * format, default value otherwise.
386      * @throws ClassCastException is thrown if the key maps to an
387      * object that is not a Boolean.
388      */

389     public Boolean JavaDoc getBoolean(String JavaDoc key, Boolean JavaDoc defaultValue)
390     {
391         Object JavaDoc value = getValueFromJNDI(key);
392         if (value instanceof Boolean JavaDoc)
393         {
394             return (Boolean JavaDoc) value;
395         }
396         else if (value instanceof String JavaDoc)
397         {
398             return testBoolean((String JavaDoc) value);
399         }
400         else if (value == null)
401         {
402             if (defaults != null)
403             {
404                 return defaults.getBoolean(key, defaultValue);
405             }
406             else
407             {
408                 return defaultValue;
409             }
410         }
411         else
412         {
413             throw new ClassCastException JavaDoc(
414                 '\'' + key + "' doesn't map to a Boolean object");
415         }
416     }
417
418     /**
419      * Get a byte associated with the given configuration key.
420      *
421      * @param key The configuration key.
422      * @param defaultValue The default value.
423      * @return The associated byte if key is found and has valid format, default
424      * value otherwise.
425      * @throws ClassCastException is thrown if the key maps to an object that
426      * is not a Byte.
427      * @throws NumberFormatException is thrown if the value mapped by the key
428      * has not a valid number format.
429      */

430     public Byte JavaDoc getByte(String JavaDoc key, Byte JavaDoc defaultValue)
431     {
432         Object JavaDoc value = getValueFromJNDI(key);
433         if (value instanceof Byte JavaDoc)
434         {
435             return (Byte JavaDoc) value;
436         }
437         else if (value instanceof String JavaDoc)
438         {
439             Byte JavaDoc b = new Byte JavaDoc((String JavaDoc) value);
440             return b;
441         }
442         else if (value == null)
443         {
444             return defaultValue;
445         }
446         else
447         {
448             throw new ClassCastException JavaDoc(
449                 '\'' + key + "' doesn't map to a Byte object");
450         }
451     }
452
453     /**
454      * Get a double associated with the given configuration key.
455      *
456      * @param key The configuration key.
457      * @param defaultValue The default value.
458      * @return The associated double if key is found and has valid
459      * format, default value otherwise.
460      * @throws ClassCastException is thrown if the key maps to an
461      * object that is not a Double.
462      * @throws NumberFormatException is thrown if the value mapped
463      * by the key has not a valid number format.
464      */

465     public Double JavaDoc getDouble(String JavaDoc key, Double JavaDoc defaultValue)
466     {
467         Object JavaDoc value = this.getValueFromJNDI(key);
468         if (value instanceof Double JavaDoc)
469         {
470             return (Double JavaDoc) value;
471         }
472         else if (value instanceof String JavaDoc)
473         {
474             Double JavaDoc d = new Double JavaDoc((String JavaDoc) value);
475             return d;
476         }
477         else if (value == null)
478         {
479             return defaultValue;
480         }
481         else
482         {
483             throw new ClassCastException JavaDoc(
484                 '\'' + key + "' doesn't map to a Double object");
485         }
486     }
487
488     /**
489      * Get a float associated with the given configuration key.
490      *
491      * @param key The configuration key.
492      * @param defaultValue The default value.
493      * @return The associated float if key is found and has valid
494      * format, default value otherwise.
495      * @throws ClassCastException is thrown if the key maps to an
496      * object that is not a Float.
497      * @throws NumberFormatException is thrown if the value mapped
498      * by the key has not a valid number format.
499      */

500     public Float JavaDoc getFloat(String JavaDoc key, Float JavaDoc defaultValue)
501     {
502         Object JavaDoc value = getValueFromJNDI(key);
503         if (value instanceof Float JavaDoc)
504         {
505             return (Float JavaDoc) value;
506         }
507         else if (value instanceof String JavaDoc)
508         {
509             Float JavaDoc f = new Float JavaDoc((String JavaDoc) value);
510             return f;
511         }
512         else if (value == null)
513         {
514             return defaultValue;
515         }
516         else
517         {
518             throw new ClassCastException JavaDoc(
519                 '\'' + key + "' doesn't map to a Float object");
520         }
521     }
522
523     /**
524      * Get a int associated with the given configuration key.
525      *
526      * @param key The configuration key.
527      * @param defaultValue The default value.
528      * @return The associated int if key is found and has valid format, default
529      * value otherwise.
530      * @throws ClassCastException is thrown if the key maps to an object that
531      * is not a Integer.
532      * @throws NumberFormatException is thrown if the value mapped by the key
533      * has not a valid number format.
534      */

535     public Integer JavaDoc getInteger(String JavaDoc key, Integer JavaDoc defaultValue)
536     {
537         Object JavaDoc value = getValueFromJNDI(key);
538         if (value instanceof Integer JavaDoc)
539         {
540             return (Integer JavaDoc) value;
541         }
542         else if (value instanceof String JavaDoc)
543         {
544             Integer JavaDoc i = new Integer JavaDoc((String JavaDoc) value);
545             return i;
546         }
547         else if (value == null)
548         {
549             return defaultValue;
550         }
551         else
552         {
553             throw new ClassCastException JavaDoc(
554                 '\'' + key + "' doesn't map to a Integer object");
555         }
556     }
557
558     /**
559      * Get a long associated with the given configuration key.
560      *
561      * @param key The configuration key.
562      * @param defaultValue The default value.
563      * @return The associated long if key is found and has valid
564      * format, default value otherwise.
565      * @throws ClassCastException is thrown if the key maps to an
566      * object that is not a Long.
567      * @throws NumberFormatException is thrown if the value mapped
568      * by the key has not a valid number format.
569      */

570     public Long JavaDoc getLong(String JavaDoc key, Long JavaDoc defaultValue)
571     {
572         Object JavaDoc value = getValueFromJNDI(key);
573         if (value instanceof Long JavaDoc)
574         {
575             return (Long JavaDoc) value;
576         }
577         else if (value instanceof String JavaDoc)
578         {
579             Long JavaDoc l = new Long JavaDoc((String JavaDoc) value);
580             return l;
581         }
582         else if (value == null)
583         {
584             return defaultValue;
585         }
586         else
587         {
588             throw new ClassCastException JavaDoc(
589                 '\'' + key + "' doesn't map to a Long object");
590         }
591     }
592
593     /**
594      * Get a short associated with the given configuration key.
595      *
596      * @param key The configuration key.
597      * @param defaultValue The default value.
598      * @return The associated short if key is found and has valid
599      * format, default value otherwise.
600      * @throws ClassCastException is thrown if the key maps to an
601      * object that is not a Short.
602      * @throws NumberFormatException is thrown if the value mapped
603      * by the key has not a valid number format.
604      */

605     public Short JavaDoc getShort(String JavaDoc key, Short JavaDoc defaultValue)
606     {
607         Object JavaDoc value = getValueFromJNDI(key);
608         if (value instanceof Short JavaDoc)
609         {
610             return (Short JavaDoc) value;
611         }
612         else if (value instanceof String JavaDoc)
613         {
614             Short JavaDoc s = new Short JavaDoc((String JavaDoc) value);
615             return s;
616         }
617         else if (value == null)
618         {
619             return defaultValue;
620         }
621         else
622         {
623             throw new ClassCastException JavaDoc(
624                 '\'' + key + "' doesn't map to a Short object");
625         }
626     }
627
628     /**
629      * Get a string associated with the given configuration key.
630      *
631      * @param key The configuration key.
632      * @param defaultValue The default value.
633      * @return The associated string if key is found, default value otherwise.
634      * @throws ClassCastException is thrown if the key maps to an object that
635      * is not a String.
636      */

637     public String JavaDoc getString(String JavaDoc key, String JavaDoc defaultValue)
638     {
639         try
640         {
641             Object JavaDoc o = getValueFromJNDI(key);
642             if (o == null)
643             {
644                 return defaultValue;
645             }
646             else
647             {
648                 return (String JavaDoc) o;
649             }
650         }
651         catch (NoSuchElementException JavaDoc nsee)
652         {
653             return defaultValue;
654         }
655     }
656     /**
657      * Get an array of strings associated with the given configuration
658      * key.
659      *
660      * @param key The configuration key.
661      * @return The associated string array if key is found.
662      * @throws ClassCastException is thrown if the key maps to an
663      * object that is not a String/Vector of Strings.
664      */

665     public String JavaDoc[] getStringArray(String JavaDoc key)
666     {
667         Object JavaDoc value = getValueFromJNDI(key);
668         String JavaDoc[] tokens;
669         if (value instanceof String JavaDoc)
670         {
671             tokens = new String JavaDoc[1];
672             tokens[0] = interpolate((String JavaDoc) value);
673         }
674         else if (value instanceof Container)
675         {
676             tokens = new String JavaDoc[((Container) value).size()];
677             for (int i = 0; i < tokens.length; i++)
678             {
679                 tokens[i] = interpolate((String JavaDoc) ((Container) value).get(i));
680             }
681         }
682         else if (value == null)
683         {
684             tokens = new String JavaDoc[0];
685         }
686         else
687         {
688             throw new ClassCastException JavaDoc(
689                 '\'' + key + "' doesn't map to a String/Vector object");
690         }
691         return tokens;
692     }
693
694     /**
695      * Get a Vector of strings associated with the given configuration key.
696      * Typically this will be just a single item, as you can't have multiple
697      * properties with the same name.
698      *
699      * @param key The configuration key.
700      * @param defaultValue The default value.
701      * @return The associated Vector.
702      */

703     public Vector JavaDoc getVector(String JavaDoc key, Vector JavaDoc defaultValue)
704     {
705         try
706         {
707             Object JavaDoc value = this.getValueFromJNDI(key);
708             if (value != null)
709             {
710                 Vector JavaDoc v = new Vector JavaDoc(1);
711                 v.add(value.toString());
712                 return v;
713             }
714             else
715             {
716                 if (defaultValue == null)
717                 {
718                     defaultValue = new Vector JavaDoc();
719                 }
720                 return defaultValue;
721             }
722         }
723         catch (NoSuchElementException JavaDoc nsse)
724         {
725             return defaultValue;
726         }
727     }
728     /**
729      * @return String
730      */

731     public String JavaDoc getPrefix()
732     {
733         return prefix;
734     }
735     /**
736      * Sets the prefix.
737      * @param prefix The prefix to set
738      */

739     public void setPrefix(String JavaDoc prefix)
740     {
741         this.prefix = prefix;
742     }
743     private Object JavaDoc getValueFromJNDI(String JavaDoc key)
744     {
745         if (clearedProperties.contains(key))
746         {
747             return null;
748         }
749         try
750         {
751             key = StringUtils.replace(key, ".", "/");
752             return getContext().lookup(key);
753         }
754         catch (java.util.NoSuchElementException JavaDoc nsse)
755         {
756             return null;
757         }
758         catch (NamingException JavaDoc ne)
759         {
760             return null;
761         }
762     }
763     private Context JavaDoc getContext() throws NamingException JavaDoc
764     {
765         if (envCtx == null)
766         {
767             Context JavaDoc initCtx = new InitialContext JavaDoc();
768             envCtx = (Context JavaDoc) initCtx.lookup(getPrefix());
769         }
770         return envCtx;
771     }
772 }
773
Popular Tags