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.apache.falcon.entity.parser.DatasourceEntityParser.java

private static void validateConnection(ClassLoader hdfsClassLoader, String driverClass, String connectUrl,
        Properties userPasswdInfo) throws FalconException {
    try {//  w w w  . j a  v  a2 s .  c o m
        java.sql.Driver driver = (java.sql.Driver) hdfsClassLoader.loadClass(driverClass).newInstance();
        LOG.info("Validating connection URL: {0} using driver: {1}", connectUrl, driver.getClass().toString());
        Connection con = driver.connect(connectUrl, userPasswdInfo);
        if (con == null) {
            throw new FalconException("DriverManager.getConnection() return " + "null for URL : " + connectUrl);
        }
    } catch (Exception ex) {
        LOG.error("Exception while validating connection : ", ex);
        throw new FalconException(ex);
    }
}

From source file:org.apache.hive.beeline.BeeLine.java

public Driver findLocalDriver(String url) throws Exception {
    if (drivers == null) {
        return null;
    }//from  w ww .jav a 2s  .  co m

    for (Driver d : drivers) {
        try {
            String clazzName = d.getClass().getName();
            Driver driver = (Driver) Class
                    .forName(clazzName, true, Thread.currentThread().getContextClassLoader()).newInstance();
            if (driver.acceptsURL(url) && isSupportedLocalDriver(driver)) {
                return driver;
            }
        } catch (SQLException e) {
            error(e);
            throw new Exception(e);
        }
    }
    return null;
}

From source file:org.apache.hive.beeline.BeeLine.java

public boolean isSupportedLocalDriver(Driver driver) {
    String driverName = driver.getClass().getName();
    for (String name : supportedLocalDriver) {
        if (name.equals(driverName)) {
            return true;
        }// ww w .  j ava  2s . c  o m
    }
    return false;
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private void registerConnectionDriver(String name, DriverConnectionPoolManager manager)
        throws SQLException, OpenRDFException, IOException {
    Exception cause = null;//from  w w w . j  a v  a2 s.c  o m
    String url = this.getCalliJdbcUrl();
    List<String> classnames = new ArrayList<>(this.getCalliDriverClassName());
    ClassLoader cl = createClassLoader();
    for (String classname : classnames) {
        try {
            Object d = Class.forName(classname, true, cl).newInstance();
            if (!(d instanceof Driver)) {
                logger.error("{} is not a java.sql.Driver class", classname);
            }
            Driver driver = (Driver) d;
            if (driver.getClass().getClassLoader() == cl) {
                deregisterDriverOnReset(name, driver);
            }
            if (driver.acceptsURL(url)) {
                Config config = new Config();
                config.testOnBorrow = true;
                config.maxActive = intOrNeg(this.getCalliMaxActive());
                config.maxIdle = intOrNeg(this.getCalliMaxIdle());
                config.maxWait = intOrNeg(this.getCalliMaxWait());
                Properties props = new Properties();
                Credentials cred = getCredential(url);
                if (cred != null) {
                    props.setProperty("user", cred.getUserPrincipal().getName());
                    props.setProperty("password", cred.getPassword());
                }
                verifyDriver(url, driver, props);
                manager.registerDriver(name, driver, url, props, config, this.getCalliValidationQuery());
                return;
            }
        } catch (ClassNotFoundException e) {
            cause = e;
            logger.error("{} is not found in {}", classname, this.getCalliDriverJar());
        } catch (InstantiationException e) {
            cause = e;
            logger.error("Could not instaniate {}", classname);
        } catch (IllegalAccessException e) {
            cause = e;
            logger.error("Could not access {}", classname);
        } catch (Exception e) {
            cause = e;
            logger.error("Could not load driver {}", classname);
        }
    }
    reset();
    if (cause instanceof SQLException)
        throw (SQLException) cause;
    if (cause != null)
        throw new SQLException("Could not load driver " + classnames, cause);
    throw new SQLException("Could not load driver " + classnames);
}

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  .  j a  v  a  2 s .  co 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);
        }
    }
}

From source file:org.deegree.enterprise.servlet.OGCServletController.java

@Override
public void destroy() {
    super.destroy();
    Enumeration<Driver> e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        Driver driver = e.nextElement();
        try {//from  w  w  w.j  a  v  a  2 s.co  m
            if (driver.getClass().getClassLoader() == getClass().getClassLoader())
                DriverManager.deregisterDriver(driver);
        } catch (SQLException e1) {
            LOG.logError("Cannot unload driver: " + driver);
        }
    }
    LogFactory.releaseAll();
    LogManager.shutdown();
    // SLF4JLogFactory.releaseAll(); // should be the same as the LogFactory.releaseAll call
    Iterator<Class<?>> i = IIORegistry.getDefaultInstance().getCategories();
    while (i.hasNext()) {
        Class<?> c = i.next();
        Iterator<?> k = IIORegistry.getDefaultInstance().getServiceProviders(c, false);
        while (k.hasNext()) {
            Object o = k.next();
            if (o.getClass().getClassLoader() == getClass().getClassLoader()) {
                IIORegistry.getDefaultInstance().deregisterServiceProvider(o);
                LOG.logDebug("Deregistering JAI driver ", o.getClass());
            }
        }
    }
    Introspector.flushCaches();
    // just clear the configurations for now, it does not hurt
    CRSConfiguration.DEFINED_CONFIGURATIONS.clear();
}

From source file:org.enhydra.jdbc.standard.StandardDataSource.java

protected StandardDataSource(Driver drv) throws SQLException {
    this();/*from  w ww  .  j  av  a 2s  .c o  m*/
    driver = drv;
    driverName = drv.getClass().getName();
    setLogger(new Logger(LogFactory.getLog("org.enhydra.jdbc.xapool")));
}

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.
 *///  www .  j a  v a  2s. 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.jumpmind.db.util.BasicDataSourceFactory.java

public static void prepareDriver(String clazzName) throws Exception {
    Driver driver = (Driver) Class.forName(clazzName).newInstance();
    synchronized (DriverManager.class) {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver2 = (Driver) drivers.nextElement();
            /* /*from ww  w .  ja  v a2  s.c  o m*/
             * MySQL and Maria DB drivers cannot co-exist because
             * they use the same JDBC URL.
             */
            if ((driver.getClass().getName().equals("com.mysql.jdbc.Driver")
                    && driver2.getClass().getName().equals("org.mariadb.jdbc.Driver"))
                    || (driver.getClass().getName().equals("org.mariadb.jdbc.Driver")
                            && driver2.getClass().getName().equals("com.mysql.jdbc.Driver"))) {
                DriverManager.deregisterDriver(driver2);
            }
        }
    }
}

From source file:org.mifos.framework.ApplicationInitializer.java

private void unregisterMySQLDriver() {
    // unregister any jdbc drivers (mysql driver)
    try {//from   ww w.jav a2 s  .c  o m
        for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {
            Driver driver = e.nextElement();
            if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                DriverManager.deregisterDriver(driver);
            }
        }
    } catch (Exception e) {
        logger.error("can't unregister jdbc drivers", e);
    }
}