1 package com.tonbeller.tbutils.res; 2 3 import java.util.Collection ; 4 import java.util.Collections ; 5 6 import javax.naming.Context ; 7 import javax.naming.InitialContext ; 8 import javax.naming.NameNotFoundException ; 9 import javax.naming.NamingException ; 10 import javax.naming.NoInitialContextException ; 11 12 import org.apache.log4j.Logger; 13 16 17 public class JNDIResourceProvider implements ResourceProvider { 18 Context context = null; 19 boolean disabled = false; 20 private static Logger logger = Logger.getLogger(JNDIResourceProvider.class); 21 public static final String JNDI_NULL = "jndi.null"; 22 23 public String getString(String key) { 24 if (disabled) 25 return null; 26 try { 27 if (context == null) { 28 Context initCtx = new InitialContext (); 29 context = (Context ) initCtx.lookup("java:comp/env"); 30 } 31 Object 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 str = obj.toString(); 38 39 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 e) { 48 if (logger.isInfoEnabled()) 49 logger.info("key not found: " + key); 50 return null; 51 } catch (NoInitialContextException e) { 52 logger.warn("JNDI Context not found, assuming test environment"); 53 disabled = true; 54 return null; 55 } catch (NamingException e) { 56 logger.error(key, e); 57 return null; 58 } 59 } 60 61 public Collection keySet() { 62 return Collections.EMPTY_SET; 63 } 64 65 public void close() { 66 try { 67 if (context != null) 68 context.close(); 69 } catch (NamingException 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 getName() { 81 return "JNDI Lookup " + (disabled ? "disabled" : "enabled"); 82 } 83 84 } 85 | Popular Tags |