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:Main.java

public static void main(String[] args) throws Exception {

    Driver myDriver = new org.hsqldb.jdbcDriver();
    DriverManager.registerDriver(myDriver);
    System.out.println(myDriver.acceptsURL("jdbc:mydriver://tutorial/"));
    System.out.println("Major Version: " + myDriver.getMajorVersion());
    System.out.println("Minor Version: " + myDriver.getMinorVersion());
    System.out.println("JDBC COMPLIANT driver? " + myDriver.jdbcCompliant());

}

From source file:com.ts.db.connector.ConnectorDriverManager.java

private static Driver getDriver(File jar, String url, ClassLoader cl) throws IOException {
    ZipFile zipFile = new ZipFile(jar);
    try {//from   w w  w.  j  av  a 2  s  .c  o m
        for (ZipEntry entry : Iteration.asIterable(zipFile.entries())) {
            final String name = entry.getName();
            if (name.endsWith(".class")) {
                final String fqcn = name.replaceFirst("\\.class", "").replace('/', '.');
                try {
                    Class<?> c = DynamicLoader.loadClass(fqcn, cl);
                    if (Driver.class.isAssignableFrom(c)) {
                        Driver driver = (Driver) c.newInstance();
                        if (driver.acceptsURL(url)) {
                            return driver;
                        }
                    }
                } catch (Exception ex) {
                    if (log.isTraceEnabled()) {
                        log.trace(ex.toString());
                    }
                }
            }
        }
    } finally {
        zipFile.close();
    }
    return null;
}

From source file:com.ts.db.connector.ConnectorDriverManager.java

static Driver getDriver(String url, String driverClassName, String classpath) throws SQLException {
    assert !StringUtils.isBlank(url);
    final boolean hasClasspath = !StringUtils.isBlank(classpath);
    if (!hasClasspath) {
        for (Driver driver : new ArrayList<Driver>(drivers)) {
            if (driver.acceptsURL(url)) {
                return driver;
            }/*  ww w .j a v a2  s  .c  o m*/
        }
    }
    List<File> jars = new ArrayList<File>();
    ClassLoader cl;
    if (hasClasspath) {
        List<URL> urls = new ArrayList<URL>();
        for (String path : classpath.split(pathSeparator)) {
            final File file = new File(path);
            if (isJarFile(file)) {
                jars.add(file);
            }
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]));
    } else {
        jars.addAll(getJarFiles("."));
        jars.addAll(driverFiles);
        List<URL> urls = new ArrayList<URL>();
        for (File file : jars) {
            try {
                urls.add(file.toURI().toURL());
            } catch (MalformedURLException ex) {
                log.warn(ex.toString());
            }
        }
        cl = new URLClassLoader(urls.toArray(new URL[urls.size()]), ClassLoader.getSystemClassLoader());
    }
    driverFiles.addAll(jars);
    final boolean hasDriverClassName = !StringUtils.isBlank(driverClassName);
    if (hasDriverClassName) {
        try {
            Driver driver = DynamicLoader.newInstance(driverClassName, cl);
            assert driver != null;
            return driver;
        } catch (DynamicLoadingException ex) {
            Throwable cause = (ex.getCause() != ex) ? ex.getCause() : ex;
            SQLException exception = new SQLException(cause.toString());
            exception.initCause(cause);
            throw exception;
        }
    }
    final String jdbcDrivers = System.getProperty("jdbc.drivers");
    if (!StringUtils.isBlank(jdbcDrivers)) {
        for (String jdbcDriver : jdbcDrivers.split(":")) {
            try {
                Driver driver = DynamicLoader.newInstance(jdbcDriver, cl);
                if (driver != null) {
                    if (!hasClasspath) {
                        drivers.add(driver);
                    }
                    return driver;
                }
            } catch (DynamicLoadingException ex) {
                log.warn(ex.toString());
            }
        }
    }
    for (File jar : jars) {
        try {
            Driver driver = getDriver(jar, url, cl);
            if (driver != null) {
                if (!hasClasspath) {
                    drivers.add(driver);
                }
                return driver;
            }
        } catch (IOException ex) {
            log.warn(ex.toString());
        }
    }
    for (String path : System.getProperty("java.class.path", "").split(pathSeparator)) {
        if (isJarFile(path)) {
            Driver driver;
            try {
                driver = getDriver(new File(path), url, cl);
                if (driver != null) {
                    drivers.add(driver);
                    return driver;
                }
            } catch (IOException ex) {
                log.warn(ex.toString());
            }
        }
    }
    throw new SQLException("driver not found");
}

From source file:net.sf.hajdbc.state.sql.SQLStateManagerFactory.java

private String defaultUrlPattern() {
    ServiceLoader<Driver> drivers = ServiceLoader.load(Driver.class);

    for (EmbeddedVendor vendor : EmbeddedVendor.values()) {
        String url = MessageFormat.format(vendor.pattern, "test", Strings.USER_HOME);

        for (Driver driver : drivers) {
            try {
                if (driver.acceptsURL(url)) {
                    return vendor.pattern;
                }/*  www  .  j  a  va2 s . c  om*/
            } catch (SQLException e) {
                // Ignore
            }
        }
    }

    return null;
}

From source file:com.twosigma.beaker.sql.JDBCClient.java

public BasicDataSource getDataSource(String uri) throws DBConnectionException {
    synchronized (this) {
        try {//from   w  ww  .j  a  v  a 2 s . c  o  m

            BasicDataSource ds = dsMap.get(uri);
            if (ds == null) {
                Driver driver = null;
                for (Driver test : drivers) {
                    if (test.acceptsURL(uri)) {
                        driver = test;
                        break;
                    }
                }
                if (driver == null) {
                    DriverManager.getDriver(uri);
                }
                ds = new BasicDataSource();
                ds.setDriver(driver);
                ds.setUrl(uri);
                dsMap.put(uri, ds);
            }
            return ds;

        } catch (SQLException e) {
            //Logger.getLogger(JDBCClient.class.getName()).log(Level.SEVERE, null, e);
            throw new DBConnectionException(uri, e);
        }
    }
}

From source file:eu.peppol.jdbc.OxalisDataSourceFactoryDbcpImplTest.java

private ConnectionFactory createConnectionFactory(boolean profileSql) throws MalformedURLException,
        ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    String jdbcDriverClassPath = globalConfiguration.getJdbcDriverClassPath();
    URL url = new URL(jdbcDriverClassPath);
    try {/* www  .j a va  2s  .co  m*/
        File file = new File(url.toURI());
        if (!file.exists()) {
            throw new IllegalStateException("JDBC driver class path not found: " + file);
        }
    } catch (URISyntaxException e) {
        throw new IllegalStateException(
                "Unable to convert URL " + url.toExternalForm() + " into URI: " + e.getMessage(), e);
    }
    URLClassLoader urlClassLoader = new URLClassLoader(new URL[] { url },
            Thread.currentThread().getContextClassLoader());

    String jdbcDriverClassName = globalConfiguration.getJdbcDriverClassName();
    String connectURI = globalConfiguration.getJdbcConnectionURI(); // + "?initialTimeout=2";
    String userName = globalConfiguration.getJdbcUsername();
    String password = globalConfiguration.getJdbcPassword();

    Class<?> aClass = null;
    try {
        aClass = Class.forName(jdbcDriverClassName, true, urlClassLoader);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Unable to locate class " + jdbcDriverClassName + " in class path '"
                + jdbcDriverClassPath + "'");
    }
    Driver driver = (Driver) aClass.newInstance();
    assertTrue(driver.acceptsURL(connectURI));

    Properties properties = new Properties();
    properties.put("user", userName);
    properties.put("password", password);
    if (profileSql) {
        properties.put("profileSQL", "true"); // MySQL debug option
    }
    return new DriverConnectionFactory(driver, connectURI, properties);
}

From source file:net.big_oh.common.jdbc.JdbcDriverProxy.java

public boolean acceptsURL(String url) throws SQLException {
    Driver delegateDriver = lookupDelegateDriver(url);
    return (delegateDriver == null) ? false : delegateDriver.acceptsURL(url);
}

From source file:net.big_oh.common.jdbc.JdbcDriverProxy.java

private final Driver lookupDelegateDriver(String url) throws SQLException {
    if (!url.startsWith(getJdbcObserverUrlPrefix())) {
        logger.debug("Requested url '" + url + "' is not recognized by " + this.getClass().getName());
        return null;
    }//from www.j a v  a2 s.c o m

    url = stripJdbcObserverPrefixFromUrl(url);

    for (Driver delegateDriverCandidate : CollectionsUtil.toIterable(DriverManager.getDrivers())) {
        if (delegateDriverCandidate != this && delegateDriverCandidate.acceptsURL(url)) {
            logger.debug("Selected driver " + delegateDriverCandidate.getClass().getName() + " to service url '"
                    + url + "'");
            registerMostRecentDelegateDriver(mostRecentDelegateDriver);
            return delegateDriverCandidate;
        }
    }

    logger.warn("Failed to find an appropriate delegate driver for url '" + url + "'");
    logger.warn(
            "Maybe you need to load the delegate Driver class by calling 'Class.forName(com.somepackage.SomeDriver);' or by updating the overridden getDriverClassNamesToAutoLoad() method ?");
    return null;

}

From source file:edu.tamu.tcat.db.core.AbstractDataSourceFactory.java

/**
 * Create a new {@link BasicDataSource} from the specified {@link DSProperties}
 *///from   w  w w .  java  2  s .c  o m
protected synchronized BasicDataSource createDataSource(final Properties parameters)
        throws DataSourceException {
    BasicDataSource dataSource;
    final Driver driver = getDriver();
    final String connectionUrl = getConnectionUrl(parameters);
    final Properties connectionProps = getConnectionProperties(parameters);

    dataSource = new BasicDataSource() {
        @Override
        protected ConnectionFactory createConnectionFactory() throws SQLException {
            //The loading of the driver via class-loader does not work properly in OSGI.

            if (driver.acceptsURL(getUrl())) {
                if (getValidationQuery() == null) {
                    setTestOnBorrow(false);
                    setTestOnReturn(false);
                    setTestWhileIdle(false);
                }

                ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl,
                        connectionProps);
                return driverConnectionFactory;
            }
            return super.createConnectionFactory();
        }
    };
    //         dataSource.setDriverClassLoader(Driver.class.getClassLoader());
    // should be included in the connection properties and not needed
    //        dataSource.setUsername(key.getUsername());
    //        dataSource.setPassword(key.getPassword());
    dataSource.setDriverClassName(driver.getClass().getName());
    dataSource.setUrl(connectionUrl);
    dataSource.setMaxActive(getMaxActiveConnections(parameters));
    dataSource.setMaxIdle(getMaxIdleConnections(parameters));
    dataSource.setMinIdle(0);
    dataSource.setMinEvictableIdleTimeMillis(10000);
    dataSource.setTimeBetweenEvictionRunsMillis(1000);
    dataSource.setLogAbandoned(true);
    dataSource.setRemoveAbandoned(true);//seconds
    dataSource.setRemoveAbandonedTimeout(60);
    return dataSource;
}

From source file:net.sf.jasperreports.data.jdbc.JdbcDataAdapterService.java

public Connection getConnection() throws SQLException {
    JdbcDataAdapter jdbcDataAdapter = getJdbcDataAdapter();
    if (jdbcDataAdapter != null) {
        ClassLoader oldThreadClassLoader = Thread.currentThread().getContextClassLoader();

        try {/*from  w w w  . j av a2s  .  co  m*/
            Thread.currentThread().setContextClassLoader(getClassLoader(oldThreadClassLoader));

            Class<?> clazz = JRClassLoader.loadClassForRealName(jdbcDataAdapter.getDriver());
            Driver driver = (Driver) clazz.getDeclaredConstructor().newInstance();

            //            Driver driver = (Driver) (Class.forName(
            //                  jdbcDataAdapter.getDriver(), true, getClassLoader()))
            //                  .getDeclaredConstructor().newInstance();

            Properties connectProps = new Properties();
            Map<String, String> map = jdbcDataAdapter.getProperties();
            if (map != null)
                for (String key : map.keySet())
                    connectProps.setProperty(key, map.get(key));

            String password = jdbcDataAdapter.getPassword();
            SecretsUtil secretService = SecretsUtil.getInstance(getJasperReportsContext());
            if (secretService != null)
                password = secretService.getSecret(SECRETS_CATEGORY, password);

            connectProps.setProperty("user", jdbcDataAdapter.getUsername());
            connectProps.setProperty("password", password);

            connection = driver.connect(jdbcDataAdapter.getUrl(), connectProps);
            if (connection == null) {
                boolean urlValid = driver.acceptsURL(jdbcDataAdapter.getUrl());
                if (!urlValid) {
                    throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_INVALID_URL,
                            new Object[] { jdbcDataAdapter.getUrl(), jdbcDataAdapter.getDriver() });
                }

                throw new JRRuntimeException(EXCEPTION_MESSAGE_KEY_CONNECTION_NOT_CREATED,
                        new Object[] { jdbcDataAdapter.getUrl() });
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | NoSuchMethodException | InvocationTargetException e) {
            throw new JRRuntimeException(e);
        } finally {
            Thread.currentThread().setContextClassLoader(oldThreadClassLoader);
        }
        return connection;
    }
    return null;
}