Exemple #1
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);
   }
 }
 @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();
 }
Exemple #3
0
  public Sql2oTest(Driver driverToRegister, String url, String user, String pass, String testName) {

    if (driverToRegister != null) {
      try {
        DriverManager.registerDriver(driverToRegister);
      } catch (SQLException e) {
        throw new RuntimeException(
            "could not register driver '" + driverToRegister.getClass().getName() + "'", e);
      }
    }

    this.sql2o = new Sql2o(url, user, pass);

    HashMap<String, String> defaultColumnMap = new HashMap<String, String>();
    defaultColumnMap.put("ID", "id");
    defaultColumnMap.put("NAME", "name");
    defaultColumnMap.put("EMAIL", "email");
    defaultColumnMap.put("TEXT", "text");
    defaultColumnMap.put("ANUMBER", "aNumber");
    defaultColumnMap.put("ALONGNUMBER", "aLongNumber");
    sql2o.setDefaultColumnMappings(defaultColumnMap);

    this.url = url;
    this.user = user;
    this.pass = pass;

    if ("HyperSQL DB test".equals(testName)) {
      sql2o.createQuery("set database sql syntax MSS true").executeUpdate();
    }
  }
  /**
   * Get a Connection to the database from the underlying driver that this DriverSpy is spying on.
   * If logging is not enabled, an actual Connection to the database returned. If logging is
   * enabled, a ConnectionSpy object which wraps the real Connection is returned.
   *
   * @param url JDBC connection URL .
   * @param info a list of arbitrary string tag/value pairs as connection arguments. Normally at
   *     least a "user" and "password" property should be included.
   * @return a <code>Connection</code> object that represents a connection to the URL.
   * @throws SQLException if a database access error occurs
   */
  public Connection connect(String url, Properties info) throws SQLException {
    Driver d = getUnderlyingDriver(url);
    if (d == null) {
      return null;
    }

    // get actual URL that the real driver expects
    // (strip off "jdbc:log4" from url)
    url = url.substring(9);

    lastUnderlyingDriverRequested = d;
    Connection c = d.connect(url, info);

    if (c == null) {
      throw new SQLException("invalid or unknown driver url: " + url);
    }
    if (log.isJdbcLoggingEnabled()) {
      ConnectionSpy cspy = new ConnectionSpy(c);
      RdbmsSpecifics r = null;
      String dclass = d.getClass().getName();
      if (dclass != null && dclass.length() > 0) {
        r = (RdbmsSpecifics) rdbmsSpecifics.get(dclass);
      }

      if (r == null) {
        r = defaultRdbmsSpecifics;
      }
      cspy.setRdbmsSpecifics(r);
      return cspy;
    } else {
      return c;
    }
  }
  public static void connectToDB() throws Exception {
    if (connection == null) {
      info = new Properties();
      info.load(new FileInputStream("src/java-test/tests.properties"));

      url = info.getProperty("url");
      driver =
          (Driver)
              Class.forName(
                      DatabaseFactory.getInstance().findDefaultDriver(url),
                      true,
                      Thread.currentThread().getContextClassLoader())
                  .newInstance();

      connection = driver.connect(url, info);

      if (connection == null) {
        throw new DatabaseException(
            "Connection could not be created to "
                + url
                + " with driver "
                + driver.getClass().getName()
                + ".  Possibly the wrong driver for the given database URL");
      }

      jdbcConnection = new JdbcConnection(connection);
    }
  }
 /**
  * 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();
     }
   }
 }
  private String findDriverByUrlImpl(String url) {
    for (int i = 0; i < _driverList.size(); i++) {
      try {
        Driver driver = (Driver) _driverList.get(i);

        if (driver.acceptsURL(url)) return driver.getClass().getName();
      } catch (Exception e) {
        log.log(Level.FINE, e.toString(), e);
      }
    }

    return null;
  }
	// 关闭所有连接,撤销驱动程序的注册
	public synchronized void release() {
		// 等待直到最后一个客户程序调用
		if (--clients != 0) {
			return;
		}

		Enumeration allPools = pools.elements();
		while (allPools.hasMoreElements()) {
			DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
			pool.release();
		}
		Enumeration allDrivers = drivers.elements();
		while (allDrivers.hasMoreElements()) {
			Driver driver = (Driver) allDrivers.nextElement();
			try {
				DriverManager.deregisterDriver(driver);
				log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");
			} catch (SQLException e) {
				log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
			}
		}
	}
  private void initDriverList() {
    try {
      Thread thread = Thread.currentThread();
      ClassLoader loader = thread.getContextClassLoader();

      Enumeration iter = loader.getResources("META-INF/services/java.sql.Driver");
      while (iter.hasMoreElements()) {
        URL url = (URL) iter.nextElement();

        ReadStream is = null;
        try {
          is = Vfs.lookup(url.toString()).openRead();

          String filename;

          while ((filename = is.readLine()) != null) {
            int p = filename.indexOf('#');

            if (p >= 0) filename = filename.substring(0, p);

            filename = filename.trim();
            if (filename.length() == 0) continue;

            try {
              Class cl = Class.forName(filename, false, loader);
              Driver driver = null;

              if (Driver.class.isAssignableFrom(cl)) driver = (Driver) cl.newInstance();

              if (driver != null) {
                log.fine(L.l("DatabaseManager adding driver '{0}'", driver.getClass().getName()));

                _driverList.add(driver);
              }
            } catch (Exception e) {
              log.log(Level.FINE, e.toString(), e);
            }
          }
        } catch (Exception e) {
          log.log(Level.FINE, e.toString(), e);
        } finally {
          if (is != null) is.close();
        }
      }
    } catch (Exception e) {
      log.log(Level.FINE, e.toString(), e);
    }
  }
Exemple #10
0
  public static Connection loadDrivers(String drivername)
      throws SQLException, IOException, ClassNotFoundException, IllegalAccessException,
          InstantiationException {
    String user = P6TestOptions.getActiveInstance().getUser();
    String password = P6TestOptions.getActiveInstance().getPassword();
    String url = P6TestOptions.getActiveInstance().getUrl();

    if (drivername != null) {
      LOG.info("UTIL REGISTERING DRIVER == " + drivername);
      Class<Driver> driverClass = P6Util.forName(drivername);
      DriverManager.setLogWriter(new PrintWriter(System.out, true));
      DriverManager.registerDriver(driverClass.newInstance());
    }
    Driver driver = DriverManager.getDriver(url);
    LOG.info("UTIL USING DRIVER == " + driver.getClass().getName() + " FOR URL " + url);
    Connection connection = DriverManager.getConnection(url, user, password);
    printAllDrivers();
    return connection;
  }
  @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() + "'!");
      }
    }
  }
  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) {
      }
    }
  }
  @Test
  public void testRetrieveFromDriverManager() throws Exception {
    DriverManager.registerDriver(driver);

    EasyMock.expect(driver.connect((String) EasyMock.notNull(), (Properties) EasyMock.notNull()))
        .andReturn(connection);
    connection.setAutoCommit(false);
    connection.setHoldability(1);

    props.put(JdbcDataSource.DRIVER, driver.getClass().getName());
    props.put(JdbcDataSource.URL, "jdbc:fakedb");
    props.put("holdability", "HOLD_CURSORS_OVER_COMMIT");
    mockControl.replay();

    Connection conn = jdbcDataSource.createConnectionFactory(context, props).call();

    mockControl.verify();

    assertSame("connection", conn, connection);
  }
Exemple #14
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();
        }
      }
    }
  }
  /**
   * 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);
    }
  }
 private boolean isExpectedDriver(Driver driver, String className) {
   String actual;
   if (driver instanceof WrappedDriver) actual = driver.toString();
   else actual = driver.getClass().getName();
   return isExpectedDriverClass(actual, className);
 }
  /**
   * 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();
    }
  }
Exemple #18
0
 public DbDriverId getDbDriverId() {
   return DbDriverId.getByClassName(m_driver.getClass().toString());
 }