下面列出了怎么用javax.naming.Context的API类实例代码及写法,或者点击链接到github查看源代码。
public static Context getURLContext(
String scheme, Hashtable<?,?> environment)
throws NamingException {
return new DnsContext("", null, new Hashtable<String,String>()) {
public Attributes getAttributes(String name, String[] attrIds)
throws NamingException {
return new BasicAttributes() {
public Attribute get(String attrID) {
BasicAttribute ba = new BasicAttribute(attrID);
ba.add("1 1 99 b.com.");
ba.add("0 0 88 a.com."); // 2nd has higher priority
return ba;
}
};
}
};
}
@Test
public void testBug53465() throws Exception {
Tomcat tomcat = getTomcatInstance();
tomcat.enableNaming();
File appDir =
new File("test/webapp-3.0");
// app dir is relative to server home
org.apache.catalina.Context ctxt =
tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
tomcat.start();
ByteChunk bc = new ByteChunk();
int rc = getUrl("http://localhost:" + getPort() +
"/test/bug5nnnn/bug53465.jsp", bc, null);
Assert.assertEquals(HttpServletResponse.SC_OK, rc);
Assert.assertTrue(bc.toString().contains("<p>10</p>"));
ContextEnvironment ce =
ctxt.getNamingResources().findEnvironment("bug53465");
Assert.assertEquals("Bug53465MappedName", ce.getProperty("mappedName"));
}
private Object loadFromDatabase(Object ob)
{
Object obj = null;
try{
Context ctx = CacheFactory.getAnyInstance().getJNDIContext();
DataSource ds = (DataSource)ctx.lookup("java:/XAPooledDataSource");
Connection conn = ds.getConnection();
Statement stm = conn.createStatement();
String str = "update "+ tableName +" set name ='newname' where id = ("+(new Integer(ob.toString())).intValue()+")";
stm.executeUpdate(str);
ResultSet rs = stm.executeQuery("select name from "+ tableName +" where id = ("+(new Integer(ob.toString())).intValue()+")");
rs.next();
obj = rs.getString(1);
stm.close();
conn.close();
return obj;
}catch(Exception e){
e.printStackTrace();
}
return obj;
}
public void testConnectionPoolFunctions() {
try {
Context ctx = cache.getJNDIContext();
ds = (GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
PoolClient_1 clientA = new PoolClient_1();
ThreadA = new Thread(clientA, "ThreadA");
PoolClient_2 clientB = new PoolClient_2();
ThreadB = new Thread(clientB, "ThreadB");
// ThreadA.setDaemon(true);
//ThreadB.setDaemon(true);
ThreadA.start();
}
catch (Exception e) {
fail("Exception occured in testConnectionPoolFunctions due to " + e);
e.printStackTrace();
}
}
/**
* Tests if LDAP connection correctly initialized.
*/
public void test() {
Map<String, String> params = new HashMap<String, String>();
String dn = "dc=scriptella";
params.put(LdapConnection.SEARCH_BASEDN_KEY, dn);
params.put(LdapConnection.SEARCH_SCOPE_KEY, "subtree");
params.put(LdapConnection.FILE_MAXLENGTH_KEY, "100");
final String url = "ldap://127.0.0.1:389/";
ConnectionParameters cp = new MockConnectionParameters(params, url);
ctxInitialized = false;
LdapConnection con = new LdapConnection(cp) {
@Override
protected void initializeContext(Hashtable<String, Object> env) {
ctxInitialized = true;
//Simple checks if environment has been correctly set up
assertEquals(url, env.get(Context.PROVIDER_URL));
assertNotNull(env.get(Context.INITIAL_CONTEXT_FACTORY));
}
};
assertEquals(dn, con.getBaseDn());
assertEquals(SearchControls.SUBTREE_SCOPE, con.getSearchControls().getSearchScope());
assertEquals(100, (long) con.getMaxFileLength());
assertTrue(ctxInitialized);
}
private static boolean undeploy(final StandardContext standardContext, final Container host) {
final Container child = host.findChild(standardContext.getName());
// skip undeployment if redeploying (StandardContext.redeploy())
if (child instanceof org.apache.catalina.Context && org.apache.catalina.Context.class.cast(child).getPaused()) {
return true;
}
// skip undeployment if restarting
final TomEEWebappClassLoader tomEEWebappClassLoader = lazyClassLoader(
org.apache.catalina.Context.class.isInstance(child) ? org.apache.catalina.Context.class.cast(child) : null);
if (tomEEWebappClassLoader != null && tomEEWebappClassLoader.isRestarting()) {
return true;
}
if (child != null) {
host.removeChild(standardContext);
return true;
}
return false;
}
@Before
public void setUp() throws OpenEJBException, NamingException, IOException {
final ConfigurationFactory config = new ConfigurationFactory();
final Assembler assembler = new Assembler();
assembler.createTransactionManager(config.configureService(TransactionServiceInfo.class));
assembler.createSecurityService(config.configureService(SecurityServiceInfo.class));
final AppModule app = new AppModule(OpenEJBXmlByModuleTest.class.getClassLoader(), OpenEJBXmlByModuleTest.class.getSimpleName());
final EjbJar ejbJar = new EjbJar();
ejbJar.addEnterpriseBean(new SingletonBean(UselessBean.class));
app.getEjbModules().add(new EjbModule(ejbJar));
app.getEjbModules().iterator().next().getAltDDs().put("resources.xml", getClass().getClassLoader().getResource("META-INF/resource/appresource.openejb.xml"));
assembler.createApplication(config.configureApplication(app));
final Properties properties = new Properties();
properties.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, LocalInitialContextFactory.class.getName());
properties.setProperty("openejb.embedded.initialcontext.close", "destroy");
// some hack to be sure to call destroy()
context = new InitialContext(properties);
bean = (UselessBean) context.lookup("UselessBeanLocalBean");
}
public static void listTableData(String tableName) throws NamingException, SQLException {
Context ctx = CacheHelper.getCache().getJNDIContext();
DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
String sql = "select * from " + tableName;
Log.getLogWriter().info("listTableData: " + sql);
Connection conn = ds.getConnection();
Statement sm = conn.createStatement();
ResultSet rs = sm.executeQuery(sql);
while (rs.next()) {
Log.getLogWriter().info("id " + rs.getString(1) + " name " + rs.getString(2));
}
rs.close();
conn.close();
}
private Hashtable<String, String> createEnv(final String user, final String password)
{
// Set up the environment for creating the initial context
final Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapConfig.getCompleteServerUrl());
final String authentication = ldapConfig.getAuthentication();
if (StringUtils.isNotBlank(authentication) == true) {
env.put(Context.SECURITY_AUTHENTICATION, ldapConfig.getAuthentication());
if ("none".equals(authentication) == false || user != null || password != null) {
env.put(Context.SECURITY_PRINCIPAL, user);
env.put(Context.SECURITY_CREDENTIALS, password);
}
}
if (ldapConfig != null && StringUtils.isNotBlank(ldapConfig.getSslCertificateFile()) == true) {
env.put("java.naming.ldap.factory.socket", "org.projectforge.ldap.MySSLSocketFactory");
}
log.info("Trying to connect the LDAP server: url=["
+ ldapConfig.getCompleteServerUrl()
+ "], authentication=["
+ ldapConfig.getAuthentication()
+ "], principal=["
+ user
+ "]");
return env;
}
public static synchronized void registerConnections(IJdbcResourceFactoryProvider provider) throws ResourceFactoriesException {
// Look at the local providers
String[] names = provider.getConnectionNames();
if(names!=null) {
for(int j=0; j<names.length; j++) {
String name = names[j];
Integer n = connections.get(name);
if(n==null) {
n = 1;
//Register the dataSourceName in JNDI
try {
Context ctx = new InitialContext();
String jndiName = JndiRegistry.getJNDIBindName(name);
ctx.bind( jndiName, new JndiDataSourceProxy(name) );
} catch(NamingException ex) {
throw new ResourceFactoriesException(ex,StringUtil.format("Error while binding JNDI name {0}",name)); // $NLX-JndiRegistry.Errorwhilebinding0name1-1$ $NON-NLS-2$
}
} else {
n = n+1;
}
connections.put(name,n);
}
}
}
@Test
public void testLookupFailsWithTypeMismatch() throws Exception {
Object o = new Object();
String name = "foo";
final Context context = mock(Context.class);
given(context.lookup(name)).willReturn(o);
JndiTemplate jt = new JndiTemplate() {
@Override
protected Context createInitialContext() {
return context;
}
};
try {
jt.lookup(name, String.class);
fail("Should have thrown TypeMismatchNamingException");
}
catch (TypeMismatchNamingException ex) {
// Ok
}
verify(context).close();
}
protected void setUp() throws Exception {
// InitialContextFactoryImpl impl = new InitialContextFactoryImpl();
// impl.setAsInitial();
Hashtable table = new Hashtable();
table
.put(
Context.INITIAL_CONTEXT_FACTORY,
"com.gemstone.gemfire.internal.jndi.InitialContextFactoryImpl");
// table.put(Context.URL_PKG_PREFIXES,
// "com.gemstone.gemfire.internal.jndi");
initialCtx = new InitialContext(table);
initialCtx.bind("java:gf/env/datasource/oracle", "a");
gfCtx = (Context) initialCtx.lookup("java:gf");
envCtx = (Context) gfCtx.lookup("env");
datasourceCtx = (Context) envCtx.lookup("datasource");
}
public DefaultInstanceManager(Context context, Map<String, Map<String, String>> injectionMap, org.apache.catalina.Context catalinaContext, ClassLoader containerClassLoader) {
classLoader = catalinaContext.getLoader().getClassLoader();
privileged = catalinaContext.getPrivileged();
this.containerClassLoader = containerClassLoader;
ignoreAnnotations = catalinaContext.getIgnoreAnnotations();
StringManager sm = StringManager.getManager(Constants.Package);
restrictedServlets = loadProperties(
"org/apache/catalina/core/RestrictedServlets.properties",
sm.getString("defaultInstanceManager.restrictedServletsResource"),
catalinaContext.getLogger());
restrictedListeners = loadProperties(
"org/apache/catalina/core/RestrictedListeners.properties",
"defaultInstanceManager.restrictedListenersResources",
catalinaContext.getLogger());
restrictedFilters = loadProperties(
"org/apache/catalina/core/RestrictedFilters.properties",
"defaultInstanceManager.restrictedFiltersResource",
catalinaContext.getLogger());
this.context = context;
this.injectionMap = injectionMap;
this.postConstructMethods = catalinaContext.findPostConstructMethods();
this.preDestroyMethods = catalinaContext.findPreDestroyMethods();
}
public void run() {
while (shouldKeepBinding()) {
try {
Context objectContext = configuration.getObjectContext();
objectContext.rebind(name, server.getServant());
objectContext.close();
} catch (Exception ex) {
System.err.println("Exception binding at " + new Date() + "; will keep trying...");
ex.printStackTrace();
} finally {
try {
Thread.sleep(REBIND_PERIOD);
} catch (InterruptedException ignore) {
}
}
}
}
@Test
public void createJndiProperties() {
// given
Properties props = createConnectionProperties(jndiName);
// when
Properties jndiProps = PluginServiceFactory.createJndiProperties(props);
// then
assertEquals(props.get(Context.PROVIDER_URL),
jndiProps.get(Context.PROVIDER_URL));
assertEquals(props.get(Context.INITIAL_CONTEXT_FACTORY),
jndiProps.get(Context.INITIAL_CONTEXT_FACTORY));
assertEquals(props.get(ORBINITIALHOST), jndiProps.get(ORBINITIALHOST));
assertEquals(props.get(ORBINITIALPORT), jndiProps.get(ORBINITIALPORT));
assertEquals(4, jndiProps.size());
assertNull(props.get(PluginServiceFactory.JNDI_NAME));
}
public void testIndexOnCommitForDestroy() throws Exception {
AttributesFactory af = new AttributesFactory();
af.setDataPolicy(DataPolicy.REPLICATE);
Region region = cache.createRegion("sample", af.create());
qs.createIndex("foo", IndexType.FUNCTIONAL, "age", "/sample");
Context ctx = cache.getJNDIContext();
UserTransaction utx = (UserTransaction)ctx.lookup("java:/UserTransaction");
Integer x = new Integer(0);
utx.begin();
region.create(x, new Person("xyz", 45));
utx.commit();
Query q = qs.newQuery("select * from /sample where age < 50");
assertEquals(1, ((SelectResults)q.execute()).size());
Person dsample = (Person)CopyHelper.copy(region.get(x));
dsample.setAge(55);
utx.begin();
region.destroy(x);
utx.commit();
System.out.println((region.get(x)));
assertEquals(0, ((SelectResults) q.execute()).size());
}
private static Object createObjectFromFactories(Object obj, Name name,
Context nameCtx, Hashtable<?,?> environment, Attributes attrs)
throws Exception {
FactoryEnumeration factories = ResourceManager.getFactories(
Context.OBJECT_FACTORIES, environment, nameCtx);
if (factories == null)
return null;
ObjectFactory factory;
Object answer = null;
// Try each factory until one succeeds
while (answer == null && factories.hasMore()) {
factory = (ObjectFactory)factories.next();
if (factory instanceof DirObjectFactory) {
answer = ((DirObjectFactory)factory).
getObjectInstance(obj, name, nameCtx, environment, attrs);
} else {
answer =
factory.getObjectInstance(obj, name, nameCtx, environment);
}
}
return answer;
}
@Override
public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception {
// get the transaction manager
final TransactionManager transactionManager = SystemInstance.get().getComponent(TransactionManager.class);
if (transactionManager == null) {
throw new NamingException("transaction manager not found");
}
// if transaction manager implements user transaction we are done
if (transactionManager instanceof UserTransaction) {
return transactionManager;
}
// wrap transaction manager with user transaction
return new CoreUserTransaction(transactionManager);
}
protected String getData(String query) {
String returnValue = "";
Connection conn = null;
Statement stm = null;
try {
Context ctx = CacheFactory.getAnyInstance().getJNDIContext();
DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
conn = ds.getConnection();
stm = conn.createStatement();
ResultSet rs = stm.executeQuery(query);
rs.next();
returnValue = rs.getString(1);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (stm != null) {
stm.close();
stm = null;
}
if (conn != null) {
conn.close();
conn = null;
}
}
catch (SQLException sq) {
sq.printStackTrace();
}
}
return returnValue;
}
public static void createPool() throws Exception {
Context ctx = cache.getJNDIContext();
GemFireConnPooledDataSource ds = (GemFireConnPooledDataSource) ctx
.lookup("java:/PooledDataSource");
provider = (GemFireConnectionPoolManager) ds.getConnectionProvider();
poolCache = (ConnectionPoolCacheImpl) provider.getConnectionPoolCache();
maxPoolSize = poolCache.getMaxLimit();
}
/**
* Create a new EJB instance using OpenEJB.
*
* @param obj The reference object describing the DataSource
*/
@Override
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable<?,?> environment)
throws Exception {
Object beanObj = null;
if (obj instanceof EjbRef) {
Reference ref = (Reference) obj;
String factory = DEFAULT_OPENEJB_FACTORY;
RefAddr factoryRefAddr = ref.get("openejb.factory");
if (factoryRefAddr != null) {
// Retrieving the OpenEJB factory
factory = factoryRefAddr.getContent().toString();
}
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, factory);
RefAddr linkRefAddr = ref.get("openejb.link");
if (linkRefAddr != null) {
String ejbLink = linkRefAddr.getContent().toString();
beanObj = (new InitialContext(env)).lookup(ejbLink);
}
}
return beanObj;
}
/**
* Closes the specified {@code Context}, ignoring any exceptions thrown by the close operation.
*
* @param context the JNDI Context to close, may be {@code null}
*/
public static boolean closeSilently(final Context context) {
try {
close(context);
return true;
} catch (final NamingException ignored) {
// ignored
return false;
}
}
protected ConnectionFactory getConnectionFactory(Context context, String id, boolean createDestination, boolean useJms102) throws IbisException {
try {
return createConnectionFactory(context, id, createDestination, useJms102);
} catch (Throwable t) {
throw new IbisException("could not obtain connectionFactory ["+id+"]", t);
}
}
private static DataSource getDataSource() throws ServletException {
try {
Context envCtx = (Context)new InitialContext().lookup("java:comp/env");
return (DataSource)envCtx.lookup("jdbc/regDB");
} catch(NamingException e) {
throw new ServletException(e);
}
}
@Instrumentation.TraceEntry(message = "create ldap context", timer = "ldap")
private static LdapContext createLdapContext(String username, String password,
LdapConfig ldapConfig) throws NamingException {
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password);
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapConfig.url());
return new InitialLdapContext(env, null);
}
/**
* Create a context
* @return The context
* @exception NamingException Thrown if an error occurs
*/
protected Context createContext() throws NamingException
{
Properties properties = new Properties();
properties.setProperty("java.naming.factory.initial", "org.jnp.interfaces.LocalOnlyContextFactory");
properties.setProperty("java.naming.factory.url.pkgs", "org.jboss.naming:org.jnp.interfaces");
properties.setProperty(Context.PROVIDER_URL, jndiProtocol + "://" + jndiHost + ":" + jndiPort);
return new InitialContext(properties);
}
@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;
}
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.trace("Servlet BookServlet doGet begin");
BookEJBRemote bookEJBRemote;
try {
Context context = new InitialContext();
bookEJBRemote = (BookEJBRemote) context.lookup("java:global/ear-ejb/war-ejb-1.0-SNAPSHOT/BookEJB!edu.javacourse.BookEJBRemote");
} catch (NamingException e) {
log.error("Error while creating JNDI context: {}", e.getMessage());
throw new ServletException("Error while creating JNDI context");
}
log.debug("BookEJBLocal class: {}", bookEJBRemote == null ? "EJB not initialized" : bookEJBRemote.getClass().getCanonicalName());
List<Book> books = bookEJBRemote.getBooks();
log.debug("Books returned by EJB: {}", books);
request.setAttribute("bookClass", books.get(0).getClass().getCanonicalName());
request.setAttribute("beanClass", bookEJBRemote.getClass().getCanonicalName());
request.setAttribute("interface", "remote");
request.setAttribute("books", books);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
log.trace("Servlet BookServlet doGet end");
}
@Override
public Object getObjectInstance(final Object ref,
final Name name,
final Context ctx,
final Hashtable<?, ?> props) throws Exception {
Reference r = (Reference) ref;
byte[] bytes = (byte[]) r.get("ActiveMQ-CF").getContent();
// Deserialize
return SerializableObjectRefAddr.deserialize(bytes);
}
@Test
public void testQueueCF() throws NamingException, JMSException {
Hashtable<String, String> props = new Hashtable<>();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory");
props.put("connectionFactory.myConnectionFactory", "vm://0?type=QUEUE_CF");
Context ctx = new InitialContext(props);
ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) ctx.lookup("myConnectionFactory");
Assert.assertEquals(JMSFactoryType.QUEUE_CF.intValue(), connectionFactory.getFactoryType());
}