下面列出了怎么用javax.naming.InitialContext的API类实例代码及写法,或者点击链接到github查看源代码。
@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);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/plain;UTF-8");
PrintWriter out = resp.getWriter();
try {
Context initCtx = new InitialContext();
Boolean b1 = (Boolean) initCtx.lookup(JNDI_NAME);
Boolean b2 = (Boolean) initCtx.lookup(
new CompositeName(JNDI_NAME));
out.print(b1);
out.print(b2);
} catch (NamingException ne) {
throw new ServletException(ne);
}
}
public Object lookup(String hostPort, String name, Class<?> cls) throws NamingException {
if (cls.getName().equals("javax.transaction.TransactionManager") && useMdwTransactionManager) {
return MdwTransactionManager.getInstance();
}
else if (cls.getName().equals("javax.jms.Topic")) {
JmsProvider jmsProvider = ApplicationContext.getJmsProvider();
if (!(jmsProvider instanceof ActiveMqJms))
throw new NamingException("Unsupported JMS Provider: " + jmsProvider);
ActiveMqJms activeMqJms = (ActiveMqJms) jmsProvider;
return activeMqJms.getTopic(name);
}
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
return envCtx.lookup(name);
}
catch (Exception e) {
NamingException ne = new NamingException("Failed to look up " + name);
ne.initCause(e);
throw ne;
}
}
@Override
public void lookupPersistenceUnit() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final EntityManagerFactory emf = (EntityManagerFactory) ctx.lookup("java:comp/env/persistence/TestUnit");
Assert.assertNotNull("The EntityManagerFactory is null", emf);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
private UserTransaction getUserTransaction() {
try {
logger.debug("Attempting to look up standard UserTransaction.");
return (UserTransaction) new InitialContext().lookup(
USER_TRANSACTION_LOCATION);
} catch (NamingException ex) {
logger.debug("Could not look up standard UserTransaction.", ex);
try {
logger.debug("Attempting to look up JBoss proprietary UserTransaction.");
return (UserTransaction) new InitialContext().lookup(
JBOSS_USER_TRANSACTION_LOCATION);
} catch (NamingException ex1) {
logger.debug("Could not look up JBoss proprietary UserTransaction.", ex1);
}
}
return null;
}
public void lookupPersistenceContext() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final EntityManager em = (EntityManager) ctx.lookup("java:comp/env/persistence/TestContext");
Assert.assertNotNull("The EntityManager is null", em);
// call a do nothing method to assure entity manager actually exists
em.getFlushMode();
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
public void lookupSessionContext() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
// lookup in enc
final SessionContext sctx = (SessionContext) ctx.lookup("java:comp/env/sessioncontext");
Assert.assertNotNull("The SessionContext got from java:comp/env/sessioncontext is null", sctx);
// lookup using global name
final EJBContext ejbCtx = (EJBContext) ctx.lookup("java:comp/EJBContext");
Assert.assertNotNull("The SessionContext got from java:comp/EJBContext is null ", ejbCtx);
// verify context was set via legacy set method
Assert.assertNotNull("The SessionContext is null from setter method", ejbContext);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
@BeforeClass
public static void setup() throws Exception {
ctx = new InitialContext(new Hashtable<>(Collections.singletonMap(Context.INITIAL_CONTEXT_FACTORY,
"org.osjava.sj.memory.MemoryContextFactory")));
CADConverter converter1 = Mockito.mock(CADConverter.class);
Mockito.when(converter1.canConvertToOBJ("format")).thenReturn(true);
CADConverter converter2 = Mockito.mock(CADConverter.class);
Mockito.when(converter2.canConvertToOBJ("format")).thenReturn(true);
ctx.createSubcontext("java:global");
ctx.createSubcontext("java:global/application");
ctx.createSubcontext("java:global/application/module");
ctx.bind("java:global/application/module/c1Bean!org.polarsys.eplmp.server.converters.CADConverter", converter1);
ctx.bind("java:global/application/module/c1Bean", converter1);
ctx.bind("java:global/application/module/c2Bean", converter2);
ctx.bind("java:global/application/module/c2Bean!org.polarsys.eplmp.server.converters.CADConverter", converter2);
}
public void lookupFloatEntry() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final Float expected = new Float(1.0F);
final Float actual = (Float) ctx.lookup("java:comp/env/entity/cmp/references/Float");
Assert.assertNotNull("The Float looked up is null", actual);
Assert.assertEquals(expected, actual);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
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);
}
}
}
/**
* Obtain the default JBoss JCA WorkManager through a JMX lookup
* for the JBossWorkManagerMBean.
* @param mbeanName the JMX object name to use
* @see org.jboss.resource.work.JBossWorkManagerMBean
*/
public static WorkManager getWorkManager(String mbeanName) {
Assert.hasLength(mbeanName, "JBossWorkManagerMBean name must not be empty");
try {
Class<?> mbeanClass = JBossWorkManagerUtils.class.getClassLoader().loadClass(JBOSS_WORK_MANAGER_MBEAN_CLASS_NAME);
InitialContext jndiContext = new InitialContext();
MBeanServerConnection mconn = (MBeanServerConnection) jndiContext.lookup(MBEAN_SERVER_CONNECTION_JNDI_NAME);
ObjectName objectName = ObjectName.getInstance(mbeanName);
Object workManagerMBean = MBeanServerInvocationHandler.newProxyInstance(mconn, objectName, mbeanClass, false);
Method getInstanceMethod = workManagerMBean.getClass().getMethod("getInstance");
return (WorkManager) getInstanceMethod.invoke(workManagerMBean);
}
catch (Exception ex) {
throw new IllegalStateException(
"Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available", ex);
}
}
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
final ServletOutputStream out = response.getOutputStream();
final Map<String, Object> bindings = new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER);
try {
final Context context = (Context) new InitialContext().lookup("java:comp/");
addBindings("", bindings, context);
} catch (final NamingException e) {
throw new ServletException(e);
}
out.println("JNDI Context:");
for (final Map.Entry<String, Object> entry : bindings.entrySet()) {
if (entry.getValue() != null) {
out.println(" " + entry.getKey() + "=" + entry.getValue());
} else {
out.println(" " + entry.getKey());
}
}
}
@Override
public void lookupStatelessBusinessRemote() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final BasicStatelessBusinessRemote object = (BasicStatelessBusinessRemote) ctx.lookup("java:comp/env/stateless/beanReferences/stateless-business-remote");
Assert.assertNotNull("The EJB BusinessRemote is null", object);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
public byte[] getBytes() {
try {
final DataSource ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/DefaultDatabase");
final Connection c = ds.getConnection();
final PreparedStatement ps = c.prepareStatement("SELECT blob_column FROM storage WHERE id = ?");
ps.setInt(1, (Integer) ctx.getPrimaryKey());
final ResultSet rs = ps.executeQuery();
rs.next();
final InputStream is = rs.getBinaryStream(1);
final ByteArrayOutputStream os = new ByteArrayOutputStream();
final byte[] buffer = new byte[1024];
int count;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
is.close();
os.close();
rs.close();
ps.close();
c.close();
return os.toByteArray();
} catch (final Exception e) {
throw new EJBException(e);
}
}
public PushSocket() {
try {
// Since @Inject does not work with WebSocket ...
InitialContext initialContext = new InitialContext();
BeanManager bm = (BeanManager) initialContext.lookup("java:comp/env/BeanManager");
Bean bean;
CreationalContext ctx;
bean = bm.getBeans(INotificationService.class).iterator().next();
ctx = bm.createCreationalContext(bean);
notificationService = (INotificationService) bm.getReference(bean, INotificationService.class, ctx);
bean = bm.getBeans(ITicketingService.class).iterator().next();
ctx = bm.createCreationalContext(bean);
ticketingServices = (ITicketingService) bm.getReference(bean, ITicketingService.class, ctx);
} catch (NamingException e) {
e.printStackTrace();
}
}
public void lookupByteEntry() throws TestFailureException {
try {
try {
final InitialContext ctx = new InitialContext();
Assert.assertNotNull("The InitialContext is null", ctx);
final Byte expected = new Byte((byte) 1);
final Byte actual = (Byte) ctx.lookup("java:comp/env/entity/bmp/references/Byte");
Assert.assertNotNull("The Byte looked up is null", actual);
Assert.assertEquals(expected, actual);
} catch (final Exception e) {
Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage());
}
} catch (final AssertionFailedError afe) {
throw new TestFailureException(afe);
}
}
public void init(final Properties props) {
properties = props;
try {
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.openejb.core.LocalInitialContextFactory");
props.put("Default JDBC Database", "new://Resource?type=DataSource");
props.put("Default JDBC Database.JdbcUrl", "jdbc:hsqldb:mem:" + IvmTestServer.class.getSimpleName() + new Random().nextInt(250) + ";shutdown=true");
final Properties p = new Properties();
p.putAll(props);
p.put("openejb.loader", "embed");
new InitialContext(p); // initialize openejb via constructing jndi tree
//OpenEJB.init(properties);
} catch (final Exception oe) {
System.out.println("=========================");
System.out.println("" + oe.getMessage());
System.out.println("=========================");
oe.printStackTrace();
throw new RuntimeException("OpenEJB could not be initiated");
}
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
* @param event
* The servlet context event at initialization.
*/
public void contextInitialized(ServletContextEvent event) {
GlobalTracer.register(Tracing.init(Service.RECOMMENDER.getServiceName()));
RESTClient.setGlobalReadTimeout(REST_READ_TIMOUT);
ServiceLoadBalancer.preInitializeServiceLoadBalancers(Service.PERSISTENCE);
RegistryClient.getClient().runAfterServiceIsAvailable(Service.PERSISTENCE, () -> {
TrainingSynchronizer.getInstance().retrieveDataAndRetrain();
RegistryClient.getClient().register(event.getServletContext().getContextPath());
}, Service.RECOMMENDER);
try {
long looptime = (Long) new InitialContext().lookup("java:comp/env/recommenderLoopTime");
// if a looptime is specified, a retraining daemon is started
if (looptime > 0) {
new RetrainDaemon(looptime).start();
LOG.info("Periodic retraining every " + looptime + " milliseconds");
} else {
LOG.info("Recommender loop time not set. Disabling periodic retraining.");
}
} catch (NamingException e) {
LOG.info("Recommender loop time not set. Disabling periodic retraining.");
}
}
public static void bindDataSource() {
JdbcDataSource dataSource = new JdbcDataSource();
dataSource.setURL("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1");
dataSource.setUser(USERNAME);
dataSource.setPassword(PASSWORD);
try {
InitialContext initialContext = new InitialContext();
initialContext.bind(DATASOURCE_JNDI, dataSource);
}
catch (NamingException e) {
throw new RuntimeException(e);
}
}
public static DataSource getProarcSource() throws NamingException {
DataSource source = InitialContext.doLookup("java:/comp/env/jdbc/proarc");
if (source == null) {
throw new IllegalStateException("Cannot find 'jdbc/proarc' resource!");
}
return source;
}
@Test
public void testRemoteCFWithJGroups() throws Exception {
Hashtable<String, String> props = new Hashtable<>();
props.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.activemq.artemis.jndi.ActiveMQInitialContextFactory");
props.put("connectionFactory.myConnectionFactory", "jgroups://mychannelid?file=test-jgroups-file_ping.xml");
Context ctx = new InitialContext(props);
ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) ctx.lookup("myConnectionFactory");
connectionFactory.getDiscoveryGroupConfiguration().getBroadcastEndpointFactory().createBroadcastEndpoint().close(false);
}
@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");
}
/**
* Retrieves the initial context.
* @return The context to use or <code>null</code> in case of an error.
* @throws NamingException
* error obtaining the initial context
* @since 0.7.5
*/
Context getInitialContext() throws NamingException {
// We take the values from jndi.properties but override the port
final Hashtable<String, String> environment =
new Hashtable<String, String>();
environment.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.rmi.registry.RegistryContextFactory");
environment.put(Context.PROVIDER_URL, "rmi://localhost:" + port);
return new InitialContext(environment);
}
@GET
@Path("/jndi/{namespace}")
public JsonObject jndi(@PathParam("namespace") String namespace) throws NamingException {
JsonObjectBuilder builder = Json.createObjectBuilder();
InitialContext c = new InitialContext();
NamingEnumeration<NameClassPair> list = c.list(namespace);
while (list.hasMoreElements()) {
NameClassPair nameClassPair = list.nextElement();
String name = nameClassPair.getName();
String type = nameClassPair.getClassName();
builder.add(name, type);
}
return builder.build();
}
@Override
public void setMessageDrivenContext(final MessageDrivenContext ctx) throws EJBException {
this.mdbContext = ctx;
try {
final ConnectionFactory connectionFactory = (ConnectionFactory) new InitialContext().lookup("java:comp/env/jms");
mdbInvoker = new MdbInvoker(connectionFactory, this);
} catch (final Exception e) {
throw new EJBException(e);
}
}
public EJBObject returnEJBObject() throws javax.ejb.EJBException {
EncSingletonObject data = null;
try {
final InitialContext ctx = new InitialContext();
final EncSingletonHome home = (EncSingletonHome) ctx.lookup("java:comp/env/singleton/rmi-iiop/home");
data = home.create();
} catch (final Exception e) {
throw new javax.ejb.EJBException(e);
}
return data;
}
/**
* @throws javax.ejb.CreateException
*/
public void ejbCreate() throws javax.ejb.CreateException {
try {
jndiContext = new InitialContext();
} catch (final Exception e) {
throw new CreateException("Can not get the initial context: " + e.getMessage());
}
}
@Test
public void getBpmPlatformXmlLocationFromJndi() throws NamingException, MalformedURLException {
Context context = new InitialContext();
context.bind("java:comp/env/" + BPM_PLATFORM_XML_LOCATION, BPM_PLATFORM_XML_FILE_ABSOLUTE_LOCATION);
URL url = new TomcatParseBpmPlatformXmlStep().lookupBpmPlatformXmlLocationFromJndi();
assertEquals(new File(BPM_PLATFORM_XML_FILE_ABSOLUTE_LOCATION).toURI().toURL(), url);
}
private InitialContext getInitialContext() throws NamingException {
Properties env = new Properties();
if (System.getProperty("java.naming.provider.url") == null) {
env.put("java.naming.provider.url", "tcp://localhost:61616");
}
if (System.getProperty("java.naming.factory.initial") == null) {
env.put("java.naming.factory.initial",
"org.apache.activemq.jndi.ActiveMQInitialContextFactory");
}
return new InitialContext(env);
}
private TestingEntityLocalHome lookupTestingEntityBean() {
try {
Context c = new InitialContext();
TestingEntityLocalHome rv = (TestingEntityLocalHome) c.lookup("java:comp/env/TestingEntityBean");
return rv;
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}