KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > tbutils > res > JNDIResourceProvider


1 package com.tonbeller.tbutils.res;
2
3 import java.util.Collection JavaDoc;
4 import java.util.Collections JavaDoc;
5
6 import javax.naming.Context JavaDoc;
7 import javax.naming.InitialContext JavaDoc;
8 import javax.naming.NameNotFoundException JavaDoc;
9 import javax.naming.NamingException JavaDoc;
10 import javax.naming.NoInitialContextException JavaDoc;
11
12 import org.apache.log4j.Logger;
13 /**
14  * Adapter for java naming
15  */

16
17 public class JNDIResourceProvider implements ResourceProvider {
18   Context JavaDoc context = null;
19   boolean disabled = false;
20   private static Logger logger = Logger.getLogger(JNDIResourceProvider.class);
21   public static final String JavaDoc JNDI_NULL = "jndi.null";
22
23   public String JavaDoc getString(String JavaDoc key) {
24     if (disabled)
25       return null;
26     try {
27       if (context == null) {
28         Context JavaDoc initCtx = new InitialContext JavaDoc();
29         context = (Context JavaDoc) initCtx.lookup("java:comp/env");
30       }
31       Object JavaDoc obj = context.lookup(key);
32       if (obj == null) {
33         if (logger.isInfoEnabled())
34           logger.info("key is null: " + key);
35         return null;
36       }
37       String JavaDoc str = obj.toString();
38       
39       // there MUST be a value in web.xml
40
if (JNDI_NULL.equals(str)) {
41         if (logger.isInfoEnabled())
42           logger.info("key is jndi.null: " + key);
43         return null;
44       }
45       
46       return str;
47     } catch (NameNotFoundException JavaDoc e) {
48       if (logger.isInfoEnabled())
49         logger.info("key not found: " + key);
50       return null;
51     } catch (NoInitialContextException JavaDoc e) {
52       logger.warn("JNDI Context not found, assuming test environment");
53       disabled = true;
54       return null;
55     } catch (NamingException JavaDoc e) {
56       logger.error(key, e);
57       return null;
58     }
59   }
60
61   public Collection JavaDoc keySet() {
62     return Collections.EMPTY_SET;
63   }
64
65   public void close() {
66     try {
67       if (context != null)
68         context.close();
69     } catch (NamingException JavaDoc e) {
70       logger.error("error closing context", e);
71     } finally {
72       context = null;
73     }
74   }
75
76   public void dump(Dumper d) {
77     d.dump(this);
78   }
79   
80   public String JavaDoc getName() {
81     return "JNDI Lookup " + (disabled ? "disabled" : "enabled");
82   }
83
84 }
85
Popular Tags