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.owasp.webgoat.application.WebGoatServletListener.java

/** {@inheritDoc} */
@Override//from   w w  w. ja  v a 2  s.com
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.pentaho.pat.server.services.impl.DiscoveryServiceImpl.java

public List<String> getDrivers() {
    this.driverFinder.registerDrivers();

    // An enumeration is a very unpractical thing, so let's convert it to a List.
    // We can't even know it's size... what a shameful object.
    final Enumeration<Driver> driversEnum = DriverManager.getDrivers();
    final List<String> drivers = new ArrayList<String>();
    while (driversEnum.hasMoreElements()) {
        drivers.add(driversEnum.nextElement().getClass().getName());
    }//from   w w  w  .  j a  v a 2s .  c o  m
    Collections.sort(drivers);

    return drivers;
}

From source file:org.eclipse.che.ide.ext.datasource.server.JdbcConnectionFactory.java

/**
 * builds a JDBC {@link Connection} for a datasource.
 *
 * @param configuration the datasource configuration
 * @return a connection/*from www. j  a v a 2s . com*/
 * @throws SQLException if the creation of the connection failed
 * @throws DatabaseDefinitionException if the configuration is incorrect
 */
public Connection getDatabaseConnection(final DatabaseConfigurationDTO configuration)
        throws SQLException, DatabaseDefinitionException {
    if (LOG.isInfoEnabled()) {
        Driver[] drivers = Collections.list(DriverManager.getDrivers()).toArray(new Driver[0]);
        LOG.info("Available jdbc drivers : {}", Arrays.toString(drivers));
    }

    Properties info = new Properties();
    info.setProperty("user", configuration.getUsername());

    final String password = configuration.getPassword();
    if (password != null && !password.isEmpty()) {
        try {
            info.setProperty("password", encryptTextService.decryptText(password));
        } catch (final Exception e1) {
            LOG.error("Couldn't decrypt the password, trying by setting the password without decryption", e1);
            info.setProperty("password", password);
        }
    } else {
        info.setProperty("password", "");
    }

    try {
        Map<String, String> preferences = getPreferences();

        CodenvySSLSocketFactoryKeyStoreSettings sslSettings = new CodenvySSLSocketFactoryKeyStoreSettings();
        if (configuration.getUseSSL()) {
            info.setProperty("useSSL", Boolean.toString(configuration.getUseSSL()));
            String sslKeyStore = preferences.get(KeyStoreObject.SSL_KEY_STORE_PREF_ID);
            sslSettings.setKeyStorePassword(SslKeyStoreService.getDefaultKeystorePassword());
            if (sslKeyStore != null) {
                sslSettings.setKeyStoreContent(Base64.decodeBase64(sslKeyStore));
            }
        }

        if (configuration.getVerifyServerCertificate()) {
            info.setProperty("verifyServerCertificate",
                    Boolean.toString(configuration.getVerifyServerCertificate()));
            String trustStore = preferences.get(KeyStoreObject.TRUST_STORE_PREF_ID);
            sslSettings.setTrustStorePassword(SslKeyStoreService.getDefaultTrustorePassword());
            if (trustStore != null) {
                sslSettings.setTrustStoreContent(Base64.decodeBase64(trustStore));
            }
        }

        CodenvySSLSocketFactory.keystore.set(sslSettings);

    } catch (Exception e) {
        LOG.error(
                "An error occured while getting keystore from Codenvy Preferences, JDBC connection will be performed without SSL",
                e);
    }
    final Connection connection = DriverManager.getConnection(getJdbcUrl(configuration), info);

    return connection;
}

From source file:org.dcm4chee.proxy.tool.ProxySA.java

private static DicomConfiguration configureDicomConfiguration(CommandLine cl, HL7Configuration hl7Config)
        throws NamingException, ConfigurationException {
    if (useLdapConfiguration(cl)) {
        LdapEnv env = new LdapEnv();
        env.setUrl(cl.getOptionValue("ldap-url"));
        env.setUserDN(cl.getOptionValue("ldap-userDN"));
        env.setPassword(cl.getOptionValue("ldap-pwd"));
        return newLdapProxyConfiguration(hl7Config);
    } else if (cl.hasOption("jdbc-backend-url")) {
        if (!DriverManager.getDrivers().hasMoreElements())
            throw new RuntimeException("No jdbc driver in classpath.");

        System.setProperty("java.util.prefs.PreferencesFactory",
                "org.dcm4che.jdbc.prefs.PreferencesFactoryJDBCImpl");
        System.setProperty("jdbc.prefs.datasource", cl.getOptionValue("jdbc-backend-url"));
        System.setProperty("jdbc.prefs.connection.username", cl.getOptionValue("jdbc-user-name"));
        System.setProperty("jdbc.prefs.connection.password", cl.getOptionValue("jdbc-user-pwd"));
    }/*from   ww  w .ja  v a  2 s. c  om*/
    return newPreferencesProxyConfiguration(hl7Config);
}

From source file:org.shaigor.rest.retro.config.PersistenceConfiguration.java

@Override
/**//from ww  w.  j  av  a  2  s  .c om
 * Proper disposal of JDBC Drivers and MySQL in particular
 */
public void contextDestroyed(ServletContextEvent sce) {
    Enumeration<Driver> drivers = DriverManager.getDrivers();

    Driver driver = null;

    // clear drivers
    while (drivers.hasMoreElements()) {
        try {
            driver = drivers.nextElement();
            DriverManager.deregisterDriver(driver);

        } catch (SQLException ex) {
            logger.error("Failed to de-register Driver", ex);
        }
    }

    // MySQL driver leaves around a thread. This static method cleans it up.
    try {
        AbandonedConnectionCleanupThread.shutdown();
    } catch (InterruptedException e) {
        logger.error("Failed to stop AbandonedConnectionCleanupThread", e);
    }
}

From source file:com.mg.jet.birt.report.data.oda.ejbql.HibernateUtil.java

private static synchronized void initSessionFactory(String hibfile, String mapdir, String jndiName)
        throws HibernateException {
    //ClassLoader cl1;

    if (sessionFactory == null) {

        if (jndiName == null || jndiName.trim().length() == 0)
            jndiName = CommonConstant.DEFAULT_JNDI_URL;
        Context initCtx = null;//from  ww  w  .  j a  v a  2s .co m
        try {
            initCtx = new InitialContext();
            sessionFactory = (SessionFactory) initCtx.lookup(jndiName);
            return;
        } catch (Exception e) {
            logger.log(Level.INFO, "Unable to get JNDI data source connection", e);
        } finally {
            if (initCtx != null)
                try {
                    initCtx.close();
                } catch (NamingException e) {
                    //ignore
                }
        }

        Thread thread = Thread.currentThread();
        try {
            //Class.forName("org.hibernate.Configuration");
            //Configuration ffff = new Configuration();
            //Class.forName("org.apache.commons.logging.LogFactory");

            oldloader = thread.getContextClassLoader();
            //Class thwy = oldloader.loadClass("org.hibernate.cfg.Configuration");
            //Class thwy2 = oldloader.loadClass("org.apache.commons.logging.LogFactory");
            //refreshURLs();
            //ClassLoader changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]),HibernateUtil.class.getClassLoader());
            ClassLoader testLoader = new URLClassLoader((URL[]) URLList.toArray(new URL[0]), pluginLoader);
            //changeLoader = new URLClassLoader( (URL [])URLList.toArray(new URL[0]));

            thread.setContextClassLoader(testLoader);
            //Class thwy2 = changeLoader.loadClass("org.hibernate.cfg.Configuration");
            //Class.forName("org.apache.commons.logging.LogFactory", true, changeLoader);
            //Class cls = Class.forName("org.hibernate.cfg.Configuration", true, changeLoader);
            //Configuration cfg=null;
            //cfg = new Configuration();
            //Object oo = cls.newInstance();
            //Configuration cfg = (Configuration)oo;
            Configuration cfg = new Configuration();
            buildConfig(hibfile, mapdir, cfg);

            Class<? extends Driver> driverClass = testLoader
                    .loadClass(cfg.getProperty("connection.driver_class")).asSubclass(Driver.class);
            Driver driver = driverClass.newInstance();
            WrappedDriver wd = new WrappedDriver(driver, cfg.getProperty("connection.driver_class"));

            boolean foundDriver = false;
            Enumeration<Driver> drivers = DriverManager.getDrivers();
            while (drivers.hasMoreElements()) {
                Driver nextDriver = (Driver) drivers.nextElement();
                if (nextDriver.getClass() == wd.getClass()) {
                    if (nextDriver.toString().equals(wd.toString())) {
                        foundDriver = true;
                        break;
                    }
                }
            }
            if (!foundDriver) {

                DriverManager.registerDriver(wd);
            }

            sessionFactory = cfg.buildSessionFactory();
            //configuration = cfg;
            HibernateMapDirectory = mapdir;
            HibernateConfigFile = hibfile;
        } catch (Throwable e) {
            e.printStackTrace();
            throw new HibernateException("No Session Factory Created " + e.getLocalizedMessage(), e);
        } finally {
            thread.setContextClassLoader(oldloader);
        }
    }
}

From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java

protected void stop() throws BundleException {
    FrameworkLoader.stop();/*from  ww  w. jav a  2  s  . co  m*/
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            log.warn(String.format("Deregister JDBC driver: %s", driver));
        } catch (SQLException e) {
            log.error(String.format("Error deregistering JDBC driver %s", driver), e);
        }
    }
}

From source file:net.tirasa.connid.bundles.soap.wssample.DefaultContentLoader.java

@Override
public void contextDestroyed(final ServletContextEvent sce) {
    final Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        final Driver driver = drivers.nextElement();
        try {/*w ww. j ava 2 s .  c om*/
            DriverManager.deregisterDriver(driver);
            LOG.info("Deregistering JDBC driver: {}", driver);
        } catch (SQLException e) {
            LOG.error("Error deregistering JDBC driver {}", driver, e);
        }
    }
}

From source file:org.jwatch.listener.settings.SettingsLoaderListener.java

public void contextDestroyed(ServletContextEvent event) {
    log.info("Shutting down SettingsLoaderListener service...");
    Map qMap = QuartzInstanceService.getQuartzInstanceMap();
    for (Iterator it = qMap.entrySet().iterator(); it.hasNext();) {
        Map.Entry entry = (Map.Entry) it.next();
        String k = (String) entry.getKey();
        QuartzInstance quartzInstance = (QuartzInstance) qMap.get(k);
        try {// w w  w.  j  a  va  2s . co m
            quartzInstance.getJmxConnector().close();
        } catch (IOException e) {
            log.error("Failed to close Connection: " + quartzInstance, e);
        }
    }

    try {
        connectionUtil.shutdown();
    } catch (SQLException e) {
        log.error("Failed closing DB", e);
    }

    // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory leaks wrt this class
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        try {
            DriverManager.deregisterDriver(driver);
            log.info(String.format("deregistering jdbc driver: %s", driver));
        } catch (SQLException e) {
            log.error(String.format("Error deregistering driver %s", driver), e);
        }
    }

}

From source file:net.firejack.platform.core.utils.OpenFlameDataSource.java

@Override
public synchronized void close() throws SQLException {
    super.close();
    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        DriverManager.deregisterDriver(drivers.nextElement());
    }//from www.j a  va  2  s  .co m
}