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.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java

static boolean isDriverExisted(String driverClass) {
    Enumeration<Driver> e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        Driver driver = (Driver) e.nextElement();
        String driverClassName = (String) driver.getClass().getName();
        if (driverClassName.equals(driverClass))
            return true;
    }//from w  w  w  . ja va 2  s  . c o m
    return false;
}

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

static void deregisterTibcosoftwareincDrivers() {
    Enumeration<Driver> e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        Driver driver = (Driver) e.nextElement();
        String driverClassName = (String) driver.getClass().getName();
        try {/*from w ww .  j  av a 2s  . co m*/
            if (driverClassName.startsWith("tibcosoftwareinc."))
                DriverManager.deregisterDriver(driver);
        } catch (Exception ex) {
            printLog("Unable to deregister driver: " + driverClassName, ex);
        }
    }
}

From source file:org.allcolor.yahp.converter.CClassLoader.java

/**
 * destroy the loader tree/*from w w  w . j a va2s.c o m*/
 */
public static final void destroy() {
    if (CClassLoader.rootLoader == null) {
        return;
    }
    System.out.println("Destroying YAHP ClassLoader Tree");

    CClassLoader.urlLoader = null;

    try {
        Field f = Class.forName("java.lang.Shutdown").getDeclaredField("hooks");
        f.setAccessible(true);
        ArrayList l = (ArrayList) f.get(null);
        for (Iterator it = l.iterator(); it.hasNext();) {
            Object o = it.next();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        Field f = Class.forName("java.lang.ApplicationShutdownHooks").getDeclaredField("hooks");
        f.setAccessible(true);
        IdentityHashMap l = (IdentityHashMap) f.get(null);
        for (Iterator it = l.entrySet().iterator(); it.hasNext();) {
            Entry e = (Entry) it.next();
            Thread o = (Thread) e.getKey();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
                continue;
            }
            o = (Thread) e.getValue();
            if ((o != null) && (o.getClass().getClassLoader() != null)
                    && (o.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                it.remove();
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        if ((UIManager.getLookAndFeel() != null)
                && (UIManager.getLookAndFeel().getClass().getClassLoader() != null)
                && (UIManager.getLookAndFeel().getClass().getClassLoader().getClass() == CClassLoader.class)) {
            UIManager.setLookAndFeel((LookAndFeel) null);
        }
        Field f = UIManager.class.getDeclaredField("currentLAFState");
        f.setAccessible(true);
        Object lafstate = f.get(null);
        if (lafstate != null) {
            Field fmultiUIDefaults = lafstate.getClass().getDeclaredField("multiUIDefaults");
            fmultiUIDefaults.setAccessible(true);
            Object multiUIDefaults = fmultiUIDefaults.get(lafstate);
            Method clear = multiUIDefaults.getClass().getDeclaredMethod("clear", (Class[]) null);
            clear.setAccessible(true);
            clear.invoke(multiUIDefaults, (Object[]) null);
            Field tbl = lafstate.getClass().getDeclaredField("tables");
            tbl.setAccessible(true);
            Hashtable[] tables = (Hashtable[]) tbl.get(lafstate);
            if (tables != null) {
                for (int i = 0; i < tables.length; i++) {
                    Hashtable element = tables[i];
                    if (element != null) {
                        element.clear();
                    }
                }
            }
        }
    } catch (Throwable ignore) {
    }

    try {
        Hashtable tb = UIManager.getDefaults();
        Object cl = tb.get("ClassLoader");
        if (cl.getClass() == CClassLoader.class) {
            tb.put("ClassLoader", CClassLoader.rootLoader.getParent());
        }
    } catch (Throwable ignore) {
    }

    Method logFactoryRelease = null;

    try {
        logFactoryRelease = CClassLoader.rootLoader.loadClass("org.apache.commons.logging.LogFactory")
                .getMethod("release", new Class[] { ClassLoader.class });
    } catch (final Throwable ignore) {
    }

    CClassLoader.rootLoader._destroy(logFactoryRelease);
    CClassLoader.mandatoryLoadersMap.clear();
    CClassLoader.rootLoader = null;

    // deregister any sql driver loaded
    try {
        final List deregisterList = new ArrayList();
        for (final Enumeration it = DriverManager.getDrivers(); it.hasMoreElements();) {
            final Driver d = (Driver) it.nextElement();

            if ((d != null) && (d.getClass().getClassLoader() != null)
                    && (d.getClass().getClassLoader().getClass() == CClassLoader.class)) {
                deregisterList.add(d);
            }
        }

        for (int i = 0; i < deregisterList.size(); i++) {
            final Driver driver = (Driver) deregisterList.get(i);
            DriverManager.deregisterDriver(driver);
        }
    } catch (final Throwable ignore) {
    }

    // stop dandling thread created with this classloader
    // tested only on sun jdk
    ThreadGroup tg = Thread.currentThread().getThreadGroup();
    while ((tg != null) && (tg.getParent() != null)) {
        tg = tg.getParent();
    }
    List ltg = new ArrayList();
    ltg.add(tg);
    CClassLoader.getThreadGroups(tg, ltg);
    for (int ii = 0; ii < ltg.size(); ii++) {
        try {
            final ThreadGroup g = (ThreadGroup) ltg.get(ii);
            final Field fthreads = ThreadGroup.class.getDeclaredField("threads");
            fthreads.setAccessible(true);

            final List toStop = new ArrayList();
            Object threads[] = null;

            if (fthreads.getType() == Vector.class) {
                // in gnu classpath
                threads = ((Vector) fthreads.get(g)).toArray();
            } else {
                // sun
                threads = (Object[]) fthreads.get(g);
            }

            for (int i = 0; i < threads.length; i++) {
                if (threads[i] == null) {
                    continue;
                }
                if ((threads[i] != null) && (((Thread) threads[i]).getContextClassLoader() != null)
                        && (((Thread) threads[i]).getContextClassLoader().getClass() == CClassLoader.class)) {
                    ((Thread) threads[i]).setContextClassLoader(null);
                }
                if ((threads[i] != null) && (threads[i].getClass().getClassLoader() != null)
                        && (threads[i].getClass().getClassLoader().getClass() == CClassLoader.class)) {
                    toStop.add((Thread) threads[i]);
                }

                // remove any object in threadLocal referring an object
                // loaded
                // by this classloader tree
                try {
                    final Field fthreadLocals = Thread.class.getDeclaredField("threadLocals");
                    fthreadLocals.setAccessible(true);

                    final Object threadLocals = fthreadLocals.get(threads[i]);
                    if (threadLocals != null) {
                        final Field ftable = threadLocals.getClass().getDeclaredField("table");
                        ftable.setAccessible(true);

                        final Object table[] = (Object[]) ftable.get(threadLocals);

                        for (int kk = 0; kk < table.length; kk++) {
                            final Object element = table[kk];
                            if (element != null) {
                                final Field fvalue = element.getClass().getDeclaredField("value");
                                fvalue.setAccessible(true);

                                final Object value = fvalue.get(element);

                                if ((value != null) && (value.getClass().getClassLoader() != null) && (value
                                        .getClass().getClassLoader().getClass() == CClassLoader.class)) {
                                    fvalue.set(element, null);
                                }
                                if (value instanceof Map) {
                                    clearMap((Map) value);
                                } else if (value instanceof List) {
                                    clearList((List) value);
                                } else if (value instanceof Set) {
                                    clearSet((Set) value);
                                } else if (value instanceof Object[]) {
                                    clearArray((Object[]) value);
                                }

                                fvalue.setAccessible(false);
                            }
                        }
                        ftable.setAccessible(false);
                    }
                    fthreadLocals.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }

                // remove any object in threadLocal referring an object
                // loaded
                // by this classloader tree
                try {
                    final Field fthreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals");
                    fthreadLocals.setAccessible(true);

                    final Object threadLocals = fthreadLocals.get(threads[i]);
                    if (threadLocals != null) {
                        final Field ftable = threadLocals.getClass().getDeclaredField("table");
                        ftable.setAccessible(true);

                        final Object table[] = (Object[]) ftable.get(threadLocals);

                        for (int kk = 0; kk < table.length; kk++) {
                            final Object element = table[kk];
                            if (element != null) {
                                final Field fvalue = element.getClass().getDeclaredField("value");
                                fvalue.setAccessible(true);

                                final Object value = fvalue.get(element);

                                if ((value != null) && (value.getClass().getClassLoader() != null) && (value
                                        .getClass().getClassLoader().getClass() == CClassLoader.class)) {
                                    fvalue.set(element, null);
                                }
                                if (value instanceof Map) {
                                    clearMap((Map) value);
                                } else if (value instanceof List) {
                                    clearList((List) value);
                                } else if (value instanceof Set) {
                                    clearSet((Set) value);
                                } else if (value instanceof Object[]) {
                                    clearArray((Object[]) value);
                                }

                                fvalue.setAccessible(false);
                            }
                        }

                        ftable.setAccessible(false);
                    }
                    fthreadLocals.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }

                // remove any protection domain referring this loader tree
                try {
                    final Field finheritedAccessControlContext = Thread.class
                            .getDeclaredField("inheritedAccessControlContext");
                    finheritedAccessControlContext.setAccessible(true);

                    final Object inheritedAccessControlContext = finheritedAccessControlContext.get(threads[i]);

                    if (inheritedAccessControlContext != null) {
                        final Field fcontext = AccessControlContext.class.getDeclaredField("context");
                        fcontext.setAccessible(true);

                        final Object context[] = (Object[]) fcontext.get(inheritedAccessControlContext);

                        if (context != null) {
                            for (int k = 0; k < context.length; k++) {
                                if (context[k] == null)
                                    continue;
                                final Field fclassloader = ProtectionDomain.class
                                        .getDeclaredField("classloader");
                                fclassloader.setAccessible(true);

                                final Object classloader = fclassloader.get(context[k]);

                                if ((classloader != null) && (classloader.getClass() == CClassLoader.class)) {
                                    context[k] = null;
                                }

                                fclassloader.setAccessible(false);
                            }
                        }

                        fcontext.setAccessible(false);
                    }

                    finheritedAccessControlContext.setAccessible(false);
                } catch (final Throwable ignore) {
                    ignore.printStackTrace();
                }
            }

            fthreads.setAccessible(false);
            for (int i = 0; i < toStop.size(); i++) {
                try {
                    final Thread t = (Thread) toStop.get(i);
                    final Method stop = t.getClass().getMethod("stop", (Class[]) null);
                    stop.invoke(t, (Object[]) null);
                } catch (final Throwable ignore) {
                }
            }
        } catch (final Throwable ignore) {
        }
    }
    try {
        CThreadContext.destroy();
    } catch (Throwable ignore) {
    }
    System.runFinalization();
    System.gc();
    Introspector.flushCaches();
    System.out.println("Destroying YAHP ClassLoader Tree : done");
}

From source file:se.unlogic.hierarchy.core.cache.DataSourceCache.java

public void unload() {

    try {//from www .j  a  v  a  2  s.c o  m
        w.lock();

        ArrayList<DataSourceDescriptor> descriptorList = this.getCachedDataSourceDescriptors();

        for (DataSourceDescriptor descriptor : descriptorList) {

            this.stop(descriptor.getDataSourceID());
        }

        for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {

            Driver driver = e.nextElement();

            if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {

                try {
                    log.info("Deregistering JDBC driver " + driver);
                    DriverManager.deregisterDriver(driver);

                } catch (SQLException e1) {

                    log.error("Error deregistering JDBC driver " + driver);
                }
            }
        }

        log.info("Datasource cache unloaded");

    } finally {
        w.unlock();
    }
}

From source file:org.openmrs.util.OpenmrsClassLoader.java

/**
 * This clears any references this classloader might have that will prevent garbage collection. <br>
 * <br>/*from w  w  w  . ja v a2 s.  co m*/
 * Borrowed from Tomcat's WebappClassLoader#clearReferences() (not javadoc linked intentionally) <br>
 * The only difference between this and Tomcat's implementation is that this one only acts on
 * openmrs objects and also clears out static java.* packages. Tomcat acts on all objects and
 * does not clear our static java.* objects.
 *
 * @since 1.5
 */
protected static void clearReferences() {

    // Unregister any JDBC drivers loaded by this classloader
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        if (driver.getClass().getClassLoader() == getInstance()) {
            try {
                DriverManager.deregisterDriver(driver);
            } catch (SQLException e) {
                log.warn("SQL driver deregistration failed", e);
            }
        }
    }

    // Null out any static or final fields from loaded classes,
    // as a workaround for apparent garbage collection bugs
    for (WeakReference<Class<?>> refClazz : getInstance().cachedClasses.values()) {
        if (refClazz == null) {
            continue;
        }
        Class<?> clazz = refClazz.get();
        if (clazz != null && clazz.getName().contains("openmrs")) { // only clean up openmrs classes
            try {
                Field[] fields = clazz.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    Field field = fields[i];
                    int mods = field.getModifiers();
                    if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) {
                        continue;
                    }
                    if (Modifier.isStatic(mods)) {
                        try {
                            // do not clear the log field on this class yet
                            if (clazz.equals(OpenmrsClassLoader.class) && "log".equals(field.getName())) {
                                continue;
                            }
                            field.setAccessible(true);
                            if (Modifier.isFinal(mods)) {
                                if (!(field.getType().getName().startsWith("javax."))) {
                                    nullInstance(field.get(null));
                                }
                            } else {
                                field.set(null, null);
                                if (log.isDebugEnabled()) {
                                    log.debug("Set field " + field.getName() + " to null in class "
                                            + clazz.getName());
                                }
                            }
                        } catch (Exception t) {
                            if (log.isDebugEnabled()) {
                                log.debug("Could not set field " + field.getName() + " to null in class "
                                        + clazz.getName(), t);
                            }
                        }
                    }
                }
            } catch (Exception t) {
                if (log.isDebugEnabled()) {
                    log.debug("Could not clean fields for class " + clazz.getName(), t);
                }
            }
        }
    }

    // now we can clear the log field on this class
    OpenmrsClassLoader.log = null;

    getInstance().cachedClasses.clear();
}

From source file:org.rimudb.editor.RimuDBEditor.java

protected void driverCheck() {
    driverMap = getPreferences().getDrivers();
    if (driverMap != null) {
        Set<String> keyset = driverMap.keySet();
        for (String driverName : keyset) {

            DriverEntry driverEntry = driverMap.get(driverName);

            boolean found = false;
            try {
                Class.forName(driverEntry.getJdbcDriver());
                found = true;//from w  w w  .ja v a 2s. c  om
            } catch (Exception e) {
                log.info("driverCheck() Could not find driverClass", e);
            }

            driverEntry.setFound(found);
        }

        List<Driver> drivers = Collections.list(DriverManager.getDrivers());
        for (int i = 0; i < drivers.size(); i++) {
            Driver driver = (Driver) drivers.get(i);

            // Find the driver in the map and add the version to the DriverEntry
            Collection<DriverEntry> values = driverMap.values();
            for (DriverEntry driverEntry : values) {
                if (driverEntry.getJdbcDriver().trim().equals(driver.getClass().getName())) {
                    driverEntry.setDriverVersion(driver.getMajorVersion() + "." + driver.getMinorVersion());
                }
            }

        }

    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

/**
 * Deregister JDBC drivers loaded by web app classloader
 *//*from  ww w  . j a va  2s . com*/
public void deregisterJdbcDrivers() {
    final List<Driver> driversToDeregister = new ArrayList<Driver>();
    final Enumeration<Driver> allDrivers = DriverManager.getDrivers();
    while (allDrivers.hasMoreElements()) {
        final Driver driver = allDrivers.nextElement();
        if (isLoadedInWebApplication(driver)) // Should be true for all returned by DriverManager.getDrivers()
            driversToDeregister.add(driver);
    }

    for (Driver driver : driversToDeregister) {
        try {
            warn("JDBC driver loaded by web app deregistered: " + driver.getClass());
            DriverManager.deregisterDriver(driver);
        } catch (SQLException e) {
            error(e);
        }
    }
}

From source file:org.b3log.latke.Latkes.java

/**
 * Shutdowns Latke.//w  w  w .j a va 2  s.  com
 */
public static void shutdown() {
    try {
        if (RuntimeEnv.LOCAL != getRuntimeEnv()) {
            return;
        }

        Connections.shutdownConnectionPool();

        final RuntimeDatabase runtimeDatabase = getRuntimeDatabase();

        switch (runtimeDatabase) {
        case H2:
            final String newTCPServer = Latkes.getLocalProperty("newTCPServer");

            if ("true".equals(newTCPServer)) {
                h2.stop();
                h2.shutdown();

                LOGGER.log(Level.INFO, "Closed H2 TCP server");
            }
            break;

        default:

        }

        CronService.shutdown();
        LocalThreadService.EXECUTOR_SERVICE.shutdown();
    } catch (final Exception e) {
        LOGGER.log(Level.ERROR, "Shutdowns Latke failed", e);
    }

    Lifecycle.endApplication();

    // This manually deregisters JDBC driver, which prevents Tomcat from complaining about memory leaks
    final Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        final Driver driver = drivers.nextElement();

        try {
            DriverManager.deregisterDriver(driver);
            LOGGER.log(Level.TRACE, "Deregistered JDBC driver [" + driver + "]");
        } catch (final SQLException e) {
            LOGGER.log(Level.ERROR, "Deregister JDBC driver [" + driver + "] failed", e);
        }
    }
}

From source file:org.openmrs.web.Listener.java

/**
 * Called when the webapp is shut down properly Must call Context.shutdown() and then shutdown
 * all the web layers of the modules/*from   ww  w . j a  v  a  2s.c  o m*/
 *
 * @see org.springframework.web.context.ContextLoaderListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */
@SuppressWarnings("squid:S1215")
@Override
public void contextDestroyed(ServletContextEvent event) {

    try {
        Context.openSession();

        Context.shutdown();

        WebModuleUtil.shutdownModules(event.getServletContext());

    } catch (Exception e) {
        // don't print the unhelpful "contextDAO is null" message
        if (!"contextDAO is null".equals(e.getMessage())) {
            // not using log.error here so it can be garbage collected
            System.out.println("Listener.contextDestroyed: Error while shutting down openmrs: ");
            log.error(e);
        }
    } finally {
        if ("true".equalsIgnoreCase(System.getProperty("FUNCTIONAL_TEST_MODE"))) {
            //Delete the temporary file created for functional testing and shutdown the mysql daemon
            String filename = WebConstants.WEBAPP_NAME + "-test-runtime.properties";
            File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename);
            System.out.println(filename + " delete=" + file.delete());
            //new com.mysql.management.MysqldResource(new File("../openmrs/target/database")).shutdown();
        }
        // remove the user context that we set earlier
        Context.closeSession();
    }

    // commented out because we are not init'ing it in the contextInitialization anymore
    // super.contextDestroyed(event);

    try {
        for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {
            Driver driver = e.nextElement();
            ClassLoader classLoader = driver.getClass().getClassLoader();
            // only unload drivers for this webapp
            if (classLoader == null || classLoader == getClass().getClassLoader()) {
                DriverManager.deregisterDriver(driver);
            } else {
                System.err.println("Didn't remove driver class: " + driver.getClass() + " with classloader of: "
                        + driver.getClass().getClassLoader());
            }
        }
    } catch (Exception e) {
        System.err.println("Listener.contextDestroyed: Failed to cleanup drivers in webapp");
        log.error(e);
    }

    MemoryLeakUtil.shutdownMysqlCancellationTimer();
    MemoryLeakUtil.shutdownKeepAliveTimer();

    OpenmrsClassLoader.onShutdown();

    LogManager.shutdown();

    // just to make things nice and clean.
    // Suppressing sonar issue squid:S1215
    System.gc();
    System.gc();
}

From source file:com.evolveum.midpoint.repo.sql.SqlRepositoryServiceImpl.java

@Override
public RepositoryDiag getRepositoryDiag() {
    LOGGER.debug("Getting repository diagnostics.");

    RepositoryDiag diag = new RepositoryDiag();
    diag.setImplementationShortName(IMPLEMENTATION_SHORT_NAME);
    diag.setImplementationDescription(IMPLEMENTATION_DESCRIPTION);

    SqlRepositoryConfiguration config = getConfiguration();

    //todo improve, find and use real values (which are used by sessionFactory) MID-1219
    diag.setDriverShortName(config.getDriverClassName());
    diag.setRepositoryUrl(config.getJdbcUrl());
    diag.setEmbedded(config.isEmbedded());

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while ((drivers != null && drivers.hasMoreElements())) {
        Driver driver = drivers.nextElement();
        if (!driver.getClass().getName().equals(config.getDriverClassName())) {
            continue;
        }/*  w w w .  j a v a  2  s  . c o m*/

        diag.setDriverVersion(driver.getMajorVersion() + "." + driver.getMinorVersion());
    }

    List<LabeledString> details = new ArrayList<>();
    diag.setAdditionalDetails(details);
    details.add(new LabeledString(DETAILS_DATA_SOURCE, config.getDataSource()));
    details.add(new LabeledString(DETAILS_HIBERNATE_DIALECT, config.getHibernateDialect()));
    details.add(new LabeledString(DETAILS_HIBERNATE_HBM_2_DDL, config.getHibernateHbm2ddl()));

    readDetailsFromConnection(diag, config);

    Collections.sort(details, new Comparator<LabeledString>() {

        @Override
        public int compare(LabeledString o1, LabeledString o2) {
            return String.CASE_INSENSITIVE_ORDER.compare(o1.getLabel(), o2.getLabel());
        }
    });

    return diag;
}