Example usage for java.sql Driver getClass

List of usage examples for java.sql Driver getClass

Introduction

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

Prototype

@HotSpotIntrinsicCandidate
public final native Class<?> getClass();

Source Link

Document

Returns the runtime class of this Object .

Usage

From source file:org.owasp.webgoat.application.WebGoatServletListener.java

/** {@inheritDoc} */
@Override/*from   w  w  w . j a va 2s.co  m*/
public void contextDestroyed(ServletContextEvent sce) {
    ServletContext context = sce.getServletContext();
    context.log("WebGoat is stopping");

    // Unregister JDBC drivers in this context's ClassLoader:
    // Get the webapp's ClassLoader
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    // Loop through all drivers
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        java.sql.Driver driver = drivers.nextElement();
        if (driver.getClass().getClassLoader() == cl) {
            // This driver was registered by the webapp's ClassLoader, so deregister it:
            try {
                context.log("Unregister JDBC driver {}");
                DriverManager.deregisterDriver(driver);
            } catch (SQLException ex) {
                context.log("Error unregistering JDBC driver {}");
            }
        } else {
            // driver was not registered by the webapp's ClassLoader and may be in use elsewhere
            context.log("Not unregistering JDBC driver {} as it does not belong to this webapp's ClassLoader");
        }
    }
}

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

/**
 * Unloads the loaded JDBC driver(s) to prevent memory leaks
 *//*from  www  . ja  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.ljcomputing.config.PersistenceConfiguration.java

/**
 * Gets the driver class name.//  w  ww. j av  a 2  s  .c o m
 *
 * @return the driver class name
 * @throws SQLException the SQL exception
 */
private String getDriverClassName() throws SQLException {
    final Driver driver = DriverManager.getDriver(url);
    final Class<?> driverClass = driver.getClass(); //NOPMD
    return driverClass.getName(); //NOPMD
}

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  . j av a  2s .  co m
        } else {
            // driver was not registered by the webapp's ClassLoader and may
            // be in use elsewhere
        }
    }
}

From source file:br.com.uol.runas.classloader.ClassLoaderGC.java

private void deregisterJdbcDrivers(WeakReference<ClassLoader> classLoader) {
    final List<?> drivers = Reflections.getStaticFieldValue(DriverManager.class, "registeredDrivers");

    final Map<Object, Driver> toDeregister = new HashMap<>();

    for (Object info : drivers) {
        final Driver driver = Reflections.getFieldValue(info, "driver");

        if (Objects.equals(classLoader.get(), driver.getClass().getClassLoader())) {
            toDeregister.put(info, driver);
        }/*from w w  w  .ja  v a  2  s  . com*/
    }

    drivers.removeAll(toDeregister.keySet());
}

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

private final void registerMostRecentDelegateDriver(Driver driver) {
    if (this.mostRecentDelegateDriver != null
            && !this.mostRecentDelegateDriver.getClass().isAssignableFrom(driver.getClass())) {
        logger.warn("Encountered multiple delegate driver clas types ("
                + mostRecentDelegateDriver.getClass().getName() + " & " + driver.getClass().getName()
                + ").  Using this proxy with multiple delegate types can cause surprising results to be returned by the getMajorVersion(), getMinorVersion() & jdbcCompliant() methods.");
    }/*  w ww . j  a  va2s . c om*/
    this.mostRecentDelegateDriver = driver;
}

From source file:com.buisonje.tools.xmldbloader.XmlDataSetDBLoader.java

/**
 * Instructs the {@link System}'s {@link ClassLoader} to load a JDBC driver class file from an external JAR.
 * @param jarFilePath the path to the class file to be loaded.
 * @throws IllegalArgumentException if no class could successfully loaded from the specified path.
 *///  w w  w  . j av  a2 s.  co  m
private void loadJdbcDriverClassFromJar(final String jarFilePath) throws IllegalArgumentException {

    try {

        URL u = new URL("jar:file:///" + jarFilePath + "!/");
        URLClassLoader ucl = new URLClassLoader(new URL[] { u });

        Reflections reflections = new Reflections(ucl);

        final Set<Class<? extends Driver>> detectedJdbcDrivers = reflections.getSubTypesOf(Driver.class);

        if (detectedJdbcDrivers.isEmpty()) {
            throw new IllegalArgumentException(String.format(
                    "The supplied JAR file at \"%s\" contains no JDBC drivers (which should implement the interface \"%s\").",
                    jarFilePath, Driver.class.getName()));
        }

        final int numberOfDetectedJdbcDrivers = detectedJdbcDrivers.size();
        if (numberOfDetectedJdbcDrivers > 1) {
            LOGGER.warn(
                    "Detected more than one ({}) JDBC drivers in the supplied JAR file at \"{}\". Choosing the first one...",
                    numberOfDetectedJdbcDrivers, jarFilePath);
        }

        Driver driver = detectedJdbcDrivers.iterator().next().newInstance();
        LOGGER.info("Loaded JDBC driver \"{}\".", driver.getClass().getName());
        DriverManager.registerDriver(new DriverShim(driver));

    } catch (InstantiationException e) {
        throw new IllegalArgumentException(String.format(
                "JAR file \"%s\" apparently contains a JDBC Driver that is incompatible with the Java version "
                        + "on which the application is currently running (version %s). To solve this problem, either upgrade the Java version (recommended) or "
                        + "downgrade the JDBC driver.",
                jarFilePath, System.getProperty("java.version")), e);
    } catch (Exception e) {
        throw new IllegalArgumentException(
                String.format("Unable to load JDBC Driver class from JAR \"%s\".", jarFilePath), e);
    }
}

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
 *///from w ww  .  ja v a 2 s.co m
@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());
        }
    }
}