Example usage for java.sql DriverManager getDriver

List of usage examples for java.sql DriverManager getDriver

Introduction

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

Prototype

@CallerSensitive
public static Driver getDriver(String url) throws SQLException 

Source Link

Document

Attempts to locate a driver that understands the given URL.

Usage

From source file:org.openbravo.database.ConnectionProviderImpl.java

public void destroy(String name) throws Exception {
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    driver.closePool(name);/* w w  w  . j a  v a  2  s  . c  om*/
}

From source file:org.openbravo.database.ConnectionProviderImpl.java

public void addNewPool(String dbDriver, String dbServer, String dbLogin, String dbPassword, int minConns,
        int maxConns, double maxConnTime, String dbSessionConfig, String rdbms, String name) throws Exception {
    log4j.debug("Loading underlying JDBC driver.");
    try {//from www .  j  a v  a  2 s .  c  o  m
        Class.forName(dbDriver);
    } catch (ClassNotFoundException e) {
        throw new Exception(e);
    }
    log4j.debug("Done.");

    GenericObjectPool connectionPool = new GenericObjectPool(null);
    connectionPool.setWhenExhaustedAction(GenericObjectPool.WHEN_EXHAUSTED_GROW);
    connectionPool.setMaxActive(maxConns);
    connectionPool.setTestOnBorrow(false);
    connectionPool.setTestOnReturn(false);
    connectionPool.setTestWhileIdle(false);

    KeyedObjectPoolFactory keyedObject = new StackKeyedObjectPoolFactory();
    ConnectionFactory connectionFactory = new OpenbravoDriverManagerConnectionFactory(dbServer, dbLogin,
            dbPassword, dbSessionConfig, rdbms);
    @SuppressWarnings("unused")
    // required by dbcp
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, keyedObject, null, false, true);

    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
    driver.registerPool(contextName + "_" + name, connectionPool);

    if (this.defaultPoolName == null || this.defaultPoolName.equals("")) {
        this.defaultPoolName = name;
        this.bbdd = dbServer;
        this.rdbms = rdbms;
    }
}

From source file:org.openbravo.database.ConnectionProviderImpl.java

public ObjectPool getPool(String poolName) throws PoolNotFoundException {
    if (poolName == null || poolName.equals(""))
        throw new PoolNotFoundException("Couldnt get an unnamed pool");
    ObjectPool connectionPool = null;/*w  w w . j  ava2s .  co  m*/
    try {
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        connectionPool = driver.getConnectionPool(contextName + "_" + poolName);
    } catch (SQLException ex) {
        log4j.error(ex);
    }
    if (connectionPool == null)
        throw new PoolNotFoundException(poolName + " not found");
    else
        return connectionPool;
}

From source file:org.openpythia.dbconnection.ConnectionPoolUtils.java

/**
 * Configures an Apache DBCP pool called POOL_NAME. For the given connectionUrl
 * and connectionProperties.//from  ww  w .  j  a va 2  s. c om
 *
 * @param connectionUrl the connection url
 * @param connectionProperties  the connectionProperties
 */
public static void configurePool(String connectionUrl, Properties connectionProperties) throws SQLException {
    try {
        ConnectionFactory connectionFactory = new DriverConnectionFactory(JDBCHandler.getOracleJDBCDriver(),
                connectionUrl, connectionProperties);

        userName = connectionProperties.getProperty("user");

        GenericObjectPool connectionPool = new GenericObjectPool();
        connectionPool.setFactory(
                new PoolableConnectionFactory(connectionFactory, connectionPool, null, null, false, true));

        Class.forName(POOLING_DRIVER);

        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(POOL_DRIVER_URL);
        driver.registerPool(POOL_NAME, connectionPool);

        Connection connection = DriverManager.getConnection(POOL_DRIVER_URL + POOL_NAME);
        connection.close();

        hasBeenSuccessfullyConfigured = true;
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.openpythia.dbconnection.ConnectionPoolUtils.java

/**
 * Shuts the configurePool poll down and releases all resources
 *//*from ww w .jav  a2  s  .  co m*/
public static void shutdownPool() {
    try {
        if (hasBeenSuccessfullyConfigured) {
            PoolingDriver poolingDriver = (PoolingDriver) DriverManager.getDriver(POOL_DRIVER_URL);
            poolingDriver.closePool(POOL_NAME);
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.pentaho.database.dialect.AbstractDatabaseDialect.java

@Override
public Driver getDriver(String url) {
    try {/*from w ww  . ja v  a 2s. c  o m*/
        return DriverManager.getDriver(url);
    } catch (SQLException e) {
        Log logger = LogFactory.getLog(IDatabaseDialect.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to get driver for url " + url, e);
        }
    }
    return null;
}

From source file:org.rhq.plugins.mysql.MySqlConnectionManager.java

public void shutdown() {
    Driver driver = null;//  w  w w . j a va 2 s .  c o m
    for (Connection conn : connections.values()) {
        try {
            if (driver == null) {
                String driverName = conn.getMetaData().getDriverName();
                driver = DriverManager.getDriver(driverName);
            }
            conn.close();
        } catch (SQLException e) {
            logger.info("Problem closing connection on Shutdown ignoring...");
        }
    }
    // deregister driver as well
    if (driver != null) {
        try {
            DriverManager.deregisterDriver(driver);
        } catch (SQLException ex) {
            logger.warn("Unable to deregister MySQL Driver on  shutdown");
        }
    }
}

From source file:org.rimudb.pool.DBCPConnectionManager.java

public void connect(String user, String password) throws Exception {

    // Load the jdbc driver
    Class.forName(poolConfiguration.getJdbcDriver());

    // Create an ObjectPool that serves as the actual pool of connections.
    connectionPool = new GenericObjectPool(null);
    connectionPool.setMaxActive(99999);/*from  w  w w.  jav  a  2  s.  c o  m*/

    connectionPool.setTimeBetweenEvictionRunsMillis(poolConfiguration.getTimeBetweenEvictionRunsSecs() * 1000L);
    connectionPool.setMaxActive(poolConfiguration.getMaxActive());
    connectionPool.setMinEvictableIdleTimeMillis(poolConfiguration.getMinEvictableIdleTimeSecs() * 1000L);
    connectionPool.setMinIdle(poolConfiguration.getMinIdle());
    connectionPool.setMaxIdle(poolConfiguration.getMaxIdle());
    connectionPool.setMaxWait(poolConfiguration.getMaxWaitSecs() * 1000L);

    // Create a Properties object for the connection factory
    Properties props = new Properties();
    // Pass all the properties from the configuration into the connection factory properties
    if (poolConfiguration.getProperties() != null) {
        props.putAll(poolConfiguration.getProperties());
    }
    // Set user and password 
    if (user != null && password != null) {
        props.setProperty("user", user);
        props.setProperty("pasword", password);
    }
    props.setProperty("poolPreparedStatements", "" + poolConfiguration.getStatementCaching());

    // Create a ConnectionFactory that the pool will use to create Connections.
    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(poolConfiguration.getJdbcURL(),
            props);

    KeyedObjectPoolFactory stmtPoolFactory = null;
    if (poolConfiguration.getStatementCaching()) {
        stmtPoolFactory = new GenericKeyedObjectPoolFactory(null);
    }

    // Create the PoolableConnectionFactory, which wraps the "real" Connections created by the ConnectionFactory with
    // the classes that implement the pooling functionality.
    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, stmtPoolFactory, null, false, true);

    // Create the PoolingDriver itself
    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");

    // Register the pool
    driver.registerPool(dbConfig.getDatabaseID(), connectionPool);
}

From source file:org.rimudb.pool.DBCPConnectionManager.java

public void disconnect() throws RimuDBException {
    try {/*from   w  w w. j av  a2s. co  m*/
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        driver.closePool(dbConfig.getDatabaseID());
    } catch (SQLException e) {
        throw new RimuDBException(e);
    }
}

From source file:org.sqsh.SQLDriverManager.java

/**
 * Attempts to connect to the database utilizing a driver.
 * // w  w w  .  jav a2  s .co  m
 * @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;
}