Example usage for javax.naming InitialContext InitialContext

List of usage examples for javax.naming InitialContext InitialContext

Introduction

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

Prototype

public InitialContext() throws NamingException 

Source Link

Document

Constructs an initial context.

Usage

From source file:com.sun.socialsite.business.DatabaseProvider.java

/**
 * Reads configuraiton, loads driver or locates data-source and attempts
 * to get test connecton so that we can fail early.
 *//* ww w .j  ava2 s  .c o  m*/
public DatabaseProvider() throws StartupException {

    String connectionTypeString = Config.getProperty("database.configurationType");
    if ("jdbc".equals(connectionTypeString)) {
        type = ConfigurationType.JDBC_PROPERTIES;
    }
    jndiName = Config.getProperty("database.jndi.name");
    jdbcDriverClass = Config.getProperty("database.jdbc.driverClass");
    jdbcConnectionURL = Config.getProperty("database.jdbc.connectionURL");
    jdbcUsername = Config.getProperty("database.jdbc.username");
    jdbcPassword = Config.getProperty("database.jdbc.password");

    successMessage("SUCCESS: Got parameters. Using configuration type " + type);

    // If we're doing JDBC then attempt to load JDBC driver class
    if (getType() == ConfigurationType.JDBC_PROPERTIES) {
        successMessage("-- Using JDBC driver class: " + jdbcDriverClass);
        successMessage("-- Using JDBC connection URL: " + jdbcConnectionURL);
        successMessage("-- Using JDBC username: " + jdbcUsername);
        successMessage("-- Using JDBC password: [hidden]");
        try {
            Class.forName(getJdbcDriverClass());
        } catch (ClassNotFoundException ex) {
            String errorMsg = "ERROR: cannot load JDBC driver class [" + getJdbcDriverClass() + "]. "
                    + "Likely problem: JDBC driver jar missing from server classpath.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: loaded JDBC driver class [" + getJdbcDriverClass() + "]");

        if (getJdbcUsername() != null || getJdbcPassword() != null) {
            props = new Properties();
            if (getJdbcUsername() != null)
                props.put("user", getJdbcUsername());
            if (getJdbcPassword() != null)
                props.put("password", getJdbcPassword());
        }

        // Else attempt to locate JNDI datasource
    } else {
        String name = "java:comp/env/" + getJndiName();
        successMessage("-- Using JNDI datasource name: " + name);
        try {
            InitialContext ic = new InitialContext();
            dataSource = (DataSource) ic.lookup(name);
        } catch (NamingException ex) {
            String errorMsg = "ERROR: cannot locate JNDI DataSource [" + name + "]. "
                    + "Likely problem: no DataSource or datasource is misconfigured.";
            errorMessage(errorMsg);
            throw new StartupException(errorMsg, ex, startupLog);
        }
        successMessage("SUCCESS: located JNDI DataSource [" + name + "]");
    }

    // So far so good. Now, can we get a connection?
    try {
        Connection testcon = getConnection();
        testcon.close();
    } catch (Throwable t) {
        String errorMsg = "ERROR: unable to obtain database connection. "
                + "Likely problem: bad connection parameters or database unavailable.";
        errorMessage(errorMsg);
        throw new StartupException(errorMsg, t, startupLog);
    }
}

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  w  ww  .  jav a  2s . com*/
                                } 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:edu.harvard.iq.dvn.core.web.push.stubs.NetworkStatsStubServer.java

private void initNetworkData() {
    boolean isReleased = true;

    int itemCounter = 0;
    String itemPrefix, idValue, key;
    itemPrefix = DVNITEM + itemCounter + ".";
    try {/*from www  .j ava 2s.co  m*/
        vdcNetworkService = (VDCNetworkServiceLocal) new InitialContext()
                .lookup("java:comp/env/vdcNetworkService");
    } catch (Exception e) {
        e.printStackTrace();
    }
    idValue = DVNITEM + itemCounter;
    key = itemPrefix;

    //network level
    NetworkStatsState.getNetworkStatsMap().put(key + DVNID, idValue);
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSETOTAL, this.getTotalDataverses(isReleased));
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYTOTAL, this.getTotalStudies(isReleased));
    NetworkStatsState.getNetworkStatsMap().put(key + FILESTOTAL, this.getTotalFiles(isReleased));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_DATAVERSETOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_STUDYTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_FILESTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSELABEL, "Dataverses: ");
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYLABEL, "Studies: ");
    NetworkStatsState.getNetworkStatsMap().put(key + FILESLABEL, "Files: ");

    //GROUPS COUNTS
    try {
        vdcGroupService = (VDCGroupServiceLocal) new InitialContext().lookup("java:comp/env/vdcGroupService");

        Collection<VDCGroup> vdcgroups = (Collection<VDCGroup>) vdcGroupService.findAll();

        Iterator iterator = vdcgroups.iterator();

        while (iterator.hasNext()) {
            VDCGroup vdcgroup = (VDCGroup) iterator.next();
            idValue = vdcgroup.getId().toString();
            itemPrefix = DVNITEM + idValue + ".";
            key = itemPrefix;
            NetworkStatsState.getNetworkStatsMap().put(key + DVNID, idValue);
            NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSETOTAL,
                    this.getGroupTotalDataverses(vdcgroup.getId(), "All"));
            NetworkStatsState.getNetworkStatsMap().put(key + STUDYTOTAL,
                    this.getGroupTotalStudies(vdcgroup.getId()));
            NetworkStatsState.getNetworkStatsMap().put(key + FILESTOTAL,
                    this.getGroupTotalFiles(vdcgroup.getId()));
            NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_DATAVERSETOTAL, new String("0"));
            NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_STUDYTOTAL, new String("0"));
            NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_FILESTOTAL, new String("0"));
            NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSELABEL, "Dataverses: ");
            NetworkStatsState.getNetworkStatsMap().put(key + STUDYLABEL, "Studies: ");
            NetworkStatsState.getNetworkStatsMap().put(key + FILESLABEL, "Files: ");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    //SCHOLAR
    idValue = new String("-1"); //TODO: convert to Long if convenient/time permits
    itemPrefix = DVNITEM + idValue + ".";
    key = itemPrefix;
    NetworkStatsState.getNetworkStatsMap().put(key + DVNID, idValue);
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSETOTAL,
            getGroupTotalDataverses(new Long(idValue), "Scholar"));
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYTOTAL, getGroupTotalStudies(new Long(idValue)));
    NetworkStatsState.getNetworkStatsMap().put(key + FILESTOTAL, getGroupTotalFiles(new Long(idValue)));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_DATAVERSETOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_STUDYTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_FILESTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSELABEL, "Dataverses: ");
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYLABEL, "Studies: ");
    NetworkStatsState.getNetworkStatsMap().put(key + FILESLABEL, "Files: ");

    //OTHER
    idValue = new String("-2"); //TODO: convert to Long if convenient/time permits
    itemPrefix = DVNITEM + idValue + ".";
    key = itemPrefix;
    NetworkStatsState.getNetworkStatsMap().put(key + DVNID, idValue);
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSETOTAL,
            getGroupTotalDataverses(new Long(idValue), "Basic"));
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYTOTAL, getGroupTotalStudies(new Long(idValue)));
    NetworkStatsState.getNetworkStatsMap().put(key + FILESTOTAL, getGroupTotalFiles(new Long(idValue)));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_DATAVERSETOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_STUDYTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + INITIAL_FILESTOTAL, new String("0"));
    NetworkStatsState.getNetworkStatsMap().put(key + DATAVERSELABEL, "Dataverses: ");
    NetworkStatsState.getNetworkStatsMap().put(key + STUDYLABEL, "Studies: ");
    NetworkStatsState.getNetworkStatsMap().put(key + FILESLABEL, "Files: ");
}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */// w  w w  .  j a  v a2s .co m
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

            if (DEBUG) {
                DEBUGGER.debug("xmlURL: {}", xmlURL);
            }

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:catalina.mbeans.GlobalResourcesLifecycleListener.java

/**
 * Create the MBeans for the interesting global JNDI resources.
 *//*from ww w . j  a va  2  s .c o m*/
protected void createMBeans() {

    // Look up our global naming context
    Context context = null;
    try {
        context = (Context) (new InitialContext()).lookup("java:/");
    } catch (NamingException e) {
        e.printStackTrace();
        throw new IllegalStateException("No global naming context defined for server");
    }

    // Recurse through the defined global JNDI resources context
    try {
        createMBeans("", context);
    } catch (NamingException e) {
        log("Exception processing Global JNDI Resources", e);
    }

}

From source file:gov.nih.nci.ccts.grid.studyconsumer.service.globus.resource.StudyConsumerResourceBase.java

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

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

    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 = (StudyConsumerResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:com.stratelia.webactiv.util.DBUtil.java

private synchronized Connection openConnection(String dbName) {
    SilverTrace.debug("util", "DBUtil makeConnection", "DBUtil : makeConnection : entree");
    DataSource ds = null;/*w ww  .  j a  v  a 2s.  c om*/
    if (ic == null) {
        try {
            ic = new InitialContext();
        } catch (NamingException e) {
            throw new UtilException("DBUtil.makeConnection", "util.MSG_CANT_GET_INITIAL_CONTEXT", e);
        }
    }
    try {
        ds = dsStock.get(dbName);
        if (ds == null) {
            ds = (DataSource) ic.lookup(dbName);
            dsStock.put(dbName, ds);
        }
    } catch (NamingException e) {
        throw new UtilException("DBUtil.makeConnection",
                new MultilangMessage("util.MSG_BDD_REF_NOT_FOUND", dbName).toString(), e);
    }

    try {
        return ds.getConnection();
    } catch (SQLException e) {
        throw new UtilException("DBUtil.makeConnection",
                new MultilangMessage("util.MSG_BDD_REF_CANT_GET_CONNECTION", dbName).toString(), e);
    }
}

From source file:gov.nih.nci.ccts.grid.service.globus.resource.RegistrationConsumerResourceBase.java

public RegistrationConsumerResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }//w  w  w. j a v a  2s . c om
    MessageContext ctx = MessageContext.getCurrentContext();

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

    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 = (RegistrationConsumerResourceConfiguration) 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.ORQ.service.globus.resource.ORQResourceBase.java

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

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

    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 = (ORQResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}

From source file:gov.nih.nci.ccts.grid.smoketest.service.globus.resource.SmokeTestServiceResourceBase.java

public SmokeTestServiceResourceConfiguration getConfiguration() {
    if (this.configuration != null) {
        return this.configuration;
    }/*from ww  w.  ja v a 2  s .  com*/
    MessageContext ctx = MessageContext.getCurrentContext();

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

    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 = (SmokeTestServiceResourceConfiguration) initialContext.lookup(jndiName);
    } catch (Exception e) {
        logger.error("when performing JNDI lookup for " + jndiName + ": " + e, e);
    }

    return this.configuration;
}