java.sql.Driver

Here are the examples of the java api class java.sql.Driver taken from open source projects.

1. TestClassLoaderLeak#runTest()

Project: ThriftyPaxos
File: TestClassLoaderLeak.java
/**
     * This method is called using reflection.
     */
static void runTest() throws Exception {
    Class.forName("org.h2.Driver");
    Class.forName("org.h2.upgrade.v1_1.Driver");
    Driver d1 = DriverManager.getDriver("jdbc:h2:mem:test");
    Driver d2 = DriverManager.getDriver("jdbc:h2v1_1:mem:test");
    Connection connection;
    connection = DriverManager.getConnection("jdbc:h2:mem:test");
    DriverManager.deregisterDriver(d1);
    DriverManager.deregisterDriver(d2);
    connection.close();
    connection = null;
}

2. DatabasePoolPortlet#attemptConnect()

Project: geronimo
File: DatabasePoolPortlet.java
private static String attemptConnect(PortletRequest request, PoolData data) throws SQLException, IllegalAccessException, InstantiationException {
    Class driverClass = attemptDriverLoad(request, data);
    Driver driver = (Driver) driverClass.newInstance();
    if (driver.acceptsURL(data.url)) {
        Properties props = new Properties();
        if (data.user != null) {
            props.put("user", data.user);
        }
        if (data.password != null) {
            props.put("password", data.password);
        }
        Connection con = null;
        try {
            con = driver.connect(data.url, props);
            final DatabaseMetaData metaData = con.getMetaData();
            return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
        } finally {
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    } else
        throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url);
}

3. PersistenceValidator#checkConnection()

Project: syncope
File: PersistenceValidator.java
private Status checkConnection(final DBs selectedDb) {
    Driver driver = null;
    try {
        driver = DriverLoader.load(selectedDb, isProxyEnabled, proxyHost, proxyPort, proxyUser, proxyPwd);
        final Properties props = new Properties();
        props.put("user", persistenceDbuser);
        props.put("password", persistenceDbPassword);
        driver.connect(persistenceUrl, props);
        return Status.OK;
    } catch (Exception ex) {
        error = new StringBuilder("Error during connection to database: please check inserted data.");
        error.append(driver == null ? new StringBuilder(" Unable to get ").append(selectedDb.getName()).append(" driver!").toString() : "");
        return Status.ERROR;
    }
}

4. DriverDataSource#findMatchingDriver()

Project: sling
File: DriverDataSource.java
private Driver findMatchingDriver(Collection<Driver> drivers) {
    final String url = poolProperties.getUrl();
    for (Driver driver : drivers) {
        try {
            if (driver.acceptsURL(url)) {
                return driver;
            }
        } catch (SQLException e) {
            log.debug("Error occurred while matching driver against url {}", url, e);
        }
    }
    return null;
}

5. DriverConnectInterceptorTest#driverConnect_return_Null_NPEtest()

Project: pinpoint
File: DriverConnectInterceptorTest.java
@Test
public void driverConnect_return_Null_NPEtest() throws SQLException {
    MockTraceContext mockTraceContext = new MockTraceContext();
    MethodDescriptor mock = mock(MethodDescriptor.class);
    JdbcUrlParser parser = mock(JdbcUrlParser.class);
    when(parser.parse(anyString())).thenReturn(UnKnownDatabaseInfo.INSTANCE);
    String invalidJdbcUrl = "invalidUrl";
    final Driver driver = mock(Driver.class);
    SpanEventRecorder spanEventRecorder = mock(SpanEventRecorder.class);
    DriverConnectInterceptor driverConnectInterceptor = new DriverConnectInterceptor(mockTraceContext, mock, parser);
    driverConnectInterceptor.prepareAfterTrace(driver, va(invalidJdbcUrl), null, null);
    driverConnectInterceptor.doInAfterTrace(spanEventRecorder, driver, va(invalidJdbcUrl), null, null);
}

6. DriverConnectInterceptorTest#driverConnect()

Project: pinpoint
File: DriverConnectInterceptorTest.java
@Test
public void driverConnect() throws SQLException {
    MockTraceContext mockTraceContext = new MockTraceContext();
    MethodDescriptor mock = mock(MethodDescriptor.class);
    JdbcUrlParser parser = mock(JdbcUrlParser.class);
    when(parser.parse(anyString())).thenReturn(UnKnownDatabaseInfo.INSTANCE);
    String invalidJdbcUrl = "invalidUrl";
    Driver driver = mock(Driver.class);
    DatabaseInfoAccessor setAccessor = mock(DatabaseInfoAccessor.class);
    DatabaseInfoAccessor getAccessor = mock(DatabaseInfoAccessor.class);
    SpanEventRecorder spanEventRecorder = mock(SpanEventRecorder.class);
    DriverConnectInterceptor driverConnectInterceptor = new DriverConnectInterceptor(mockTraceContext, mock, parser);
    driverConnectInterceptor.prepareAfterTrace(driver, va(invalidJdbcUrl), setAccessor, null);
    driverConnectInterceptor.doInAfterTrace(spanEventRecorder, driver, va(invalidJdbcUrl), getAccessor, null);
    verify(setAccessor, times(1))._$PINPOINT$_setDatabaseInfo(UnKnownDatabaseInfo.INSTANCE);
    verify(getAccessor, times(1))._$PINPOINT$_getDatabaseInfo();
}

7. JdbcConnectionSourceTest#testConnectionClosed()

Project: ormlite-jdbc
File: JdbcConnectionSourceTest.java
@Test(expected = SQLException.class)
public void testConnectionClosed() throws Exception {
    Connection conn = createMock(Connection.class);
    conn.setAutoCommit(true);
    expect(conn.isClosed()).andReturn(true);
    Driver driver = createMock(Driver.class);
    String url = "jdbc:bar:baz";
    expect(driver.acceptsURL(url)).andReturn(true);
    expect(driver.connect(isA(String.class), isA(Properties.class))).andReturn(conn);
    replay(driver, conn);
    DriverManager.registerDriver(driver);
    try {
        JdbcConnectionSource sds = new JdbcConnectionSource(url, databaseType);
        assertNotNull(sds.getReadOnlyConnection(null));
        sds.getReadOnlyConnection(null);
        sds.close();
        fail("Should not get here");
    } finally {
        DriverManager.deregisterDriver(driver);
    }
}

8. JdbcConnectionSourceTest#testClose()

Project: ormlite-jdbc
File: JdbcConnectionSourceTest.java
@Test
public void testClose() throws Exception {
    Connection conn = createMock(Connection.class);
    conn.setAutoCommit(true);
    conn.close();
    Driver driver = createMock(Driver.class);
    String url = "jdbc:bar:baz";
    expect(driver.acceptsURL(url)).andReturn(true);
    expect(driver.connect(isA(String.class), isA(Properties.class))).andReturn(conn);
    replay(driver, conn);
    DriverManager.registerDriver(driver);
    try {
        JdbcConnectionSource sds = new JdbcConnectionSource(url, databaseType);
        assertNotNull(sds.getReadOnlyConnection(null));
        sds.close();
        verify(driver, conn);
    } finally {
        DriverManager.deregisterDriver(driver);
    }
}

9. JdbcConnectionSourceTest#testGetConnectionNull()

Project: ormlite-jdbc
File: JdbcConnectionSourceTest.java
@Test(expected = SQLException.class)
public void testGetConnectionNull() throws Exception {
    Driver driver = createMock(Driver.class);
    Properties props = new Properties();
    String url = "jdbc:bar:baz";
    expect(driver.acceptsURL(url)).andReturn(true);
    expect(driver.connect(eq(url), eq(props))).andReturn(null);
    replay(driver);
    DriverManager.registerDriver(driver);
    try {
        JdbcConnectionSource sds = new JdbcConnectionSource(url, databaseType);
        sds.getReadOnlyConnection(null);
        sds.close();
    } finally {
        DriverManager.deregisterDriver(driver);
    }
}

10. JdbcConnectionSourceTest#testGetConnection()

Project: ormlite-jdbc
File: JdbcConnectionSourceTest.java
@Test
public void testGetConnection() throws Exception {
    Connection conn = createMock(Connection.class);
    Driver driver = createMock(Driver.class);
    String url = "jdbc:bar:mem:baz";
    expect(driver.acceptsURL(url)).andReturn(true);
    expect(driver.connect(isA(String.class), isA(Properties.class))).andReturn(conn);
    replay(driver);
    DriverManager.registerDriver(driver);
    try {
        JdbcConnectionSource sds = new JdbcConnectionSource(url, databaseType);
        assertNotNull(sds.getReadOnlyConnection(null));
        sds.close();
        verify(driver);
    } finally {
        DriverManager.deregisterDriver(driver);
    }
}

11. DriverManagerTests#test16()

Project: openjdk
File: DriverManagerTests.java
/**
     * Validate that DriverAction.release is called when a driver is registered
     * via registerDriver(Driver, DriverAction)
     *
     * @throws Exception
     */
@Test
public void test16() throws Exception {
    File file = new File(util.StubDriverDA.DriverActionCalled);
    file.delete();
    assertFalse(file.exists());
    Driver d = null;
    Class.forName("util.StubDriverDA");
    d = DriverManager.getDriver(StubDriverDAURL);
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d), "Driver is registered");
    assertTrue(file.exists());
}

12. DriverTest#assertConnect()

Project: derby
File: DriverTest.java
/**
     * Do java.sql.Driver.connect(String url, Properties info call)
     * 
     * @param expectUrlEqualsGetUrl boolean indicating embedded would
     *                  expect the url passed in to equal metadata.getURL()
     * @param url       url to pass to Driver.connect()
     * @param info      properties to pass to Driver.Connect()
     * 
     * @throws SQLException on error.
     */
private static void assertConnect(boolean expectUrlEqualsGetUrl, String url, Properties info) throws SQLException {
    Driver driver = DriverManager.getDriver(url);
    Connection conn = driver.connect(url, info);
    assertNotNull(conn);
    if (expectUrlEqualsGetUrl)
        assertEquals(url, conn.getMetaData().getURL());
    else
        assertNotSame(url, conn.getMetaData().getURL());
    ResultSet rs = conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
    rs.next();
    assertEquals(rs.getString(1), conn.getMetaData().getUserName().toUpperCase());
    rs.close();
    conn.close();
    return;
}

13. Driver40UnbootedTest#main()

Project: derby
File: Driver40UnbootedTest.java
///////////////////////////////////////////////////////////////////////////////////
//
// ENTRY POINT
//
///////////////////////////////////////////////////////////////////////////////////
/**
     * <p>
     * This entry point is used to run a separate java process in order to verify
     * that the correct exception is being raised by getParentLogger() when the
     * engine hasn't been booted yet.
     * </p>
     */
public static void main(String[] args) throws Exception {
    Driver embeddedDriver = DriverManager.getDriver("jdbc:derby:");
    Wrapper41Driver embeddedWrapper = new Wrapper41Driver(embeddedDriver);
    String statusMessage = SUCCESS;
    try {
        embeddedWrapper.getParentLogger();
        statusMessage = "getParentLogger() unexpectedly succeeded";
    } catch (Exception se) {
        if (!(se instanceof SQLFeatureNotSupportedException)) {
            statusMessage = "Exception was not a SQLFeatureNotSupportedException. It was a " + se.getClass().getName();
        }
    }
    System.out.print(statusMessage);
}

14. Driver40Test#test_jdbc4_1()

Project: derby
File: Driver40Test.java
///////////////////////////////////////////////////////////////////////////////////
//
// TESTS
//
///////////////////////////////////////////////////////////////////////////////////
/**
     * <p>
     * Test new method added by JDBC 4.1.
     * </p>
     */
public void test_jdbc4_1() throws Exception {
    Driver driver = DriverManager.getDriver(getTestConfiguration().getJDBCClient().getUrlBase());
    println("Testing a " + driver.getClass().getName());
    Wrapper41Driver wrapper = new Wrapper41Driver(driver);
    try {
        wrapper.getParentLogger();
        fail("Should raise an Unimplemented Feature exception.");
    } catch (SQLException se) {
        assertEquals(SQLFeatureNotSupportedException.class.getName(), se.getClass().getName());
    }
}

15. AbstractTestBaseForInternalJDBC#connect()

Project: sis
File: AbstractTestBaseForInternalJDBC.java
/**
     * Connect to test database.
     * @return Connection to database.
     * @throws SQLException if the connection failed.
     */
public Connection connect() throws SQLException {
    final Driver driver = new DBFDriver();
    return driver.connect(this.dbfFile.getAbsolutePath(), null);
}

16. SimpleDriverDataSource#getConnectionFromDriver()

Project: effectivejava
File: SimpleDriverDataSource.java
@Override
protected Connection getConnectionFromDriver(Properties props) throws SQLException {
    Driver driver = getDriver();
    String url = getUrl();
    Assert.notNull(driver, "Driver must not be null");
    if (logger.isDebugEnabled()) {
        logger.debug("Creating new JDBC Driver Connection to [" + url + "]");
    }
    return driver.connect(url, props);
}

17. SimpleDBConnection#createConnection()

Project: aws-toolkit-eclipse
File: SimpleDBConnection.java
@Override
protected Object createConnection(final ClassLoader cl) throws Throwable {
    Properties props = getConnectionProfile().getBaseProperties();
    Properties connectionProps = new Properties();
    String connectURL = props.getProperty(IJDBCConnectionProfileConstants.URL_PROP_ID);
    String uid = props.getProperty(IJDBCConnectionProfileConstants.USERNAME_PROP_ID);
    String pwd = props.getProperty(IJDBCConnectionProfileConstants.PASSWORD_PROP_ID);
    String nameValuePairs = props.getProperty(IJDBCConnectionProfileConstants.CONNECTION_PROPERTIES_PROP_ID);
    String endpoint = props.getProperty(ISimpleDBConnectionProfileConstants.ENDPOINT);
    String accountId = props.getProperty(ISimpleDBConnectionProfileConstants.ACCOUNT_ID);
    //$NON-NLS-1$
    String propDelim = ",";
    /*
         * Legacy support: only set their user and pass if they hadn't
         * explicitly set it before.
         */
    if (uid == null || uid.length() == 0 || pwd == null || pwd.length() == 0) {
        AccountInfo accountInfo = null;
        if (accountId != null) {
            accountInfo = AwsToolkitCore.getDefault().getAccountManager().getAccountInfo(accountId);
        } else {
            // Equivalent to useGlobal legacy property
            accountInfo = AwsToolkitCore.getDefault().getAccountInfo();
        }
        uid = accountInfo.getAccessKey();
        pwd = accountInfo.getSecretKey();
    }
    if (uid != null) {
        //$NON-NLS-1$
        connectionProps.setProperty("user", uid);
    }
    if (pwd != null) {
        //$NON-NLS-1$
        connectionProps.setProperty("password", pwd);
    }
    if (endpoint != null) {
        //$NON-NLS-1$
        connectionProps.setProperty("endpoint", endpoint);
    }
    if (nameValuePairs != null && nameValuePairs.length() > 0) {
        //$NON-NLS-1$
        String[] pairs = parseString(nameValuePairs, ",");
        //$NON-NLS-1$
        String addPairs = "";
        for (int i = 0; i < pairs.length; i++) {
            //$NON-NLS-1$
            String[] namevalue = parseString(pairs[i], "=");
            connectionProps.setProperty(namevalue[0], namevalue[1]);
            if (i == 0 || i < pairs.length - 1) {
                addPairs = addPairs + propDelim;
            }
            addPairs = addPairs + pairs[i];
        }
    }
    Driver jdbcDriver = new JdbcDriver(com.amazonaws.services.simpledb.AmazonSimpleDBClient.class);
    return jdbcDriver.connect(connectURL, connectionProps);
}

18. TestOldVersion#getDriver()

Project: ThriftyPaxos
File: TestOldVersion.java
private static Driver getDriver(ClassLoader cl) throws Exception {
    Class<?> driverClass;
    try {
        driverClass = cl.loadClass("org.h2.Driver");
    } catch (ClassNotFoundException e) {
        return null;
    }
    Method m = driverClass.getMethod("load");
    Driver driver = (Driver) m.invoke(null);
    return driver;
}

19. DriverLoader#downloadDriver()

Project: syncope
File: DriverLoader.java
private static Driver downloadDriver(final String driverUrl, final String driverClassName, final boolean isProxyEnabled, final String proxyHost, final String proxyPort, final String proxyUser, final String proxyPwd) {
    Driver driver = null;
    try {
        if (isProxyEnabled) {
            System.setProperty("http.proxyHost", proxyHost);
            System.setProperty("http.proxyPort", proxyPort);
            if (proxyUser != null && !proxyUser.isEmpty() && proxyPwd != null) {
                Authenticator.setDefault(new Authenticator() {

                    @Override
                    public PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(proxyUser, proxyPwd.toCharArray());
                    }
                });
                System.setProperty("http.proxyUser", proxyUser);
                System.setProperty("http.proxyPassword", proxyPwd);
            }
        }
        final URL[] url = { new URL(driverUrl) };
        DRIVER_LOADER = new DriverLoader(url);
        driver = (Driver) DRIVER_LOADER.loadClass(driverClassName).newInstance();
    } catch (Exception e) {
    }
    return driver;
}

20. DriverLoader#load()

Project: syncope
File: DriverLoader.java
public static Driver load(final DBs selectedDB, final boolean isProxyEnabled, final String proxyHost, final String proxyPort, final String proxyUser, final String proxyPwd) {
    Driver driver = null;
    switch(selectedDB) {
        case POSTGRES:
            driver = downloadDriver(POSTGRES_JAR, POSTGRES_CLASS_DRIVER, isProxyEnabled, proxyHost, proxyPort, proxyUser, proxyPwd);
            break;
        case MYSQL:
            driver = downloadDriver(MYSQL_JAR, MYSQL_CLASS_DRIVER, isProxyEnabled, proxyHost, proxyPort, proxyUser, proxyPwd);
            break;
        case MARIADB:
            driver = downloadDriver(MARIADB_JAR, MARIADB_CLASS_DRIVER, isProxyEnabled, proxyHost, proxyPort, proxyUser, proxyPwd);
            break;
        case SQLSERVER:
            break;
        case ORACLE:
            break;
        default:
            break;
    }
    return driver;
}

21. BasicDataSource#createDataSource()

Project: servicemix4-bundles
File: BasicDataSource.java
// ------------------------------------------------------ Protected Methods
/**
     * <p>Create (if necessary) and return the internal data source we are
     * using to manage our connections.</p>
     *
     * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
     * "double checked locking" idiom in an attempt to avoid synchronizing
     * on every single call to this method.  However, this idiom fails to
     * work correctly in the face of some optimizations that are legal for
     * a JVM to perform.</p>
     *
     * @throws java.sql.SQLException if the object pool cannot be created.
     */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    Class driverFromCCL = null;
    if (driverClassName != null) {
        try {
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
            }
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        if (driverFromCCL != null) {
            driver = (Driver) driverFromCCL.newInstance();
            if (!driver.acceptsURL(url)) {
                new SQLException("No suitable driver", "08001");
            }
        } else {
            driver = DriverManager.getDriver(url);
        }
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, // unlimited maxActive (per key)
        -1, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, // maxWait
        0, // maxIdle (per key) 
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

22. BasicDataSource#createDataSource()

Project: servicemix4-bundles
File: BasicDataSource.java
// ------------------------------------------------------ Protected Methods
/**
     * <p>Create (if necessary) and return the internal data source we are
     * using to manage our connections.</p>
     *
     * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
     * "double checked locking" idiom in an attempt to avoid synchronizing
     * on every single call to this method.  However, this idiom fails to
     * work correctly in the face of some optimizations that are legal for
     * a JVM to perform.</p>
     *
     * @throws SQLException if the object pool cannot be created.
     */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    Class driverFromCCL = null;
    if (driverClassName != null) {
        try {
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
            }
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        if (driverFromCCL != null) {
            driver = (Driver) driverFromCCL.newInstance();
            if (!driver.acceptsURL(url)) {
                new SQLException("No suitable driver", "08001");
            }
        } else {
            driver = DriverManager.getDriver(url);
        }
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, // unlimited maxActive (per key)
        -1, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, // maxWait
        0, // maxIdle (per key) 
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

23. BasicDataSource#createDataSource()

Project: servicemix-bundles
File: BasicDataSource.java
// ------------------------------------------------------ Protected Methods
/**
     * <p>Create (if necessary) and return the internal data source we are
     * using to manage our connections.</p>
     *
     * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
     * "double checked locking" idiom in an attempt to avoid synchronizing
     * on every single call to this method.  However, this idiom fails to
     * work correctly in the face of some optimizations that are legal for
     * a JVM to perform.</p>
     *
     * @throws java.sql.SQLException if the object pool cannot be created.
     */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    Class driverFromCCL = null;
    if (driverClassName != null) {
        try {
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
            }
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        if (driverFromCCL != null) {
            driver = (Driver) driverFromCCL.newInstance();
            if (!driver.acceptsURL(url)) {
                new SQLException("No suitable driver", "08001");
            }
        } else {
            driver = DriverManager.getDriver(url);
        }
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, // unlimited maxActive (per key)
        -1, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, // maxWait
        0, // maxIdle (per key) 
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

24. BasicDataSource#createDataSource()

Project: servicemix-bundles
File: BasicDataSource.java
// ------------------------------------------------------ Protected Methods
/**
     * <p>Create (if necessary) and return the internal data source we are
     * using to manage our connections.</p>
     *
     * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
     * "double checked locking" idiom in an attempt to avoid synchronizing
     * on every single call to this method.  However, this idiom fails to
     * work correctly in the face of some optimizations that are legal for
     * a JVM to perform.</p>
     *
     * @throws SQLException if the object pool cannot be created.
     */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    Class driverFromCCL = null;
    if (driverClassName != null) {
        try {
            try {
                Class.forName(driverClassName);
            } catch (ClassNotFoundException e) {
                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
            }
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        if (driverFromCCL != null) {
            driver = (Driver) driverFromCCL.newInstance();
            if (!driver.acceptsURL(url)) {
                new SQLException("No suitable driver", "08001");
            }
        } else {
            driver = DriverManager.getDriver(url);
        }
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, // unlimited maxActive (per key)
        -1, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, // maxWait
        0, // maxIdle (per key) 
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

25. BaseDatabaseConnectionOptions#createConnectionProperties()

Project: SchemaCrawler
File: BaseDatabaseConnectionOptions.java
private Properties createConnectionProperties(final String user, final String password) throws SQLException {
    final List<String> skipProperties = Arrays.asList("server", "host", "port", "database", "urlx", "user", "password", "url");
    final Driver jdbcDriver = getJdbcDriver();
    final DriverPropertyInfo[] propertyInfo = jdbcDriver.getPropertyInfo(getConnectionUrl(), new Properties());
    final Map<String, Boolean> jdbcDriverProperties = new HashMap<>();
    for (final DriverPropertyInfo driverPropertyInfo : propertyInfo) {
        final String jdbcPropertyName = driverPropertyInfo.name.toLowerCase();
        if (skipProperties.contains(jdbcPropertyName)) {
            continue;
        }
        jdbcDriverProperties.put(jdbcPropertyName, driverPropertyInfo.required);
    }
    final Properties jdbcConnectionProperties = new Properties();
    if (user != null) {
        jdbcConnectionProperties.put("user", user);
    }
    if (password != null) {
        jdbcConnectionProperties.put("password", password);
    }
    if (connectionProperties != null) {
        for (final String connectionProperty : connectionProperties.keySet()) {
            final String value = connectionProperties.get(connectionProperty);
            if (jdbcDriverProperties.containsKey(connectionProperty.toLowerCase()) && value != null) {
                jdbcConnectionProperties.put(connectionProperty, value);
            }
        }
        final Properties urlxConnectionProperties = parseConnectionProperties(connectionProperties.get("urlx"));
        jdbcConnectionProperties.putAll(urlxConnectionProperties);
    }
    return jdbcConnectionProperties;
}

26. SakaiBasicDataSource#createDataSource()

Project: sakai
File: SakaiBasicDataSource.java
/**
	 * <p>
	 * Sakai changes: use the SakaiPoolableConnectionFactory, removed some not-visible (damn the use of private!) code.
	 * </p>
	 * <p>
	 * Create (if necessary) and return the internal data source we are using to manage our connections.
	 * </p>
	 * <p>
	 * <strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the "double checked locking" idiom in an attempt to avoid synchronizing on every single call to this method. However, this idiom fails to work correctly in the face of some optimizations
	 * that are legal for a JVM to perform.
	 * </p>
	 * 
	 * @exception SQLException
	 *            if the object pool cannot be created.
	 */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    if (driverClassName != null) {
        try {
            Class.forName(driverClassName);
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        driver = DriverManager.getDriver(url);
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    // Sakai:
    // if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned() == true))
    // {
    // connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    // }
    // else
    {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new // unlimited maxActive (per key)
        GenericKeyedObjectPoolFactory(// unlimited maxActive (per key)
        null, // unlimited maxActive (per key)
        -1, // maxWait
        GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, 0, // maxIdle (per key)
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
    // Sakai: log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
    // Sakai: log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new SakaiPoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, /* abandonedConfig Sakai: */
        null, m_rollbackOnReturn);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
    // Sakai: validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

27. PGDataSourceFactoryTest#testCreateDriverDefault()

Project: pgjdbc
File: PGDataSourceFactoryTest.java
@Test
public void testCreateDriverDefault() throws Exception {
    Driver driver = _dataSourceFactory.createDriver(null);
    Assert.assertTrue(driver instanceof org.postgresql.Driver);
}

28. MockDriver#deregeisterInstances()

Project: pentaho-kettle
File: MockDriver.java
public static synchronized void deregeisterInstances() throws SQLException {
    for (Driver driver : drivers) {
        DriverManager.deregisterDriver(driver);
    }
    drivers.clear();
}

29. OrientJdbcDriverTest#shouldAcceptsWellFormattedURLOnly()

Project: orientdb
File: OrientJdbcDriverTest.java
@Test
public void shouldAcceptsWellFormattedURLOnly() throws ClassNotFoundException, SQLException {
    Driver drv = new OrientJdbcDriver();
    assertThat(drv.acceptsURL("jdbc:orient:local:./working/db/test"), is(true));
    assertThat(drv.acceptsURL("local:./working/db/test"), is(false));
}

30. DriverManagerTests#test15()

Project: openjdk
File: DriverManagerTests.java
/**
     * Register a driver and make sure you find it via its URL. Deregister the
     * driver and validate it is not longer registered
     *
     * @throws Exception
     */
@Test()
public void test15() throws Exception {
    DriverManager.registerDriver(new StubDriver());
    Driver d = DriverManager.getDriver(StubDriverURL);
    assertTrue(d != null);
    assertTrue(isDriverRegistered(d));
    DriverManager.deregisterDriver(d);
    assertFalse(isDriverRegistered(d));
}

31. DriverManagerTests#test2()

Project: openjdk
File: DriverManagerTests.java
/**
     * Validate that NullPointerException is thrown when null is passed to
     * registerDriver
     */
@Test(expectedExceptions = NullPointerException.class)
public void test2() throws Exception {
    Driver d = null;
    DriverManager.registerDriver(d, null);
}

32. DriverManagerTests#test1()

Project: openjdk
File: DriverManagerTests.java
/**
     * Validate that NullPointerException is thrown when null is passed to
     * registerDriver
     */
@Test(expectedExceptions = NullPointerException.class)
public void test1() throws Exception {
    Driver d = null;
    DriverManager.registerDriver(d);
}

33. DatabaseTestContext#openDatabaseConnection()

Project: liquibase
File: DatabaseTestContext.java
public DatabaseConnection openDatabaseConnection(String url) throws Exception {
    String username = getUsername(url);
    String password = getPassword(url);
    JUnitJDBCDriverClassLoader jdbcDriverLoader = JUnitJDBCDriverClassLoader.getInstance();
    final Driver driver;
    try {
        driver = (Driver) Class.forName(DatabaseFactory.getInstance().findDefaultDriver(url), true, jdbcDriverLoader).newInstance();
    } catch (Exception e) {
        System.out.println("Could not connect to " + url + ": Will not test against.  " + e.getMessage());
        return null;
    }
    Properties info = new Properties();
    info.put("user", username);
    if (password != null) {
        info.put("password", password);
    }
    //for db2
    info.put("retrieveMessagesFromServerOnGetMessage", "true");
    Connection connection;
    try {
        connection = driver.connect(url, info);
    } catch (SQLException e) {
        System.out.println("Could not connect to " + url + ": Will not test against.  " + e.getMessage());
        return null;
    }
    if (connection == null) {
        throw new DatabaseException("Connection could not be created to " + url + " with driver " + driver.getClass().getName() + ".  Possibly the wrong driver for the given database URL");
    }
    return new JdbcConnection(connection);
}

34. TracingProxyDriverClassLoadingTest#testClassLoading()

Project: drill
File: TracingProxyDriverClassLoadingTest.java
@Ignore("except when run in own JVM (so Drill Driver not already loaded)")
@Test
public void testClassLoading() throws SQLException, ClassNotFoundException {
    // 1.  Confirm that Drill driver is not loaded/registered.
    try {
        DriverManager.getDriver("jdbc:drill:zk=local");
        throw new IllegalStateException("Drill driver seems loaded already; can't test loading.");
    } catch (SQLException e) {
        assertThat("Not expected messsage.  (Did JDK change?)", e.getMessage(), equalTo("No suitable driver"));
    }
    try {
        DriverManager.getConnection("jdbc:drill:zk=local", null);
        throw new IllegalStateException("Drill driver seems loaded already; can't test loading.");
    } catch (SQLException e) {
        assertThat("Not expected messsage.  (Did JDK change?)", e.getMessage(), equalTo("No suitable driver found for jdbc:drill:zk=local"));
    }
    // 2.  Confirm that TracingProxyDriver is not loaded/registered.
    try {
        DriverManager.getDriver("jdbc:proxy::jdbc:drill:zk=local");
        throw new IllegalStateException("Proxy driver seems loaded already; can't test loading.");
    } catch (SQLException e) {
        assertThat("Not expected messsage.  (Did JDK change?)", e.getMessage(), equalTo("No suitable driver"));
    }
    try {
        DriverManager.getConnection("jdbc:proxy::jdbc:drill:zk=local", null);
        throw new IllegalStateException("Proxy driver seems loaded already; can't test loading.");
    } catch (SQLException e) {
        assertThat("Not expected messsage.  (Did JDK change?)", e.getMessage(), equalTo("No suitable driver found for jdbc:proxy::jdbc:drill:zk=local"));
    }
    // 3.  Load TracingProxyDriver.
    Class.forName("org.apache.drill.jdbc.proxy.TracingProxyDriver");
    // 4.  Confirm that Drill driver still is not registered.
    try {
        DriverManager.getConnection("jdbc:proxy::jdbc:drill:zk=local", null);
        throw new IllegalStateException("Drill driver seems loaded already; can't test loading.");
    } catch (ProxySetupSQLException e) {
        assertThat("Not expected messsage.  (Was it just modified?)", e.getMessage(), equalTo("Error getting driver from DriverManager for proxied URL" + " \"jdbc:drill:zk=local\" (from proxy driver URL" + " \"jdbc:proxy::jdbc:drill:zk=local\" (after third colon))" + ": java.sql.SQLException: No suitable driver"));
    }
    // 5.  Test that TracingProxyDriver can load and use a specified Driver class.
    final Driver driver = DriverManager.getDriver("jdbc:proxy:org.apache.drill.jdbc.Driver:jdbc:drill:zk=local");
    assertThat(driver.acceptsURL("jdbc:proxy::jdbc:drill:zk=local"), equalTo(true));
    assertThat(driver.acceptsURL("jdbc:drill:zk=local"), equalTo(false));
    // 7.  Test minimally that driver can get connection that works.
    final Connection proxyConnection = DriverManager.getConnection("jdbc:proxy::jdbc:drill:zk=local", null);
    assertThat(proxyConnection, notNullValue());
    final DatabaseMetaData dbMetaData = proxyConnection.getMetaData();
    assertThat(dbMetaData, instanceOf(DatabaseMetaData.class));
}

35. SetDerbyVersion#checkJars()

Project: derby
File: SetDerbyVersion.java
/**
     * Checks that all required jars are found in the jar directory.
     *
     * @return {@code true} if all required jars exist, {@code false} otherwise.
     */
public boolean checkJars() throws Exception {
    if (!SANE.exists() && !INSANE.exists()) {
        warn("No jars exist. Produce a Derby release build.");
        return false;
    }
    if (SANE.exists() && INSANE.exists()) {
        warn("Both SANE and INSANE jars exist.");
        return false;
    }
    PREFIX = SANE.exists() ? SANE : INSANE;
    if (SANE.exists()) {
        warn("Only SANE jars exist. Normally INSANE jars are used for a " + "release.");
        boolean answer = getYesNoInput(PROMPT_USE_SANE);
        if (!answer) {
            return false;
        }
    }
    URL[] URLS = new URL[JARS.length];
    for (int i = 0; i < JARS.length; i++) {
        URLS[i] = new File(PREFIX, JARS[i]).toURI().toURL();
    }
    // Reuse the warnings flag.
    warnings = false;
    // Make sure the files are there.
    for (URL url : URLS) {
        File f = new File(url.toURI());
        info(String.format("Checking file: %-30s %,12d bytes", f.getName(), f.length()));
        if (!f.exists()) {
            warn("Missing file: " + f.getCanonicalPath());
        } else if (f.length() == 0) {
            warn("Empty file: " + f.getCanonicalPath());
        }
    }
    info("");
    if (warnings) {
        // Fail here.
        warn("There are missing or empty jar files.");
        return false;
    }
    // The class loader used for the Derby jars.
    URLClassLoader cl = new URLClassLoader(URLS, null);
    // Extra sanity check for the sanity...
    try {
        Class.forName("org.apache.derby.shared.common.sanity.SanityManager", true, cl);
        if (PREFIX == INSANE) {
            warn("Found SanityManager in INSANE build. Aborting.");
            return false;
        }
    } catch (ClassNotFoundException cnfe) {
        if (PREFIX == SANE) {
            warn("Unable to load SanityManager in SANE build. Aborting.");
            return false;
        }
    }
    // Fire up Derby to get the version string.
    Class driverClass = Class.forName("org.apache.derby.jdbc.EmbeddedDriver", true, cl);
    Driver driver = (Driver) driverClass.newInstance();
    Connection con = driver.connect(JDBC_URL, null);
    DatabaseMetaData meta = con.getMetaData();
    con.close();
    // Delete the derby.log file.
    new File("derby.log").delete();
    // I.e.: 10.6.0.0 alpha - (882129M)
    String fullVersion = meta.getDatabaseProductVersion();
    String[] components = fullVersion.split(" - ");
    versionString = components[0].replaceAll(" ", "_");
    String srcRevision = components[1].replaceAll("\\(|\\)", "");
    info("Obtained product version string: " + fullVersion);
    info("(version=" + versionString + ", revision=" + srcRevision + ")");
    if (versionString.contains("beta")) {
        warn("This is a BETA build.");
    }
    if (versionString.contains("alpha")) {
        warn("This is an ALPHA build.");
    }
    if (srcRevision.endsWith("M")) {
        warn("The sources had been modified when the jars were built.");
        warnings = true;
    }
    if (warnings) {
        if (!getYesNoInput(PROMPT_CONT_WARN)) {
            return false;
        }
    }
    return true;
}

36. BootAllTest#testSettingBootAllPropertyWithHomePropertySet()

Project: derby
File: BootAllTest.java
/**
     * DERBY-1296 - Setting property derby.system.bootAll causes an Exception
     *
     * Check that setting the system property "derby.system.bootAll" will not 
     * cause an exception when used in combination with the system property
     * "derby.system.home".
     *
     * The property "derby.system.home" is set by default for all tests and does
     * not need to be explicitly set in this test.
     */
public void testSettingBootAllPropertyWithHomePropertySet() throws Exception {
    JDBCClient embedded = getTestConfiguration().getJDBCClient();
    String driverName = embedded.getJDBCDriverName();
    String url = embedded.getUrlBase();
    // Ensure the engine is not booted.
    try {
        DriverManager.getDriver(url);
        fail("Derby is booted!");
    } catch (SQLException e) {
    }
    Class<?> clazz = Class.forName(driverName);
    clazz.getConstructor().newInstance();
    Driver driver = DriverManager.getDriver(url);
    DriverPropertyInfo[] attributes = driver.getPropertyInfo(url, null);
    String returnedDatabases[] = null;
    for (int i = 0; i < attributes.length; i++) {
        if (attributes[i].name.equalsIgnoreCase("databaseName")) {
            returnedDatabases = attributes[i].choices;
        }
    }
    // We expect at least four databases to be booted,
    // but it could be more if other tests have left databases
    // around.
    // DERBY-2069 the single use databases are not
    // booted automatically, once DERBY-2069 is fixed
    // the length can be compared to four.
    assertNotNull(returnedDatabases);
    assertTrue("Fewer databases booted than expected", returnedDatabases.length >= 1);
}

37. JDBCMBeanTest#testAttributeMinorVersion()

Project: derby
File: JDBCMBeanTest.java
/**
     * <p>
     * Tests the MinorVersion attribute of the JDBCMBean. Will test that there
     * exists an attribute with that name that we are able to read, that it 
     * returns the correct type, and that the return value is as expected.</p>
     * <p>
     * The expected value is retreived from the embedded driver that is directly
     * accessible to this JVM, making the assumption that this driver's version
     * information is the same as the version information of the embedded driver
     * used in the JVM being instrumented using JMX (this may or may not be the
     * same JVM).</p>
     * 
     * @throws java.lang.Exception if an error occurs, or if the test fails.
     */
public void testAttributeMinorVersion() throws Exception {
    /* since the JDBCMBean instruments the embedded driver (InternalDriver),
         * we need to get expected values from the embedded driver even if
         * this test configuration is client/server.
         * Assuming that DriverManager is available in the classpath.
         */
    Driver d = new org.apache.derby.jdbc.EmbeddedDriver();
    int expected = d.getMinorVersion();
    assertIntAttribute(expected, getJdbcMBeanObjectName(), "MinorVersion");
}

38. JDBCMBeanTest#testAttributeMajorVersion()

Project: derby
File: JDBCMBeanTest.java
/**
     * <p>
     * Tests the MajorVersion attribute of the JDBCMBean. Will test that there
     * exists an attribute with that name that we are able to read, that it 
     * returns the correct type, and that the return value is as expected.</p>
     * <p>
     * The expected value is retreived from the embedded driver that is directly
     * accessible to this JVM, making the assumption that this driver's version
     * information is the same as the version information of the embedded driver
     * used in the JVM being instrumented using JMX (this may or may not be the
     * same JVM).</p>
     * 
     * @throws java.lang.Exception if an error occurs, or if the test fails.
     */
public void testAttributeMajorVersion() throws Exception {
    /* since the JDBCMBean instruments the embedded driver (InternalDriver),
         * we need to get expected values from the embedded driver even if
         * this test configuration is client/server.
         * Assuming that the embedded driver is available in the classpath.
         */
    Driver d = new org.apache.derby.jdbc.EmbeddedDriver();
    int expected = d.getMajorVersion();
    assertIntAttribute(expected, getJdbcMBeanObjectName(), "MajorVersion");
}

39. DriverTest#shutdownDB()

Project: derby
File: DriverTest.java
/**
     * use this method to shutdown databases in an effort to release
     * any locks they may be holding
     */
private static void shutdownDB(String url, Properties info) throws SQLException {
    Driver driver = DriverManager.getDriver(url);
    try {
        driver.connect(url, info);
    } catch (SQLException se) {
        assertSQLState("08006", se);
    }
}

40. DriverTest#testAcceptsURL()

Project: derby
File: DriverTest.java
/**
     * Check that drivers accept the correct urls and reject those for other supported drivers.
     * 
     * @throws SQLException, Exception
     */
public void testAcceptsURL() throws SQLException, Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String orgurl = TestConfiguration.getCurrent().getJDBCUrl(dbName);
    loadDriver();
    String defaultdburl = orgurl + ";create=true";
    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);
    int frameworkOffset;
    int EMBEDDED_OFFSET = 0;
    int DERBYNETCLIENT_OFFSET = 1;
    if (usingDerbyNetClient())
        frameworkOffset = DERBYNETCLIENT_OFFSET;
    else
        // assume (usingEmbedded())
        frameworkOffset = EMBEDDED_OFFSET;
    // URLS to check.  New urls need to also be added to the acceptsUrl table
    String EMBEDDED_URL = "jdbc:derby:";
    String INVALID_URL = "jdbc:db2j:";
    String hostName = TestConfiguration.getCurrent().getHostName();
    int port = TestConfiguration.getCurrent().getPort();
    String CLIENT_URL = "jdbc:derby://" + hostName + ":" + port + "/" + dbName + ";create=true";
    String[] urls = new String[] { EMBEDDED_URL, CLIENT_URL, INVALID_URL };
    // Table that shows whether tested urls should return true for 
    // acceptsURL under the given framework
    // The acceptsURLTable uses  the frameworkOffset column int he table 
    // to check for valid results for each framework
    boolean[][] acceptsURLTable = new boolean[][] { /* EMBEDDED_URL*/
    { true, false }, /* CLIENT_URL  */
    { false, true }, /* INVALID_URL */
    { false, false } };
    for (int u = 0; u < urls.length; u++) {
        String url = urls[u];
        boolean expectedAcceptance = acceptsURLTable[u][frameworkOffset];
        boolean actualAcceptance = driver.acceptsURL(url);
        assertEquals(expectedAcceptance, actualAcceptance);
    }
}

41. DriverTest#testDriverCompliantVersion()

Project: derby
File: DriverTest.java
/**
     * Load the driver and check java.sql.Driver.jdbcCompliant() and
     * driver.get*Version
     * @throws Exception
     */
public void testDriverCompliantVersion() throws Exception {
    String dbName = TestConfiguration.getCurrent().getDefaultDatabaseName();
    String url = TestConfiguration.getCurrent().getJDBCUrl(dbName);
    loadDriver();
    String defaultdburl = url + ";create=true";
    // Test that we loaded the right driver by making a connection
    Driver driver = DriverManager.getDriver(defaultdburl);
    Properties props = new Properties();
    props.put("user", "testuser");
    props.put("password", "testpass");
    Connection conn = DriverManager.getConnection(defaultdburl, props);
    // Driver should be jdbc compliant.
    assertTrue(driver.jdbcCompliant());
    // compare driver.get*Version() with DatabaseMetadata.getDriver*Version.
    DatabaseMetaData dbmd = conn.getMetaData();
    assertEquals(dbmd.getDriverMajorVersion(), driver.getMajorVersion());
    assertEquals(dbmd.getDriverMinorVersion(), driver.getMinorVersion());
    // Test that the driver class is the expected one. Currently, the same
    // driver class is used regardless of JDBC version.
    println("Driver is a " + driver.getClass().getName());
    assertEquals(usingEmbedded() ? "AutoloadedDriver" : "ClientDriver", driver.getClass().getSimpleName());
    // test that null connection URLs raise a SQLException per JDBC 4.2 spec clarification
    try {
        driver.acceptsURL(null);
        fail("Should not have accepted a null connection url");
    } catch (SQLException se) {
        assertSQLState(MALFORMED_URL, se);
    }
    try {
        driver.connect(null, props);
        fail("Should not have accepted a null connection url");
    } catch (SQLException se) {
        assertSQLState(MALFORMED_URL, se);
    }
    conn.close();
}

42. AutoloadTest#testRegisteredDriver()

Project: derby
File: AutoloadTest.java
/**
     * @throws SQLException
     * 
     */
public void testRegisteredDriver() throws SQLException {
    String protocol = getTestConfiguration().getJDBCClient().getUrlBase();
    Driver driver = DriverManager.getDriver(protocol);
    assertNotNull("Expected registered driver", driver);
}

43. ShutdownWithoutDeregisterPermissionTest#testShutdownWithoutPermission()

Project: derby
File: ShutdownWithoutDeregisterPermissionTest.java
public void testShutdownWithoutPermission() throws SQLException {
    // First get a connection to make sure the engine is booted.
    getConnection().close();
    // Shut down the engine. This used to fail with an
    // AccessControlException on Java 8 before DERBY-6224.
    TestConfiguration config = TestConfiguration.getCurrent();
    config.shutdownEngine();
    // Test whether shutdown deregistered the driver. On versions prior
    // to Java 8/JDBC 4.2, we expect the driver to be deregistered even
    // though the permission is missing, and the call to getDrivers()
    // should not return any instance of AutoloadedDriver.
    // On Java 8/JDBC 4.2 and higher, we expect AutoloadedDriver to
    // be in the list of registered drivers.
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    Driver found = null;
    while (found == null && drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        if (driver.getClass().getName().startsWith("org.apache.derby.jdbc.AutoloadedDriver")) {
            found = driver;
        }
    }
    if (JDBC.vmSupportsJDBC42()) {
        assertNotNull("Expected driver to be registered", found);
    } else {
        assertNull("Expected driver to be deregistered", found);
    }
}

44. BasicDataSource#createConnectionFactory()

Project: commons-dbcp
File: BasicDataSource.java
/**
     * Creates a JDBC connection factory for this datasource.  The JDBC driver
     * is loaded using the following algorithm:
     * <ol>
     * <li>If a Driver instance has been specified via
     * {@link #setDriver(Driver)} use it</li>
     * <li>If no Driver instance was specified and {@link #driverClassName} is
     * specified that class is loaded using the {@link ClassLoader} of this
     * class or, if {@link #driverClassLoader} is set, {@link #driverClassName}
     * is loaded with the specified {@link ClassLoader}.</li>
     * <li>If {@link #driverClassName} is specified and the previous attempt
     * fails, the class is loaded using the context class loader of the current
     * thread.</li>
     * <li>If a driver still isn't loaded one is loaded via the
     * {@link DriverManager} using the specified {@link #url}.
     * </ol>
     * This method exists so subclasses can replace the implementation class.
     */
protected ConnectionFactory createConnectionFactory() throws SQLException {
    // Load the JDBC driver class
    Driver driverToUse = this.driver;
    if (driverToUse == null) {
        Class<?> driverFromCCL = null;
        if (driverClassName != null) {
            try {
                try {
                    if (driverClassLoader == null) {
                        driverFromCCL = Class.forName(driverClassName);
                    } else {
                        driverFromCCL = Class.forName(driverClassName, true, driverClassLoader);
                    }
                } catch (final ClassNotFoundException cnfe) {
                    driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
                }
            } catch (final Exception t) {
                final String message = "Cannot load JDBC driver class '" + driverClassName + "'";
                logWriter.println(message);
                t.printStackTrace(logWriter);
                throw new SQLException(message, t);
            }
        }
        try {
            if (driverFromCCL == null) {
                driverToUse = DriverManager.getDriver(url);
            } else {
                // Usage of DriverManager is not possible, as it does not
                // respect the ContextClassLoader
                // N.B. This cast may cause ClassCastException which is handled below
                driverToUse = (Driver) driverFromCCL.newInstance();
                if (!driverToUse.acceptsURL(url)) {
                    throw new SQLException("No suitable driver", "08001");
                }
            }
        } catch (final Exception t) {
            final String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLException(message, t);
        }
    }
    // Set up the driver connection factory we will use
    final String user = username;
    if (user != null) {
        connectionProperties.put("user", user);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    final String pwd = password;
    if (pwd != null) {
        connectionProperties.put("password", pwd);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    final ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driverToUse, url, connectionProperties);
    return driverConnectionFactory;
}

45. BasicDataSource#createConnectionFactory()

Project: bboss
File: BasicDataSource.java
/**
     * Creates a JDBC connection factory for this datasource.  The JDBC driver
     * is loaded using the following algorithm:
     * <ol>
     * <li>If a Driver instance has been specified via
     * {@link #setDriver(Driver)} use it</li>
     * <li>If no Driver instance was specified and {@link #driverClassName} is
     * specified that class is loaded using the {@link ClassLoader} of this
     * class or, if {@link #driverClassLoader} is set, {@link #driverClassName}
     * is loaded with the specified {@link ClassLoader}.</li>
     * <li>If {@link #driverClassName} is specified and the previous attempt
     * fails, the class is loaded using the context class loader of the current
     * thread.</li>
     * <li>If a driver still isn't loaded one is loaded via the
     * {@link DriverManager} using the specified {@link #url}.
     * </ol>
     * This method exists so subclasses can replace the implementation class.
     */
protected ConnectionFactory createConnectionFactory() throws SQLException {
    // Load the JDBC driver class
    Driver driverToUse = this.driver;
    if (driverToUse == null) {
        Class<?> driverFromCCL = null;
        if (driverClassName != null) {
            try {
                try {
                    if (driverClassLoader == null) {
                        driverFromCCL = Class.forName(driverClassName);
                    } else {
                        driverFromCCL = Class.forName(driverClassName, true, driverClassLoader);
                    }
                } catch (ClassNotFoundException cnfe) {
                    driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
                }
            } catch (Exception t) {
                String message = "Cannot load JDBC driver class '" + driverClassName + "'";
                logWriter.println(message);
                t.printStackTrace(logWriter);
                throw new SQLException(message, t);
            }
        }
        try {
            if (driverFromCCL == null) {
                driverToUse = DriverManager.getDriver(url);
            } else {
                // Usage of DriverManager is not possible, as it does not
                // respect the ContextClassLoader
                // N.B. This cast may cause ClassCastException which is handled below
                driverToUse = (Driver) driverFromCCL.newInstance();
                if (!driverToUse.acceptsURL(url)) {
                    throw new SQLException("No suitable driver", "08001");
                }
            }
        } catch (Exception t) {
            String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLException(message, t);
        }
    }
    // Set up the driver connection factory we will use
    String user = username;
    if (user != null) {
        connectionProperties.put("user", user);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    String pwd = password;
    if (pwd != null) {
        connectionProperties.put("password", pwd);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driverToUse, url, connectionProperties);
    return driverConnectionFactory;
}

46. BasicDataSource#createConnectionFactory()

Project: bboss
File: BasicDataSource.java
/**
     * Creates a JDBC connection factory for this datasource.  This method only
     * exists so subclasses can replace the implementation class.
     */
protected ConnectionFactory createConnectionFactory() throws SQLException {
    // Load the JDBC driver class
    Class driverFromCCL = null;
    if (driverClassName != null) {
        try {
            try {
                if (driverClassLoader == null) {
                    Class.forName(driverClassName);
                } else {
                    Class.forName(driverClassName, true, driverClassLoader);
                }
            } catch (ClassNotFoundException cnfe) {
                driverFromCCL = Thread.currentThread().getContextClassLoader().loadClass(driverClassName);
            }
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        if (driverFromCCL == null) {
            driver = DriverManager.getDriver(url);
        } else {
            // Usage of DriverManager is not possible, as it does not
            // respect the ContextClassLoader
            driver = (Driver) driverFromCCL.newInstance();
            if (!driver.acceptsURL(url)) {
                throw new SQLException("No suitable driver", "08001");
            }
        }
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Set up the driver connection factory we will use
    String user = username;
    if (user != null) {
        connectionProperties.put("user", user);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    String pwd = password;
    if (pwd != null) {
        connectionProperties.put("password", pwd);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    return driverConnectionFactory;
}

47. BasicDataSource#createDataSource()

Project: bboss
File: BasicDataSource.java
// ------------------------------------------------------ Protected Methods
/**
     * <p>Create (if necessary) and return the internal data source we are
     * using to manage our connections.</p>
     *
     * <p><strong>IMPLEMENTATION NOTE</strong> - It is tempting to use the
     * "double checked locking" idiom in an attempt to avoid synchronizing
     * on every single call to this method.  However, this idiom fails to
     * work correctly in the face of some optimizations that are legal for
     * a JVM to perform.</p>
     *
     * @throws SQLException if the object pool cannot be created.
     */
protected synchronized DataSource createDataSource() throws SQLException {
    // Return the pool if we have already created it
    if (dataSource != null) {
        return (dataSource);
    }
    // Load the JDBC driver class
    if (driverClassName != null) {
        try {
            Class.forName(driverClassName);
        } catch (Throwable t) {
            String message = "Cannot load JDBC driver class '" + driverClassName + "'";
            logWriter.println(message);
            t.printStackTrace(logWriter);
            throw new SQLNestedException(message, t);
        }
    }
    // Create a JDBC driver instance
    Driver driver = null;
    try {
        driver = DriverManager.getDriver(url);
    } catch (Throwable t) {
        String message = "Cannot create JDBC driver of class '" + (driverClassName != null ? driverClassName : "") + "' for connect URL '" + url + "'";
        logWriter.println(message);
        t.printStackTrace(logWriter);
        throw new SQLNestedException(message, t);
    }
    // Can't test without a validationQuery
    if (validationQuery == null) {
        setTestOnBorrow(false);
        setTestOnReturn(false);
        setTestWhileIdle(false);
    }
    // Create an object pool to contain our active connections
    if ((abandonedConfig != null) && (abandonedConfig.getRemoveAbandoned())) {
        connectionPool = new AbandonedObjectPool(null, abandonedConfig);
    } else {
        connectionPool = new GenericObjectPool();
    }
    connectionPool.setMaxActive(maxActive);
    connectionPool.setMaxIdle(maxIdle);
    connectionPool.setMinIdle(minIdle);
    connectionPool.setMaxWait(maxWait);
    connectionPool.setTestOnBorrow(testOnBorrow);
    connectionPool.setTestOnReturn(testOnReturn);
    connectionPool.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
    connectionPool.setNumTestsPerEvictionRun(numTestsPerEvictionRun);
    connectionPool.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
    connectionPool.setTestWhileIdle(testWhileIdle);
    connectionPool.setWhenExhaustedAction(this.whenExhaustedAction);
    // Set up statement pool, if desired
    GenericKeyedObjectPoolFactory statementPoolFactory = null;
    if (isPoolPreparedStatements()) {
        statementPoolFactory = new GenericKeyedObjectPoolFactory(null, // unlimited maxActive (per key)
        -1, GenericKeyedObjectPool.WHEN_EXHAUSTED_FAIL, // maxWait
        0, // maxIdle (per key) 
        1, maxOpenPreparedStatements);
    }
    // Set up the driver connection factory we will use
    if (username != null) {
        connectionProperties.put("user", username);
    } else {
        log("DBCP DataSource configured without a 'username'");
    }
    if (password != null) {
        connectionProperties.put("password", password);
    } else {
        log("DBCP DataSource configured without a 'password'");
    }
    DriverConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, url, connectionProperties);
    // Set up the poolable connection factory we will use
    PoolableConnectionFactory connectionFactory = null;
    try {
        connectionFactory = new PoolableConnectionFactory(driverConnectionFactory, connectionPool, statementPoolFactory, validationQuery, defaultReadOnly, defaultAutoCommit, defaultTransactionIsolation, defaultCatalog, abandonedConfig);
        if (connectionFactory == null) {
            throw new SQLException("Cannot create PoolableConnectionFactory");
        }
        validateConnectionFactory(connectionFactory);
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new SQLNestedException("Cannot create PoolableConnectionFactory (" + e.getMessage() + ")", e);
    }
    // Create and return the pooling data source to manage the connections
    dataSource = new PoolingDataSource(connectionPool);
    ((PoolingDataSource) dataSource).setAccessToUnderlyingConnectionAllowed(isAccessToUnderlyingConnectionAllowed());
    dataSource.setLogWriter(logWriter);
    try {
        for (int i = 0; i < initialSize; i++) {
            connectionPool.addObject();
        }
    } catch (Exception e) {
        throw new SQLNestedException("Error preloading the connection pool", e);
    }
    return dataSource;
}

48. ActiveMQTestBase#destroyTables()

Project: activemq-artemis
File: ActiveMQTestBase.java
public void destroyTables(List<String> tableNames) throws Exception {
    Driver driver = JDBCUtils.getDriver(getJDBCClassName());
    Connection connection = driver.connect(getTestJDBCConnectionUrl(), null);
    Statement statement = connection.createStatement();
    try {
        for (String tableName : tableNames) {
            connection.setAutoCommit(false);
            SQLProvider sqlProvider = JDBCUtils.getSQLProvider(getJDBCClassName(), tableName);
            try (ResultSet rs = connection.getMetaData().getTables(null, null, sqlProvider.getTableName(), null)) {
                if (rs.next()) {
                    statement.execute("DROP TABLE " + sqlProvider.getTableName());
                }
                connection.commit();
            } catch (SQLException e) {
                connection.rollback();
            }
        }
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        connection.close();
    }
}