Example usage for java.sql Driver acceptsURL

List of usage examples for java.sql Driver acceptsURL

Introduction

In this page you can find the example usage for java.sql Driver acceptsURL.

Prototype

boolean acceptsURL(String url) throws SQLException;

Source Link

Document

Retrieves whether the driver thinks that it can open a connection to the given URL.

Usage

From source file:com.frameworkset.commons.dbcp2.BasicDataSource.java

/**
 * Creates a JDBC connection factory for this datasource.  The JDBC driver
 * is loaded using the following algorithm:
 * <ol>//from www.j  a  v  a2  s .c  o  m
 * <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;
}

From source file:org.apache.geronimo.console.databasemanager.wizard.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);
        }/*ww  w. ja  v  a  2s.c  o m*/
        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) {
                    //ignore
                }
            }
        }
    } else
        throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url);
}

From source file:org.apache.hive.beeline.BeeLine.java

private Driver findRegisteredDriver(String url) {
    for (Enumeration drivers = DriverManager.getDrivers(); drivers != null && drivers.hasMoreElements();) {
        Driver driver = (Driver) drivers.nextElement();
        try {//from   w  w  w  .j a v a  2 s .c om
            if (driver.acceptsURL(url)) {
                return driver;
            }
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:org.apache.hive.beeline.BeeLine.java

public Driver findLocalDriver(String url) throws Exception {
    if (drivers == null) {
        return null;
    }// w  ww . j  a v  a 2s.  co m

    for (Driver d : drivers) {
        try {
            String clazzName = d.getClass().getName();
            Driver driver = (Driver) Class
                    .forName(clazzName, true, Thread.currentThread().getContextClassLoader()).newInstance();
            if (driver.acceptsURL(url) && isSupportedLocalDriver(driver)) {
                return driver;
            }
        } catch (SQLException e) {
            error(e);
            throw new Exception(e);
        }
    }
    return null;
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private void registerConnectionDriver(String name, DriverConnectionPoolManager manager)
        throws SQLException, OpenRDFException, IOException {
    Exception cause = null;//w  ww .ja  va2s  .  c  om
    String url = this.getCalliJdbcUrl();
    List<String> classnames = new ArrayList<>(this.getCalliDriverClassName());
    ClassLoader cl = createClassLoader();
    for (String classname : classnames) {
        try {
            Object d = Class.forName(classname, true, cl).newInstance();
            if (!(d instanceof Driver)) {
                logger.error("{} is not a java.sql.Driver class", classname);
            }
            Driver driver = (Driver) d;
            if (driver.getClass().getClassLoader() == cl) {
                deregisterDriverOnReset(name, driver);
            }
            if (driver.acceptsURL(url)) {
                Config config = new Config();
                config.testOnBorrow = true;
                config.maxActive = intOrNeg(this.getCalliMaxActive());
                config.maxIdle = intOrNeg(this.getCalliMaxIdle());
                config.maxWait = intOrNeg(this.getCalliMaxWait());
                Properties props = new Properties();
                Credentials cred = getCredential(url);
                if (cred != null) {
                    props.setProperty("user", cred.getUserPrincipal().getName());
                    props.setProperty("password", cred.getPassword());
                }
                verifyDriver(url, driver, props);
                manager.registerDriver(name, driver, url, props, config, this.getCalliValidationQuery());
                return;
            }
        } catch (ClassNotFoundException e) {
            cause = e;
            logger.error("{} is not found in {}", classname, this.getCalliDriverJar());
        } catch (InstantiationException e) {
            cause = e;
            logger.error("Could not instaniate {}", classname);
        } catch (IllegalAccessException e) {
            cause = e;
            logger.error("Could not access {}", classname);
        } catch (Exception e) {
            cause = e;
            logger.error("Could not load driver {}", classname);
        }
    }
    reset();
    if (cause instanceof SQLException)
        throw (SQLException) cause;
    if (cause != null)
        throw new SQLException("Could not load driver " + classnames, cause);
    throw new SQLException("Could not load driver " + classnames);
}

From source file:org.datacleaner.connection.JdbcDatastore.java

private void initializeDriver() {
    if (_jdbcUrl == null) {
        throw new IllegalStateException("JDBC URL is null, cannot create connection!");
    }//from  ww  w  .  jav  a 2  s.  c o m

    logger.debug("Determining if driver initialization is nescesary");

    // it's best to avoid initializing the driver, so we do this check.
    // It may already have been initialized and Class.forName(...) does
    // not always work if the driver is in a different classloader
    boolean installDriver = true;

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            if (driver.acceptsURL(_jdbcUrl)) {
                installDriver = false;
                break;
            }
        } catch (Exception e) {
            logger.warn("Driver threw exception when acceptURL(...) was invoked", e);
        }
    }

    if (installDriver) {
        try {
            Class.forName(_driverClass);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException("Could not initialize JDBC driver", e);
        }
    }
}

From source file:org.sqsh.SQLDriverManager.java

/**
 * Similar to DriverManager.getDriver() except that it searches
 * through our shiny new classloader./*w w  w .  ja v  a2 s  . com*/
 * 
 * @param url
 * @return
 * @throws SQLException
 */
private Driver getDriverFromUrl(String url) throws SQLException {

    for (SQLDriver driver : drivers.values()) {

        try {

            Driver d = (Driver) Class.forName(driver.getDriverClass(), true, classLoader).newInstance();

            if (d.acceptsURL(url)) {

                return d;
            }
        } catch (Exception e) {

            /* IGNORED */
        }
    }

    return DriverManager.getDriver(url);
}