本文整理汇总了Java中javax.naming.Context.lookup方法的典型用法代码示例。如果您正苦于以下问题:Java Context.lookup方法的具体用法?Java Context.lookup怎么用?Java Context.lookup使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.naming.Context
的用法示例。
在下文中一共展示了Context.lookup方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: doGet
import javax.naming.Context; //导入方法依赖的package包/类
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain;UTF-8");
PrintWriter out = resp.getWriter();
try {
Context ctx = new InitialContext();
Object obj = ctx.lookup("java:comp/env/bug50351");
TesterObject to = (TesterObject) obj;
out.print(to.getFoo());
} catch (NamingException ne) {
ne.printStackTrace(out);
}
}
示例2: getInstance
import javax.naming.Context; //导入方法依赖的package包/类
public Object getInstance() throws InstantiationException
{
String type = remote ? "remote" : "local";
try
{
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/jndi.properties"));
Context jndi = new InitialContext(props);
return jndi.lookup(bean + beanNamePostfix + "/" + type);
}
catch (Exception ex)
{
throw new InstantiationException(bean + "/" + type + " not bound:" + ex.getMessage());
}
}
示例3: testReturnPooledConnectionToPool
import javax.naming.Context; //导入方法依赖的package包/类
/**
* Test of returnPooledConnectionToPool method, of class
* org.apache.geode.internal.datasource.AbstractPoolCache.
*/
@Test
public void testReturnPooledConnectionToPool() throws Exception {
Context ctx = cache.getJNDIContext();
GemFireConnPooledDataSource ds =
(GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
GemFireConnectionPoolManager provider =
(GemFireConnectionPoolManager) ds.getConnectionProvider();
ConnectionPoolCacheImpl poolCache = (ConnectionPoolCacheImpl) provider.getConnectionPoolCache();
PooledConnection conn = (PooledConnection) poolCache.getPooledConnectionFromPool();
if (poolCache.availableCache.containsKey(conn))
fail("connection not removed from available cache list");
if (!poolCache.activeCache.containsKey(conn))
fail("connection not put in active connection list");
provider.returnConnection(conn);
if (!poolCache.availableCache.containsKey(conn))
fail("connection not returned to pool");
if (poolCache.activeCache.containsKey(conn))
fail("connection not returned to active list");
}
示例4: testIndexOnCommitForDestroy
import javax.naming.Context; //导入方法依赖的package包/类
@Test
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();
CacheUtils.log(((Person) region.get(x)));
assertEquals(0, ((SelectResults) q.execute()).size());
}
示例5: getConnection
import javax.naming.Context; //导入方法依赖的package包/类
/**
* 获取连接,使用数据库连接池
* @param jndi 配置在tomcat的context.xml里面的东西
* @return 创建的连接对象
*/
public Connection getConnection(String jndi)
{
try
{
log.debug("开始尝试连接数据库!");
Context context=new InitialContext();
DataSource dataSource=(DataSource)context.lookup("java:comp/env/"+jndi);
con=dataSource.getConnection();
log.debug("连接成功!");
}
catch (Exception e)
{
log.error("连接数据库失败!", e);
}
return con;
}
示例6: init
import javax.naming.Context; //导入方法依赖的package包/类
private void init() {
if (!isAlwaysLookup()) {
Context ctx = null;
try {
ctx = (props != null) ? new InitialContext(props) : new InitialContext();
datasource = (DataSource) ctx.lookup(url);
} catch (Exception e) {
getLog().error(
"Error looking up datasource: " + e.getMessage(), e);
} finally {
if (ctx != null) {
try { ctx.close(); } catch(Exception ignore) {}
}
}
}
}
示例7: startInternal
import javax.naming.Context; //导入方法依赖的package包/类
/**
* Prepare for the beginning of active use of the public methods of this
* component and implement the requirements of
* {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
*
* @exception LifecycleException if this component detects a fatal error
* that prevents this component from being used
*/
@Override
protected void startInternal() throws LifecycleException {
try {
Context context = getServer().getGlobalNamingContext();
database = (UserDatabase) context.lookup(resourceName);
} catch (Throwable e) {
ExceptionUtils.handleThrowable(e);
containerLog.error(sm.getString("userDatabaseRealm.lookup",
resourceName),
e);
database = null;
}
if (database == null) {
throw new LifecycleException
(sm.getString("userDatabaseRealm.noDatabase", resourceName));
}
super.startInternal();
}
示例8: testValidateConnection
import javax.naming.Context; //导入方法依赖的package包/类
/**
* Test of validateConnection method, of class
* org.apache.geode.internal.datasource.AbstractPoolCache.
*/
@Test
public void testValidateConnection() throws Exception {
Context ctx = cache.getJNDIContext();
GemFireConnPooledDataSource ds =
(GemFireConnPooledDataSource) ctx.lookup("java:/PooledDataSource");
GemFireConnectionPoolManager provider =
(GemFireConnectionPoolManager) ds.getConnectionProvider();
ConnectionPoolCacheImpl poolCache = (ConnectionPoolCacheImpl) provider.getConnectionPoolCache();
PooledConnection poolConn = (PooledConnection) poolCache.getPooledConnectionFromPool();
Connection conn = poolConn.getConnection();
if (!ds.validateConnection(conn))
fail("validate connection failed");
conn.close();
if (ds.validateConnection(conn))
fail("validate connection failed");
}
示例9: lookupMethodResource
import javax.naming.Context; //导入方法依赖的package包/类
/**
* Inject resources in specified method.
*
* @param context
* jndi context to extract value from
* @param instance
* object to inject into
* @param method
* field target for injection
* @param name
* jndi name value is bound under
* @param clazz
* class annotation is defined in
* @throws IllegalAccessException
* if method is inaccessible
* @throws javax.naming.NamingException
* if value is not accessible in naming context
* @throws java.lang.reflect.InvocationTargetException
* if setter call fails
*/
protected static void lookupMethodResource(Context context, Object instance, Method method, String name,
Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException {
if (!Introspection.isValidSetter(method)) {
throw new IllegalArgumentException(sm.getString("defaultInstanceManager.invalidInjection"));
}
Object lookedupResource;
boolean accessibility;
String normalizedName = normalize(name);
if ((normalizedName != null) && (normalizedName.length() > 0)) {
lookedupResource = context.lookup(normalizedName);
} else {
lookedupResource = context.lookup(clazz.getName() + "/" + Introspection.getPropertyName(method));
}
synchronized (method) {
accessibility = method.isAccessible();
method.setAccessible(true);
method.invoke(instance, lookedupResource);
method.setAccessible(accessibility);
}
}
示例10: getConnection
import javax.naming.Context; //导入方法依赖的package包/类
public Connection getConnection() throws SQLException {
Context ctx = null;
try {
Object ds = this.datasource;
if (ds == null || isAlwaysLookup()) {
ctx = (props != null) ? new InitialContext(props): new InitialContext();
ds = ctx.lookup(url);
if (!isAlwaysLookup()) {
this.datasource = ds;
}
}
if (ds == null) {
throw new SQLException( "There is no object at the JNDI URL '" + url + "'");
}
if (ds instanceof XADataSource) {
return (((XADataSource) ds).getXAConnection().getConnection());
} else if (ds instanceof DataSource) {
return ((DataSource) ds).getConnection();
} else {
throw new SQLException("Object at JNDI URL '" + url + "' is not a DataSource.");
}
} catch (Exception e) {
this.datasource = null;
throw new SQLException(
"Could not retrieve datasource via JNDI url '" + url + "' "
+ e.getClass().getName() + ": " + e.getMessage());
} finally {
if (ctx != null) {
try { ctx.close(); } catch(Exception ignore) {}
}
}
}
示例11: testGetTranxDataSource
import javax.naming.Context; //导入方法依赖的package包/类
@Test
public void testGetTranxDataSource() throws Exception {
Context ctx = cache.getJNDIContext();
GemFireTransactionDataSource ds =
(GemFireTransactionDataSource) ctx.lookup("java:/XAPooledDataSource");
// DataSourceFactory dsf = new DataSourceFactory();
// GemFireTransactionDataSource ds =
// (GemFireTransactionDataSource)dsf.getTranxDataSource(map);
Connection conn = ds.getConnection();
if (conn == null)
fail(
"DataSourceFactoryJUnitTest-testGetTranxDataSource() Error in creating the getTranxDataSource");
}
示例12: getTargetContext
import javax.naming.Context; //导入方法依赖的package包/类
protected DirContextNamePair getTargetContext(Name name)
throws NamingException {
if (cpe.getResolvedObj() == null)
throw (NamingException)cpe.fillInStackTrace();
Context ctx = NamingManager.getContext(cpe.getResolvedObj(),
cpe.getAltName(),
cpe.getAltNameCtx(),
env);
if (ctx == null)
throw (NamingException)cpe.fillInStackTrace();
if (ctx instanceof DirContext)
return new DirContextNamePair((DirContext)ctx, name);
if (ctx instanceof Resolver) {
Resolver res = (Resolver)ctx;
ResolveResult rr = res.resolveToClass(name, DirContext.class);
// Reached a DirContext; return result.
DirContext dctx = (DirContext)rr.getResolvedObj();
return (new DirContextNamePair(dctx, rr.getRemainingName()));
}
// Resolve all the way using lookup(). This may allow the operation
// to succeed if it doesn't require the penultimate context.
Object ultimate = ctx.lookup(name);
if (ultimate instanceof DirContext) {
return (new DirContextNamePair((DirContext)ultimate,
new CompositeName()));
}
throw (NamingException)cpe.fillInStackTrace();
}
示例13: lookupRemoteStatelessHello
import javax.naming.Context; //导入方法依赖的package包/类
/**
* Looks up and returns the proxy to remote stateless calculator bean
*
* @return
* @throws NamingException
*/
private static RemoteHello lookupRemoteStatelessHello() throws NamingException {
final Hashtable<String, Object> jndiProperties = new Hashtable<String, Object>();
jndiProperties.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
final Context context = new InitialContext(jndiProperties);
try {
// The app name is the application name of the deployed EJBs. This is typically the ear name
// without the .ear suffix. However, the application name could be overridden in the application.xml of the
// EJB deployment on the server.
// Since we haven't deployed the application as a .ear, the app name for us will be an empty string
final String appName = "";
// This is the module name of the deployed EJBs on the server. This is typically the jar name of the
// EJB deployment, without the .jar suffix, but can be overridden via the ejb-jar.xml
// In this example, we have deployed the EJBs in a jboss-as-ejb-remote-app.jar, so the module name is
// jboss-as-ejb-remote-app
final String moduleName = "ejb-module";
// AS7 allows each deployment to have an (optional) distinct name. We haven't specified a distinct name for
// our EJB deployment, so this is an empty string
final String distinctName = "";
// The EJB name which by default is the simple class name of the bean implementation class
final String beanName = HelloBean.class.getSimpleName();
// the remote view fully qualified class name
final String viewClassName = RemoteHello.class.getName();
// let's do the lookup
String lookupKey = "ejb:" + appName + "/" + moduleName + "/" + distinctName + "/" + beanName + "!" + viewClassName;
System.out.println("Lookup for remote EJB bean: " + lookupKey);
return (RemoteHello) context.lookup(lookupKey);
} finally {
context.close();
}
}
示例14: testWith
import javax.naming.Context; //导入方法依赖的package包/类
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");
}
示例15: testGetSimpleDataSource
import javax.naming.Context; //导入方法依赖的package包/类
@Test
public void testGetSimpleDataSource() throws Exception {
try {
Context ctx = cache.getJNDIContext();
GemFireBasicDataSource ds = (GemFireBasicDataSource) ctx.lookup("java:/SimpleDataSource");
Connection conn = ds.getConnection();
if (conn == null)
fail(
"DataSourceFactoryTest-testGetSimpleDataSource() Error in creating the GemFireBasicDataSource");
} catch (Exception e) {
fail("Exception occured in testGetSimpleDataSource due to " + e);
e.printStackTrace();
}
}