import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
public class JndiUtil {
private static final Map<String, Properties> cache = new HashMap<String, Properties>();
static {
cacheProp();
}
/**
* 获取默认的jndi连接.
* @param jndi
* @return Object
*/
public static Object lookup(String jndi) {
Object obj = null;
try {
obj = new InitialContext(cache.get("default")).lookup(jndi);
} catch (Exception e) {
System.out.print("Can't connect the ejb");
e.printStackTrace();
}
return obj;
}
/**
* 获取默认jndi连接.
* @param jndi
* @param cla
* @return Object
*/
public static Object lookup(String jndi, Class<?> cla) {
Object obj = null;
try {
obj = PortableRemoteObject.narrow(new InitialContext(cache.get("default")).lookup(jndi), cla);
} catch (Exception e) {
System.out.print("Can't connect the ejb");
e.printStackTrace();
}
return obj;
}
/**
* 获取指定远程EJB的JNDI方法.
* @param jndi
* @param name
* @return
*/
public static Object lookup(String jndi, String propName) {
Object obj = null;
try {
obj = new InitialContext(cache.get(propName)).lookup(jndi);
} catch (Exception e) {
System.out.print("Can't connect the ejb");
e.printStackTrace();
}
return obj;
}
private static void cacheProp() {
try {
Properties prop = new Properties();
prop.load(JndiUtil.class.getResourceAsStream("/jndi_service.properties"));
cache.put("default", prop);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String get(String key, String prop) {
if (null != prop && !"".equals(prop))
return cache.get(prop).getProperty(key);
else
return cache.get("default").getProperty(key);
}
}
jndi_service.properties:
java.naming.factory.initial = org.jnp.interfaces.NamingContextFactory
java.naming.provider.url = jnp://127.0.0.1:1099
java.naming.factory.url.pkgs = org.jboss.naming