Example usage for java.sql DriverManager registerDriver

List of usage examples for java.sql DriverManager registerDriver

Introduction

In this page you can find the example usage for java.sql DriverManager registerDriver.

Prototype

public static void registerDriver(java.sql.Driver driver) throws SQLException 

Source Link

Document

Registers the given driver with the DriverManager .

Usage

From source file:org.apache.ranger.hive.client.HiveClient.java

private void initConnection(String userName, String password) {

    Properties prop = getConfigHolder().getRangerSection();
    String driverClassName = prop.getProperty("jdbc.driverClassName");
    String url = prop.getProperty("jdbc.url");
    String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check xa_portal.log for more info.";

    if (driverClassName != null) {
        try {//from w  ww  .j  a va  2 s.  c  o  m
            Driver driver = (Driver) Class.forName(driverClassName).newInstance();
            DriverManager.registerDriver(driver);
        } catch (SQLException e) {
            String msgDesc = "initConnection: Caught SQLException while registering "
                    + "Hive driver, so Unable to connect to Hive Thrift Server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, e);
            hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null);
            throw hdpException;
        } catch (IllegalAccessException ilae) {
            String msgDesc = "initConnection: Class or its nullary constructor might not accessible."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, ilae);
            hdpException.generateResponseDataMap(false, getMessage(ilae), msgDesc + errMsg, null, null);
            throw hdpException;
        } catch (InstantiationException ie) {
            String msgDesc = "initConnection: Class may not have its nullary constructor or "
                    + "may be the instantiation fails for some other reason."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, ie);
            hdpException.generateResponseDataMap(false, getMessage(ie), msgDesc + errMsg, null, null);
            throw hdpException;

        } catch (ExceptionInInitializerError eie) {
            String msgDesc = "initConnection: Got ExceptionInInitializerError, "
                    + "The initialization provoked by this method fails."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, eie);
            hdpException.generateResponseDataMap(false, getMessage(eie), msgDesc + errMsg, null, null);
            throw hdpException;
        } catch (SecurityException se) {
            String msgDesc = "initConnection: unable to initiate connection to hive thrift server instance,"
                    + " The caller's class loader is not the same as or an ancestor "
                    + "of the class loader for the current class and invocation of "
                    + "s.checkPackageAccess() denies access to the package of this class.";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            throw hdpException;
        } catch (Throwable t) {
            String msgDesc = "initConnection: Unable to connect to Hive Thrift Server instance, "
                    + "please provide valid value of field : {jdbc.driverClassName}.";
            HadoopException hdpException = new HadoopException(msgDesc, t);
            hdpException.generateResponseDataMap(false, getMessage(t), msgDesc + errMsg, null,
                    "jdbc.driverClassName");
            throw hdpException;
        }
    }

    try {

        if (userName == null && password == null) {
            con = DriverManager.getConnection(url);
        } else {
            con = DriverManager.getConnection(url, userName, password);
        }

    } catch (SQLException e) {
        String msgDesc = "Unable to connect to Hive Thrift Server instance.";
        HadoopException hdpException = new HadoopException(msgDesc, e);
        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null);
        throw hdpException;
    } catch (SecurityException se) {
        String msgDesc = "Unable to connect to Hive Thrift Server instance.";
        HadoopException hdpException = new HadoopException(msgDesc, se);
        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
        throw hdpException;
    }
}

From source file:edu.education.ucsb.muster.MusterServlet.java

private Driver registerDriver(String driver, String url) {
    try {/*from   ww w . ja v a  2 s .co  m*/
        DriverManager
                .registerDriver((Driver) Class.forName(driver).getConstructor().newInstance((Object[]) null));
        return DriverManager.getDriver(url);
    } catch (Exception e) {
        addException(e, "Could not load driver `" + driver + "` for url `" + url + "`");
    }
    return null;
}

From source file:com.buisonje.tools.xmldbloader.XmlDataSetDBLoader.java

/**
 * Instructs the {@link System}'s {@link ClassLoader} to load a JDBC driver class file from an external JAR.
 * @param jarFilePath the path to the class file to be loaded.
 * @throws IllegalArgumentException if no class could successfully loaded from the specified path.
 *///from   w w  w. j  a va 2 s.c om
private void loadJdbcDriverClassFromJar(final String jarFilePath) throws IllegalArgumentException {

    try {

        URL u = new URL("jar:file:///" + jarFilePath + "!/");
        URLClassLoader ucl = new URLClassLoader(new URL[] { u });

        Reflections reflections = new Reflections(ucl);

        final Set<Class<? extends Driver>> detectedJdbcDrivers = reflections.getSubTypesOf(Driver.class);

        if (detectedJdbcDrivers.isEmpty()) {
            throw new IllegalArgumentException(String.format(
                    "The supplied JAR file at \"%s\" contains no JDBC drivers (which should implement the interface \"%s\").",
                    jarFilePath, Driver.class.getName()));
        }

        final int numberOfDetectedJdbcDrivers = detectedJdbcDrivers.size();
        if (numberOfDetectedJdbcDrivers > 1) {
            LOGGER.warn(
                    "Detected more than one ({}) JDBC drivers in the supplied JAR file at \"{}\". Choosing the first one...",
                    numberOfDetectedJdbcDrivers, jarFilePath);
        }

        Driver driver = detectedJdbcDrivers.iterator().next().newInstance();
        LOGGER.info("Loaded JDBC driver \"{}\".", driver.getClass().getName());
        DriverManager.registerDriver(new DriverShim(driver));

    } catch (InstantiationException e) {
        throw new IllegalArgumentException(String.format(
                "JAR file \"%s\" apparently contains a JDBC Driver that is incompatible with the Java version "
                        + "on which the application is currently running (version %s). To solve this problem, either upgrade the Java version (recommended) or "
                        + "downgrade the JDBC driver.",
                jarFilePath, System.getProperty("java.version")), e);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                String.format("Unable to load JDBC Driver class from JAR \"%s\".", jarFilePath), e);
    }
}

From source file:org.mule.test.spring.config.DatabaseMuleArtifactTestCase.java

private void loadDriver(String driverClass) throws Exception {
    DriverManager.registerDriver((Driver) ClassUtils.instanciateClass(driverClass));
}

From source file:com.thinkbiganalytics.nifi.v2.thrift.ThriftConnectionPool.java

/**
 * using Thread.currentThread().getContextClassLoader() will ensure that you are using the ClassLoader for your NAR.
 *
 * @param urlString URL of the class//  w  w  w.  j  a v a  2  s .c  om
 * @param drvName   the driver string
 * @return the class loader
 * @throws InitializationException if there is a problem obtaining the ClassLoader
 */
protected ClassLoader getDriverClassLoader(String urlString, String drvName) throws InitializationException {
    if (urlString != null && urlString.length() > 0) {
        try {
            final URL[] urls = new URL[] { new URL(urlString) };
            final URLClassLoader ucl = new URLClassLoader(urls);

            // Workaround which allows to use URLClassLoader for JDBC driver loading.
            // (Because the DriverManager will refuse to use a driver not loaded by the system ClassLoader.)
            final Class<?> clazz = Class.forName(drvName, true, ucl);
            if (clazz == null) {
                throw new InitializationException("Can't load Database Driver " + drvName);
            }
            final Driver driver = (Driver) clazz.newInstance();
            DriverManager.registerDriver(new DriverShim(driver));

            return ucl;
        } catch (final MalformedURLException e) {
            throw new InitializationException("Invalid Database Driver Jar Url", e);
        } catch (final Exception e) {
            throw new InitializationException("Can't load Database Driver", e);
        }
    } else {
        // That will ensure that you are using the ClassLoader for you NAR.
        return Thread.currentThread().getContextClassLoader();
    }
}

From source file:org.sqsh.SQLDriverManager.java

/**
 * Attempts to connect to the database utilizing a driver.
 * /*w  ww . ja  v  a2  s  . c om*/
 * @param driver The name of the driver to utilize. The special
 *    driver name "generic" can be provided if the manager does not
 *    have a registered driver that can be used. 
 * @param session The session for which the connection is being 
 *    established. The session is primarly used as a place to
 *    send error messages.
 * @param properties Connection properties to be utilized.
 * @return A newly created connection.
 * @throws SQLException Thrown if the connection could not be 
 *    established.
 */
public SQLConnectionContext connect(Session session, ConnectionDescriptor connDesc) throws SQLException {

    SQLDriver sqlDriver = null;

    /*
     * If no driver was supplied, then set it to the default.
     */
    if (connDesc.getDriver() == null) {

        connDesc.setDriver(defaultDriver);
    }

    /*
     * Make sure we are going to have enough to connect with here!
     */
    if (connDesc.getDriver() == null && connDesc.getUrl() == null) {

        throw new SQLException("Either an explicit JSqsh driver name must be supplied "
                + "(via --driver) or a JDBC fully qualified JDBC url "
                + "must be provided (via --jdbc-url). In most cases the "
                + "JDBC url must also be accompanied with the "
                + "name of the JDBC driver class (via --jdbc-class");
    }

    /*
     * We need to have a SQLDriver object because it makes our life
     * easier expanding variables. To allow for no driver being
     * supplied by the user, we will use one called "generic".
     */
    if (connDesc.getDriver() == null) {

        connDesc.setDriver("generic");
    }

    sqlDriver = getDriver(connDesc.getDriver());
    if (sqlDriver == null) {

        throw new SQLException("JSqsh has no driver registered under " + "the name '" + connDesc.getDriver()
                + "'. To see a list of available drivers, use the " + "\\drivers command");
    }

    /*
     * If the user asked for a JDBC driver class, then make sure
     * that we can load it.
     */
    if (connDesc.getJdbcClass() != null) {

        try {

            Class<? extends Driver> driverClass = Class.forName(connDesc.getJdbcClass(), true, classLoader)
                    .asSubclass(Driver.class);
            Driver d = driverClass.newInstance();
            DriverManager.registerDriver(new DriverShim(d));
        } catch (Exception e) {

            throw new SQLException(
                    "Cannot load JDBC driver class '" + connDesc.getJdbcClass() + "': " + e.getMessage());
        }
    }

    /*
     * The JDBC URL will either be one the one supplied by the user
     * or the one that is defined by the JDBC driver.
     */
    String url = connDesc.getUrl();
    if (url == null) {

        url = sqlDriver.getUrl();
    }

    /*
     * Turn our connection descriptor into properties that can be
     * referenced while expanding the URL.
     */
    Map<String, String> properties = toProperties(session, connDesc);

    /*
     * Expand the url of its variables.
     */
    url = getUrl(session, properties, sqlDriver.getVariables(), url);

    Connection conn = null;
    try {

        Driver jdbcDriver = DriverManager.getDriver(url);

        /*
         * Similar to above, we'll iterate through the properties supported by
         * the driver and set them as necessary.
         */
        Properties props = new Properties();
        try {

            /*
             * One little trick we can do is to ask the driver for all
             * of the properties that it supports. If there so happens to
             * exist an variable associated with the driver that matches
             * that variable name, we will set it. 
             */
            DriverPropertyInfo[] supportedProperties = jdbcDriver.getPropertyInfo(url, null);

            for (int i = 0; i < supportedProperties.length; i++) {

                String name = supportedProperties[i].name;
                String value = getProperty(properties, sqlDriver.getVariables(), name);

                if (!SQLDriver.SERVER_PROPERTY.equals(name) && (value != null)) {
                    LOG.fine("Setting connection property '" + name + "' to '" + value + "'");
                    props.put(name, value);
                }
            }

        } catch (Exception e) {

            session.err.println("WARNING: Failed to retrieve JDBC driver "
                    + "supported connection property list (" + e.getMessage() + ")");
        }

        /*
         * If the driver explicitly declares a property 
         * we just blindly pass it in.
         */
        for (String name : sqlDriver.getPropertyNames()) {

            props.put(name, sqlDriver.getProperty(name));
        }

        /*
         * If the connection descriptor specified a set of properties to use
         * then use them too (wow, we have a lot of ways to get properties
         * to the driver!)
         */
        Map<String, String> descProps = connDesc.getPropertiesMap();
        if (descProps.size() > 0) {

            for (Entry<String, String> e : descProps.entrySet()) {

                props.put(e.getKey(), e.getValue());
            }
        }

        String s = getProperty(properties, sqlDriver.getVariables(), SQLDriver.USER_PROPERTY);
        if (s == null) {

            if (defaultUsername == null) {

                s = System.getProperty("user.name");
            }

            if (s == null) {

                s = promptInput(session, "Username", false);
            }
            connDesc.setUsername(s);
        }
        if (s != null) {

            props.put(SQLDriver.USER_PROPERTY, s);
        }

        s = getProperty(properties, sqlDriver.getVariables(), SQLDriver.PASSWORD_PROPERTY);
        if (s == null) {

            s = promptInput(session, "Password", true);
        }
        if (s != null) {

            props.put(SQLDriver.PASSWORD_PROPERTY, s);
        }

        conn = DriverManager.getConnection(url, props);
        SQLTools.printWarnings(session, conn);
    } catch (SQLException e) {

        throw new SQLException("Unable to connect via JDBC url '" + url + "': " + e.getMessage(),
                e.getSQLState(), e.getErrorCode(), e);
    }

    String database = getProperty(properties, sqlDriver.getVariables(), SQLDriver.DATABASE_PROPERTY);
    if (database == null && defaultDatabase != null) {

        database = defaultDatabase;
    }

    if (database != null) {
        /*            
                    try {
                
        conn.setCatalog(database);
        SQLTools.printWarnings(session, conn);
                    }
                    catch (SQLException e) {
                
        session.err.println("WARNING: Could not switch database context"
            + " to '" + database + "': " + e.getMessage());
                    }
        */
    }

    try {

        conn.setAutoCommit(defaultAutoCommit);
        SQLTools.printWarnings(session, conn);
    } catch (SQLException e) {

        session.err.println("WARNING: Unable to set auto-commit mode to " + defaultAutoCommit);
    }

    /*
     * AWFUL AWFUL HACK!!!
     * In a second we will transfer variables defined by the 
     * driver via the SessionVariable setting. However, often
     * these variables will be setting information in the ConnectionContext
     * that belongs to the session -- which is likely the one we are
     * about to return, but haven't yet.  This hack temporarily
     * stuffs it into the session so it can get set, then pulls it
     * back out.
     */
    ConnectionContext oldContext = session.getConnectionContext();
    SQLConnectionContext newContext = new SQLConnectionContext(session, connDesc, conn, url,
            sqlDriver.getAnalyzer(), sqlDriver.getNormalizer(), sqlDriver.getCurrentSchemaQuery());
    session.setConnectionContext(newContext, false);

    try {

        /*
         * Now that we have our connection established, set session
         * variables that have been requested by the driver.
         */
        Iterator<String> varIter = sqlDriver.getSessionVariables().keySet().iterator();
        while (varIter.hasNext()) {

            String name = varIter.next();
            session.setVariable(name, sqlDriver.getSessionVariable(name));
        }
    } finally {

        session.setConnectionContext(oldContext, false);
    }

    return newContext;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstOracle.CFAstOracleSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }//from w w  w.j a  v  a  2s.c  om

    if (configuration != null) {
        try {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:oracle:thin:@" + dbServer;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.rollback();
            setDbSchemaName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from PooledConnection for ConnectionPoolDataSource \""
                                + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:org.apache.ranger.services.hive.client.HiveClient.java

private void initConnection(String userName, String password) throws HadoopException {

    Properties prop = getConfigHolder().getRangerSection();
    String driverClassName = prop.getProperty("jdbc.driverClassName");
    String url = prop.getProperty("jdbc.url");
    String errMsg = " You can still save the repository and start creating "
            + "policies, but you would not be able to use autocomplete for "
            + "resource names. Check ranger_admin.log for more info.";

    if (driverClassName != null) {
        try {//from  ww w .  j av a 2s  .c om
            Driver driver = (Driver) Class.forName(driverClassName).newInstance();
            DriverManager.registerDriver(driver);
        } catch (SQLException e) {
            String msgDesc = "initConnection: Caught SQLException while registering "
                    + "Hive driver, so Unable to connect to Hive Thrift Server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, e);
            hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null);
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;
        } catch (IllegalAccessException ilae) {
            String msgDesc = "initConnection: Class or its nullary constructor might not accessible."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, ilae);
            hdpException.generateResponseDataMap(false, getMessage(ilae), msgDesc + errMsg, null, null);
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;
        } catch (InstantiationException ie) {
            String msgDesc = "initConnection: Class may not have its nullary constructor or "
                    + "may be the instantiation fails for some other reason."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, ie);
            hdpException.generateResponseDataMap(false, getMessage(ie), msgDesc + errMsg, null, null);
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;

        } catch (ExceptionInInitializerError eie) {
            String msgDesc = "initConnection: Got ExceptionInInitializerError, "
                    + "The initialization provoked by this method fails."
                    + "So unable to initiate connection to hive thrift server instance.";
            HadoopException hdpException = new HadoopException(msgDesc, eie);
            hdpException.generateResponseDataMap(false, getMessage(eie), msgDesc + errMsg, null, null);
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;
        } catch (SecurityException se) {
            String msgDesc = "initConnection: unable to initiate connection to hive thrift server instance,"
                    + " The caller's class loader is not the same as or an ancestor "
                    + "of the class loader for the current class and invocation of "
                    + "s.checkPackageAccess() denies access to the package of this class.";
            HadoopException hdpException = new HadoopException(msgDesc, se);
            hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;
        } catch (Throwable t) {
            String msgDesc = "initConnection: Unable to connect to Hive Thrift Server instance, "
                    + "please provide valid value of field : {jdbc.driverClassName}.";
            HadoopException hdpException = new HadoopException(msgDesc, t);
            hdpException.generateResponseDataMap(false, getMessage(t), msgDesc + errMsg, null,
                    "jdbc.driverClassName");
            if (LOG.isDebugEnabled()) {
                LOG.debug(msgDesc, hdpException);
            }
            throw hdpException;
        }
    }

    try {

        if (userName == null && password == null) {
            con = DriverManager.getConnection(url);
        } else {
            con = DriverManager.getConnection(url, userName, password);
        }

    } catch (SQLException e) {
        String msgDesc = "Unable to connect to Hive Thrift Server instance.";
        HadoopException hdpException = new HadoopException(msgDesc, e);
        hdpException.generateResponseDataMap(false, getMessage(e), msgDesc + errMsg, null, null);
        if (LOG.isDebugEnabled()) {
            LOG.debug(msgDesc, hdpException);
        }
        throw hdpException;
    } catch (SecurityException se) {
        String msgDesc = "Unable to connect to Hive Thrift Server instance.";
        HadoopException hdpException = new HadoopException(msgDesc, se);
        hdpException.generateResponseDataMap(false, getMessage(se), msgDesc + errMsg, null, null);
        if (LOG.isDebugEnabled()) {
            LOG.debug(msgDesc, hdpException);
        }
        throw hdpException;
    } catch (Throwable t) {
        String msgDesc = "Unable to connect to Hive Thrift Server instance";
        HadoopException hdpException = new HadoopException(msgDesc, t);
        hdpException.generateResponseDataMap(false, getMessage(t), msgDesc + errMsg, null, url);
        if (LOG.isDebugEnabled()) {
            LOG.debug(msgDesc, hdpException);
        }
        throw hdpException;
    }
}

From source file:net.sourceforge.msscodefactory.cfacc.v2_0.CFAccOracle.CFAccOracleSchema.java

public boolean connect() {
    final String S_ProcName = "connect";
    if (cnx != null) {
        return (false);
    }//from  w w w.  j a va  2 s  .c  om

    if (configuration != null) {
        try {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = configuration.getDbUserName();
        String dbPassword = configuration.getDbPassword();
        String url = "jdbc:oracle:thin:@" + dbServer;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.rollback();
            setSchemaDbName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    if (jndiName != null) {
        try {
            Context ctx = new InitialContext();
            DataSource ds = (DataSource) ctx.lookup(jndiName);
            if (ds == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get resolve DataSource \"" + jndiName + "\"");
            }
            cnx = ds.getConnection();
            if (cnx == null) {
                throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                        "Could not get Connection from DataSource \"" + jndiName + "\"");
            }
            cnx.setAutoCommit(false);
            cnx.rollback();
        } catch (NamingException e) {
            cnx = null;
            throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                    "NamingException " + e.getMessage(), e);
        } catch (SQLException e) {
            cnx = null;
            inTransaction = false;
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "Neither configurationFile nor jndiName found, do not know how to connect to database");
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_1.CFAstOracle.CFAstOracleSchema.java

public boolean connect(String username, String password) {
    final String S_ProcName = "connect-userpw";
    if (cnx != null) {
        return (false);
    }/*from  w ww .ja v a2  s . c o  m*/
    if ((username == null) || (username.length() <= 0)) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "username");
    }
    if (password == null) {
        throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 1,
                "password");
    }

    if (configuration != null) {
        try {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        String dbServer = configuration.getDbServer();
        int dbPort = configuration.getDbPort();
        String dbDatabase = configuration.getDbDatabase();
        String dbUserName = username;
        String dbPassword = password;
        String url = "jdbc:oracle:thin:@" + dbServer;
        Properties props = new Properties();
        props.setProperty("user", dbUserName);
        props.setProperty("password", dbPassword);
        try {
            cnx = DriverManager.getConnection(url, props);
            cnx.setAutoCommit(false);
            cnx.rollback();
            setDbSchemaName(dbDatabase);
        } catch (SQLException e) {
            throw CFLib.getDefaultExceptionFactory().newDbException(getClass(), S_ProcName, e);
        }
        return (true);
    }
    throw CFLib.getDefaultExceptionFactory().newUsageException(getClass(), S_ProcName,
            "configurationFile not found, do not know how to connect to database");
}