Example usage for javax.naming InitialContext rebind

List of usage examples for javax.naming InitialContext rebind

Introduction

In this page you can find the example usage for javax.naming InitialContext rebind.

Prototype

public void rebind(Name name, Object obj) throws NamingException 

Source Link

Usage

From source file:com.silverpeas.sharing.model.SimpleFileAccessControlTest.java

@Before
public void generalSetUp() throws Exception {
    InitialContext ic = new InitialContext();
    ic.rebind(JNDINames.ATTACHMENT_DATASOURCE, dataSource);
    IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());
    DatabaseOperation.DELETE_ALL.execute(connection, dataSet);
    DatabaseOperation.CLEAN_INSERT.execute(connection, dataSet);
    DBUtil.getInstanceForTest(dataSource.getConnection());
    if (!registred) {
        Reader reader = null;//from   w  ww  . j av  a 2s  .c  o  m
        try {
            reader = new InputStreamReader(SimpleFileAccessControlTest.class.getClassLoader()
                    .getResourceAsStream("silverpeas-jcr.txt"), CharEncoding.UTF_8);
            SilverpeasRegister.registerNodeTypes(reader);
        } finally {
            IOUtils.closeQuietly(reader);
        }
        registred = true;
        DBUtil.getInstanceForTest(dataSource.getConnection());
    }
    Session session = null;
    try {
        session = getRepository().login(new SilverpeasSystemCredentials());
        if (!session.getRootNode().hasNode(instanceId)) {
            session.getRootNode().addNode(instanceId, NT_FOLDER);
        }
        session.save();
    } finally {
        if (session != null) {
            session.logout();
        }
    }
}

From source file:com.sf.ddao.JNDIDaoTest.java

protected void setUp() throws Exception {
    super.setUp();
    JDBCMockObjectFactory factory = getJDBCMockObjectFactory();
    MockDataSource ds = factory.getMockDataSource();
    MockContextFactory.setAsInitial();/*from w w  w .  j  a va 2 s.  co m*/
    InitialContext context = new InitialContext();
    context.rebind(JNDIDataSourceHandler.DS_CTX_PREFIX + "jdbc/testdb", ds);
    this.injector = Guice.createInjector(new ChainModule(TestUserDao.class));
}

From source file:com.silverpeas.components.model.AbstractTestDao.java

/**
 * Configure the data source from a JNDI context. This is called directly by JUnit 4 at test class
 * loading or by the setUp() method at each test invocation in JUnit 3.
 *
 * @throws IOException if an error occurs while communicating with the JNDI context.
 * @throws NamingException if the data source cannot be found in the JNDI context.
 * @throws Exception if the data source cannot be created.
 *//*from   ww  w .  jav  a 2  s. co m*/
public void configureJNDIDatasource() throws Exception {
    InitialContext ic = new InitialContext();
    EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
    datasource = builder.setType(EmbeddedDatabaseType.H2).addScript(getTableCreationScript()).build();
    ic.rebind(jndiName, datasource);
}

From source file:com.silverpeas.components.model.AbstractSpringJndiDaoTest.java

@Before
public void init() throws Exception {
    InitialContext ic = new InitialContext();
    Properties props = new Properties();
    props.load(AbstractTestDao.class.getClassLoader().getResourceAsStream("jdbc.properties"));
    jndiName = props.getProperty("jndi.name");
    rebind(ic, jndiName, this.dataSource);
    ic.rebind(jndiName, this.dataSource);
    IDatabaseConnection connection = getConnection();
    getSetUpOperation().execute(connection, getDataSet());
    connection.close();//  w  ww. j a v a  2s. c  o m
}

From source file:com.silverpeas.components.model.SilverpeasJndiCase.java

public void configureJNDIDatasource() throws IOException, NamingException, Exception {
    InitialContext ic = new InitialContext();
    if (datasource == null) {
        Properties props = new Properties();
        props.load(SilverpeasJndiCase.class.getClassLoader().getResourceAsStream("jdbc.properties"));
        datasource = (BasicDataSource) BasicDataSourceFactory.createDataSource(props);
        jndiName = props.getProperty("jndi.name");
        ic.rebind(jndiName, datasource);
    }//  w  w w .  j av a2  s .  c o m
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

@Before
public void init() throws Exception {
    InitialContext ic = new InitialContext();
    Properties properties = new Properties();
    properties.load(PathTestUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"));
    DataSource ds = BasicDataSourceFactory.createDataSource(properties);
    rebind(ic, JNDINames.DATABASE_DATASOURCE, ds);
    ic.rebind(JNDINames.DATABASE_DATASOURCE, ds);
    rebind(ic, JNDINames.ADMIN_DATASOURCE, ds);
    ic.rebind(JNDINames.ADMIN_DATASOURCE, ds);
    setUpDatabase();/*from w  ww  .  j  a  v a  2s  .  co  m*/
}

From source file:org.alfresco.reporting.test.TestReporting.java

private static void setJndiDataSource(String source) throws NamingException, RemoteException {
    System.out.println("enter setJndiDataSource source=" + source);

    ConnectionPoolDataSource dataSource = new MysqlConnectionPoolDataSource();
    ((MysqlDataSource) dataSource).setUser("alfrescoo");
    ((MysqlDataSource) dataSource).setPassword("d=dMdva1fresco");
    ((MysqlDataSource) dataSource).setServerName("localhost");
    ((MysqlDataSource) dataSource).setPort(3306);
    ((MysqlDataSource) dataSource).setDatabaseName("alfrescoreporting");
    DataSource ds = (javax.sql.DataSource) dataSource;
    InitialContext context = createContext();
    context.rebind("java:/comp/env/jdbc/" + source, ds);
    System.out.println("exit setJndiDataSource");
}

From source file:org.apache.synapse.commons.datasource.JNDIBasedDataSourceRepository.java

/**
 * Register a DataSource in the JNDI tree
 *
 * @see DataSourceRepository#register(DataSourceInformation)
 *//*from ww w  .j  av a 2  s.  c o m*/
public void register(DataSourceInformation information) {

    validateInitialized();
    String dataSourceName = information.getDatasourceName();
    validateDSName(dataSourceName);
    Properties properties = information.getProperties();

    InitialContext context = null;
    Properties jndiEvn = null;

    if (properties == null || properties.isEmpty()) {
        if (initialContext != null) {
            context = initialContext;
            if (log.isDebugEnabled()) {
                log.debug("Empty JNDI properties for datasource " + dataSourceName);
                log.debug("Using system-wide jndi properties : " + jndiProperties);
            }

            jndiEvn = jndiProperties;
        }
    }

    if (context == null) {

        jndiEvn = createJNDIEnvironment(properties, information.getAlias());
        context = createInitialContext(jndiEvn);

        if (context == null) {

            validateInitialContext(initialContext);
            context = initialContext;

            if (log.isDebugEnabled()) {
                log.debug("Cannot create a name context with provided jndi properties : " + jndiEvn);
                log.debug("Using system-wide JNDI properties : " + jndiProperties);
            }

            jndiEvn = jndiProperties;
        } else {
            perDataSourceICMap.put(dataSourceName, context);
        }
    }

    String dsType = information.getType();
    String driver = information.getDriver();
    String url = information.getUrl();

    String user = information.getSecretInformation().getUser();
    String password = information.getSecretInformation().getResolvedSecret();

    String maxActive = String.valueOf(information.getMaxActive());
    String maxIdle = String.valueOf(information.getMaxIdle());
    String maxWait = String.valueOf(information.getMaxWait());

    //populates context tree
    populateContextTree(context, dataSourceName);

    if (DataSourceInformation.BASIC_DATA_SOURCE.equals(dsType)) {

        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);

        ref.add(new StringRefAddr(DataSourceConstants.PROP_DRIVER_CLS_NAME, driver));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_URL, url));
        ref.add(new StringRefAddr(SecurityConstants.PROP_USER_NAME, user));
        ref.add(new StringRefAddr(SecurityConstants.PROP_PASSWORD, password));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_ACTIVE, maxActive));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_IDLE, maxIdle));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_MAX_WAIT, maxWait));

        // set BasicDataSource specific parameters
        setBasicDataSourceParameters(ref, information);
        //set default jndiProperties for reference
        setCommonParameters(ref, information);

        try {

            if (log.isDebugEnabled()) {
                log.debug("Registering a DataSource with name : " + dataSourceName
                        + " in the JNDI tree with jndiProperties : " + jndiEvn);
            }

            context.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = " Error binding name ' " + dataSourceName + " ' to "
                    + "the DataSource(BasicDataSource) reference";
            throw new SynapseCommonsException(msg, e, log);
        }

    } else if (DataSourceInformation.PER_USER_POOL_DATA_SOURCE.equals(dsType)) {

        // Construct DriverAdapterCPDS reference
        String className = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_CLASS_NAME);
        String factory = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_FACTORY);
        String name = (String) information.getParameter(DataSourceConstants.PROP_CPDS_ADAPTER
                + DataSourceConstants.DOT_STRING + DataSourceConstants.PROP_CPDS_NAME);

        Reference cpdsRef = new Reference(className, factory, null);

        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_DRIVER, driver));
        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_URL, url));
        cpdsRef.add(new StringRefAddr(DataSourceConstants.PROP_USER, user));
        cpdsRef.add(new StringRefAddr(SecurityConstants.PROP_PASSWORD, password));

        try {
            context.rebind(name, cpdsRef);
        } catch (NamingException e) {
            String msg = "Error binding name '" + name + "' to " + "the DriverAdapterCPDS reference";
            throw new SynapseCommonsException(msg, e, log);
        }

        // Construct PerUserPoolDataSource reference
        Reference ref = new Reference("org.apache.commons.dbcp.datasources.PerUserPoolDataSource",
                "org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory", null);

        ref.add(new BinaryRefAddr(DataSourceConstants.PROP_JNDI_ENV, MiscellaneousUtil.serialize(jndiEvn)));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DATA_SOURCE_NAME, name));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_ACTIVE, maxActive));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_IDLE, maxIdle));
        ref.add(new StringRefAddr(DataSourceConstants.PROP_DEFAULT_MAX_WAIT, maxWait));

        //set default jndiProperties for reference
        setCommonParameters(ref, information);

        try {

            if (log.isDebugEnabled()) {
                log.debug("Registering a DataSource with name : " + dataSourceName
                        + " in the JNDI tree with jndiProperties : " + jndiEvn);
            }

            context.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = "Error binding name ' " + dataSourceName + " ' to "
                    + "the PerUserPoolDataSource reference";
            throw new SynapseCommonsException(msg, e, log);
        }

    } else {
        throw new SynapseCommonsException("Unsupported data source type : " + dsType, log);
    }
    cachedNameList.add(dataSourceName);
}

From source file:org.apache.synapse.util.DataSourceRegistrar.java

/**
 * Helper method to register a single data source .The given data source name is used ,
 * if there is no property with name dsName ,when,data source is binding to the initial context,
 *
 * @param dsName         The name of the data source
 * @param dsProperties   The property bag
 * @param initialContext The initial context instance
 * @param jndiEnv        The JNDI environment properties
 */// ww  w  . j  ava 2 s  . c o  m
private static void registerDataSource(String dsName, Properties dsProperties, InitialContext initialContext,
        Properties jndiEnv) {

    if (dsName == null || "".equals(dsName)) {
        if (log.isDebugEnabled()) {
            log.debug("DataSource name is either empty or null, ignoring..");
        }
        return;
    }

    StringBuffer buffer = new StringBuffer();
    buffer.append(SynapseConstants.SYNAPSE_DATASOURCES);
    buffer.append(DOT_STRING);
    buffer.append(dsName);
    buffer.append(DOT_STRING);

    // Prefix for getting particular data source's properties
    String prefix = buffer.toString();

    String driver = getProperty(dsProperties, prefix + PROP_DRIVER_CLS_NAME, null);
    if (driver == null) {
        handleException(prefix + PROP_DRIVER_CLS_NAME + " cannot be found.");
    }

    String url = getProperty(dsProperties, prefix + PROP_URL, null);
    if (url == null) {
        handleException(prefix + PROP_URL + " cannot be found.");
    }

    // get other required properties
    String user = getProperty(dsProperties, prefix + PROP_USER_NAME, "synapse");
    String password = getProperty(dsProperties, prefix + PROP_PASSWORD, "synapse");
    String dataSourceName = getProperty(dsProperties, prefix + PROP_DSNAME, dsName);

    //populates context tree
    populateContextTree(initialContext, dataSourceName);

    String dsType = getProperty(dsProperties, prefix + "type", "BasicDataSource");

    String maxActive = getProperty(dsProperties, prefix + PROP_MAXACTIVE,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_ACTIVE));
    String maxIdle = getProperty(dsProperties, prefix + PROP_MAXIDLE,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_IDLE));
    String maxWait = getProperty(dsProperties, prefix + PROP_MAXWAIT,
            String.valueOf(GenericObjectPool.DEFAULT_MAX_WAIT));

    if ("BasicDataSource".equals(dsType)) {

        Reference ref = new Reference("javax.sql.DataSource", "org.apache.commons.dbcp.BasicDataSourceFactory",
                null);

        ref.add(new StringRefAddr(PROP_DRIVER_CLS_NAME, driver));
        ref.add(new StringRefAddr(PROP_URL, url));
        ref.add(new StringRefAddr(PROP_USER_NAME, user));
        ref.add(new StringRefAddr(PROP_PASSWORD, password));
        ref.add(new StringRefAddr(PROP_MAXACTIVE, maxActive));
        ref.add(new StringRefAddr(PROP_MAXIDLE, maxIdle));
        ref.add(new StringRefAddr(PROP_MAXWAIT, maxWait));

        //set BasicDataSource specific parameters
        setBasicDataSourceParameters(ref, dsProperties, prefix);
        //set default properties for reference
        setCommonParameters(ref, dsProperties, prefix);

        try {
            initialContext.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = " Error binding name ' " + dataSourceName + " ' to "
                    + "the DataSource(BasicDataSource) reference";
            handleException(msg, e);
        }

    } else if ("PerUserPoolDataSource".equals(dsType)) {

        // Construct DriverAdapterCPDS reference
        String className = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "className",
                "org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS");
        String factory = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "factory",
                "org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS");
        String name = getProperty(dsProperties, prefix + PROP_CPDSADAPTER + DOT_STRING + "name", "cpds");

        Reference cpdsRef = new Reference(className, factory, null);

        cpdsRef.add(new StringRefAddr(PROP_DRIVER, driver));
        cpdsRef.add(new StringRefAddr(PROP_URL, url));
        cpdsRef.add(new StringRefAddr(PROP_USER, user));
        cpdsRef.add(new StringRefAddr(PROP_PASSWORD, password));

        try {
            initialContext.rebind(name, cpdsRef);
        } catch (NamingException e) {
            String msg = "Error binding name '" + name + "' to " + "the DriverAdapterCPDS reference";
            handleException(msg, e);
        }

        // Construct PerUserPoolDataSource reference
        Reference ref = new Reference("org.apache.commons.dbcp.datasources.PerUserPoolDataSource",
                "org.apache.commons.dbcp.datasources.PerUserPoolDataSourceFactory", null);

        ref.add(new BinaryRefAddr(PROP_JNDI_ENV, serialize(jndiEnv)));
        ref.add(new StringRefAddr(PROP_DATA_SOURCE_NAME, name));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXACTIVE, maxActive));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXIDLE, maxIdle));
        ref.add(new StringRefAddr(PROP_DEFAULTMAXWAIT, maxWait));

        //set default properties for reference
        setCommonParameters(ref, dsProperties, prefix);

        try {
            initialContext.rebind(dataSourceName, ref);
        } catch (NamingException e) {
            String msg = "Error binding name ' " + dataSourceName + " ' to "
                    + "the PerUserPoolDataSource reference";
            handleException(msg, e);
        }

    } else {
        handleException("Unsupported data source type : " + dsType);
    }
}

From source file:org.exoplatform.services.naming.InitialContextTest.java

public void testGetContext() throws Exception {
    assertNotNull(System.getProperty(Context.INITIAL_CONTEXT_FACTORY));
    InitialContext ctx = new InitialContext();
    assertNotNull(ctx);/*from   w w  w  . j a  v  a 2s  .co  m*/
    ctx.bind("test", "test");
    assertEquals("test", ctx.lookup("test"));
    try {
        ctx.bind("test", "test2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("test", ctx.lookup("test"));
    ctx.rebind("test", "test2");
    assertEquals("test2", ctx.lookup("test"));

    initializer.getInitialContext().bind("test", "test3");
    assertEquals("test3", ctx.lookup("test"));
    ctx.rebind("test", "test4");
    assertEquals("test3", ctx.lookup("test"));
    initializer.getInitialContext().rebind("test", "test5");
    assertEquals("test5", ctx.lookup("test"));
    initializer.getInitialContext().unbind("test");
    try {
        initializer.getInitialContext().lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    assertEquals("test4", ctx.lookup("test"));
    ctx.unbind("test");
    try {
        ctx.lookup("test");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    try {
        initializer.getInitialContext().unbind("test2");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().bind("foo", "foo");
    assertEquals("foo", ctx.lookup("foo"));
    initializer.getInitialContext().bind("foo2", "foo2");
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo", "foo2");
        fail("A NameAlreadyBoundException is expected here");
    } catch (NameAlreadyBoundException e) {
        // expected exception
    }
    assertEquals("foo", ctx.lookup("foo"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().rename("foo3", "foo4");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }
    initializer.getInitialContext().rename("foo", "foo3");
    assertEquals("foo", ctx.lookup("foo3"));
    assertEquals("foo2", ctx.lookup("foo2"));
    try {
        initializer.getInitialContext().lookup("foo");
        fail("A NameNotFoundException is expected here");
    } catch (NameNotFoundException e) {
        // expected exception
    }

    // check same instance
    initializer.getInitialContext().bind("bla", "bla");
    Object obj1 = initializer.getInitialContext().lookup("bla");
    Object obj2 = initializer.getInitialContext().lookup("bla");
    assertTrue(obj1 == obj2);
}