List of usage examples for java.sql Driver getClass
@HotSpotIntrinsicCandidate public final native Class<?> getClass();
From source file:org.openmrs.util.OpenmrsClassLoader.java
/** * This clears any references this classloader might have that will prevent garbage collection. <br> * <br>/*from w ww.ja v a 2 s. com*/ * Borrowed from Tomcat's WebappClassLoader#clearReferences() (not javadoc linked intentionally) <br> * The only difference between this and Tomcat's implementation is that this one only acts on * openmrs objects and also clears out static java.* packages. Tomcat acts on all objects and * does not clear our static java.* objects. * * @since 1.5 */ protected static void clearReferences() { // Unregister any JDBC drivers loaded by this classloader Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { Driver driver = drivers.nextElement(); if (driver.getClass().getClassLoader() == getInstance()) { try { DriverManager.deregisterDriver(driver); } catch (SQLException e) { log.warn("SQL driver deregistration failed", e); } } } // Null out any static or final fields from loaded classes, // as a workaround for apparent garbage collection bugs for (WeakReference<Class<?>> refClazz : getInstance().cachedClasses.values()) { if (refClazz == null) { continue; } Class<?> clazz = refClazz.get(); if (clazz != null && clazz.getName().contains("openmrs")) { // only clean up openmrs classes try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } if (Modifier.isStatic(mods)) { try { // do not clear the log field on this class yet if (clazz.equals(OpenmrsClassLoader.class) && "log".equals(field.getName())) { continue; } field.setAccessible(true); if (Modifier.isFinal(mods)) { if (!(field.getType().getName().startsWith("javax."))) { nullInstance(field.get(null)); } } else { field.set(null, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + clazz.getName()); } } } catch (Exception t) { if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } } } } } catch (Exception t) { if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } } } } // now we can clear the log field on this class OpenmrsClassLoader.log = null; getInstance().cachedClasses.clear(); }
From source file:org.openmrs.web.Listener.java
/** * Called when the webapp is shut down properly Must call Context.shutdown() and then shutdown * all the web layers of the modules//w ww. ja v a 2s . co m * * @see org.springframework.web.context.ContextLoaderListener#contextDestroyed(javax.servlet.ServletContextEvent) */ @SuppressWarnings("squid:S1215") @Override public void contextDestroyed(ServletContextEvent event) { try { Context.openSession(); Context.shutdown(); WebModuleUtil.shutdownModules(event.getServletContext()); } catch (Exception e) { // don't print the unhelpful "contextDAO is null" message if (!"contextDAO is null".equals(e.getMessage())) { // not using log.error here so it can be garbage collected System.out.println("Listener.contextDestroyed: Error while shutting down openmrs: "); log.error(e); } } finally { if ("true".equalsIgnoreCase(System.getProperty("FUNCTIONAL_TEST_MODE"))) { //Delete the temporary file created for functional testing and shutdown the mysql daemon String filename = WebConstants.WEBAPP_NAME + "-test-runtime.properties"; File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename); System.out.println(filename + " delete=" + file.delete()); //new com.mysql.management.MysqldResource(new File("../openmrs/target/database")).shutdown(); } // remove the user context that we set earlier Context.closeSession(); } // commented out because we are not init'ing it in the contextInitialization anymore // super.contextDestroyed(event); try { for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) { Driver driver = e.nextElement(); ClassLoader classLoader = driver.getClass().getClassLoader(); // only unload drivers for this webapp if (classLoader == null || classLoader == getClass().getClassLoader()) { DriverManager.deregisterDriver(driver); } else { System.err.println("Didn't remove driver class: " + driver.getClass() + " with classloader of: " + driver.getClass().getClassLoader()); } } } catch (Exception e) { System.err.println("Listener.contextDestroyed: Failed to cleanup drivers in webapp"); log.error(e); } MemoryLeakUtil.shutdownMysqlCancellationTimer(); MemoryLeakUtil.shutdownKeepAliveTimer(); OpenmrsClassLoader.onShutdown(); LogManager.shutdown(); // just to make things nice and clean. // Suppressing sonar issue squid:S1215 System.gc(); System.gc(); }
From source file:org.red5.server.war.MainServlet.java
/** * Clearing the in-memory configuration parameters, we will receive * notification that the servlet context is about to be shut down *///from ww w . ja v a 2s . co m public void contextDestroyed(ServletContextEvent sce) { 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 { // 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 spring // get web application context from the servlet context ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) servletContext .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); ConfigurableBeanFactory factory = applicationContext.getBeanFactory(); if (factory.containsSingleton("default.context")) { for (String scope : factory.getRegisteredScopeNames()) { logger.debug("Registered scope: " + scope); } for (String singleton : factory.getSingletonNames()) { logger.debug("Registered singleton: " + singleton); // factory.destroyScopedBean(singleton); } factory.destroySingletons(); } servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE); applicationContext.close(); // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print // LogFactory.release(Thread.currentThread().getContextClassLoader()); } catch (Throwable e) { // may get a java.lang.StackOverflowError when shutting appcontext // down in jboss e.printStackTrace(); } }
From source file:org.red5.server.war.WarLoaderServlet.java
/** * Clearing the in-memory configuration parameters, we will receive * notification that the servlet context is about to be shut down *///from w w w. ja v a2 s . co m @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(); } } }
From source file:org.rhq.plugins.database.DatabasePluginLifecycleListener.java
public void shutdown() { // so we do not cause our classloader to leak perm gen, we need to de-register // any and all JDBC drivers this plugin registered Enumeration<Driver> drivers = DriverManager.getDrivers(); while (drivers.hasMoreElements()) { try {/*from www .ja va 2s. c o m*/ Driver driver = drivers.nextElement(); DriverManager.deregisterDriver(driver); log.debug("Deregistered JDBC driver: " + driver.getClass()); } catch (Exception e) { log.warn("Failed to deregister JDBC drivers - memory might leak" + ThrowableUtil.getAllMessages(e)); } } log.debug(this.getClass().getSimpleName() + " completed shutdown."); return; }
From source file:org.rimudb.editor.RimuDBEditor.java
protected void driverCheck() { driverMap = getPreferences().getDrivers(); if (driverMap != null) { Set<String> keyset = driverMap.keySet(); for (String driverName : keyset) { DriverEntry driverEntry = driverMap.get(driverName); boolean found = false; try { Class.forName(driverEntry.getJdbcDriver()); found = true;//from w w w . j av a 2 s .c om } catch (Exception e) { log.info("driverCheck() Could not find driverClass", e); } driverEntry.setFound(found); } List<Driver> drivers = Collections.list(DriverManager.getDrivers()); for (int i = 0; i < drivers.size(); i++) { Driver driver = (Driver) drivers.get(i); // Find the driver in the map and add the version to the DriverEntry Collection<DriverEntry> values = driverMap.values(); for (DriverEntry driverEntry : values) { if (driverEntry.getJdbcDriver().trim().equals(driver.getClass().getName())) { driverEntry.setDriverVersion(driver.getMajorVersion() + "." + driver.getMinorVersion()); } } } } }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.BaseJDBCStorageClientPool.java
@Override @Activate//from w w w . j a v a 2s .c o m @SuppressWarnings(value = { "NP_CLOSING_NULL" }, justification = "Invalid report, if this was the case then nothing would work") public void activate(Map<String, Object> properties) throws ClassNotFoundException { this.properties = properties; super.activate(properties); connectionManager = new ConnectionManager(this); timer = new Timer(); timer.schedule(connectionManager, 30000L, 30000L); // this is a default cache used where none has been provided. if (LOGGER.isDebugEnabled()) { DriverManager.setLogWriter(new PrintWriter(System.err)); } String jdbcDriver = StorageClientUtils.getSetting(properties.get(JDBC_DRIVER), ""); Class<?> driverClass = this.getClass().getClassLoader().loadClass(jdbcDriver); if (driverClass != null) { LOGGER.info("Loaded Driver Class {} with classloader {} ", driverClass, driverClass.getClassLoader()); try { Driver d = (Driver) driverClass.newInstance(); LOGGER.info("Created Driver Instance as {} ", d); } catch (InstantiationException e) { LOGGER.info("Error Creating Driver {} ", driverClass, e); } catch (IllegalAccessException e) { LOGGER.info("Error Creating Driver {} ", driverClass, e); } } else { LOGGER.error( "Failed to Load the DB Driver {}, unless the driver is available in the core bundle, it probably wont be found.", jdbcDriver); } connectionProperties = getConnectionProperties(properties); username = StorageClientUtils.getSetting(properties.get(USERNAME), ""); password = StorageClientUtils.getSetting(properties.get(PASSWORD), ""); url = StorageClientUtils.getSetting(properties.get(CONNECTION_URL), ""); LOGGER.info("Loaded Database Driver {} as {} ", jdbcDriver, driverClass); boolean registered = false; for (Enumeration<Driver> ed = DriverManager.getDrivers(); ed.hasMoreElements();) { registered = true; Driver d = ed.nextElement(); LOGGER.info("JDBC Driver Registration [{}] [{}] [{}] ", new Object[] { d, d.getClass(), d.getClass().getClassLoader() }); } if (!registered) { LOGGER.warn( "The SQL Driver has no drivers registered, did you ensure that that your Driver started up before this bundle ?"); } JDBCStorageClient client = null; try { // dont use the pool, we dont want this client to be in the pool. client = new JDBCStorageClient(this, properties, getSqlConfig(), getIndexColumns(), getIndexColumnsTypes(), getIndexColumnsNames(), false); client = checkSchema(client); if (client == null) { LOGGER.warn("Failed to check Schema, no connection"); } } catch (ClientPoolException e) { LOGGER.warn("Failed to check Schema", e); } catch (NoSuchAlgorithmException e) { LOGGER.warn("Failed to check Schema", e); } catch (SQLException e) { LOGGER.warn("Failed to check Schema", e); } catch (StorageClientException e) { LOGGER.warn("Failed to check Schema", e); } finally { if (client != null) { // do not close as this will add the client into the pool. client.passivate(); client.destroy(); } } }
From source file:org.sakaiproject.nakamura.lite.storage.jdbc.JDBCStorageClientPool.java
@Override @Activate/*from w w w . j a va 2 s . c o m*/ @SuppressWarnings(value = { "NP_CLOSING_NULL" }, justification = "Invalid report, if this was the case then nothing would work") public void activate(Map<String, Object> properties) throws ClassNotFoundException { this.properties = properties; super.activate(properties); connectionManager = new ConnectionManager(); timer = new Timer(); timer.schedule(connectionManager, 30000L, 30000L); sharedCache = new ConcurrentLRUMap<String, CacheHolder>(10000); // this is a default cache used where none has been provided. defaultStorageManagerCache = new StorageCacheManager() { public Map<String, CacheHolder> getContentCache() { return sharedCache; } public Map<String, CacheHolder> getAuthorizableCache() { return sharedCache; } public Map<String, CacheHolder> getAccessControlCache() { return sharedCache; } }; if (LOGGER.isDebugEnabled()) { DriverManager.setLogWriter(new PrintWriter(System.err)); } String jdbcDriver = StorageClientUtils.getSetting(properties.get(JDBC_DRIVER), ""); Class<?> driverClass = this.getClass().getClassLoader().loadClass(jdbcDriver); if (driverClass != null) { LOGGER.info("Loaded Driver Class {} with classloader {} ", driverClass, driverClass.getClassLoader()); try { Driver d = (Driver) driverClass.newInstance(); if (d == null) { LOGGER.error("Error creating driver instance, got null from {} ", driverClass); } else { LOGGER.info("Created Driver Instance as {} ", d); } } catch (InstantiationException e) { LOGGER.info("Error Creating Driver {} ", driverClass, e); } catch (IllegalAccessException e) { LOGGER.info("Error Creating Driver {} ", driverClass, e); } } else { LOGGER.error( "Failed to Load the DB Driver {}, unless the driver is available in the core bundle, it probably wont be found.", jdbcDriver); } connectionProperties = getConnectionProperties(properties); username = StorageClientUtils.getSetting(properties.get(USERNAME), ""); password = StorageClientUtils.getSetting(properties.get(PASSWORD), ""); url = StorageClientUtils.getSetting(properties.get(CONNECTION_URL), ""); LOGGER.info("Loaded Database Driver {} as {} ", jdbcDriver, driverClass); boolean registered = false; for (Enumeration<Driver> ed = DriverManager.getDrivers(); ed.hasMoreElements();) { registered = true; Driver d = ed.nextElement(); LOGGER.info("JDBC Driver Registration [{}] [{}] [{}] ", new Object[] { d, d.getClass(), d.getClass().getClassLoader() }); } if (!registered) { LOGGER.warn( "The SQL Driver has no drivers registered, did you ensure that that your Driver started up before this bundle ?"); } JDBCStorageClient client = null; try { client = (JDBCStorageClient) getClient(); if (client == null) { LOGGER.warn("Failed to check Schema, no connection"); } } catch (ClientPoolException e) { LOGGER.warn("Failed to check Schema", e); } finally { if (client != null) { client.close(); } } }
From source file:se.unlogic.hierarchy.core.cache.DataSourceCache.java
public void unload() { try {/* w w w. ja va 2 s. c o m*/ w.lock(); ArrayList<DataSourceDescriptor> descriptorList = this.getCachedDataSourceDescriptors(); for (DataSourceDescriptor descriptor : descriptorList) { this.stop(descriptor.getDataSourceID()); } for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) { Driver driver = e.nextElement(); if (driver.getClass().getClassLoader() == getClass().getClassLoader()) { try { log.info("Deregistering JDBC driver " + driver); DriverManager.deregisterDriver(driver); } catch (SQLException e1) { log.error("Error deregistering JDBC driver " + driver); } } } log.info("Datasource cache unloaded"); } finally { w.unlock(); } }