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:net.big_oh.common.jdbc.JdbcDriverProxy.java

private final Driver lookupDelegateDriver(String url) throws SQLException {
    if (!url.startsWith(getJdbcObserverUrlPrefix())) {
        logger.debug("Requested url '" + url + "' is not recognized by " + this.getClass().getName());
        return null;
    }//w w w.j a  v  a  2  s .com

    url = stripJdbcObserverPrefixFromUrl(url);

    for (Driver delegateDriverCandidate : CollectionsUtil.toIterable(DriverManager.getDrivers())) {
        if (delegateDriverCandidate != this && delegateDriverCandidate.acceptsURL(url)) {
            logger.debug("Selected driver " + delegateDriverCandidate.getClass().getName() + " to service url '"
                    + url + "'");
            registerMostRecentDelegateDriver(mostRecentDelegateDriver);
            return delegateDriverCandidate;
        }
    }

    logger.warn("Failed to find an appropriate delegate driver for url '" + url + "'");
    logger.warn(
            "Maybe you need to load the delegate Driver class by calling 'Class.forName(com.somepackage.SomeDriver);' or by updating the overridden getDriverClassNamesToAutoLoad() method ?");
    return null;

}

From source file:de.innovationgate.webgate.api.jdbc.pool.DBCPConnectionProvider.java

public void configure(Map propsMap) throws HibernateException {
    try {/*from  w  w w . ja  va 2s . co  m*/
        log.debug("Configure DBCPConnectionProvider");
        Properties props = new Properties();
        props.putAll(propsMap);

        String jdbcUrl = (String) props.getProperty(Environment.URL);

        // DBCP properties used to create the BasicDataSource
        Properties dbcpProperties = new Properties();

        // DriverClass & url
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);

        // Try to determine driver by jdbc-URL
        if (jdbcDriverClass == null) {
            Driver driver = DriverManager.getDriver(jdbcUrl);
            if (driver != null) {
                jdbcDriverClass = driver.getClass().getName();
            } else {
                throw new HibernateException("Driver class not available");
            }
        }

        dbcpProperties.put("driverClassName", jdbcDriverClass);
        dbcpProperties.put("url", jdbcUrl);

        // Username / password
        String username = props.getProperty(Environment.USER);
        if (username != null) {
            dbcpProperties.put("username", username);
        }

        String password = props.getProperty(Environment.PASS);
        if (password != null) {
            dbcpProperties.put("password", password);
        }

        // Isolation level
        String isolationLevel = props.getProperty(Environment.ISOLATION);
        if ((isolationLevel != null) && (isolationLevel.trim().length() > 0)) {
            dbcpProperties.put("defaultTransactionIsolation", isolationLevel);
        }

        // Turn off autocommit (unless autocommit property is set) 
        String autocommit = props.getProperty(AUTOCOMMIT);
        if ((autocommit != null) && (autocommit.trim().length() > 0)) {
            dbcpProperties.put("defaultAutoCommit", autocommit);
        } else {
            dbcpProperties.put("defaultAutoCommit", String.valueOf(Boolean.FALSE));
        }

        // Pool size
        String poolSize = props.getProperty(Environment.POOL_SIZE);
        if ((poolSize != null) && (poolSize.trim().length() > 0) && (Integer.parseInt(poolSize) > 0)) {
            dbcpProperties.put("maxActive", poolSize);
        }

        // Copy all "driver" properties into "connectionProperties"
        Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props);
        if (driverProps.size() > 0) {
            StringBuffer connectionProperties = new StringBuffer();
            for (Iterator iter = driverProps.keySet().iterator(); iter.hasNext();) {
                String key = (String) iter.next();
                String value = driverProps.getProperty(key);
                connectionProperties.append(key).append('=').append(value);
                if (iter.hasNext()) {
                    connectionProperties.append(';');
                }
            }
            dbcpProperties.put("connectionProperties", connectionProperties.toString());
        }

        // Copy all DBCP properties removing the prefix
        for (Iterator iter = props.keySet().iterator(); iter.hasNext();) {
            String key = String.valueOf(iter.next());
            if (key.startsWith(PREFIX)) {
                String property = key.substring(PREFIX.length());
                String value = props.getProperty(key);
                dbcpProperties.put(property, value);
            }
        }

        // Backward-compatibility
        if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
            dbcpProperties.put("poolPreparedStatements", String.valueOf(Boolean.TRUE));
            dbcpProperties.put("maxOpenPreparedStatements", props.getProperty(DBCP_PS_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXACTIVE) != null) {
            dbcpProperties.put("maxTotal", props.getProperty(DBCP_MAXACTIVE));
        }
        if (props.getProperty(DBCP_MAXWAIT) != null) {
            dbcpProperties.put("maxWaitMillis", props.getProperty(DBCP_MAXWAIT));
        }

        // Some debug info
        if (log.isDebugEnabled()) {
            log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
            StringWriter sw = new StringWriter();
            dbcpProperties.list(new PrintWriter(sw, true));
            log.debug(sw.toString());
        }

        String dbKey = (String) props.get("hibernate.dbcp.dbkey");
        String databaseServerId = (String) props.get("hibernate.dbcp.dbserver.id");

        // Enable DBCP2 JMX monitoring information
        if (dbKey != null) {
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey));
        } else if (databaseServerId != null) {
            String entityTitle = props.getProperty("hibernate.dbcp.dbserver.title");
            dbcpProperties.put("jmxName",
                    JMX_DBCP2_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(entityTitle));
        }

        // Let the factory create the pool
        _ds = BasicDataSourceFactory.createDataSource(dbcpProperties);
        _ds.setLogExpiredConnections(false);

        // The BasicDataSource has lazy initialization
        // borrowing a connection will start the DataSource
        // and make sure it is configured correctly.
        Connection conn = _ds.getConnection();
        conn.close();

        // Create Legacy JMX monitoring information, provided by WGA
        if ("true".equals(props.getProperty("hibernate.dbcp.legacyJMX"))) {
            try {
                if (dbKey != null) {
                    _entityKey = dbKey;
                    _entityTitle = dbKey;
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this),
                            new ObjectName(JMX_DBPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(dbKey)));
                } else if (databaseServerId != null) {
                    _server = true;
                    _entityKey = databaseServerId;
                    _entityTitle = (String) props.get("hibernate.dbcp.dbserver.title");
                    _jmxManager = new JmxManager(new DBCPPoolInformation(this), new ObjectName(
                            JMX_SERVERPOOLS_ADDRESS + ",pool=" + JmxManager.normalizeJmxKey(_entityTitle)));
                }
            } catch (Throwable e) {
                log.error("Error enabling JMX metrics for connection pool", e);
            }
        }

    } catch (Exception e) {
        String message = "Could not create a DBCP pool";
        if (_ds != null) {
            try {
                _ds.close();
            } catch (Exception e2) {
                // ignore
            }
            _ds = null;
        }
        throw new HibernateException(message, e);
    }
    log.debug("Configure DBCPConnectionProvider complete");

}

From source file:com.jaspersoft.jasperserver.api.common.service.impl.JdbcDriverServiceImpl.java

private void registerDriver(String driverClassName, Class driverClass, ClassLoader driverClassLoader)
        throws Exception {
    Driver driver = null;//from w  ww . j  a va  2  s.c  o  m
    String oldUrl = driverClassToUrlMap.get(driverClassName);

    if (driverClassLoader != getSystemClassLoader()) {
        //Need to register driver shim, since it was loaded not by system class loader
        Driver driverFromRepository = (Driver) driverClass.newInstance();

        //Create and register shim for jdbc driver
        driver = new JdbcDriverShim(driverFromRepository);
        registerDriverInJVM(driver);

        if (getUrlByDriverClassName(driverClassName) == null) {
            String url = classLoaderToUrlMap.get(driverClassLoader);
            driverClassToUrlMap.put(driverClassName, url);
            mapDriverToClassLoaderInGlobalPropertiesList(driverClassName, url, oldUrl);
        }
    } else {
        Enumeration<Driver> driverEnumeration = getDriversRegisteredInJVM();
        while (driverEnumeration.hasMoreElements()) {
            Driver nextDriver = driverEnumeration.nextElement();
            if (nextDriver.getClass().equals(driverClass)) {
                driver = nextDriver;
                break;
            }
        }
        if (driver == null) {
            driver = (Driver) driverClass.newInstance();
            registerDriverInJVM(driver);
        }
        driverClassToUrlMap.put(driverClassName, SYSTEM_CLASSLOADER_PATH);
        classLoaderToUrlMap.put(driverClassLoader, SYSTEM_CLASSLOADER_PATH);
        mapDriverToClassLoaderInGlobalPropertiesList(driverClassName, SYSTEM_CLASSLOADER_PATH, oldUrl);
    }

    if (driver != null) {
        driverClassToDriverMap.put(driverClassName, driver);
        driverToClassLoaderMap.put(driver, driverClassLoader);
    } else {
        throw new IllegalStateException(String.format(
                "Driver was loaded by System class loader but not registered in DriverManager: [%s]",
                driverClassName));
    }
}

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;
        }/*ww  w  .ja  va2 s. c om*/

        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;
}

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

public Connection connect(String url, Properties connectionProperties) throws SQLException {
    Driver delegateDriver = lookupDelegateDriver(url);

    if (delegateDriver == null) {
        // return null per the API guidelines
        return null;
    }/*  www  . j  a va2  s .  c  om*/

    url = stripJdbcObserverPrefixFromUrl(url);

    ConnectionInstantiationEvent connectionInstantiationEvent = new ConnectionInstantiationEvent(this,
            delegateDriver, url, connectionProperties);

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionRequested(connectionInstantiationEvent);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    Connection newConnection = delegateDriver.connect(url, connectionProperties);

    if (newConnection == null) {
        throw new SQLException("Failed to connect to url '" + url + "' using delegate driver "
                + delegateDriver.getClass().getName());
    }

    // Create a proxy for the returned connection
    boolean newConnectionInterfacesContainsConnection = Arrays.asList(newConnection.getClass().getInterfaces())
            .contains(Connection.class);
    Class<?>[] interfaces = new Class<?>[(newConnection.getClass().getInterfaces().length
            + ((newConnectionInterfacesContainsConnection) ? 0 : 1))];
    System.arraycopy(newConnection.getClass().getInterfaces(), 0, interfaces, 0,
            newConnection.getClass().getInterfaces().length);
    if (!newConnectionInterfacesContainsConnection) {
        interfaces[newConnection.getClass().getInterfaces().length] = Connection.class;
    }
    Connection connectionProxy = (Connection) Proxy.newProxyInstance(this.getClass().getClassLoader(),
            interfaces, new JdbcObserverProxyConnectionInvocationHandler(newConnection, listeners));

    for (JDBCEventListener listener : listeners) {
        try {
            listener.connectionInstantiated(connectionInstantiationEvent, connectionProxy);
        } catch (RuntimeException rte) {
            logger.error(rte);
        }
    }

    return connectionProxy;
}

From source file:edu.tamu.tcat.db.core.AbstractDataSourceFactory.java

/**
 * Create a new {@link BasicDataSource} from the specified {@link DSProperties}
 *//*from   www  .  j a  v  a 2 s.c  om*/
protected synchronized BasicDataSource createDataSource(final Properties parameters)
        throws DataSourceException {
    BasicDataSource dataSource;
    final Driver driver = getDriver();
    final String connectionUrl = getConnectionUrl(parameters);
    final Properties connectionProps = getConnectionProperties(parameters);

    dataSource = new BasicDataSource() {
        @Override
        protected ConnectionFactory createConnectionFactory() throws SQLException {
            //The loading of the driver via class-loader does not work properly in OSGI.

            if (driver.acceptsURL(getUrl())) {
                if (getValidationQuery() == null) {
                    setTestOnBorrow(false);
                    setTestOnReturn(false);
                    setTestWhileIdle(false);
                }

                ConnectionFactory driverConnectionFactory = new DriverConnectionFactory(driver, connectionUrl,
                        connectionProps);
                return driverConnectionFactory;
            }
            return super.createConnectionFactory();
        }
    };
    //         dataSource.setDriverClassLoader(Driver.class.getClassLoader());
    // should be included in the connection properties and not needed
    //        dataSource.setUsername(key.getUsername());
    //        dataSource.setPassword(key.getPassword());
    dataSource.setDriverClassName(driver.getClass().getName());
    dataSource.setUrl(connectionUrl);
    dataSource.setMaxActive(getMaxActiveConnections(parameters));
    dataSource.setMaxIdle(getMaxIdleConnections(parameters));
    dataSource.setMinIdle(0);
    dataSource.setMinEvictableIdleTimeMillis(10000);
    dataSource.setTimeBetweenEvictionRunsMillis(1000);
    dataSource.setLogAbandoned(true);
    dataSource.setRemoveAbandoned(true);//seconds
    dataSource.setRemoveAbandonedTimeout(60);
    return dataSource;
}

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

/**
 * Deregister JDBC drivers loaded by web app classloader
 *///from  w  ww .  j  ava2 s .  c  om
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:orca.util.db.MySqlBase.java

/**
 * Deregister the sun ODBC bridge driver. We don't need it and it is broken
 * on some platforms//ww  w  .  j a v  a 2s. c  o m
 */
protected void checkDrivers() {
    try {
        logger.debug(DriverManager.getDriver(source + pool));

        Enumeration<Driver> drivers = DriverManager.getDrivers();
        Driver odbcDriver;

        if ((odbcDriver = drivers.nextElement()) != null) {
            if (odbcDriver.getClass().getName().matches(".*odbc.*")) {
                DriverManager.deregisterDriver(odbcDriver);
                logger.debug("Deregistering " + odbcDriver);
            }
        }
    } catch (Exception e) {
    }
}

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

/**
 * destroy the loader tree//from  w w w . ja v  a  2  s . co  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");
}