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:net.sf.taverna.t2.provenance.api.ProvenanceAccess.java

/**
 * Initialises a named JNDI DataSource if not already set up externally.
 * The DataSource is named jdbc/taverna/* w w w.  j  a va 2  s .c  o  m*/
 *
 * @param driverClassName - the classname for the driver to be used.
 * @param jdbcUrl - the jdbc connection url
 * @param username - the username, if required (otherwise null)
 * @param password - the password, if required (oteherwise null)
 * @param minIdle - if the driver supports multiple connections, then the minumum number of idle connections in the pool
 * @param maxIdle - if the driver supports multiple connections, then the maximum number of idle connections in the pool
 * @param maxActive - if the driver supports multiple connections, then the minumum number of connections in the pool
 */
public static void initDataSource(String driverClassName, String jdbcUrl, String username, String password,
        int minIdle, int maxIdle, int maxActive) {
    System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "org.osjava.sj.memory.MemoryContextFactory");
    System.setProperty("org.osjava.sj.jndi.shared", "true");

    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName(driverClassName);
    ds.setDefaultTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
    ds.setMaxActive(maxActive);
    ds.setMinIdle(minIdle);
    ds.setMaxIdle(maxIdle);
    ds.setDefaultAutoCommit(true);
    if (username != null) {
        ds.setUsername(username);
    }
    if (password != null) {
        ds.setPassword(password);
    }

    ds.setUrl(jdbcUrl);

    InitialContext context;
    try {
        context = new InitialContext();
        context.rebind("jdbc/taverna", ds);
    } catch (NamingException ex) {
        logger.error("Problem rebinding the jdbc context: " + ex);
    }

}

From source file:com.gtwm.pb.servlets.AppController.java

/**
 * init() is called once automatically by the servlet container (e.g.
 * Tomcat) at servlet startup. We use it to initialise various things,
 * namely:/*w w w. java2s  .  co m*/
 * 
 * a) create the DatabaseDefn object which is the top level application
 * object. The DatabaseDefn object will load the list of tables & reports
 * into memory when it is constructed. It will also configure and load the
 * object database
 * 
 * b) create a DataSource object here to pass to the DatabaseDefn. This data
 * source then acts as a pool of connections from which a connection to the
 * relational database can be called up whenever needed.
 */
public void init() throws ServletException {

    logger.info("Initialising " + AppProperties.applicationName);
    ServletContext servletContext = getServletContext();
    this.webAppRoot = servletContext.getRealPath("/");

    // Create and cache a DatabaseDefn object which is an entry point to all
    // application logic
    // and schema information. The relational database is also gotten
    DataSource relationalDataSource = null;
    InitialContext initialContext = null;
    try {
        // Get a data source for the relational database to pass to the
        // DatabaseDefn object
        initialContext = new InitialContext();
        relationalDataSource = (DataSource) initialContext.lookup("java:comp/env/jdbc/agileBaseData");
        if (relationalDataSource == null) {
            throw new ServletException("Can't get data source");
        }
        this.relationalDataSource = relationalDataSource;
        // Store 'global objects' data sources and webAppRoot in
        // databaseDefn
        this.databaseDefn = new DatabaseDefn(relationalDataSource, this.webAppRoot);
        // Store top level stuff in the context so that other servlets can
        // access it
        servletContext.setAttribute("com.gtwm.pb.servlets.databaseDefn", this.databaseDefn);
        servletContext.setAttribute("com.gtwm.pb.servlets.relationalDataSource", this.relationalDataSource);
    } catch (NullPointerException npex) {
        ServletUtilMethods.logException(npex, "Error initialising controller servlet");
        throw new ServletException("Error initialising controller servlet", npex);
    } catch (SQLException sqlex) {
        ServletUtilMethods.logException(sqlex, "Database error loading schema");
        throw new ServletException("Database error loading schema", sqlex);
    } catch (NamingException neex) {
        ServletUtilMethods.logException(neex, "Can't get initial context");
        throw new ServletException("Can't get initial context");
    } catch (RuntimeException rtex) {
        ServletUtilMethods.logException(rtex, "Runtime initialisation error");
        throw new ServletException("Runtime initialisation error", rtex);
    } catch (Exception ex) {
        ServletUtilMethods.logException(ex, "General initialisation error");
        throw new ServletException("General initialisation error", ex);
    }
    logger.info("Application fully loaded");
}

From source file:gov.nih.nci.cabig.ctms.grid.ae.service.globus.resource.AdverseEventConsumerResourceBase.java

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

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

    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 = (AdverseEventConsumerResourceConfiguration) 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.cagrid.caarray.service.globus.resource.CaArraySvcResourceBase.java

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

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

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

    return this.configuration;
}

From source file:CiudadesApp.Modelo.Actions.Ciudad_Actions.java

private CiudadFacade lookupCiudadFacadeBean() {
    try {/*from  ww  w  .  j  a v a 2 s.co  m*/
        Context c = new InitialContext();
        return (CiudadFacade) c
                .lookup("java:global/ForodeCiudades/CiudadFacade!CiudadesApp.Modelo.EJBFacade.CiudadFacade");
    } catch (NamingException ne) {
        Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
        throw new RuntimeException(ne);
    }
}

From source file:com.alfaariss.oa.util.database.jdbc.DataSourceFactory.java

private static DataSource createByContext(IConfigurationManager configurationManager, Element eConfig)
        throws DatabaseException {
    DataSource dataSource = null;
    try {//from w w w . j ava  2  s. c  om
        String sContext = configurationManager.getParam(eConfig, "environment_context");
        if (sContext == null) {
            _logger.info("Could not find the optional 'environment_context' item in config");
        } else {
            String sResourceRef = configurationManager.getParam(eConfig, "resource-ref");
            if (sResourceRef == null) {
                _logger.warn("Could not find the 'resource-ref' item in config");
                throw new DatabaseException(SystemErrors.ERROR_CONFIG_READ);
            }

            Context envCtx = null;
            try {
                envCtx = (Context) new InitialContext().lookup(sContext);
            } catch (NamingException e) {
                _logger.warn("Could not find context: " + sContext, e);
                throw new DatabaseException(SystemErrors.ERROR_INIT);
            }

            try {
                dataSource = (DataSource) envCtx.lookup(sResourceRef);
            } catch (NamingException e) {
                _logger.warn("Could not find resource ref: " + sResourceRef, e);
                throw new DatabaseException(SystemErrors.ERROR_INIT);
            }
        }
    } catch (DatabaseException e) {
        throw e;
    } catch (Exception e) {
        _logger.warn("Could not create datasource", e);
        throw new DatabaseException(SystemErrors.ERROR_INTERNAL);
    }
    return dataSource;
}

From source file:br.ufc.ivela.servlets.ChallengeSolver.java

private ChallengeRemote getChallengeRemote() {
    ChallengeRemote challengeRemote = null;

    try {//from  w  w  w  .  j  a  v  a 2s.  c om
        InitialContext initialContext = new InitialContext();
        java.lang.Object ejbRemoteRef = initialContext
                .lookup("ChallengeBean#br.ufc.ivela.ejb.interfaces.ChallengeRemote");
        challengeRemote = (ChallengeRemote) javax.rmi.PortableRemoteObject.narrow(ejbRemoteRef,
                ChallengeRemote.class);
    } catch (NamingException e) {
        log.error("Error Retrieving Challenge Remote", e);
    }

    return challengeRemote;
}

From source file:org.mobicents.slee.enabler.rest.client.example.RESTClientEnablerExampleSbb.java

public void setSbbContext(SbbContext context) {
    sbbContext = (SbbContextExt) context;
    this.tracer = this.sbbContext.getTracer("WsClientEnabler");
    // this.timerFacility = sbbContext.getTimerFacility();
    try {//  w ww  . j  av a  2s. c  o  m
        Context myEnv = (Context) new InitialContext().lookup("java:comp/env");
        String twitterConsumerKey = (String) myEnv.lookup("twitter.consumerKey");
        String twitterConsumerSecret = (String) myEnv.lookup("twitter.consumerSecret");
        String twitterAccessToken = (String) myEnv.lookup("twitter.accessToken");
        String twitterAccessTokenKey = (String) myEnv.lookup("twitter.accessTokenKey");
        consumer = new CommonsHttpOAuthConsumer(twitterConsumerKey, twitterConsumerSecret);
        consumer.setTokenWithSecret(twitterAccessToken, twitterAccessTokenKey);
    } catch (NamingException e) {
        tracer.severe("failed to set sbb context", e);
    }
}

From source file:org.jboss.spring.deployers.AbstractSpringMetaDataDeployer.java

/**
 * Bind factory to non-serializable JNDI context.
 *
 * @param beanFactory the bean factory/*from   w w  w . j  a  v a2s  . c o m*/
 * @param name        the jndi name
 * @throws DeploymentException for any error
 */
protected void bindIfPossible(T beanFactory, String name) throws DeploymentException {
    InitialContext ctx = null;
    try {
        ctx = new InitialContext();
        Object existingObject = NonSerializableFactory.lookup(name);
        if (existingObject != null) {
            throw new DeploymentException(
                    "Unable to bind BeanFactory into JNDI as " + name + " : binding already" + " exists");
        }
        NonSerializableFactory.rebind(ctx, name, beanFactory);
    } catch (NamingException e) {
        throw new DeploymentException("Unable to bind BeanFactory into JNDI", e);
    } finally {
        if (ctx != null) {
            try {
                ctx.close();
            } catch (Throwable ignored) {
            }
        }
    }
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.NetworkDataAnalysisPage.java

public void init() {
    super.init();

    try {//  www .jav a  2 s  .c o  m
        file = (NetworkDataFile) studyFileService.getStudyFile(fileId);

        if (versionNumber != null) {
            StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNumber);
            studyUI = new StudyUI(sv, null);
            if (sv == null) {
                redirect("/faces/IdDoesNotExistPage.xhtml?type=Study%20Version");
                return;
            }

        } else {
            studyUI = new StudyUI(file.getStudy().getReleasedVersion(), null);
        }

    } catch (Exception e) { // id not a long, or file is not a NetworkDataFile (TODO: redirect to a different page if not network data file)
        redirect("/faces/IdDoesNotExistPage.xhtml?type=File");
        return;
    }

    //init workspace and page components 
    try {
        Context ctx = new InitialContext();
        networkDataService = (NetworkDataServiceLocal) ctx.lookup("java:comp/env/networkData");
        String sessionId = FacesContext.getCurrentInstance().getExternalContext().getSession(false).toString();
        networkDataService.initAnalysis(file.getFileSystemLocation(), sessionId);
        initComponents();
    } catch (Exception ex) {
        Logger.getLogger(NetworkDataAnalysisPage.class.getName()).log(Level.SEVERE, null, ex);
        redirect("/faces/ErrorPage.xhtml?errorMsg=" + ex.getMessage());
    }
}