Example usage for javax.naming Context bind

List of usage examples for javax.naming Context bind

Introduction

In this page you can find the example usage for javax.naming Context bind.

Prototype

public void bind(String name, Object obj) throws NamingException;

Source Link

Document

Binds a name to an object.

Usage

From source file:org.jboss.test.NamingUtil.java

/**
 * Create test data. It needs to use org.jboss.naming.HttpNamingContextFactory since JNDI through RMI
 * is already secured and disallow bind/unbind/rebind operations.
 * /*from w  ww  . ja v  a  2s.  c o m*/
 *   
 *   
 * @param jndiName JNDI path where to bind data.
 * @param dataKey key under which data is bound
 * @param data Data object to bind. In case data is null last path element is considered subContext. 
 * @param serverHost host on which to create binding 
 * @throws Exception
 */
public static void createTestJNDIBinding(String jndiName, String dataKey, Object data, String serverHost,
        boolean useHAJNDI) throws Exception {

    log.debug("XXX");

    Context ctx = null;
    if (useHAJNDI) {
        ctx = NamingUtil.getFullHAInitialContext(serverHost);
    } else {
        ctx = NamingUtil.getFullInitialContext(serverHost);
    }

    String[] path = jndiName.split("/");
    String subPath = "";
    for (int i = 0; i < path.length; i++) {

        if (path[i].equals("")) {
            continue;
        }

        subPath = subPath + "/" + path[i];
        log.debug("creating subcontext=" + subPath);
        try {
            ctx.createSubcontext(subPath);
            log.debug("subcontext=" + subPath + " created.");
        } catch (NameAlreadyBoundException e) {
            // ignore
        }
    }

    if (data != null) {
        log.debug("bind s=" + subPath + ", dataKey=" + dataKey + ", data=" + data);
        ctx.bind(subPath + "/" + dataKey, data);
        log.debug(data + " bound.");
    }

    ctx.close();

}

From source file:org.jsecurity.jndi.JndiTemplate.java

/**
 * Bind the given object to the current JNDI context, using the given name.
 *
 * @param name   the JNDI name of the object
 * @param object the object to bind/* ww w.ja  v a2 s.c  om*/
 * @throws NamingException thrown by JNDI, mostly name already bound
 */
public void bind(final String name, final Object object) throws NamingException {
    if (log.isDebugEnabled()) {
        log.debug("Binding JNDI object with name [" + name + "]");
    }
    execute(new JndiCallback() {
        public Object doInContext(Context ctx) throws NamingException {
            ctx.bind(name, object);
            return null;
        }
    });
}

From source file:org.nuxeo.runtime.datasource.DataSourceDescriptor.java

public void bindSelf(Context naming) throws NamingException {
    if (xaDataSource != null) {
        String xaName = DataSourceHelper.relativize(getName() + "-xa");
        poolReference = new Reference(XADataSource.class.getName(), PoolFactory.class.getName(), null);
        poolReference.add(new StringRefAddr("dataSourceJNDI", xaName));
        xaReference = new Reference(Framework.expandVars(xaDataSource),
                GenericNamingResourcesFactory.class.getName(), null);
        for (Entry<String, String> e : properties.entrySet()) {
            String key = e.getKey();
            String value = Framework.expandVars(e.getValue());
            StringRefAddr addr = new StringRefAddr(key, value);
            xaReference.add(addr);/* ww w.  j a v  a 2 s  .  co  m*/
        }
        naming.bind(DataSourceHelper.getDataSourceJNDIName(xaName), xaReference);
    } else if (dataSource != null) {
        poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
        final String name = Framework.expandVars(dataSource);
        poolReference.add(new StringRefAddr("dataSourceJNDI", DataSourceHelper.getDataSourceJNDIName(name)));
    } else if (driverClasssName != null) {
        poolReference = new Reference(DataSource.class.getName(), PoolFactory.class.getName(), null);
    } else {
        throw new RuntimeException(
                "Datasource " + getName() + " should have xaDataSource or driverClassName attribute");
    }

    for (Entry<String, String> e : properties.entrySet()) {
        String key = e.getKey();
        String value = Framework.expandVars(e.getValue());
        StringRefAddr addr = new StringRefAddr(key, value);
        poolReference.add(addr);
    }

    NamedNodeMap attrs = element.getAttributes();
    for (int i = 0; i < attrs.getLength(); i++) {
        Node attr = attrs.item(i);
        String attrName = attr.getNodeName();
        String value = Framework.expandVars(attr.getNodeValue());
        StringRefAddr addr = new StringRefAddr(attrName, value);
        poolReference.add(addr);
    }

    LogFactory.getLog(DataSourceDescriptor.class).info("binding " + getName());
    String jndiName = DataSourceHelper.getDataSourceJNDIName(getName());
    naming.bind(jndiName, poolReference);
    // create pooled
    naming.lookup(jndiName);
}

From source file:org.settings4j.connector.JNDIConnectorTest.java

/**
 * SmokeTest: tests if the {@link #setTomcatJNDIContextProperties()} works which is required for all other
 * TestCases.// w w  w. ja  va2 s.com
 *
 * @throws Exception in case of an error
 */
@Test
public void testSmokeTest() throws Exception {
    LOG.info("START: testJNDIConnectorWithoutJNDI");
    // Set JNDI Tomcat Configs
    setTomcatJNDIContextProperties();
    final InitialContext initialContext = new InitialContext();
    Context tmpCtx = initialContext.createSubcontext("java:");
    tmpCtx = tmpCtx.createSubcontext("comp");
    tmpCtx = tmpCtx.createSubcontext("env");
    tmpCtx.bind("testKey", "testValue");

    // start getting the JNDI Resource
    final Context envCtx = (Context) new InitialContext().lookup("java:/comp/env");
    final Object testValue = envCtx.lookup("testKey");

    assertThat(testValue, is((Object) "testValue"));

}

From source file:org.superbiz.DataSourceCipheredExampleTest.java

@Test
public void accessDatasource() throws Exception {
    // define the datasource
    Properties properties = new Properties();
    properties.setProperty("ProtectedDatasource", "new://Resource?type=DataSource");
    properties.setProperty("ProtectedDatasource.JdbcDriver", "org.hsqldb.jdbcDriver");
    properties.setProperty("ProtectedDatasource.JdbcUrl", DATASOURCE_URL);
    properties.setProperty("ProtectedDatasource.UserName", USER);
    properties.setProperty("ProtectedDatasource.Password", "fEroTNXjaL5SOTyRQ92x3DNVS/ksbtgs");
    properties.setProperty("ProtectedDatasource.PasswordCipher", "Static3DES");
    properties.setProperty("ProtectedDatasource.JtaManaged", "true");

    // start the context and makes junit test injections
    EJBContainer container = EJBContainer.createEJBContainer(properties);
    Context context = container.getContext();
    context.bind("inject", this);

    // test the datasource
    assertNotNull(dataSource);/*from   w w w  .  j a  va2  s  . co m*/
    assertNotNull(dataSource.getConnection());

    // closing the context
    container.close();
}

From source file:org.superbiz.DataSourceCipheredExampleTest.java

@Test
public void accessDatasourceWithMyImplementation() throws Exception {
    // define the datasource
    Properties properties = new Properties();
    properties.setProperty("ProtectedDatasource", "new://Resource?type=DataSource");
    properties.setProperty("ProtectedDatasource.JdbcDriver", "org.hsqldb.jdbcDriver");
    properties.setProperty("ProtectedDatasource.JdbcUrl", "jdbc:hsqldb:mem:protected");
    properties.setProperty("ProtectedDatasource.UserName", USER);
    properties.setProperty("ProtectedDatasource.Password", "3MdniFr3v3NLLuoY");
    properties.setProperty("ProtectedDatasource.PasswordCipher", "reverse");
    properties.setProperty("ProtectedDatasource.JtaManaged", "true");

    // start the context and makes junit test injections
    EJBContainer container = EJBContainer.createEJBContainer(properties);
    Context context = container.getContext();
    context.bind("inject", this);

    // test the datasource
    assertNotNull(dataSource);//from  www.  j  a v  a 2s.co m
    assertNotNull(dataSource.getConnection());

    // closing the context
    container.close();
}

From source file:org.wso2.carbon.transaction.manager.TransactionManagerComponent.java

protected static void bindTransactionManagerWithJNDIForTenant(int tid) {
    PrivilegedCarbonContext.startTenantFlow();
    PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId(tid);

    try {/*from w w w  .  j a  v a  2  s  .  c  o  m*/
        Context currentCtx = PrivilegedCarbonContext.getThreadLocalCarbonContext().getJNDIContext();
        Context javaCtx = null;
        try {
            javaCtx = (Context) currentCtx.lookup("java:comp");
        } catch (NameNotFoundException ignore) {
            //ignore
        }
        if (javaCtx == null) {
            currentCtx = currentCtx.createSubcontext("java:comp");
        }

        Object txManager = null, userTx = null;
        try {
            txManager = currentCtx.lookup("java:comp/TransactionManager");
        } catch (NameNotFoundException ignore) {
            //ignore
        }
        try {
            userTx = currentCtx.lookup("java:comp/UserTransaction");
        } catch (NameNotFoundException ignore) {
            //ignore
        }
        if (txManager == null) {
            currentCtx.bind("TransactionManager", getTransactionManager());
        }
        if (userTx == null) {
            currentCtx.bind("UserTransaction", getUserTransaction());
        }
    } catch (Exception e) {
        log.error("Error in binding transaction manager for tenant: " + tid, e);
    } finally {
        PrivilegedCarbonContext.endTenantFlow();
    }
}

From source file:org.xbib.io.jdbc.SQLConnectionFactory.java

/**
 * Get connection//from  w ww  .j av  a  2s.  co  m
 *
 * @param uri
 *
 * @return an SQL connection
 *
 * @throws java.io.IOException
 */
@Override
public Connection<SQLSession> getConnection(final URI uri) throws IOException {
    this.properties = URIUtil.getPropertiesFromURI(uri);
    Context context = null;
    DataSource ds = null;
    for (String name : new String[] { "jdbc/" + properties.getProperty("host"),
            "java:comp/env/" + properties.getProperty("scheme") + ":" + properties.getProperty("host") + ":"
                    + properties.getProperty("port") }) {
        this.jndiName = name;
        try {
            context = new InitialContext();
            Object o = context.lookup(jndiName);
            if (o instanceof DataSource) {
                logger.info("DataSource ''{}'' found in naming context", jndiName);
                ds = (DataSource) o;
                break;
            } else {
                logger.warn("JNDI object {} not a DataSource class: {} - ignored", jndiName, o.getClass());
            }
        } catch (NameNotFoundException e) {
            logger.warn("DataSource ''{}'' not found in context", jndiName);
        } catch (NamingException e) {
            logger.warn(e.getMessage(), e);
        }
    }
    try {
        if (ds == null) {
            BasicDataSource bsource = new BasicDataSource();
            bsource.setDriverClassName(properties.getProperty("driverClassName"));
            String url = properties.getProperty("jdbcScheme") + properties.getProperty("host") + ":"
                    + properties.getProperty("port")
                    + ("jdbc:oracle:thin:@".equals(properties.getProperty("jdbcScheme")) ? ":" : "/")
                    + properties.getProperty("cluster");
            bsource.setUrl(url);
            if (properties.containsKey("username")) {
                bsource.setUsername(properties.getProperty("username"));
            }
            if (properties.containsKey("password")) {
                bsource.setPassword(properties.getProperty("password"));
            }
            if (properties.containsKey("n")) {
                bsource.setInitialSize(Integer.parseInt(properties.getProperty("n")));
                bsource.setMaxActive(Integer.parseInt(properties.getProperty("n")));
            }
            // Other BasicDataSource settings, not used yet:
            //  setAccessToUnderlyingConnectionAllowed(boolean allow)
            //  setDefaultAutoCommit(boolean defaultAutoCommit)
            //  setDefaultCatalog(String defaultCatalog)
            //  setDefaultReadOnly(boolean defaultReadOnly)
            //  setDefaultTransactionIsolation(int defaultTransactionIsolation)
            //  setLogAbandoned(boolean logAbandoned)
            //  setLoginTimeout(int loginTimeout)
            //  setLogWriter(PrintWriter logWriter)
            //  setMaxIdle(int maxIdle)
            //  setMaxOpenPreparedStatements(int maxOpenStatements)
            //  setMaxWait(long maxWait)
            //  setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis)
            //  setMinIdle(int minIdle)
            //  setNumTestsPerEvictionRun(int numTestsPerEvictionRun)
            //  setPoolPreparedStatements(boolean poolingStatements)
            //  setTestOnBorrow(boolean testOnBorrow)
            //  setTestOnReturn(boolean testOnReturn)
            //  setTestWhileIdle(boolean testWhileIdle)
            //  setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis)
            //  setValidationQuery(String validationQuery)
            context.bind(jndiName, bsource);
            ds = (DataSource) bsource;
        }
    } catch (NamingException e) {
        throw new IOException(e.getMessage());
    }
    try {
        ds.getConnection().setAutoCommit("false".equals(properties.getProperty("autoCommit")) ? false : true);
    } catch (SQLException e) {
        throw new IOException(e.getMessage());
    }
    return new SQLConnection(ds);
}