Example usage for javax.naming Context lookup

List of usage examples for javax.naming Context lookup

Introduction

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

Prototype

public Object lookup(String name) throws NamingException;

Source Link

Document

Retrieves the named object.

Usage

From source file:BeanServlet.java

public void init() throws ServletException {

    Context env = null;

    try {//from w w w  .  j ava2 s  . c  om
        // Compile error since there is no StockPriceBean.class
        // change the name according to your requirements
        env = (Context) new InitialContext().lookup("java:comp/env");
        spbean = (StockPriceBean) env.lookup("bean/pricebean");

        //close the InitialContext
        env.close();

        if (spbean == null)
            throw new ServletException("bean/pricebean is an unknown JNDI object");

    } catch (NamingException ne) {

        try {
            env.close();
        } catch (NamingException nex) {
        }

        throw new ServletException(ne);

    }

}

From source file:de.zib.gndms.dspace.service.globus.resource.DSpaceResourceBase.java

public DSpaceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//  www  .java 2  s. com
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/DSpace";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (DSpaceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:de.zib.gndms.GORFX.service.globus.resource.GORFXResourceBase.java

public GORFXResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }/*from w  w  w . j a  va  2  s.c o  m*/
    MessageContext ctx = MessageContext.getCurrentContext();

    String servicePath = ctx.getTargetService();
    servicePath = servicePath.substring(0, servicePath.lastIndexOf("/"));
    servicePath += "/GORFX";

    String jndiName = Constants.JNDI_SERVICES_BASE_NAME + servicePath + "/configuration";
    logger.debug("Will read configuration from jndi name: " + jndiName);
    try {
        Context initialContext = new InitialContext();
        this.configuration = (GORFXResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:org.apache.ojb.ejb.odmg.StressTest.java

/**
 * Setting up the test fixture./*ww w  .j a  v  a  2 s. co m*/
 */
private void init() throws Exception {
    Context ctx = ContextHelper.getContext();
    times = new long[4];
    try {
        Object object = PortableRemoteObject.narrow(ctx.lookup(ODMGSessionHome.JNDI_NAME), EJBHome.class);
        bean = ((ODMGSessionHome) object).create();
    } catch (Exception e) {
        e.printStackTrace(System.err);
        throw e;
    }
}

From source file:org.apache.ojb.ejb.pb.StressTest.java

/**
 * Setting up the test fixture.//w ww.ja  v  a  2s  .c o m
 */
private void init() throws Exception {
    Context ctx = ContextHelper.getContext();
    times = new long[4];
    try {
        Object object = PortableRemoteObject.narrow(ctx.lookup(PBSessionHome.JNDI_NAME), EJBHome.class);
        bean = ((PBSessionHome) object).create();
    } catch (Exception e) {
        e.printStackTrace(System.err);
        throw e;
    }
}

From source file:org.datacleaner.connection.JdbcDatastore.java

@Override
protected UsageAwareDatastoreConnection<UpdateableDataContext> createDatastoreConnection() {
    if (StringUtils.isNullOrEmpty(_datasourceJndiUrl)) {
        if (isMultipleConnections()) {
            final DataSource dataSource = createDataSource();
            return new DataSourceDatastoreConnection(dataSource, getTableTypes(), _catalogName, this);
        } else {//from www  .  j a va 2 s.  c  o m
            final Connection connection = createConnection();
            final UpdateableDataContext dataContext = new JdbcDataContext(connection, getTableTypes(),
                    _catalogName);
            return new UpdateableDatastoreConnectionImpl<UpdateableDataContext>(dataContext, this);
        }
    } else {
        try {
            Context initialContext = getJndiNamingContext();
            DataSource dataSource = (DataSource) initialContext.lookup(_datasourceJndiUrl);
            return new DataSourceDatastoreConnection(dataSource, getTableTypes(), _catalogName, this);
        } catch (Exception e) {
            logger.error("Could not retrieve DataSource '{}'", _datasourceJndiUrl);
            throw new IllegalStateException(e);
        }
    }
}

From source file:binky.reportrunner.service.impl.DatasourceServiceImpl.java

private DataSource getDs(RunnerDataSource runnerDs)
        throws SecurityException, InstantiationException, IllegalAccessException, ClassNotFoundException,
        PropertyVetoException, NamingException, EncryptionException {

    final String jndiDataSource = runnerDs.getJndiName();

    if (StringUtils.isBlank(jndiDataSource)) {
        EncryptionUtil enc = new EncryptionUtil();
        logger.info("using dbcp pooled connection for: " + runnerDs.getDataSourceName());

        String jdbcUser = runnerDs.getUsername();
        if (StringUtils.isBlank(runnerDs.getPassword()))
            throw new SecurityException("password is empty");
        String jdbcPassword = enc.decrpyt(secureKey, runnerDs.getPassword());

        String jdbcUrl = runnerDs.getJdbcUrl();
        String databaseDriver = runnerDs.getJdbcClass();

        Class.forName(databaseDriver).newInstance();

        BasicDataSource ds1 = new BasicDataSource();
        ds1.setDriverClassName(databaseDriver);
        ds1.setUrl(jdbcUrl);/* ww  w .j a  v a  2 s  . c om*/
        ds1.setUsername(jdbcUser);
        ds1.setPassword(jdbcPassword);
        ds1.setInitialSize(runnerDs.getInitialPoolSize());
        ds1.setMaxActive(runnerDs.getMaxPoolSize());

        ds1.setRemoveAbandoned(true);
        ds1.setRemoveAbandonedTimeout(600);

        // do not want anything updating anything
        ds1.setDefaultReadOnly(true);

        ds1.setLogAbandoned(true);
        ds1.setTestOnBorrow(true);
        ds1.setTestOnReturn(true);
        ds1.setTestWhileIdle(true);

        // does this work across all RBMS? - no it doesn't
        //ds1.setValidationQuery("select 1");
        //ds1.setValidationQueryTimeout(300);

        return ds1;
    } else {
        logger.info(
                "getting datasource from JNDI url: " + jndiDataSource + " for " + runnerDs.getDataSourceName());
        Context initContext = new InitialContext();
        DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiDataSource);
        return ds;
    }
}

From source file:it.cnr.icar.eric.server.repository.hibernate.RepositoryHibernateUtil.java

@SuppressWarnings("unused")
protected Configuration getConfiguration() {
    if (configuration == null) {
        synchronized (RepositoryHibernateUtil.class) {
            if (configuration == null) {
                try {
                    String cfgResource;
                    DataSource ds = null;

                    boolean useConnectionPool = Boolean
                            .valueOf(RegistryProperties.getInstance()
                                    .getProperty("eric.persistence.rdb.useConnectionPooling", "true"))
                            .booleanValue();
                    boolean debugConnectionPool = Boolean.valueOf(RegistryProperties.getInstance()
                            .getProperty("eric.persistence.rdb.pool.debug", "false")).booleanValue();

                    // Try DataSource first, if configured
                    if (useConnectionPool && !debugConnectionPool) {
                        cfgResource = "/repository.datasource.cfg.xml";
                        configuration = new Configuration().configure(cfgResource);

                        String dataSourceName = configuration.getProperty("connection.datasource");
                        if (dataSourceName != null && !"".equals(dataSourceName)) {
                            try {
                                Context ctx = new InitialContext();
                                if (ctx != null) {
                                    ds = (DataSource) ctx.lookup(dataSourceName);
                                    if (ds != null) {
                                        // create a test connection to
                                        // make sure all is well with
                                        // DataSource
                                        Connection connection = null;
                                        try {
                                            connection = ds.getConnection();
                                        } catch (Exception e) {
                                            ds = null;
                                            log.info(ServerResourceBundle.getInstance().getString(
                                                    "message.UnableToCreateTestConnectionForDataSource",
                                                    new Object[] { dataSourceName }), e);
                                        } finally {
                                            if (connection != null) {
                                                try {
                                                    connection.close();
                                                } catch (Exception e1) {
                                                    //Do nothing.
                                                    connection = null;
                                                }
                                            }
                                        }
                                    }/*from  ww w .jav  a 2s  . c om*/
                                } else {
                                    log.info(ServerResourceBundle.getInstance()
                                            .getString("message.UnableToGetInitialContext"));
                                }
                            } catch (NamingException e) {
                                log.info(ServerResourceBundle.getInstance().getString(
                                        "message.UnableToGetJNDIContextForDataSource",
                                        new Object[] { dataSourceName }));
                            }
                        }
                    }

                    if (ds == null) {
                        // fall back to jdbc
                        cfgResource = "/repository.jdbc.cfg.xml";
                        configuration = new Configuration().configure(cfgResource);
                    }

                    // support $user.home and $eric.home in eric repository cfg
                    String connUrl = configuration.getProperty("hibernate.connection.url");
                    if (connUrl != null && !"".equals(connUrl)) {
                        connUrl = substituteVariable(connUrl, "$user.home", System.getProperty("user.home"));
                        connUrl = substituteVariable(connUrl, "$eric.home",
                                RegistryProperties.getInstance().getProperty("eric.home"));
                        configuration.setProperty("hibernate.connection.url", connUrl);
                    }

                    sessionFactory = configuration.buildSessionFactory();
                } catch (HibernateException ex) {
                    throw new RuntimeException(ServerResourceBundle.getInstance()
                            .getString("message.buildingSessionFactory", new Object[] { ex.getMessage() }), ex);
                }
            }
        }
    }
    return configuration;
}

From source file:com.autentia.intra.util.ConfigurationUtil.java

/**
 * Constructor//from ww  w .  ja va2 s .c o  m
 *
 * @param jndiPathVar JNDI variable in which configuration directory is stored
 * @param file        path to configuration file
 */
public ConfigurationUtil(String jndiPathVar, String file) throws ConfigurationException, NamingException {
    Context ctx = new InitialContext();
    configDir = (String) ctx.lookup(jndiPathVar);
    if (!configDir.endsWith("/") && !configDir.endsWith("\\")) {
        configDir += "/";
    }
    config = new PropertiesConfiguration(configDir + file);
}

From source file:hnu.helper.DataBaseConnection.java

/** Fetches new DataBaseConnection from Pool */
public Connection getDBConnection() {
    Connection conn = null;//from ww w.java  2 s.  c om

    try {
        Context ctx = new InitialContext();
        DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/hnuDB");

        conn = ds.getConnection();
    } catch (Exception sqle) {
        log.error("Couln't get connection from DataSource", sqle);
        //sqle.printStackTrace();
    }

    return conn;
}