Java Code Examples for javax.naming.Context#lookup()
The following examples show how to use
javax.naming.Context#lookup() .
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: JPAResource.java From microprofile-sandbox with Apache License 2.0 | 9 votes |
@SuppressWarnings("unchecked") public void retrieveThing(StringBuilder builder) throws SystemException, NamingException { // Look up the EntityManager in JNDI Context ctx = new InitialContext(); EntityManager em = (EntityManager) ctx.lookup(JNDI_NAME); // Compose a JPQL query String query = "SELECT t FROM Thing t"; Query q = em.createQuery(query); // Execute the query List<Thing> things = q.getResultList(); builder.append("Query returned " + things.size() + " things").append(newline); // Let's see what we got back! for (Thing thing : things) { builder.append("Thing in list " + thing).append(newline); } }
Example 2
Source File: MaxPoolSizeDUnitTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
public static void createTable(String tableName) throws NamingException, SQLException { Context ctx = cache.getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource"); //String sql = "create table " + tableName + " (id number primary key, name // varchar2(50))"; //String sql = "create table " + tableName + " (id integer primary key, // name varchar(50))"; String sql = "create table " + tableName + " (id integer NOT NULL, name varchar(50), CONSTRAINT the_key PRIMARY KEY(id))"; getLogWriter().fine(sql); Connection conn = ds.getConnection(); Statement sm = conn.createStatement(); sm.execute(sql); sm.close(); sm = conn.createStatement(); for (int i = 1; i <= 10; i++) { sql = "insert into " + tableName + " values (" + i + ",'name" + i + "')"; sm.addBatch(sql); getLogWriter().fine(sql); } sm.executeBatch(); conn.close(); }
Example 3
Source File: DataSourceFactoryTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
public void testGetTranxDataSource() throws Exception { try { 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("DataSourceFactoryTest-testGetTranxDataSource() Error in creating the getTranxDataSource"); } catch (Exception e) { fail("Exception occured in testGetTranxDataSource due to "+e); e.printStackTrace(); } }
Example 4
Source File: LookupFactory.java From tomee with Apache License 2.0 | 6 votes |
@Override public Object getObjectInstance(final Object object, final Name name, final Context context, final Hashtable environment) throws Exception { if (!(object instanceof Reference)) { return null; } final Reference reference = ((Reference) object); final String jndiName = NamingUtil.getProperty(reference, NamingUtil.JNDI_NAME); if (jndiName == null) { return null; } try { return context.lookup(jndiName.replaceFirst("^java:", "")); } catch (final NameNotFoundException e) { return new InitialContext().lookup(jndiName); } }
Example 5
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 6
Source File: ConnectionUtil.java From tutorials with MIT License | 6 votes |
public static Connection getConnection() { try { String jndiName = "java:/comp/env/jdbc/MyDataSource"; Context initialContext = new InitialContext(); DataSource datasource = (DataSource)initialContext.lookup(jndiName); if (datasource != null) { return datasource.getConnection(); } else { logger.error("Failed to lookup datasource."); } } catch (NamingException | SQLException exc) { logger.error(exc.getMessage()); } return null; }
Example 7
Source File: MoviesBusinessBean.java From tomee with Apache License 2.0 | 6 votes |
public void doLogic() { try { final Context initial = new InitialContext(); final LocalActorHome actorHome = (LocalActorHome) initial.lookup("java:comp/env/ejb/Actor"); final Context initial1 = new InitialContext(); final LocalMovieHome movieHome = (LocalMovieHome) initial1.lookup("java:comp/env/ejb/Movie"); final LocalMovie movie = movieHome.create("Bad Boys", "Action Comedy"); final LocalActor actor1 = actorHome.create("Will Smith"); final LocalActor actor2 = actorHome.create("Martin Lawrence"); movie.addActor(actor1); movie.addActor(actor2); } catch (final Exception ex) { throw new EJBException(ex.getMessage()); } }
Example 8
Source File: AbstractPoolCacheTest.java From gemfirexd-oss with Apache License 2.0 | 6 votes |
/** * Test of validateConnection method, of class * com.gemstone.gemfire.internal.datasource.AbstractPoolCache. */ public void testValidateConnection() { try { 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"); } catch (Exception e) { fail("Exception occured in testValidateConnection due to " + e); e.printStackTrace(); } }
Example 9
Source File: LoginHandler.java From development with Apache License 2.0 | 5 votes |
private String getUserKey(String userId, String orgId, String tenantId) throws NamingException, SQLException { Context context = new InitialContext(); DataSource ds = (DataSource) context.lookup("BSSDS"); AbstractKeyQuery keyQuery = null; if (StringUtils.isNotEmpty(tenantId)) { VOConfigurationSetting setting = getConfigService(context) .getVOConfigurationSetting( ConfigurationKey.SSO_DEFAULT_TENANT_ID, Configuration.GLOBAL_CONTEXT); String defaultTenantId = setting.getValue(); if (tenantId.equals(defaultTenantId)) { keyQuery = new UserKeyQuery(ds, userId); } else { keyQuery = new UserKeyForTenantQuery(ds, userId, tenantId); } } else if (StringUtils.isNotEmpty(orgId)) { keyQuery = new UserKeyForOrganizationQuery(ds, userId, orgId); } keyQuery.execute(); long userKey = keyQuery.getKey(); if (userKey == 0) { throw new SQLException( "User not found [user id: " + userId + ", tenant id: " + tenantId + ", orgaznization id: " + orgId + " ]"); } return String.valueOf(userKey); }
Example 10
Source File: JndiReference.java From tomee with Apache License 2.0 | 5 votes |
public Object getObject() throws NamingException { final Context externalContext = getContext(); synchronized (externalContext) { /* According to the JNDI SPI specification multiple threads may not access the same JNDI Context *instance* concurrently. Since we don't know the origines of the federated context we must synchonrize access to it. JNDI SPI Sepecifiation 1.2 Section 2.2 */ return externalContext.lookup(jndiName); } }
Example 11
Source File: ComponentRegistryTest.java From tomee with Apache License 2.0 | 5 votes |
@Test public void oneInstancePerMultipleReferences() throws Exception { final Context context = ejbContainer.getContext(); // Both references below will point to the exact same instance final ComponentRegistry one = (ComponentRegistry) context.lookup("java:global/simple-singleton/ComponentRegistry"); final ComponentRegistry two = (ComponentRegistry) context.lookup("java:global/simple-singleton/ComponentRegistry"); final URI expectedUri = new URI("foo://bar/baz"); one.setComponent(URI.class, expectedUri); final URI actualUri = two.getComponent(URI.class); Assert.assertSame(expectedUri, actualUri); two.removeComponent(URI.class); URI uri = one.getComponent(URI.class); Assert.assertNull(uri); one.removeComponent(URI.class); uri = two.getComponent(URI.class); Assert.assertNull(uri); final Date expectedDate = new Date(); two.setComponent(Date.class, expectedDate); final Date actualDate = one.getComponent(Date.class); Assert.assertSame(expectedDate, actualDate); Collection<?> collection = one.getComponents(); System.out.println(collection); Assert.assertEquals("Reference 'one' - ComponentRegistry contains one record", collection.size(), 1); collection = two.getComponents(); Assert.assertEquals("Reference 'two' - ComponentRegistry contains one record", collection.size(), 1); }
Example 12
Source File: JTADUnitTest.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
private int executeQuery(String query) { int returnValue = 0; Connection conn = null; Statement stm = null; try { Context ctx = CacheFactory.getAnyInstance().getJNDIContext(); DataSource ds = (DataSource) ctx.lookup("java:/XAPooledDataSource"); conn = ds.getConnection(); stm = conn.createStatement(); returnValue = stm.executeUpdate(query); } 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; }
Example 13
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 14
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 15
Source File: AbstractPoolCacheTest.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
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 thrown in testGetSimpleDataSource due to " + e); e.printStackTrace(); } }
Example 16
Source File: MyResource.java From thorntail with Apache License 2.0 | 5 votes |
@GET @Produces("text/plain") public String get() throws NamingException, SQLException { Context ctx = new InitialContext(); DataSource ds = (DataSource) ctx.lookup("jboss/datasources/ExampleDS"); try (Connection conn = ds.getConnection()) { return "Howdy using connection: " + conn; } }
Example 17
Source File: SimpleJNDIClientTest.java From activemq-artemis with Apache License 2.0 | 5 votes |
@Test public void testRemoteCFWithTCP() 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", "tcp://127.0.0.1:61616"); Context ctx = new InitialContext(props); ConnectionFactory connectionFactory = (ConnectionFactory) ctx.lookup("myConnectionFactory"); connectionFactory.createConnection().close(); }
Example 18
Source File: DefaultInstanceManager.java From tomcatsrc with Apache License 2.0 | 5 votes |
/** * 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); } }
Example 19
Source File: JdbcMigrationLauncherFactory.java From lams with GNU General Public License v2.0 | 4 votes |
/** * Used to configure the migration launcher with properties from a servlet * context. You do not need migration.properties to use this method. * * @param launcher the launcher to configure * @param sce the event to get the context and associated parameters from * @throws MigrationException if a problem with the look up in JNDI occurs */ private void configureFromServletContext(JdbcMigrationLauncher launcher, ServletContextEvent sce) throws MigrationException { String readOnly = sce.getServletContext().getInitParameter("migration.readonly"); launcher.setReadOnly(false); if ("true".equals(readOnly)) { launcher.setReadOnly(true); } // See if they want to override the lock after a certain amount of time String lockPollRetries = sce.getServletContext().getInitParameter("migration.lockPollRetries"); if (lockPollRetries != null) { launcher.setLockPollRetries(Integer.parseInt(lockPollRetries)); } String patchPath = ConfigurationUtil.getRequiredParam("migration.patchpath", sce, this); launcher.setPatchPath(patchPath); String postPatchPath = sce.getServletContext().getInitParameter("migration.postpatchpath"); launcher.setPostPatchPath(postPatchPath); String databases = sce.getServletContext().getInitParameter("migration.jdbc.systems"); String[] databaseNames; if ((databases == null) || "".equals(databases)) { databaseNames = new String[1]; databaseNames[0] = ""; log.debug("jdbc.systems was null or empty, not multi-node"); } else { databaseNames = databases.split(","); log.debug("jdbc.systems was set to " + databases + ", configuring multi-node"); } for (int i = 0; i < databaseNames.length; i++) { String databaseName = databaseNames[i]; if (databaseName != "") { databaseName = databaseName + "."; } String databaseType = ConfigurationUtil.getRequiredParam("migration." + databaseName + "databasetype", sce, this); String systemName = ConfigurationUtil.getRequiredParam("migration.systemname", sce, this); String dataSource = ConfigurationUtil.getRequiredParam("migration." + databaseName + "datasource", sce, this); DataSourceMigrationContext context = getDataSourceMigrationContext(); context.setSystemName(systemName); context.setDatabaseType(new DatabaseType(databaseType)); try { Context ctx = new InitialContext(); if (ctx == null) { throw new IllegalArgumentException("A jndi context must be " + "present to use this configuration."); } DataSource ds = (DataSource) ctx.lookup(dataSource); context.setDataSource(ds); log.debug("adding context with datasource " + dataSource + " of type " + databaseType); launcher.addContext(context); } catch (NamingException e) { throw new MigrationException("Problem with JNDI look up of " + dataSource, e); } } }
Example 20
Source File: MultithreadTest.java From tomee with Apache License 2.0 | 4 votes |
@Before public void setUp() throws Exception { final int poolSize = 10; System.setProperty("openejb.client.connectionpool.size", "" + (poolSize * 2)); final EjbServer ejbServer = new EjbServer(); final KeepAliveServer keepAliveServer = new KeepAliveServer(ejbServer, false); final Properties initProps = new Properties(); initProps.setProperty("openejb.deployments.classpath.include", ""); initProps.setProperty("openejb.deployments.classpath.filter.descriptors", "true"); OpenEJB.init(initProps, new ServerFederation()); ejbServer.init(new Properties()); final ServicePool pool = new ServicePool(keepAliveServer, (poolSize * 2)); this.serviceDaemon = new ServiceDaemon(pool, 0, "localhost"); serviceDaemon.start(); final int port = serviceDaemon.getPort(); final ConfigurationFactory config = new ConfigurationFactory(); final Assembler assembler = SystemInstance.get().getComponent(Assembler.class); // containers final StatelessSessionContainerInfo statelessContainerInfo = config.configureService(StatelessSessionContainerInfo.class); statelessContainerInfo.properties.setProperty("TimeOut", "100"); statelessContainerInfo.properties.setProperty("PoolSize", "" + poolSize); statelessContainerInfo.properties.setProperty("MinSize", "2"); statelessContainerInfo.properties.setProperty("StrictPooling", "true"); assembler.createContainer(statelessContainerInfo); // Setup the descriptor information final StatelessBean bean = new StatelessBean(CounterBean.class); bean.addBusinessLocal(Counter.class.getName()); bean.addBusinessRemote(RemoteCounter.class.getName()); bean.addPostConstruct("init"); bean.addPreDestroy("destroy"); final EjbJar ejbJar = new EjbJar(); ejbJar.addEnterpriseBean(bean); CounterBean.instances.set(0); assembler.createApplication(config.configureApplication(ejbJar)); final Properties props = new Properties(); props.put("java.naming.factory.initial", "org.apache.openejb.client.RemoteInitialContextFactory"); props.put("java.naming.provider.url", "ejbd://127.0.0.1:" + port); final Context context = new InitialContext(props); counter = (Counter) context.lookup("CounterBeanRemote"); }