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:org.geoserver.GeoserverInitStartupListener.java

/**
 * This method tries hard to stop all threads and remove all references to classes in GeoServer
 * so that we can avoid permgen leaks on application undeploy.
 * What happes is that, if any JDK class references to one of the classes loaded by the
 * webapp classloader, then the classloader cannot be collected and neither can all the
 * classes loaded by it (since each class keeps a back reference to the classloader that
 * loaded it). The same happens for any residual thread launched by the web app.
 *///w w w  .  j  a  v  a  2  s . c o  m
public void contextDestroyed(ServletContextEvent sce) {
    try {
        LOGGER.info("Beginning GeoServer cleanup sequence");

        // the dreaded classloader
        ClassLoader webappClassLoader = getClass().getClassLoader();

        // unload all of the jdbc drivers we have loaded. We need to store them and unregister
        // later to avoid concurrent modification exceptions
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Set<Driver> driversToUnload = new HashSet<Driver>();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                // the driver class loader can be null if the driver comes from the JDK, such as the 
                // sun.jdbc.odbc.JdbcOdbcDriver
                ClassLoader driverClassLoader = driver.getClass().getClassLoader();
                if (driverClassLoader != null && webappClassLoader.equals(driverClassLoader)) {
                    driversToUnload.add(driver);
                }
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
        for (Driver driver : driversToUnload) {
            try {
                DriverManager.deregisterDriver(driver);
                LOGGER.info("Unregistered JDBC driver " + driver);
            } catch (Exception e) {
                LOGGER.log(Level.SEVERE, "Could now unload driver " + driver.getClass(), e);
            }
        }
        drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
        }
        try {
            Class h2Driver = Class.forName("org.h2.Driver");
            Method m = h2Driver.getMethod("unload");
            m.invoke(null);
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "Failed to unload the H2 driver", e);
        }

        // unload all deferred authority factories so that we get rid of the timer tasks in them
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCoordinateOperationAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCRSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }
        try {
            disposeAuthorityFactories(ReferencingFactoryFinder.getCSAuthorityFactories(null));
        } catch (Throwable e) {
            LOGGER.log(Level.WARNING, "Error occurred trying to dispose authority factories", e);
        }

        // kill the threads created by referencing
        WeakCollectionCleaner.DEFAULT.exit();
        DeferredAuthorityFactory.exit();
        CRS.reset("all");
        LOGGER.info("Shut down GT referencing threads ");
        // reset 
        ReferencingFactoryFinder.reset();
        CommonFactoryFinder.reset();
        DataStoreFinder.reset();
        DataAccessFinder.reset();
        LOGGER.info("Shut down GT  SPI ");

        LOGGER.info("Shut down coverage thread pool ");
        Object o = Hints.getSystemDefault(Hints.EXECUTOR_SERVICE);
        if (o != null && o instanceof ExecutorService) {
            final ThreadPoolExecutor executor = (ThreadPoolExecutor) o;
            try {
                executor.shutdown();
            } finally {
                try {
                    executor.shutdownNow();
                } finally {

                }
            }
        }

        // unload everything that JAI ImageIO can still refer to
        // We need to store them and unregister later to avoid concurrent modification exceptions
        final IIORegistry ioRegistry = IIORegistry.getDefaultInstance();
        Set<IIOServiceProvider> providersToUnload = new HashSet();
        for (Iterator<Class<?>> cats = ioRegistry.getCategories(); cats.hasNext();) {
            Class<?> category = cats.next();
            for (Iterator it = ioRegistry.getServiceProviders(category, false); it.hasNext();) {
                final IIOServiceProvider provider = (IIOServiceProvider) it.next();
                if (webappClassLoader.equals(provider.getClass().getClassLoader())) {
                    providersToUnload.add(provider);
                }
            }
        }
        for (IIOServiceProvider provider : providersToUnload) {
            ioRegistry.deregisterServiceProvider(provider);
            LOGGER.info("Unregistering Image I/O provider " + provider);
        }

        // unload everything that JAI can still refer to
        final OperationRegistry opRegistry = JAI.getDefaultInstance().getOperationRegistry();
        for (String mode : RegistryMode.getModeNames()) {
            for (Iterator descriptors = opRegistry.getDescriptors(mode).iterator(); descriptors != null
                    && descriptors.hasNext();) {
                RegistryElementDescriptor red = (RegistryElementDescriptor) descriptors.next();
                int factoryCount = 0;
                int unregisteredCount = 0;
                // look for all the factories for that operation
                for (Iterator factories = opRegistry.getFactoryIterator(mode, red.getName()); factories != null
                        && factories.hasNext();) {
                    Object factory = factories.next();
                    if (factory == null) {
                        continue;
                    }
                    factoryCount++;
                    if (webappClassLoader.equals(factory.getClass().getClassLoader())) {
                        boolean unregistered = false;
                        // we need to scan against all "products" to unregister the factory
                        Vector orderedProductList = opRegistry.getOrderedProductList(mode, red.getName());
                        if (orderedProductList != null) {
                            for (Iterator products = orderedProductList.iterator(); products != null
                                    && products.hasNext();) {
                                String product = (String) products.next();
                                try {
                                    opRegistry.unregisterFactory(mode, red.getName(), product, factory);
                                    LOGGER.info("Unregistering JAI factory " + factory.getClass());
                                } catch (Throwable t) {
                                    // may fail due to the factory not being registered against that product
                                }
                            }
                        }
                        if (unregistered) {
                            unregisteredCount++;
                        }

                    }
                }

                // if all the factories were unregistered, get rid of the descriptor as well
                if (factoryCount > 0 && unregisteredCount == factoryCount) {
                    opRegistry.unregisterDescriptor(red);
                }
            }
        }

        // flush all javabean introspection caches as this too can keep a webapp classloader from being unloaded
        Introspector.flushCaches();
        LOGGER.info("Cleaned up javabean caches");

        // unload the logging framework
        if (!relinquishLoggingControl)
            LogManager.shutdown();
        LogFactory.release(Thread.currentThread().getContextClassLoader());

        // GeoTools/GeoServer have a lot of finalizers and until they are run the JVM
        // itself wil keepup the class loader...
        try {
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
            System.gc();
            System.runFinalization();
        } catch (Throwable t) {
            System.out.println("Failed to perform closing up finalization");
            t.printStackTrace();
        }
    } catch (Throwable t) {
        // if anything goes south during the cleanup procedures I want to know what it is
        t.printStackTrace();
    }
}

From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClientPool.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();
    timer = new Timer();
    timer.schedule(connectionManager, 30000L, 30000L);

    sharedCache = new ConcurrentLRUMap<String, CacheHolder>(10000);
    // this is a default cache used where none has been provided.
    defaultStorageManagerCache = new StorageCacheManager() {

        public Map<String, CacheHolder> getContentCache() {
            return sharedCache;
        }

        public Map<String, CacheHolder> getAuthorizableCache() {
            return sharedCache;
        }

        public Map<String, CacheHolder> getAccessControlCache() {
            return sharedCache;
        }
    };
    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();
            if (d == null) {
                LOGGER.error("Error creating driver instance, got null from {} ", driverClass);
            } else {
                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 {
        client = (JDBCStorageClient) getClient();
        if (client == null) {
            LOGGER.warn("Failed to check Schema, no connection");
        }
    } catch (ClientPoolException e) {
        LOGGER.warn("Failed to check Schema", e);
    } finally {
        if (client != null) {
            client.close();
        }
    }

}

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 w  w  w  .j a va2  s .c  om

    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.springframework.data.hadoop.mapreduce.ExecutionUtils.java

/**
 * Utility method used before invoking custom code for preventing custom classloader, set as the Thread
 * context class-loader, to leak (typically through JDK classes).
 *///from   w ww.j  a  v  a 2 s  . c o  m
static void preventJreTcclLeaks() {
    if (log.isDebugEnabled()) {
        log.debug("Preventing JRE TCCL leaks");
    }

    // get the root CL to be used instead
    ClassLoader sysLoader = ClassLoader.getSystemClassLoader();

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    try {
        // set the sysCL as the TCCL
        Thread.currentThread().setContextClassLoader(sysLoader);

        //
        // Handle security
        //

        // Policy holds the TCCL as static
        ClassUtils.resolveClassName("javax.security.auth.Policy", sysLoader);
        // since the class init may be lazy, call the method directly
        Policy.getPolicy();
        // Configuration holds the TCCL as static
        // call method with minimal side-effects (since just doing class loading doesn't seem to trigger the static init)
        try {
            javax.security.auth.login.Configuration.getInstance(null, null, (String) null);
        } catch (Exception ex) {
            // ignore
        }
        // seems to cause side-effects/exceptions
        // javax.security.auth.login.Configuration.getConfiguration();
        java.security.Security.getProviders();

        // load the JDBC drivers (used by Hive and co)
        DriverManager.getDrivers();
        // Initialize
        // sun.awt.AppContext.getAppContext()
        ImageIO.getCacheDirectory();

    } finally {
        Thread.currentThread().setContextClassLoader(cl);
    }
}

From source file:net.noctuasource.noctua.core.database.impl.DatabaseInitializerImpl.java

public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new org.sqlite.JDBC());

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        logger.debug("Treiber: " + driver.toString());
    }/*from  w  ww .  ja v  a2 s  .co m*/

    String connectionString = "jdbc:sqlite:" + databaseFile.toString();
    logger.debug("Connection-String: " + connectionString);
    return DriverManager.getConnection(connectionString);
}

From source file:edu.cornell.mannlib.vitro.webapp.triplesource.impl.sdb.ContentTripleSourceSDB.java

private void attemptToDeregisterJdbcDriver(String driverClassName) {
    ClassLoader cl = Thread.currentThread().getContextClassLoader();

    for (Enumeration<Driver> drivers = DriverManager.getDrivers(); drivers.hasMoreElements();) {
        Driver driver = drivers.nextElement();
        if (driver.getClass().getClassLoader() == cl) {
            // This driver was registered by the webapp's ClassLoader, so
            // deregister it:
            try {
                DriverManager.deregisterDriver(driver);
            } catch (SQLException ex) {
                log.error("Error deregistering JDBC driver {" + driver + "}", ex);
            }//  w  w w.ja v  a  2  s  .c om
        } else {
            // driver was not registered by the webapp's ClassLoader and may
            // be in use elsewhere
        }
    }
}

From source file:org.red5.server.war.RootContextLoaderServlet.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 va  2s  .c  om*/
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (instance) {
        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();
            // if the ctx being destroyed is root then kill the timer
            if (ctx.getContextPath().equals("/ROOT")) {
                timer.cancel();
            } else {
                // remove from registered list
                registeredContexts.remove(ctx);
            }
            // 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
            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();
            }
            instance.getContextLoader().closeWebApplicationContext(ctx);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // 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());
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java

static public void printDrivers() {
    printLog("PRINT DRIVERS...");
    Enumeration<Driver> e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        String driverClass = (String) ((Driver) e.nextElement()).getClass().getName();
        printLog(driverClass);//w w w  . j  a va  2 s .c om
    }
}

From source file:org.craftercms.studio.impl.v1.dal.DataSourceInitializerImpl.java

public void shutdown() {
    if (mariaDB4jService != null) {
        DB db = mariaDB4jService.getDB();
        if (db != null) {
            try {
                db.stop();//from   w w w .jav a  2 s .  c o  m
            } catch (ManagedProcessException e) {
                logger.error("Failed to stop database", e);
            }
        }
        try {
            mariaDB4jService.stop();
        } catch (ManagedProcessException e) {
            logger.error("Failed to stop database", e);
        }
    }
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
        } catch (SQLException e) {
            logger.error("Failed to unregister driver " + driver.getClass().getCanonicalName() + " on shutdown",
                    e);
        }
    }
}