List of usage examples for javax.naming InitialContext bind
public void bind(Name name, Object obj) throws NamingException
From source file:io.apiman.gateway.engine.policies.BasicAuthenticationPolicyTest.java
/** * Test method for {@link io.apiman.gateway.engine.policies.BasicAuthenticationPolicy#apply(ServiceRequest, IPolicyContext, Object, IPolicyChain)}. *//*from ww w .java 2 s .co m*/ @Test public void testApplyJdbc() throws Exception { System.setProperty(Context.INITIAL_CONTEXT_FACTORY, InitialContextFactoryForTest.class.getName()); // Create a test datasource and bind it to JNDI BasicDataSource ds = createInMemoryDatasource(); InitialContext ctx = new InitialContext(); ensureCtx(ctx, "java:comp/env"); //$NON-NLS-1$ ensureCtx(ctx, "java:comp/env/jdbc"); //$NON-NLS-1$ ctx.bind("java:comp/env/jdbc/TestAuthDS", ds); //$NON-NLS-1$ // A live LDAP server is required to run this test! BasicAuthenticationPolicy policy = new BasicAuthenticationPolicy(); String json = "{\r\n" + " \"realm\" : \"TestRealm\",\r\n" + " \"forwardIdentityHttpHeader\" : \"X-Authenticated-Identity\",\r\n" + " \"jdbcIdentity\" : {\r\n" + " \"datasourcePath\" : \"jdbc/TestAuthDS\",\r\n" + " \"query\" : \"SELECT * FROM users WHERE username = ? AND password = ?\",\r\n" + " \"hashAlgorithm\" : \"SHA1\"\r\n" + " }\r\n" + "}"; Object config = policy.parseConfiguration(json); ServiceRequest request = new ServiceRequest(); request.setType("GET"); request.setApiKey("12345"); request.setRemoteAddr("1.2.3.4"); request.setDestination("/"); IPolicyContext context = Mockito.mock(IPolicyContext.class); final PolicyFailure failure = new PolicyFailure(); Mockito.when(context.getComponent(IPolicyFailureFactoryComponent.class)) .thenReturn(new IPolicyFailureFactoryComponent() { @Override public PolicyFailure createFailure(PolicyFailureType type, int failureCode, String message) { return failure; } }); IPolicyChain<ServiceRequest> chain = Mockito.mock(IPolicyChain.class); // Failure policy.apply(request, context, config, chain); Mockito.verify(chain).doFailure(failure); // Failure request.getHeaders().put("Authorization", createBasicAuthorization(JDBC_USER, "invalid_password")); chain = Mockito.mock(IPolicyChain.class); policy.apply(request, context, config, chain); Mockito.verify(chain).doFailure(failure); // Success request.getHeaders().put("Authorization", createBasicAuthorization(JDBC_USER, JDBC_PASSWORD)); chain = Mockito.mock(IPolicyChain.class); policy.apply(request, context, config, chain); Mockito.verify(chain).doApply(request); }
From source file:org.apache.naming.ant.JndiSet.java
public void execute() { try {/*from ww w . j a v a 2s. c o m*/ InitialContext ic = new InitialContext(); Object o = null; if (refId != null) { o = project.getReference(refId); if (o instanceof TaskAdapter) o = ((TaskAdapter) o).getProxy(); } if (o == null) o = value; // Add other cases. log.info("Binding " + contextName + " " + o); ic.bind(contextName, o); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:io.apiman.gateway.test.junit.servlet.ServletGatewayTestServer.java
/** * Does some configuration before starting the server. * @throws IOException/* w w w. j a v a2 s . c o m*/ */ private void preStart() throws IOException { if (withES && node == null) { System.out.println("******* Creating the ES node for gateway testing."); File esHome = new File("target/es"); String esHomeSP = System.getProperty("apiman.test.es-home", null); if (esHomeSP != null) { esHome = new File(esHomeSP); } if (esHome.isDirectory()) { FileUtils.deleteDirectory(esHome); } Builder settings = NodeBuilder.nodeBuilder().settings(); settings.put("path.home", esHome.getAbsolutePath()); settings.put("http.port", "6500-6600"); settings.put("transport.tcp.port", "6600-6700"); settings.put("script.disable_dynamic", "false"); String clusterName = System.getProperty("apiman.test.es-cluster-name", ES_CLUSTER_NAME); boolean isPersistent = "true".equals(System.getProperty("apiman.test.es-persistence", "false")); if (!isPersistent) { settings.put("index.store.type", "memory").put("gateway.type", "none") .put("index.number_of_shards", 1).put("index.number_of_replicas", 1); node = NodeBuilder.nodeBuilder().client(false).clusterName(clusterName).data(true).local(true) .settings(settings).build(); } else { node = NodeBuilder.nodeBuilder().client(false).clusterName(clusterName).data(true).local(false) .settings(settings).build(); } System.out.println("Starting the ES node."); node.start(); System.out.println("ES node was successfully started."); String connectionUrl = "http://localhost:6500"; JestClientFactory factory = new JestClientFactory(); factory.setHttpClientConfig(new HttpClientConfig.Builder(connectionUrl).multiThreaded(true) .connTimeout(JEST_TIMEOUT).readTimeout(JEST_TIMEOUT).build()); client = factory.getObject(); ES_CLIENT = client; } if (withDB) { TestUtil.setProperty("apiman-gateway", DB_JNDI_LOC); 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) { throw new RuntimeException(e); } } if (withISPN) { cacheContainer = new DefaultCacheManager(); Cache<Object, Object> registryCache = cacheContainer.getCache("registry"); if (registryCache == null) { throw new RuntimeException("Error with ISPN cache: 'registry'"); } try { InitialContext ctx = TestUtil.initialContext(); TestUtil.ensureCtx(ctx, "java:jboss"); TestUtil.ensureCtx(ctx, "java:jboss/infinispan"); ctx.bind(ISPN_JNDI_LOC, cacheContainer); } catch (Exception e) { throw new RuntimeException(e); } } }
From source file:org.rimudb.JNDIPoolTests.java
@Before public void setUp() throws Exception { try {/* w w w .j a v a 2s. c o m*/ // Create initial context System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory"); System.setProperty("org.osjava.sj.jndi.shared", "true"); InitialContext ic = new InitialContext(); ic.createSubcontext("java:/comp/env/"); com.mysql.jdbc.jdbc2.optional.MysqlDataSource mysql_datasource = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource(); mysql_datasource.setServerName("localhost"); mysql_datasource.setPortNumber(3306); mysql_datasource.setDatabaseName("dbtest"); mysql_datasource.setUser("dbtest"); mysql_datasource.setPassword("dbtest"); // Create a connection pool datasource org.h2.jdbcx.JdbcDataSource h2_datasource = new org.h2.jdbcx.JdbcDataSource(); h2_datasource.setURL("jdbc:h2:mem:test"); h2_datasource.setUser("sa"); h2_datasource.setPassword(""); ic.bind("jdbc/dbtest", mysql_datasource); } catch (NamingException ex) { log.error(ex); } }
From source file:com.redhat.lightblue.rest.crud.ITCaseCrudResourceRDBMSTest.java
@Before public void setup() throws Exception { File folder = new File("/tmp"); File[] files = folder.listFiles(new FilenameFilter() { @Override//from w w w. j a v a 2 s. com public boolean accept(final File dir, final String name) { return name.startsWith("test.db"); } }); for (final File file : files) { if (!file.delete()) { System.out.println("Failed to remove " + file.getAbsolutePath()); } } mongo.dropDatabase(DB_NAME); mongo.dropDatabase("local"); mongo.dropDatabase("admin"); mongo.dropDatabase("mongo"); mongo.getDB(DB_NAME).dropDatabase(); mongo.getDB("local").dropDatabase(); mongo.getDB("admin").dropDatabase(); mongo.getDB("mongo").dropDatabase(); db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).remove(new BasicDBObject()); mongo.getDB("mongo").getCollection("metadata").remove(new BasicDBObject()); db.createCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION, null); BasicDBObject index = new BasicDBObject("name", 1); index.put("version.value", 1); db.getCollection(MongoMetadata.DEFAULT_METADATA_COLLECTION).ensureIndex(index, "name", true); if (notRegistered) { notRegistered = false; try { // Create initial context System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); // already tried System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.as.naming.InitialContextFactory"); InitialContext ic = new InitialContext(); ic.createSubcontext("java:"); ic.createSubcontext("java:/comp"); ic.createSubcontext("java:/comp/env"); ic.createSubcontext("java:/comp/env/jdbc"); JdbcConnectionPool ds = JdbcConnectionPool.create( "jdbc:h2:file:/tmp/test.db;FILE_LOCK=NO;MVCC=TRUE;DB_CLOSE_ON_EXIT=TRUE", "sa", "sasasa"); ic.bind("java:/mydatasource", ds); } catch (NamingException ex) { throw new IllegalStateException(ex); } } else { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup("java:/mydatasource"); Connection conn = ds.getConnection(); Statement stmt = conn.createStatement(); stmt.execute("DROP ALL OBJECTS "); stmt.close(); } }
From source file:org.wso2.carbon.apimgt.impl.dao.test.APIMgtDAOTest.java
private void initializeDatabase(String configFilePath) { InputStream in = null;/* w ww. j a v a 2 s . com*/ try { in = FileUtils.openInputStream(new File(configFilePath)); StAXOMBuilder builder = new StAXOMBuilder(in); String dataSource = builder.getDocumentElement().getFirstChildWithName(new QName("DataSourceName")) .getText(); OMElement databaseElement = builder.getDocumentElement().getFirstChildWithName(new QName("Database")); String databaseURL = databaseElement.getFirstChildWithName(new QName("URL")).getText(); String databaseUser = databaseElement.getFirstChildWithName(new QName("Username")).getText(); String databasePass = databaseElement.getFirstChildWithName(new QName("Password")).getText(); String databaseDriver = databaseElement.getFirstChildWithName(new QName("Driver")).getText(); BasicDataSource basicDataSource = new BasicDataSource(); basicDataSource.setDriverClassName(databaseDriver); basicDataSource.setUrl(databaseURL); basicDataSource.setUsername(databaseUser); basicDataSource.setPassword(databasePass); // Create initial context System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); System.setProperty(Context.URL_PKG_PREFIXES, "org.apache.naming"); try { InitialContext.doLookup("java:/comp/env/jdbc/WSO2AM_DB"); } catch (NamingException e) { InitialContext ic = new InitialContext(); ic.createSubcontext("java:"); ic.createSubcontext("java:/comp"); ic.createSubcontext("java:/comp/env"); ic.createSubcontext("java:/comp/env/jdbc"); ic.bind("java:/comp/env/jdbc/WSO2AM_DB", basicDataSource); } } catch (XMLStreamException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NamingException e) { e.printStackTrace(); } }
From source file:gov.nih.nci.ncicb.cadsr.bulkloader.util.MainTestCase.java
protected void bindToJNDI(String envJNDIName, String realJNDITree) throws Exception { InitialContext ctx = new InitialContext(); Object dataSourceObject = (DataSource) jndiLookup(envJNDIName); if (dataSourceObject == null) { dataSourceObject = (DataSource) jndiLookup(realJNDITree); if (dataSourceObject == null) { throw new NullPointerException( "The env JNDI='" + envJNDIName + "' and real JNDI='" + realJNDITree + "' are both empty."); }/* w w w.j a va 2 s .co m*/ ctx.bind(envJNDIName, dataSourceObject); } }
From source file:org.mifos.framework.ApplicationInitializer.java
private void initJNDIforPentaho(ApplicationContext applicationContext) { try {/* w w w. j a v a2 s . c o m*/ InitialContext ic = new InitialContext(); //check if ds is already bound boolean dataSourceBound = true; boolean dataSourceBoundDw = true; try { DataSource datasource = (DataSource) ic.lookup("jdbc/SourceDB"); if (datasource != null) { dataSourceBound = true; } } catch (Exception ex) { dataSourceBound = false; } try { DataSource datasourcedw = (DataSource) ic.lookup("jdbc/DestinationDB"); if (datasourcedw != null) { dataSourceBoundDw = true; } } catch (Exception ex) { dataSourceBoundDw = false; } if (!dataSourceBound) { Object dataSource = applicationContext.getBean("dataSource"); try { ic.createSubcontext("jdbc"); } catch (NameAlreadyBoundException ex) { logger.info("Subcontext jdbc was already bound"); } ic.bind("jdbc/SourceDB", dataSource); logger.info("Bound datasource to jdbc/SourceDB"); } else { logger.info("jdbc/SourceDB is already bound"); } if (!dataSourceBoundDw) { Object dataSourcedw = applicationContext.getBean("dataSourcePentahoDW"); try { ic.createSubcontext("jdbc"); } catch (NameAlreadyBoundException ex) { logger.info("Subcontext jdbc was already bound"); } ic.bind("jdbc/DestinationDB", dataSourcedw); logger.info("Bound datasource to jdbc/DestinationDB"); } else { logger.info("jdbc/DestinationDB is already bound"); } } catch (Exception ex) { logger.error("Unable to bind dataSource to JNDI"); } }