Example usage for javax.naming InitialContext lookup

List of usage examples for javax.naming InitialContext lookup

Introduction

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

Prototype

public Object lookup(Name name) throws NamingException 

Source Link

Usage

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

public ServiceOperationInterface getServiceScript(String scriptName) throws Exception {

    ServletContext context = getServletContext();
    ServicePool pool = null;//from  w w w . j  a va 2  s . c o m
    ServiceOperationInterface toaster = null;
    Connection connection = null;
    DBConnectionPool dbpool = null;
    String db_jndi_name = null;
    String db_jdbc_poolname = null;

    try {
        pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);
    } catch (Exception ex) {
        log.error("Error getting the toaster pool from the servlet context [" + ATTRIB_SERVICE_POOL + "]");
        throw new Exception("ERROR - could not get toast pool from server context [" + ATTRIB_SERVICE_POOL
                + "]: " + ex.toString(), ex);
    }

    if (pool == null) {
        /* Toaster pool is not set-up - this is very bad...! */
        log.error("The toaster pool does not exists in the servlet context.");
        throw new Exception("The toaster pool does not exist in the servlet context.");
    }

    try {
        toaster = pool.getService(scriptName);
    } catch (Exception ex) {
        log.error("Exception getting a toaster instance: " + ex.toString());
        throw new Exception(
                "ERROR - could not get toaster instance from pool for " + scriptName + ": " + ex.toString(),
                ex);
    }

    /**
     * DATABASE CONNECTION...
     *   if the DbJDNI property is set to non null value, or the default connection is a JNDI one,
     *   then try to use JNDI.
     */

    println(">> Starting database connection");

    db_jndi_name = toaster.getDbJNDI(); // get jndi name from the scripts' properties file (if any)
    db_jdbc_poolname = toaster.getJDBCpoolname(); // get jdbc name from the scripts' properties file (if any)

    if (db_jndi_name != null || default_db_jndi_name != null) {

        // JNDI - Container managed connection pool.
        // Lookup the JNDI name for the connection pool and create the database connection.

        if (db_jndi_name == null) {
            db_jndi_name = default_db_jndi_name;
        }

        println("Looking up database connection for JNDI name " + db_jndi_name + "... "
                + "An exception here probably indicates that the JNDI name or corresponing connection pool isn't setup on your application server.");

        try {
            // The following code for Websphere 6...
            InitialContext ic = new InitialContext();
            DataSource dataSource = null;

            dataSource = (DataSource) ic.lookup(db_jndi_name);
            connection = dataSource.getConnection();
        } catch (Exception ex) {
            log.error("Exception getting JNDI database connection: " + ex.toString());
            throw new Exception("ERROR - getting a connection to the database (using JNDI name " + db_jndi_name
                    + "): " + ex.toString(), ex);
        }

    } else if (db_jdbc_poolname != null || default_db_jdbc_name != null) {

        if (db_jdbc_poolname == null) {
            db_jdbc_poolname = default_db_jdbc_name; // it isn't, so use the default one.
        }

        // find the connection pool in the servlet context
        try {
            String attr = ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname;
            println(">> Trying to get DB connection pool (" + attr + ")");
            dbpool = (DBConnectionPool) context.getAttribute(attr);
        } catch (Exception ex) {
            log.error("Could not get a database connection from the pool: " + ex.toString());
            throw new Exception("ERROR - could not get DB connection pool from server context ("
                    + ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname + ") " + ex.toString(), ex);
        }

        if (dbpool == null) {
            if (toaster != null) {
                pool.freeService(scriptName, toaster);
            }
            throw new Exception("ERROR - The database connection pool has not been created (dbpool for "
                    + ATTRIB_JDBC_CONN_POOL + "." + db_jdbc_poolname + " is null).");
        }
        try {
            connection = dbpool.getConnection();
        } catch (Exception ex) {
            if (toaster != null) {
                pool.freeService(scriptName, toaster);
            }
            throw new Exception("ERROR - could not get DB connection from DB connection pool. " + ex.toString(),
                    ex);
        }

    }

    /*
     *  Give the Toaster the database connection we created earlier...
     */
    toaster.setConnection(connection);

    return (toaster);
}

From source file:br.org.indt.ndg.server.survey.SurveyHandlerBean.java

public ArrayList<String> loadSurveysFromServerToEditor(String userName) throws MSMApplicationException {
    ArrayList<String> surveyList = new ArrayList<String>();

    InitialContext initialContext = null;

    try {/*  ww  w .  ja va2s .  c o  m*/
        initialContext = new InitialContext();
    } catch (NamingException e) {
        e.printStackTrace();
    }

    UserManager userManager = null;

    try {
        userManager = (UserManager) initialContext.lookup("ndg-core/UserManagerBean/remote");
    } catch (NamingException e) {
        e.printStackTrace();
    }

    NdgUser user = null;

    try {
        try {
            if (userManager != null) {
                user = userManager.findNdgUserByName(userName);
            }
        } catch (MSMApplicationException e) {
            e.printStackTrace();
        }
    } catch (NoResultException e) {
        // empty
    }

    ArrayList<SurveyXML> userSurveyList = new ArrayList<SurveyXML>();

    try {
        userSurveyList = loadSurveysDB(user);
    } catch (MSMSystemException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < userSurveyList.size(); i++) {
        Survey survey = manager.find(Survey.class, ((SurveyXML) userSurveyList.toArray()[i]).getId());

        surveyList.add(survey.getSurveyXml().toString());
    }

    return surveyList;
}

From source file:org.intalio.deploy.deployment.impl.DeploymentServiceImpl.java

/**
 * Initialize the service/*  w  ww .  j  a  v  a 2 s. co  m*/
 */
public void init() {
    synchronized (LIFECYCLE_LOCK) {
        if (_serviceState != null) {
            throw new IllegalStateException("Service already initialized");
        }
        if (_dataSource == null) {
            // by this time, if no datasource is set by the setter, use the default one
            try {
                InitialContext initialContext = new InitialContext();
                _dataSource = (DataSource) initialContext.lookup(_dataSourceJndiPath);
            } catch (NamingException e) {
                throw new IllegalStateException("Couldn't find datasource through jndi");
            }
        }

        _persist = new Persistence(new File(_deployDir), _dataSource);
        _timer = new Timer("Deployment Service Timer", true);
        _serviceState = ServiceState.INITIALIZED;
        LOG.info(_("DeploymentService state is now INITIALIZED(replaceExistingAssemblies="
                + replaceExistingAssemblies + ")."));
    }
}

From source file:org.forgerock.openidm.repo.jdbc.impl.JDBCRepoService.java

/**
 * Initializes the JDBC Repository Service with the supplied configuration
 * /* w  w w  . j a  va2  s  .c om*/
 * @param config            the configuration object
 * @param bundleContext     the bundle context
 * @throws InvalidException
 */
void init(JsonValue config, BundleContext bundleContext) throws InvalidException {
    try {
        String enabled = config.get("enabled").asString();
        if ("false".equals(enabled)) {
            logger.debug("JDBC repository not enabled");
            throw new RuntimeException("JDBC repository not enabled.");
        }

        JsonValue connectionConfig = config.get(CONFIG_CONNECTION).isNull() ? config
                : config.get(CONFIG_CONNECTION);

        maxTxRetry = connectionConfig.get("maxTxRetry").defaultTo(5).asInteger().intValue();

        // Data Source configuration
        jndiName = connectionConfig.get(CONFIG_JNDI_NAME).asString();
        String jtaName = connectionConfig.get(CONFIG_JTA_NAME).asString();
        if (jndiName != null && jndiName.trim().length() > 0) {
            // Get DB connection via JNDI
            logger.info("Using DB connection configured via Driver Manager");
            InitialContext ctx = null;
            try {
                ctx = new InitialContext();
            } catch (NamingException ex) {
                logger.warn("Getting JNDI initial context failed: " + ex.getMessage(), ex);
            }
            if (ctx == null) {
                throw new InvalidException(
                        "Current platform context does not support lookup of repository DB via JNDI. "
                                + " Configure DB initialization via direct " + CONFIG_DB_DRIVER
                                + " configuration instead.");
            }

            useDataSource = true;
            ds = (DataSource) ctx.lookup(jndiName); // e.g. "java:comp/env/jdbc/MySQLDB"
        } else if (!StringUtils.isBlank(jtaName)) {
            // e.g. osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/openidm)
            OsgiName lookupName = OsgiName.parse(jtaName);
            Object service = ServiceUtil.getService(bundleContext, lookupName, null, true);
            if (service instanceof DataSource) {
                useDataSource = true;
                ds = (DataSource) service;
            } else {
                throw new RuntimeException("DataSource can not be retrieved for: " + jtaName);
            }
        } else {
            // Get DB Connection via Driver Manager
            dbDriver = connectionConfig.get(CONFIG_DB_DRIVER).asString();
            if (dbDriver == null || dbDriver.trim().length() == 0) {
                throw new InvalidException(
                        "Either a JNDI name (" + CONFIG_JNDI_NAME + "), " + "or a DB driver lookup ("
                                + CONFIG_DB_DRIVER + ") needs to be configured to connect to a DB.");
            }
            dbUrl = connectionConfig.get(CONFIG_DB_URL).required().asString();
            user = connectionConfig.get(CONFIG_USER).required().asString();
            password = connectionConfig.get(CONFIG_PASSWORD).defaultTo("").asString();
            logger.info("Using DB connection configured via Driver Manager with Driver {} and URL", dbDriver,
                    dbUrl);
            try {
                Class.forName(dbDriver);
            } catch (ClassNotFoundException ex) {
                logger.error("Could not find configured database driver " + dbDriver + " to start repository ",
                        ex);
                throw new InvalidException(
                        "Could not find configured database driver " + dbDriver + " to start repository ", ex);
            }
            Boolean enableConnectionPool = connectionConfig.get("enableConnectionPool").defaultTo(Boolean.FALSE)
                    .asBoolean();
            if (null == sharedDataSource) {
                Dictionary<String, String> serviceParams = new Hashtable<String, String>(1);
                serviceParams.put("osgi.jndi.service.name", "jdbc/openidm");
                sharedDataSource = bundleContext.registerService(DataSource.class.getName(),
                        DataSourceFactory.newInstance(connectionConfig), serviceParams);
            }
            if (enableConnectionPool) {
                ds = DataSourceFactory.newInstance(connectionConfig);
                useDataSource = true;
                logger.info("DataSource connection pool enabled.");
            } else {
                logger.info("No DataSource connection pool enabled.");
            }
        }

        // Table handling configuration
        String dbSchemaName = connectionConfig.get(CONFIG_DB_SCHEMA).defaultTo(null).asString();
        JsonValue genericQueries = config.get("queries").get("genericTables");
        int maxBatchSize = connectionConfig.get(CONFIG_MAX_BATCH_SIZE).defaultTo(100).asInteger();

        tableHandlers = new HashMap<String, TableHandler>();
        //TODO Make safe the database type detection
        DatabaseType databaseType = DatabaseType.valueOf(
                connectionConfig.get(CONFIG_DB_TYPE).defaultTo(DatabaseType.ANSI_SQL99.name()).asString());

        JsonValue defaultMapping = config.get("resourceMapping").get("default");
        if (!defaultMapping.isNull()) {
            defaultTableHandler = getGenericTableHandler(databaseType, defaultMapping, dbSchemaName,
                    genericQueries, maxBatchSize);
            logger.debug("Using default table handler: {}", defaultTableHandler);
        } else {
            logger.warn("No default table handler configured");
        }

        // Default the configuration table for bootstrap
        JsonValue defaultTableProps = new JsonValue(new HashMap());
        defaultTableProps.put("mainTable", "configobjects");
        defaultTableProps.put("propertiesTable", "configobjectproperties");
        defaultTableProps.put("searchableDefault", Boolean.FALSE);
        GenericTableHandler defaultConfigHandler = getGenericTableHandler(databaseType, defaultTableProps,
                dbSchemaName, genericQueries, 1);
        tableHandlers.put("config", defaultConfigHandler);

        JsonValue genericMapping = config.get("resourceMapping").get("genericMapping");
        if (!genericMapping.isNull()) {
            for (String key : genericMapping.keys()) {
                JsonValue value = genericMapping.get(key);
                if (key.endsWith("/*")) {
                    // For matching purposes strip the wildcard at the end
                    key = key.substring(0, key.length() - 1);
                }
                TableHandler handler = getGenericTableHandler(databaseType, value, dbSchemaName, genericQueries,
                        maxBatchSize);

                tableHandlers.put(key, handler);
                logger.debug("For pattern {} added handler: {}", key, handler);
            }
        }

        JsonValue explicitQueries = config.get("queries").get("explicitTables");
        JsonValue explicitMapping = config.get("resourceMapping").get("explicitMapping");
        if (!explicitMapping.isNull()) {
            for (Object keyObj : explicitMapping.keys()) {
                JsonValue value = explicitMapping.get((String) keyObj);
                String key = (String) keyObj;
                if (key.endsWith("/*")) {
                    // For matching purposes strip the wildcard at the end
                    key = key.substring(0, key.length() - 1);
                }
                TableHandler handler = getMappedTableHandler(databaseType, value,
                        value.get("table").required().asString(),
                        value.get("objectToColumn").required().asMap(), dbSchemaName, explicitQueries,
                        maxBatchSize);

                tableHandlers.put(key, handler);
                logger.debug("For pattern {} added handler: {}", key, handler);
            }
        }

    } catch (RuntimeException ex) {
        logger.warn("Configuration invalid, can not start JDBC repository.", ex);
        throw new InvalidException("Configuration invalid, can not start JDBC repository.", ex);
    } catch (NamingException ex) {
        throw new InvalidException("Could not find configured jndiName " + jndiName + " to start repository ",
                ex);
    } catch (InternalServerErrorException ex) {
        throw new InvalidException("Could not initialize mapped table handler, can not start JDBC repository.",
                ex);
    }

    Connection testConn = null;
    try {
        // Check if we can get a connection
        testConn = getConnection();
        testConn.setAutoCommit(true); // Ensure we do not implicitly start transaction isolation
    } catch (Exception ex) {
        logger.warn("JDBC Repository start-up experienced a failure getting a DB connection: " + ex.getMessage()
                + ". If this is not temporary or resolved, Repository operation will be affected.", ex);
    } finally {
        if (testConn != null) {
            try {
                testConn.close();
            } catch (SQLException ex) {
                logger.warn("Failure during test connection close ", ex);
            }
        }
    }
}

From source file:csiro.pidsvc.mappingstore.Manager.java

/**************************************************************************
 *  Construction/destruction./*w w w .j a va2s.  c  om*/
 */

public Manager() throws NamingException, SQLException, IOException {
    InitialContext initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");
    DataSource ds = (DataSource) envCtx.lookup(Settings.getInstance().getProperty("jndiReferenceName"));
    _connection = ds.getConnection();
    refreshCaseSensitivity();
}

From source file:org.j2free.jpa.Controller.java

private Controller(boolean beginTX) throws NamingException, NotSupportedException, SystemException {
    InitialContext ctx = new InitialContext();

    tx = (UserTransaction) ctx.lookup("UserTransaction");
    em = (EntityManager) ctx.lookup("java:comp/env/persistence/EntityManager");

    problem = null;//from   www  .j a  va2  s. c o m

    if (beginTX)
        begin();
}

From source file:edu.ucsd.library.dams.api.DAMSAPIServlet.java

private static Properties loadDefaultConfig() throws NamingException, FileNotFoundException, IOException {
    String damsHome = null;/* ww  w.j  a  va  2 s.co m*/
    InitialContext ctx = new InitialContext();
    try {
        damsHome = (String) ctx.lookup("java:comp/env/dams/home");
    } catch (Exception ex) {
        damsHome = "dams";
        log.error("Error looking up enviroment variable: java:comp/env/dams/home", ex);
    }
    File f = new File(damsHome, "dams.properties");
    Properties props = new Properties();
    props.load(new FileInputStream(f));
    return props;
}

From source file:prodandes.Prodandes.java

@GET
@Path("/inicializarColas")
public String inicializarColas() throws JMSException, NamingException {
    InitialContext init = new InitialContext();
    this.cf = (ConnectionFactory) init.lookup("RemoteConnectionFactory");
    this.d = (Destination) init.lookup("queue/queue1");
    this.c = (javax.jms.Connection) this.cf.createConnection("guest123", "guest");
    ((javax.jms.Connection) this.c).start();
    this.s = ((javax.jms.Connection) this.c).createSession(false, Session.AUTO_ACKNOWLEDGE);
    mc = s.createConsumer(d);/* ww w. j  av a  2 s.  c o m*/
    this.mc.setMessageListener(this);
    buzon = new ArrayList<String>();
    return "Inicializo bien";
}

From source file:com.portfolio.rest.RestServicePortfolio.java

public RestServicePortfolio(@Context ServletConfig sc, @Context ServletContext context) {
    try {/*  w w  w  .ja v a 2 s  .co m*/
        // Initialize data provider and cas
        try {
            casUrlValidation = context.getInitParameter("casUrlValidation");
        } catch (Exception ex) {
            casUrlValidation = null;
        }
        ;

        try {
            elggDefaultApiUrl = context.getInitParameter("elggDefaultApiUrl");
        } catch (Exception ex) {
            elggDefaultApiUrl = null;
        }
        ;

        try {
            elggDefaultSiteUrl = context.getInitParameter("elggDefaultSiteUrl");
        } catch (Exception ex) {
            elggDefaultSiteUrl = null;
        }
        ;

        try {
            elggApiKey = context.getInitParameter("elggApiKey");
        } catch (Exception ex) {
            elggApiKey = null;
        }
        ;

        try {
            elggDefaultUserPassword = context.getInitParameter("elggDefaultUserPassword");
        } catch (Exception ex) {
            elggDefaultUserPassword = null;
        }
        ;

        servContext = context;
        String dataProviderName = sc.getInitParameter("dataProviderClass");
        dataProvider = (DataProvider) Class.forName(dataProviderName).newInstance();

        // Try to initialize Datasource
        InitialContext cxt = new InitialContext();
        if (cxt == null) {
            throw new Exception("no context found!");
        }

        /// Init this here, might fail depending on server hosting
        ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/portfolio-backend");
        if (ds == null) {
            throw new Exception("Data  jdbc/portfolio-backend source not found!");
        }
    } catch (Exception e) {
        logger.error("CAN'T INIT PROVIDER: " + e.toString());
        e.printStackTrace();
    }
}