@Test
 public void testOneDriver() throws Exception {
   DriverManager.registerDriver(new TestDriver());
   DriverManager.registerDriver(new TestDriver());
   getJDBCMockObjectFactory();
   Enumeration drivers = DriverManager.getDrivers();
   assertTrue(drivers.nextElement() instanceof MockDriver);
   assertFalse(drivers.hasMoreElements());
   super.tearDown();
   drivers = DriverManager.getDrivers();
   assertTrue(drivers.hasMoreElements());
   drivers.nextElement();
   assertTrue(drivers.hasMoreElements());
 }
Esempio n. 2
0
 @Override
 public void processPostRecording() {
   Enumeration<Driver> drivers = java.sql.DriverManager.getDrivers();
   if ((drivers != null) && !drivers.hasMoreElements()) {
     Factory.getManager().unregisterFactory(SoleilArcFactory.NAME);
   }
 }
Esempio n. 3
0
 /**
  * Must be executed as part of a test suite that opens the database connection.
  *
  * @throws Exception Flow network error.
  */
 @Override
 protected void define() throws Exception {
   /**
    * String userHome = System.getProperty("user.home"); StringBuilder sb = new StringBuilder();
    * String[] subStr = userHome.split("\\Q\\\\E"); for (String subStr1 : subStr) {
    * sb.append(subStr1); sb.append("/"); } sb.append(".fbpTest/db"); String dbName =
    * sb.toString(); String connectionURL = "jdbc:derby:" + dbName + ";create=true";
    * System.out.println("Insert Test '" + connectionURL + "'");
    * SingletonDbWrapper.instance().setConnectionUrl(connectionURL);
    *
    * <p>conn = SingletonDbWrapper.instance().getConnection();
    */
   Enumeration<Driver> dList = DriverManager.getDrivers();
   while (dList.hasMoreElements()) {
     Driver aDriver = dList.nextElement();
     System.out.println(aDriver.toString());
   }
   tableStruct();
   component("DbInsert", Insert.class);
   component("Output", Output.class);
   connect(
       component("DbInsert"), port(Insert.OP),
       component("Output"), port("IN"));
   //  connect("DbInsert.COMPLETION_STATUS", "Output.IN");
   String insertStmt = "INSERT INTO TEST_ONE (TEXT_STRING, INT_VALUE)" + " VALUES (?, ?)";
   Map<String, Object> params = new HashMap();
   params.put(RDB_CONNECTION, conn);
   params.put(SQL_INSERT_STATEMENT_KEY, insertStmt);
   params.put(Integer.toString(0), "String");
   params.put(Integer.toString(1), "Integer");
   initialize(params, component("DbInsert"), port(Insert.IIP));
   String[] recd01 = {"First Value", "12"};
   initialize(recd01, component("DbInsert"), port(Insert.IP));
 }
Esempio n. 4
0
  /*
   * (non-Javadoc)
   *
   * @see
   * com.absir.bean.config.IBeanFactoryStopping#stopping(com.absir.bean.basis
   * .BeanFactory)
   */
  @Override
  public void stopping(BeanFactory beanFactory) {
    LOGGER.info("stop begin");
    stopConnectionProvider(sessionFactory);
    for (SessionFactoryImpl sessionFactory : sessionFactoryMapName.keySet()) {
      stopConnectionProvider(sessionFactory);
    }

    Environment.setStarted(false);
    if (!driverShared) {
      Enumeration<Driver> enumeration = DriverManager.getDrivers();
      while (enumeration.hasMoreElements()) {
        Driver driver = enumeration.nextElement();
        try {
          DriverManager.deregisterDriver(driver);

        } catch (Exception e) {
          LOGGER.error("deregisterDriver " + driver, e);
        }
      }
    }

    if (driverStoppingCommand != null) {
      for (String stoppingCommand : driverStoppingCommand) {
        KernelClass.invokeCommandString(stoppingCommand);
      }

      driverStoppingCommand = null;
    }

    LOGGER.info("stop complete");
  }
  public void contextDestroyed(ServletContextEvent sce) {

    // This manually deregisters JDBC driver, which prevents Tomcat 7 from complaining about memory
    // leaks wrto 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.warn(String.format("Error deregistering driver %s", driver), e);
      }
    }

    // Try to kill the TOMCAT abandoned connection clean up thread
    // to prevent it from holding the whole context in memory causing
    // a leak

    Set<Thread> threadSet = Thread.getAllStackTraces().keySet();
    Thread[] threadArray = threadSet.toArray(new Thread[threadSet.size()]);

    for (Thread t : threadArray) {
      if (t.getName().contains("Abandoned connection cleanup thread")) {
        synchronized (t) {
          t.stop(); // don't complain, it works
        }
      }
    }
  }
 @Override
 public void destroy() {
   super.destroy();
   Enumeration<Driver> e = DriverManager.getDrivers();
   while (e.hasMoreElements()) {
     Driver driver = e.nextElement();
     try {
       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();
 }
  /**
   * Context destroyed.
   *
   * @param sce the sce
   */
  @Override
  public void contextDestroyed(ServletContextEvent sce) {

    ConnectionPool connectionPool;
    connectionPool = ConnectionPool.getInstance();
    connectionPool.shutDown();

    //  ShutDown Abandoned Connection  :  memory leaks after Tomcat stops
    try {
      AbandonedConnectionCleanupThread.shutdown();
      LOG.info("Abandoned connection shut down!");
    } catch (InterruptedException e) {
      LOG.warn("SEVERE problem cleaning up: " + e.getMessage());
      e.printStackTrace();
    }
    //  This manually deregisters JDBC driver, which prevents Tomcat  from complaining about memory
    // leaks 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);
      }
    }
  }
Esempio n. 8
0
  private void initializeDriver() {
    if (_jdbcUrl == null) {
      throw new IllegalStateException("JDBC URL is null, cannot create connection!");
    }

    logger.debug("Determining if driver initialization is nescesary");

    // it's best to avoid initializing the driver, so we do this check.
    // It may already have been initialized and Class.forName(...) does
    // not always work if the driver is in a different classloader
    boolean installDriver = true;

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      try {
        if (driver.acceptsURL(_jdbcUrl)) {
          installDriver = false;
          break;
        }
      } catch (Exception e) {
        logger.warn("Driver threw exception when acceptURL(...) was invoked", e);
      }
    }

    if (installDriver) {
      try {
        Class.forName(_driverClass);
      } catch (ClassNotFoundException e) {
        throw new IllegalStateException("Could not initialize JDBC driver", e);
      }
    }
  }
Esempio n. 9
0
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   java.util.Enumeration e = java.sql.DriverManager.getDrivers();
   while (e.hasMoreElements()) {
     Object driverAsObject = e.nextElement();
     System.out.println("JDBC Driver=" + driverAsObject);
   }
 }
Esempio n. 10
0
 /**
  * Clearing the in-memory configuration parameters, we will receive notification that the servlet
  * context is about to be shut down
  */
 @Override
 public void contextDestroyed(ServletContextEvent sce) {
   synchronized (servletContext) {
     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();
       // 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 the persistence thread
       FilePersistenceThread persistenceThread = FilePersistenceThread.getInstance();
       if (persistenceThread != null) {
         persistenceThread.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();
       }
       getContextLoader().closeWebApplicationContext(ctx);
       //				org.apache.commons.logging.LogFactory.releaseAll();
       //				org.apache.log4j.LogManager.getLoggerRepository().shutdown();
       //				org.apache.log4j.LogManager.shutdown();
     } catch (Throwable e) {
       e.printStackTrace();
     }
   }
 }
 @Test
 public void testCreate() throws Exception {
   JDBCMockObjectFactory factory = new JDBCMockObjectFactory();
   assertTrue(
       factory.getMockDriver().connect("", null) == factory.getMockDataSource().getConnection());
   assertNotNull(DriverManager.getConnection("test"));
   assertTrue(factory.getMockDriver().connect("", null) == DriverManager.getConnection("test"));
   Enumeration drivers = DriverManager.getDrivers();
   drivers.nextElement();
   assertFalse(drivers.hasMoreElements());
 }
Esempio n. 12
0
  public static void unloadDrivers() {
    Enumeration<Driver> drivers = DriverManager.getDrivers();

    try {
      while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        DriverManager.deregisterDriver(driver);
      }
    } catch (Exception e) {
      log.error("Error unloading the JDBC Drivers", e);
    }
  }
Esempio n. 13
0
 private static void deregisterDrivers() {
   Enumeration<Driver> drivers = DriverManager.getDrivers();
   while (drivers.hasMoreElements()) {
     Driver driver = drivers.nextElement();
     try {
       DriverManager.deregisterDriver(driver);
     } catch (SQLException e) {
       log.warn("卸载JDBC驱动失败:" + driver, e);
       log.warn("Fail to uninstall JDBC driver:" + driver, e, Locale.ENGLISH);
     }
   }
 }
Esempio n. 14
0
 public void contextDestroyed(ServletContextEvent event) {
   try {
     Introspector.flushCaches();
     for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
       Driver driver = (Driver) e.nextElement();
       if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
         DriverManager.deregisterDriver(driver);
         LOG.debug("deregistering driver: " + driver.getClass().getName());
       }
     }
   } catch (Throwable e) {
     LOG.error("Failled to cleanup ClassLoader for webapp", e);
   }
 }
Esempio n. 15
0
 private Driver getUnderlyingDriver(String url) throws SQLException {
   if (url.startsWith(JDBC_SHARDS_PREFIX)) {
     Iterable<String> urls = getUnderlyingUrls(url);
     String underlyingUrl = Iterables.get(urls, 0);
     Enumeration e = DriverManager.getDrivers();
     Driver d;
     while (e.hasMoreElements()) {
       d = (Driver) e.nextElement();
       if (d.acceptsURL(underlyingUrl)) {
         return d;
       }
     }
   }
   return null;
 }
Esempio n. 16
0
  /**
   * Given a <code>jdbc:log4</code> type URL, find the underlying real driver that accepts the URL.
   *
   * @param url JDBC connection URL.
   * @return Underlying driver for the given URL. Null is returned if the URL is not a <code>
   *     jdbc:log4</code> type URL or there is no underlying driver that accepts the URL.
   * @throws SQLException if a database access error occurs.
   */
  private Driver getUnderlyingDriver(String url) throws SQLException {
    if (url.startsWith("jdbc:log4")) {
      url = url.substring(9);

      Enumeration e = DriverManager.getDrivers();

      Driver d;
      while (e.hasMoreElements()) {
        d = (Driver) e.nextElement();

        if (d.acceptsURL(url)) {
          return d;
        }
      }
    }
    return null;
  }
  private String defaultUrlPattern() {
    for (EmbeddedVendor vendor : EmbeddedVendor.values()) {
      String url = MessageFormat.format(vendor.pattern, "test", Strings.HA_JDBC_HOME);

      try {
        for (Driver driver : Collections.list(DriverManager.getDrivers())) {
          if (driver.acceptsURL(url)) {
            return vendor.pattern;
          }
        }
      } catch (SQLException e) {
        // Skip vendor
      }
    }

    return null;
  }
 @Test
 public void testRestoreDivers() throws Exception {
   DriverManager.registerDriver(new TestDriver());
   DriverManager.registerDriver(new TestDriver());
   ArrayList oldDrivers = new ArrayList();
   Enumeration drivers = DriverManager.getDrivers();
   while (drivers.hasMoreElements()) {
     oldDrivers.add(drivers.nextElement());
   }
   JDBCMockObjectFactory factory = new JDBCMockObjectFactory();
   new JDBCMockObjectFactory();
   new JDBCMockObjectFactory();
   drivers = DriverManager.getDrivers();
   assertTrue(drivers.nextElement() instanceof MockDriver);
   assertFalse(drivers.hasMoreElements());
   factory.restoreDrivers();
   drivers = DriverManager.getDrivers();
   int numberDrivers = 0;
   while (drivers.hasMoreElements()) {
     numberDrivers++;
     assertTrue(oldDrivers.contains(drivers.nextElement()));
   }
   factory.restoreDrivers();
   factory.restoreDrivers();
   factory.restoreDrivers();
   int newNumberDrivers = 0;
   drivers = DriverManager.getDrivers();
   while (drivers.hasMoreElements()) {
     newNumberDrivers++;
     assertTrue(oldDrivers.contains(drivers.nextElement()));
   }
   assertTrue(numberDrivers == newNumberDrivers);
   factory.registerMockDriver();
   drivers = DriverManager.getDrivers();
   numberDrivers = 0;
   while (drivers.hasMoreElements()) {
     numberDrivers++;
     assertTrue(drivers.nextElement() instanceof MockDriver);
   }
   assertTrue(numberDrivers == 1);
   factory.registerMockDriver();
   factory.registerMockDriver();
   factory.restoreDrivers();
   factory.restoreDrivers();
   drivers = DriverManager.getDrivers();
   numberDrivers = 0;
   while (drivers.hasMoreElements()) {
     numberDrivers++;
     assertTrue(oldDrivers.contains(drivers.nextElement()));
   }
   assertTrue(numberDrivers == newNumberDrivers);
 }
  private void deregisterJdbcDrivers() {
    final Enumeration<Driver> driverEnumeration = DriverManager.getDrivers();
    final List<Driver> drivers = new ArrayList<Driver>();

    while (driverEnumeration.hasMoreElements()) {
      drivers.add(driverEnumeration.nextElement());
    }

    for (Driver driver : drivers) {
      if (driver.getClass().getClassLoader() != getClass().getClassLoader()) {
        continue;
      }

      try {
        DriverManager.deregisterDriver(driver);
        deregisterOracleDiagnosabilityMBean();
      } catch (Throwable e) {
      }
    }
  }
  @Override
  public void contextDestroyed(ServletContextEvent contextEvent) {
    // stop polling TimerTask
    polling.cancel();

    // closing Hibernate SessionFactory:
    HibernateUtil.getSessionFactory().close();

    // unregisters JDBC driver
    Enumeration<Driver> drivers = DriverManager.getDrivers();

    while (drivers.hasMoreElements()) {
      Driver d = drivers.nextElement();
      try {
        DriverManager.deregisterDriver(d);
      } catch (SQLException e) {
        LOGGER.warning("Error deregistering driver '" + d.getClass().getName() + "'!");
      }
    }
  }
Esempio n. 21
0
  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    LOGGER.info("Destroying webapp..");

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
      Driver driver = drivers.nextElement();
      ClassLoader driverclassLoader = driver.getClass().getClassLoader();
      ClassLoader thisClassLoader = this.getClass().getClassLoader();
      if (driverclassLoader != null
          && thisClassLoader != null
          && driverclassLoader.equals(thisClassLoader)) {
        try {
          LOGGER.info("Deregistering: " + driver);
          DriverManager.deregisterDriver(driver);
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }
    }
  }
 public static void destroy() {
   ComboPooledDataSource tmp = pool;
   pool = null;
   try {
     tmp.resetPoolManager(true);
     tmp.hardReset();
     sleep(50);
   } catch (Exception e) {
   }
   try {
     tmp.close();
     sleep(50);
   } catch (Exception e) {
   }
   Enumeration<Driver> drivers = DriverManager.getDrivers();
   while (drivers.hasMoreElements()) {
     Driver next = drivers.nextElement();
     try {
       DriverManager.deregisterDriver(next);
     } catch (SQLException e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 23
0
  /**
   * Clean up resources used by the application when stopped
   *
   * @param event
   */
  @Override
  public void contextDestroyed(ServletContextEvent event) {
    webApp.deregister();

    try {
      // Remove the database pool
      DatabaseManager.shutdown();

      // Clean out the introspector
      Introspector.flushCaches();

      // Remove any drivers registered by this classloader
      for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
        Driver driver = (Driver) e.nextElement();
        if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
          DriverManager.deregisterDriver(driver);
        }
      }
    } catch (RuntimeException e) {
      log.error("Failed to cleanup ClassLoader for webapp", e);
    } catch (Exception e) {
      log.error("Failed to cleanup ClassLoader for webapp", e);
    }
  }
Esempio n. 24
0
  /**
   * Tests whether the given connection properties can be used to obtain a connection.
   *
   * @param driverClassName the name of driver class
   * @param connectionString the JDBC driver connection URL
   * @param jndiNameUrl the JNDI name to look up a Data Source name service; may be null or empty
   * @param userId the login user id
   * @param password the login password
   * @return true if the the specified properties are valid to obtain a connection; false otherwise
   * @throws OdaException
   */
  public boolean testConnection(
      String driverClassName,
      String connectionString,
      String jndiNameUrl,
      String userId,
      String password)
      throws OdaException {
    boolean canConnect = false;
    try {
      //	If connection is provided by driverInfo extension, use it to create connection
      if (getDriverConnectionFactory(driverClassName) != null) {
        tryCreateConnection(driverClassName, connectionString, userId, password);
        return true;
      }

      // no driverinfo extension for driverClass connectionFactory

      // if JNDI Data Source URL is defined, try use name service to get connection
      if (jndiNameUrl != null) {
        Connection jndiDSConnection =
            getJndiDSConnection(
                driverClassName,
                jndiNameUrl,
                addUserAuthenticationProperties(null, userId, password));

        if (jndiDSConnection != null) // test connection successful
        {
          closeConnection(jndiDSConnection);
          return true;
        } else if (connectionString != null && connectionString.trim().length() > 0) {
          return testConnection(driverClassName, connectionString, userId, password);
        } else {
          throw new JDBCException(ResourceConstants.CANNOT_PARSE_JNDI, null);
        }
      }

      // no JNDI Data Source URL defined, or
      // not able to get a JNDI data source connection,
      // use the JDBC DriverManager instead to get a JDBC connection
      loadAndRegisterDriver(driverClassName, null);

      // If the connections built upon the given driver has been tested
      // once,
      // it will be add to cachedDrivers hashmap so that next time we can
      // directly
      // test the connection using specific driver rather than iterate all
      // available
      // drivers in DriverManager

      if (cachedDriversMap.get(driverClassName) == null) {
        Enumeration enumeration = DriverManager.getDrivers();
        while (enumeration.hasMoreElements()) {
          Driver driver = (Driver) enumeration.nextElement();

          // The driver might be a wrapped driver. The toString()
          // method
          // of a wrapped driver is overriden
          // so that the name of driver being wrapped is returned.
          if (isExpectedDriver(driver, driverClassName)) {
            if (driver.acceptsURL(connectionString)) {
              cachedDriversMap.put(driverClassName, driver);
              // if connection can be built then the test
              // connection
              // succeed. Otherwise Exception would be thrown. The
              // source
              // of the exception is
              tryCreateConnection(driverClassName, connectionString, userId, password);
              canConnect = true;
              break;
            }
          }
        }
        // If the test url can be accepted by DriverManager (because the
        // driver which can pass
        // that url has been registered.) but a connection
        // cannot be built using driver whose name is given, throw a
        // exception.
        if (!canConnect) throw new JDBCException(ResourceConstants.CANNOT_PARSE_URL, null);
      } else {
        if (((Driver) this.cachedDriversMap.get(driverClassName)).acceptsURL(connectionString)) {
          tryCreateConnection(driverClassName, connectionString, userId, password);
          canConnect = true;
        }
      }
    } catch (SQLException e) {
      throw new JDBCException(e.getLocalizedMessage(), null);
    }
    // If the given url cannot be parsed.
    if (canConnect == false) throw new JDBCException(ResourceConstants.NO_SUITABLE_DRIVER, null);

    return true;
  }
Esempio n. 25
0
 /**
  * Indicates whether JDBC is set up so that it might work.
  *
  * @return true iff any JDBC drivers are installed
  */
 public static boolean isSqlAvailable() {
   return DriverManager.getDrivers().hasMoreElements();
 }
Esempio n. 26
0
 protected static void printAllDrivers() {
   for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements(); ) {
     LOG.info("DRIVER FOUND: " + e.nextElement());
   }
 }
  /**
   * 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.
   */
  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) {
        LOGGER.severe("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();
    }
  }
  public void lifecycleEvent(LifecycleEvent event) {
    // Initialise these classes when Tomcat starts
    if (Lifecycle.INIT_EVENT.equals(event.getType())) {

      ClassLoader loader = Thread.currentThread().getContextClassLoader();

      try {
        // Use the system classloader as the victim for all this
        // ClassLoader pinning we're about to do.
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        /*
         * First call to this loads all drivers in the current class
         * loader
         */
        if (driverManagerProtection) {
          DriverManager.getDrivers();
        }

        /*
         * Several components end up calling:
         * sun.awt.AppContext.getAppContext()
         *
         * Those libraries / components known to trigger memory leaks
         * due to eventual calls to getAppContext() are:
         * - Google Web Toolkit via its use of javax.imageio
         * - Tomcat via its use of java.beans.Introspector.flushCaches()
         *   in 1.6.0_15 onwards
         * - others TBD
         */

        // Trigger a call to sun.awt.AppContext.getAppContext(). This
        // will pin the system class loader in memory but that shouldn't
        // be an issue.
        if (appContextProtection) {
          ImageIO.getCacheDirectory();
        }

        // Trigger the creation of the AWT (AWT-Windows, AWT-XAWT,
        // etc.) thread
        if (awtThreadProtection) {
          java.awt.Toolkit.getDefaultToolkit();
        }

        /*
         * Several components end up calling
         * sun.misc.GC.requestLatency(long) which creates a daemon
         * thread without setting the TCCL.
         *
         * Those libraries / components known to trigger memory leaks
         * due to eventual calls to requestLatency(long) are:
         * - javax.management.remote.rmi.RMIConnectorServer.start()
         *
         * Note: Long.MAX_VALUE is a special case that causes the thread
         *       to terminate
         *
         */
        if (gcDaemonProtection) {
          try {
            Class<?> clazz = Class.forName("sun.misc.GC");
            Method method = clazz.getDeclaredMethod("requestLatency", new Class[] {long.class});
            method.invoke(null, Long.valueOf(Long.MAX_VALUE - 1));
          } catch (ClassNotFoundException e) {
            if (System.getProperty("java.vendor").startsWith("Sun")) {
              log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
            } else {
              log.debug(sm.getString("jreLeakListener.gcDaemonFail"), e);
            }
          } catch (SecurityException e) {
            log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
          } catch (NoSuchMethodException e) {
            log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
          } catch (IllegalArgumentException e) {
            log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
          } catch (IllegalAccessException e) {
            log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
          } catch (InvocationTargetException e) {
            log.error(sm.getString("jreLeakListener.gcDaemonFail"), e);
          }
        }

        /*
         * Calling getPolicy retains a static reference to the context
         * class loader.
         */
        if (securityPolicyProtection) {
          try {
            // Policy.getPolicy();
            Class<?> policyClass = Class.forName("javax.security.auth.Policy");
            Method method = policyClass.getMethod("getPolicy");
            method.invoke(null);
          } catch (ClassNotFoundException e) {
            // Ignore. The class is deprecated.
          } catch (SecurityException e) {
            // Ignore. Don't need call to getPolicy() to be
            // successful, just need to trigger static initializer.
          } catch (NoSuchMethodException e) {
            log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
          } catch (IllegalArgumentException e) {
            log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
          } catch (IllegalAccessException e) {
            log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
          } catch (InvocationTargetException e) {
            log.warn(sm.getString("jreLeakListener.authPolicyFail"), e);
          }
        }

        /*
         * Initializing javax.security.auth.login.Configuration retains a static reference to the context
         * class loader.
         */
        if (securityLoginConfigurationProtection) {
          try {
            Class.forName(
                "javax.security.auth.login.Configuration",
                true,
                ClassLoader.getSystemClassLoader());
          } catch (ClassNotFoundException e) {
            // Ignore
          }
        }

        /*
         * Creating a MessageDigest during web application startup
         * initializes the Java Cryptography Architecture. Under certain
         * conditions this starts a Token poller thread with TCCL equal
         * to the web application class loader.
         *
         * Instead we initialize JCA right now.
         */
        if (tokenPollerProtection) {
          java.security.Security.getProviders();
        }

        /*
         * Several components end up opening JarURLConnections without
         * first disabling caching. This effectively locks the file.
         * Whilst more noticeable and harder to ignore on Windows, it
         * affects all operating systems.
         *
         * Those libraries/components known to trigger this issue
         * include:
         * - log4j versions 1.2.15 and earlier
         * - javax.xml.bind.JAXBContext.newInstance()
         */

        // Set the default URL caching policy to not to cache
        if (urlCacheProtection) {
          try {
            // Doesn't matter that this JAR doesn't exist - just as
            // long as the URL is well-formed
            URL url = new URL("jar:file://dummy.jar!/");
            URLConnection uConn = url.openConnection();
            uConn.setDefaultUseCaches(false);
          } catch (MalformedURLException e) {
            log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
          } catch (IOException e) {
            log.error(sm.getString("jreLeakListener.jarUrlConnCacheFail"), e);
          }
        }

        /*
         * Haven't got to the root of what is going on with this leak
         * but if a web app is the first to make the calls below the web
         * application class loader will be pinned in memory.
         */
        if (xmlParsingProtection) {
          DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
          try {
            factory.newDocumentBuilder();
          } catch (ParserConfigurationException e) {
            log.error(sm.getString("jreLeakListener.xmlParseFail"), e);
          }
        }

        if (ldapPoolProtection) {
          try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
          } catch (ClassNotFoundException e) {
            if (System.getProperty("java.vendor").startsWith("Sun")) {
              log.error(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
            } else {
              log.debug(sm.getString("jreLeakListener.ldapPoolManagerFail"), e);
            }
          }
        }

        if (classesToInitialize != null) {
          StringTokenizer strTok = new StringTokenizer(classesToInitialize, ", \r\n\t");
          while (strTok.hasMoreTokens()) {
            String classNameToLoad = strTok.nextToken();
            try {
              Class.forName(classNameToLoad);
            } catch (ClassNotFoundException e) {
              log.error(sm.getString("jreLeakListener.classToInitializeFail", classNameToLoad), e);
              // continue with next class to load
            }
          }
        }

      } finally {
        Thread.currentThread().setContextClassLoader(loader);
      }
    }
  }
 static {
   // Attempt to prevent deadlocks - see DBCP - 272
   DriverManager.getDrivers();
 }