下面列出了javax.naming.spi.InitialContextFactory#javax.naming.NoInitialContextException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public InitialContextFactory createInitialContextFactory(Hashtable<?, ?> environment) throws NamingException {
final String className = (String) environment.get(Context.INITIAL_CONTEXT_FACTORY);
try {
final ClassLoader cl = Thread.currentThread().getContextClassLoader();
return (InitialContextFactory) Class.forName(className, true, cl).newInstance();
} catch (Exception e) {
NoInitialContextException ne = new NoInitialContextException(
"Cannot instantiate class: " + className);
ne.setRootCause(e);
throw ne;
}
}
private static void testWith(String appletProperty) throws NamingException {
Hashtable<Object, Object> env = new Hashtable<>();
// Deliberately put java.lang.Object rather than java.applet.Applet
// if an applet was used we would see a ClassCastException down there
env.put(appletProperty, new Object());
// It's ok to instantiate InitialContext with no parameters
// and be unaware of it right until you try to use it
Context ctx = new InitialContext(env);
boolean threw = true;
try {
ctx.lookup("whatever");
threw = false;
} catch (NoInitialContextException e) {
String m = e.getMessage();
if (m == null || m.contains("applet"))
throw new RuntimeException("The exception message is incorrect", e);
} catch (Throwable t) {
throw new RuntimeException(
"The test was supposed to catch NoInitialContextException" +
" here, but caught: " + t.getClass().getName(), t);
} finally {
ctx.close();
}
if (!threw)
throw new RuntimeException("The test was supposed to catch NoInitialContextException here");
}
static Map<String, DataSource> getJndiAndSpringDataSources() throws NamingException {
Map<String, DataSource> dataSources;
try {
dataSources = new LinkedHashMap<String, DataSource>(getJndiDataSources());
} catch (final NoInitialContextException e) {
dataSources = new LinkedHashMap<String, DataSource>();
}
dataSources.putAll(SPRING_DATASOURCES);
return dataSources;
}
@Test
@Order(1)
void givenNoContext_whenLookupObject_thenThrowNoInitialContext() {
assertThrows(NoInitialContextException.class, () -> {
JndiTemplate jndiTemplate = new JndiTemplate();
InitialContext ctx = (InitialContext) jndiTemplate.getContext();
ctx.lookup("java:comp/env/jdbc/datasource");
}).printStackTrace();
}
private static NoInitialContextException createNamingException(Exception e) {
final NoInitialContextException ex = new NoInitialContextException(e.toString());
ex.initCause(e);
return ex;
}