1
//$Id: NamingHelper.java 8149 2005-09-11 21:10:52Z oneovthafew $
2
package org.hibernate.util;
4
import java.util.HashSet;
5
import java.util.Hashtable;
6
import java.util.Iterator;
7
import java.util.Properties;
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;
17
import org.hibernate.cfg.Environment;
19
public final class NamingHelper {
21
private static final Log log = LogFactory.getLog(NamingHelper.class);
23
public static InitialContext getInitialContext(Properties props) throws NamingException {
25
Hashtable hash = getJndiProperties(props);
26
log.info("JNDI InitialContext properties:" + hash);
28
return hash.size()==0 ?
29
new InitialContext() :
30
new InitialContext(hash);
32
catch (NamingException e) {
33
log.error("Could not obtain initial context", e);
39
* Bind val to name in ctx, and make sure that all intermediate contexts exist.
41
* @param ctx the root context
42
* @param name the name as a string
43
* @param val the object to be bound
44
* @throws NamingException
46
public static void bind(Context ctx, String name, Object val) throws NamingException {
48
log.trace("binding: " + name);
49
ctx.rebind(name, val);
52
Name n = ctx.getNameParser("").parse(name);
53
while ( n.size() > 1 ) {
54
String ctxName = n.get(0);
58
log.trace("lookup: " + ctxName);
59
subctx = (Context) ctx.lookup(ctxName);
61
catch (NameNotFoundException nfe) {}
64
log.debug("Found subcontext: " + ctxName);
68
log.info("Creating subcontext: " + ctxName);
69
ctx = ctx.createSubcontext(ctxName);
73
log.trace("binding: " + n);
76
log.debug("Bound name: " + name);
80
* Transform JNDI properties passed in the form <tt>hibernate.jndi.*</tt> to the
81
* format accepted by <tt>InitialContext</tt> by triming the leading "<tt>hibernate.jndi</tt>".
83
public static Properties getJndiProperties(Properties properties) {
85
HashSet specialProps = new HashSet();
86
specialProps.add(Environment.JNDI_CLASS);
87
specialProps.add(Environment.JNDI_URL);
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) ) {
95
prop.substring( Environment.JNDI_PREFIX.length()+1 ),
96
properties.getProperty(prop)
101
String jndiClass = properties.getProperty(Environment.JNDI_CLASS);
102
String jndiURL = properties.getProperty(Environment.JNDI_URL);
103
// we want to be able to just use the defaults,
104
// if JNDI environment properties are not supplied
105
// so don't put null in anywhere
106
if (jndiClass != null) result.put(Context.INITIAL_CONTEXT_FACTORY, jndiClass);
107
if (jndiURL != null) result.put(Context.PROVIDER_URL, jndiURL);
112
private NamingHelper() {}