Example usage for java.sql DriverManager getDrivers

List of usage examples for java.sql DriverManager getDrivers

Introduction

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

Prototype

@CallerSensitive
public static Enumeration<Driver> getDrivers() 

Source Link

Document

Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.

Usage

From source file:com.alibaba.wasp.jdbcx.JdbcDataSource.java

private static Connection getConnectionInternal(String url, Properties properties) throws SQLException {
    //com.alibaba.wasp.jdbc.Driver.load();
    Enumeration<java.sql.Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        java.sql.Driver driver = (java.sql.Driver) drivers.nextElement();
        if (!(driver instanceof Driver)) {
            DriverManager.deregisterDriver(driver);
        }/*from   ww w  . ja  va  2 s . c  o m*/
    }
    return DriverManager.getConnection(url, properties);
}

From source file:com.jt.dbcp.example.ManualPoolingDataSourceExample.java

public static void printDataSourceStats(DataSource ds) {
    Enumeration<Driver> driver = DriverManager.getDrivers();
    while (driver.hasMoreElements()) {
        Driver d = driver.nextElement();
        System.out.println(d.getClass());
    }// w  ww  .j  a v  a 2 s.co m
}

From source file:de.uniwue.info6.webapp.misc.InitVariables.java

/**
 * @param event//from ww  w.j a v a2 s.c  o  m
 */
@Override
public void contextDestroyed(final ServletContextEvent event) {
    // ------------------------------------------------ //

    ConnectionTools.inst().cleanUp();

    // ------------------------------------------------ //

    C3P0Registry.getNumPooledDataSources();
    PooledDataSource dataSource = null;
    @SuppressWarnings({ "unchecked", "rawtypes" })
    Iterator<Set> it = C3P0Registry.getPooledDataSources().iterator();
    while (it.hasNext()) {
        try {
            dataSource = (PooledDataSource) it.next();
            dataSource.close();
        } catch (Exception e) {
            LOGGER.error("Error deregistering driver %s", dataSource, e);
        }
    }

    // ------------------------------------------------ //

    final HashMap<Scenario, ComboPooledDataSource> pools = ConnectionManager.instance().getPools();
    for (Scenario scenario : pools.keySet()) {
        final String dbHost = scenario.getDbHost();
        final String dbPort = scenario.getDbPort();
        final String url = ConnectionManager.URL_PREFIX + dbHost + ":" + dbPort + "/";

        Driver mariaDBDriver = null;
        try {
            final ComboPooledDataSource cpds = pools.get(scenario);
            mariaDBDriver = DriverManager.getDriver(url);
            if (mariaDBDriver != null) {
                DriverManager.deregisterDriver(mariaDBDriver);
            }
            DataSources.destroy(cpds);
        } catch (SQLException e) {
        } catch (Exception e) {
            LOGGER.error(String.format("Error deregistering driver %s", mariaDBDriver), e);
        }
    }

    // ------------------------------------------------ //

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            LOGGER.info(String.format("deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            LOGGER.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

    // ------------------------------------------------ //

    // for (Thread thread : Thread.getAllStackTraces().keySet()) {
    // }

    // ------------------------------------------------ //
}

From source file:org.zlogic.vogon.web.PersistenceConfiguration.java

/**
 * Unloads the loaded JDBC driver(s) to prevent memory leaks
 *///from   w  w w  . j  a v a  2 s . c om
@PreDestroy
public void unloadJDBCDriver() {
    log.info(messages.getString("UNLOADING_JDBC_DRIVERS"));
    for (Enumeration<Driver> drivers = DriverManager.getDrivers(); drivers.hasMoreElements();) {
        try {
            Driver driver = drivers.nextElement();
            if (driver.getClass().getClassLoader() == PersistenceConfiguration.class.getClassLoader()) {
                log.info(MessageFormat.format(messages.getString("UNLOADING_DRIVER"), new Object[] { driver }));
                DriverManager.deregisterDriver(driver);
            } else {
                log.debug(MessageFormat.format(messages.getString("SKIPPING_DRIVER"), new Object[] { driver }));
            }
        } catch (SQLException ex) {
            log.error(messages.getString("ERROR_UNLOADING_DRIVER"), ex);
        }
    }
}

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 a 2 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:org.red5.server.war.WarLoaderServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *//*  w  w  w.j a  v  a 2s  .  co m*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (servletContext) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown the persistence thread
            FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance();
            if (persistenceThread != null) {
                persistenceThread.shutdown();
            }
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();
                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            getContextLoader().closeWebApplicationContext(ctx);
            //            org.apache.commons.logging.LogFactory.releaseAll();
            //            org.apache.log4j.LogManager.getLoggerRepository().shutdown();
            //            org.apache.log4j.LogManager.shutdown();
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.BaseJDBCStorageClientPool.java

@Override
@Activate//  ww  w .j a v a 2 s .co  m
@SuppressWarnings(value = {
        "NP_CLOSING_NULL" }, justification = "Invalid report, if this was the case then nothing would work")
public void activate(Map<String, Object> properties) throws ClassNotFoundException {
    this.properties = properties;
    super.activate(properties);

    connectionManager = new ConnectionManager(this);
    timer = new Timer();
    timer.schedule(connectionManager, 30000L, 30000L);

    // this is a default cache used where none has been provided.
    if (LOGGER.isDebugEnabled()) {
        DriverManager.setLogWriter(new PrintWriter(System.err));
    }

    String jdbcDriver = StorageClientUtils.getSetting(properties.get(JDBC_DRIVER), "");
    Class<?> driverClass = this.getClass().getClassLoader().loadClass(jdbcDriver);
    if (driverClass != null) {
        LOGGER.info("Loaded Driver Class {} with classloader {} ", driverClass, driverClass.getClassLoader());
        try {
            Driver d = (Driver) driverClass.newInstance();
            LOGGER.info("Created Driver Instance as {} ", d);
        } catch (InstantiationException e) {
            LOGGER.info("Error Creating Driver {} ", driverClass, e);
        } catch (IllegalAccessException e) {
            LOGGER.info("Error Creating Driver {} ", driverClass, e);
        }
    } else {
        LOGGER.error(
                "Failed to Load the DB Driver {}, unless the driver is available in the core bundle, it probably wont be found.",
                jdbcDriver);
    }
    connectionProperties = getConnectionProperties(properties);
    username = StorageClientUtils.getSetting(properties.get(USERNAME), "");
    password = StorageClientUtils.getSetting(properties.get(PASSWORD), "");
    url = StorageClientUtils.getSetting(properties.get(CONNECTION_URL), "");

    LOGGER.info("Loaded Database Driver {} as {}  ", jdbcDriver, driverClass);
    boolean registered = false;
    for (Enumeration<Driver> ed = DriverManager.getDrivers(); ed.hasMoreElements();) {
        registered = true;
        Driver d = ed.nextElement();
        LOGGER.info("JDBC Driver Registration [{}] [{}] [{}] ",
                new Object[] { d, d.getClass(), d.getClass().getClassLoader() });
    }
    if (!registered) {
        LOGGER.warn(
                "The SQL Driver has no drivers registered, did you ensure that that your Driver started up before this bundle ?");
    }
    JDBCStorageClient client = null;
    try {
        // dont use the pool, we dont want this client to be in the pool.
        client = new JDBCStorageClient(this, properties, getSqlConfig(), getIndexColumns(),
                getIndexColumnsTypes(), getIndexColumnsNames(), false);
        client = checkSchema(client);
        if (client == null) {
            LOGGER.warn("Failed to check Schema, no connection");
        }
    } catch (ClientPoolException e) {
        LOGGER.warn("Failed to check Schema", e);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.warn("Failed to check Schema", e);
    } catch (SQLException e) {
        LOGGER.warn("Failed to check Schema", e);
    } catch (StorageClientException e) {
        LOGGER.warn("Failed to check Schema", e);
    } finally {
        if (client != null) {
            // do not close as this will add the client into the pool.
            client.passivate();
            client.destroy();
        }
    }

}

From source file:orca.util.db.MySqlBase.java

/**
 * Deregister the sun ODBC bridge driver. We don't need it and it is broken
 * on some platforms/*from  w w  w.ja  va 2 s .  c om*/
 */
protected void checkDrivers() {
    try {
        logger.debug(DriverManager.getDriver(source + pool));

        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Driver odbcDriver;

        if ((odbcDriver = drivers.nextElement()) != null) {
            if (odbcDriver.getClass().getName().matches(".*odbc.*")) {
                DriverManager.deregisterDriver(odbcDriver);
                logger.debug("Deregistering " + odbcDriver);
            }
        }
    } catch (Exception e) {
    }
}

From source file:org.red5.server.war.MainServlet.java

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///from   ww  w.ja  va 2s  . c o m
public void contextDestroyed(ServletContextEvent sce) {
    logger.info("Webapp shutdown");
    // XXX Paul: grabbed this from
    // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
    // in hopes that we can clear all the issues with J2EE containers during
    // shutdown
    try {
        // prepare spring for shutdown
        Introspector.flushCaches();
        // dereg any drivers
        for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
            Driver driver = (Driver) e.nextElement();
            if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                DriverManager.deregisterDriver(driver);
            }
        }
        // shutdown jmx
        JMXAgent.shutdown();
        // shutdown spring
        // get web application context from the servlet context
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) servletContext
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        if (factory.containsSingleton("default.context")) {
            for (String scope : factory.getRegisteredScopeNames()) {
                logger.debug("Registered scope: " + scope);
            }
            for (String singleton : factory.getSingletonNames()) {
                logger.debug("Registered singleton: " + singleton);
                // factory.destroyScopedBean(singleton);
            }
            factory.destroySingletons();
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        applicationContext.close();
        // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
        // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
        // LogFactory.release(Thread.currentThread().getContextClassLoader());
    } catch (Throwable e) {
        // may get a java.lang.StackOverflowError when shutting appcontext
        // down in jboss
        e.printStackTrace();
    }
}