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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: RMIConnectorServer.java From jdk8u60 with GNU General Public License v2.0 | 5 votes |
/** * Bind a stub to a registry. * @param jndiUrl URL of the stub in the registry, extracted * from the <code>JMXServiceURL</code>. * @param attributes A Hashtable containing environment parameters, * built from the Map specified at this object creation. * @param rmiServer The object to bind in the registry * @param rebind true if the object must be rebound. **/ void bind(String jndiUrl, Hashtable<?, ?> attributes, RMIServer rmiServer, boolean rebind) throws NamingException, MalformedURLException { // if jndiURL is not null, we nust bind the stub to a // directory. InitialContext ctx = new InitialContext(attributes); if (rebind) ctx.rebind(jndiUrl, rmiServer); else ctx.bind(jndiUrl, rmiServer); ctx.close(); }
Example #20
Source File: testUseDatabase1InSB_TestingSessionBean.java From netbeans with Apache License 2.0 | 5 votes |
private TestingEntityLocalHome lookupTestingEntityBeanLocal() { 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); } }
Example #21
Source File: SimpleJNDIClientTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Test public void testXACF() 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=XA_CF"); Context ctx = new InitialContext(props); ActiveMQConnectionFactory connectionFactory = (ActiveMQConnectionFactory) ctx.lookup("myConnectionFactory"); Assert.assertEquals(JMSFactoryType.XA_CF.intValue(), connectionFactory.getFactoryType()); }
Example #22
Source File: EncCmp2Bean.java From tomee with Apache License 2.0 | 5 votes |
public void lookupStatefulBusinessLocal() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final BasicStatefulBusinessLocal object = (BasicStatefulBusinessLocal) ctx.lookup("java:comp/env/entity/cmp/beanReferences/stateful-business-local"); Assert.assertNotNull("The EJB BusinessLocal is null", object); } catch (final Exception e) { Assert.fail("Received Exception " + e.getClass() + " : " + e.getMessage()); } } catch (final AssertionFailedError afe) { throw new TestFailureException(afe); } }
Example #23
Source File: ConfigurationBeanTest.java From development with Apache License 2.0 | 5 votes |
@Test(expected = IllegalStateException.class) public void testMissingBeanException() throws Exception { // Simulate missing EJB InitialContext context = new InitialContext(); context.unbind(APPlatformService.JNDI_NAME); // And invoke internal EJB constructor new ConfigurationBean(); }
Example #24
Source File: EncStatelessBean.java From tomee with Apache License 2.0 | 5 votes |
public void lookupStatefulBusinessRemote() throws TestFailureException { try { try { final InitialContext ctx = new InitialContext(); Assert.assertNotNull("The InitialContext is null", ctx); final BasicStatefulBusinessRemote object = (BasicStatefulBusinessRemote) ctx.lookup("java:comp/env/stateless/beanReferences/stateful-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 #25
Source File: JBossJtaTransactionManagerLookup.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void init(Config.Scope config) { try { InitialContext ctx = new InitialContext(); tm = (TransactionManager)ctx.lookup("java:jboss/TransactionManager"); if (tm == null) { logger.debug("Could not locate TransactionManager"); } } catch (NamingException e) { logger.debug("Could not load TransactionManager", e); } }
Example #26
Source File: TomEEWebappObserver.java From tomee with Apache License 2.0 | 5 votes |
public void beforeSuite(@Observes final BeforeSuite event) { final WebBeansContext webBeansContext = AppFinder.findAppContextOrWeb( Thread.currentThread().getContextClassLoader(), AppFinder.WebBeansContextTransformer.INSTANCE); if (webBeansContext != null) { beanManager.set(webBeansContext.getBeanManagerImpl()); } try { context.set(new InitialContext()); } catch (final NamingException e) { // no-op } }
Example #27
Source File: JNDIThreadPoolService.java From incubator-batchee with Apache License 2.0 | 5 votes |
public void executeTask(Runnable work, Object config) { try { final Context ctx = new InitialContext(); final ExecutorService delegateService = (ExecutorService) ctx.lookup(jndiLocation); delegateService.execute(runnableLoaderAware(work)); } catch (final NamingException e) { throw new BatchContainerServiceException(e); } }
Example #28
Source File: JdbcMetricsTest.java From apiman with Apache License 2.0 | 5 votes |
@BeforeClass public static void setup() { try { InitialContext ctx = TestUtil.initialContext(); TestUtil.ensureCtx(ctx, "java:/comp/env"); TestUtil.ensureCtx(ctx, "java:/comp/env/jdbc"); ds = createInMemoryDatasource(); ctx.bind(DB_JNDI_LOC, ds); System.out.println("DataSource created and bound to JNDI: " + DB_JNDI_LOC); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } }
Example #29
Source File: RMIConnectorServer.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
/** * Bind a stub to a registry. * @param jndiUrl URL of the stub in the registry, extracted * from the <code>JMXServiceURL</code>. * @param attributes A Hashtable containing environment parameters, * built from the Map specified at this object creation. * @param rmiServer The object to bind in the registry * @param rebind true if the object must be rebound. **/ void bind(String jndiUrl, Hashtable<?, ?> attributes, RMIServer rmiServer, boolean rebind) throws NamingException, MalformedURLException { // if jndiURL is not null, we nust bind the stub to a // directory. InitialContext ctx = new InitialContext(attributes); if (rebind) ctx.rebind(jndiUrl, rmiServer); else ctx.bind(jndiUrl, rmiServer); ctx.close(); }
Example #30
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); } }