javax.naming.InitialContext Java Examples
The following examples show how to use
javax.naming.InitialContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestNamingContext.java From Tomcat8-Source-Read with MIT License | 7 votes |
@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); } }
Example #2
Source File: TestNamingContext.java From Tomcat8-Source-Read with MIT License | 6 votes |
@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); } }
Example #3
Source File: TomcatContext.java From mdw with Apache License 2.0 | 6 votes |
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; } }
Example #4
Source File: EncMdbBean.java From tomee with Apache License 2.0 | 6 votes |
@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); } }
Example #5
Source File: JtaTransaction.java From cdi with Apache License 2.0 | 6 votes |
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; }
Example #6
Source File: EncSingletonBean.java From tomee with Apache License 2.0 | 6 votes |
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); } }
Example #7
Source File: ContextLookupSingletonBean.java From tomee with Apache License 2.0 | 6 votes |
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); } }
Example #8
Source File: BeanLocatorTest.java From eplmp with Eclipse Public License 1.0 | 6 votes |
@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); }
Example #9
Source File: EncCmpBean.java From tomee with Apache License 2.0 | 6 votes |
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); } }
Example #10
Source File: JndiRegistry.java From XPagesExtensionLibrary with Apache License 2.0 | 6 votes |
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); } } }
Example #11
Source File: JBossWorkManagerUtils.java From lams with GNU General Public License v2.0 | 6 votes |
/** * 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); } }
Example #12
Source File: JndiServlet.java From tomee with Apache License 2.0 | 6 votes |
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()); } } }
Example #13
Source File: EncMdbBean.java From tomee with Apache License 2.0 | 6 votes |
@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); } }
Example #14
Source File: StorageBean.java From tomee with Apache License 2.0 | 6 votes |
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); } }
Example #15
Source File: PushSocket.java From CodeDefenders with GNU Lesser General Public License v3.0 | 6 votes |
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(); } }
Example #16
Source File: EncBmpBean.java From tomee with Apache License 2.0 | 6 votes |
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); } }
Example #17
Source File: IvmTestServer.java From tomee with Apache License 2.0 | 6 votes |
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"); } }
Example #18
Source File: RecommenderStartup.java From TeaStore with Apache License 2.0 | 6 votes |
/** * @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."); } }
Example #19
Source File: TransactionalConnectionProvider.java From hibernate-demos with Apache License 2.0 | 5 votes |
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); } }
Example #20
Source File: DbUtils.java From proarc with GNU General Public License v3.0 | 5 votes |
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; }
Example #21
Source File: SimpleJNDIClientTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@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); }
Example #22
Source File: BookServletRemote.java From java-course-ee with MIT License | 5 votes |
@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"); }
Example #23
Source File: JndiRemoteShutdown.java From JVoiceXML with GNU Lesser General Public License v2.1 | 5 votes |
/** * 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); }
Example #24
Source File: PingsResource.java From ping with Apache License 2.0 | 5 votes |
@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(); }
Example #25
Source File: ContextLookupMdbBean.java From tomee with Apache License 2.0 | 5 votes |
@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); } }
Example #26
Source File: RmiIiopSingletonBean.java From tomee with Apache License 2.0 | 5 votes |
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; }
Example #27
Source File: ContainerTxStatelessBean.java From tomee with Apache License 2.0 | 5 votes |
/** * @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()); } }
Example #28
Source File: BpmPlatformXmlLocationTest.java From camunda-bpm-platform with Apache License 2.0 | 5 votes |
@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); }
Example #29
Source File: MDDProducer.java From micro-integrator with Apache License 2.0 | 5 votes |
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); }
Example #30
Source File: testCallEJB2InSB_TestingSessionBean.java From netbeans with Apache License 2.0 | 5 votes |
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); } }