1 package org.hibernate.util; 3 4 import java.util.HashSet ; 5 import java.util.Hashtable ; 6 import java.util.Iterator ; 7 import java.util.Properties ; 8 9 import javax.naming.Context ; 10 import javax.naming.InitialContext ; 11 import javax.naming.Name ; 12 import javax.naming.NameNotFoundException ; 13 import javax.naming.NamingException ; 14 import org.apache.commons.logging.Log; 15 import org.apache.commons.logging.LogFactory; 16 17 import org.hibernate.cfg.Environment; 18 19 public final class NamingHelper { 20 21 private static final Log log = LogFactory.getLog(NamingHelper.class); 22 23 public static InitialContext getInitialContext(Properties props) throws NamingException { 24 25 Hashtable hash = getJndiProperties(props); 26 log.info("JNDI InitialContext properties:" + hash); 27 try { 28 return ( hash.size()==0 ) ? 29 new InitialContext () : 30 new InitialContext (hash); 31 } 32 catch (NamingException e) { 33 log.error("Could not obtain initial context", e); 34 throw e; 35 } 36 } 37 38 46 public static void bind(Context ctx, String name, Object val) throws NamingException { 47 try { 48 log.trace("binding: " + name); 49 ctx.rebind(name, val); 50 } 51 catch (Exception e) { 52 Name n = ctx.getNameParser("").parse(name); 53 while ( n.size() > 1 ) { 54 String ctxName = n.get(0); 55 56 Context subctx=null; 57 try { 58 log.trace("lookup: " + ctxName); 59 subctx = (Context ) ctx.lookup(ctxName); 60 } 61 catch (NameNotFoundException nfe) {} 62 63 if (subctx!=null) { 64 log.debug("Found subcontext: " + ctxName); 65 ctx = subctx; 66 } 67 else { 68 log.info("Creating subcontext: " + ctxName); 69 ctx = ctx.createSubcontext(ctxName); 70 } 71 n = n.getSuffix(1); 72 } 73 log.trace("binding: " + n); 74 ctx.rebind(n, val); 75 } 76 log.debug("Bound name: " + name); 77 } 78 79 83 public static Properties getJndiProperties(Properties properties) { 84 85 HashSet specialProps = new HashSet (); 86 specialProps.add(Environment.JNDI_CLASS); 87 specialProps.add(Environment.JNDI_URL); 88 89 Iterator iter = properties.keySet().iterator(); 90 Properties result = new Properties (); 91 while ( iter.hasNext() ) { 92 String prop = (String ) iter.next(); 93 if ( prop.indexOf(Environment.JNDI_PREFIX) > -1 && !specialProps.contains(prop) ) { 94 result.setProperty( 95 prop.substring( Environment.JNDI_PREFIX.length()+1 ), 96 properties.getProperty(prop) 97 ); 98 } 99 } 100 101 String jndiClass = properties.getProperty(Environment.JNDI_CLASS); 102 String jndiURL = properties.getProperty(Environment.JNDI_URL); 103 if (jndiClass != null) result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass); 107 if (jndiURL != null) result.put(Context.PROVIDER_URL, jndiURL); 108 109 return result; 110 } 111 112 private NamingHelper() {} 113 114 } 115 116 117 118 119 120 121 122 | Popular Tags |