Clean up resources used by the application when stopped

@see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet
.ServletContextEvent)
495596
@Override
    public void contextDestroyed(ServletContextEvent event) {
        // deregister database drivers
        try {
            for (Enumeration<Driver> e = DriverManager.getDrivers(); e
                    .hasMoreElements();) {
                Driver driver = e.nextElement();
                if (driver.getClass().getClassLoader() == getClass()
                        .getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
        } catch (Throwable e) {
            // Any errors thrown in clearing the caches aren't significant to
            // the normal execution of the application, so we ignore them
        }
        // Clean the axis method cache, see FCREPO-496
//        org.apache.axis.utils.cache.MethodCache.getInstance().clearCache();
    }
481068
protected void destroyEurekaServerContext() throws Exception {
		EurekaMonitors.shutdown();
		if (this.awsBinder != null) {
			this.awsBinder.shutdown();
		}
		if (this.serverContext != null) {
			this.serverContext.shutdown();
		}
	}
483190
public final void contextDestroyed(final ServletContextEvent sce) {
		// Stop the TciIpServer
		if (this.tcpIpServer != null) {
			this.tcpIpServer.stop();
		}

		// Stop the JmxServer
		if (this.jmxServer != null) {
			this.jmxServer.stop();
		}

		// Stop the SshServer
		if (this.sshServer != null) {
			try {
				this.sshServer.stop();
			} catch (InterruptedException e) {
				LaunchingMessageKind.ESSH0002.format(e);
			}
		}
	}
131017
@Override
	public synchronized void removeContext(Context context) {

        if( log.isDebugEnabled() )
            log.debug("Removing context[" + context.getPath() + "]");

        boolean isContextExists = isContextExists(context);
        if(!isContextExists)
        	return;
        
        // Remove this Context from the associated Host
        if( log.isDebugEnabled() )
            log.debug(" Removing this Context");
        context.getParent().removeChild(context);

    }
555828
public void destroy() {
        XmlWebApplicationContext wac = (XmlWebApplicationContext)WebApplicationContextUtils.getWebApplicationContext(_context);
        if (wac != null) {
            _context.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        } else {
            _logger.warning("Nothing more to destroy");
            return;
        }

        _logger.info("<<<< Service Platform(" + _application + ") destruction starting");
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        while (!_manageables.empty()) {
            ObjectName on = _manageables.pop();
            _logger.info("<<<<<<<< MBean(" + on + ") unregistration starting");
            try {
                mbs.unregisterMBean(on);
            } catch (Exception x) {
                _logger.log(Level.WARNING, on.toString());
            }
            _logger.info("<<<<<<<< MBean(" + on + ") unregistration complete");
        }
        while (!_plca.empty()) {
            List<Pair<String, PlatformAware>> plcas = _plca.pop();
            for (Pair<String, PlatformAware> plca: plcas) {
                _logger.info("<<<<<<<< PlatformAware(" + plca.first + '/' + plca.second.getClass().getName() + ") termination starting");
                plca.second.terminate(_application, plca.first);
                _logger.info("<<<<<<<< PlatformAware(" + plca.first + '/' + plca.second.getClass().getName() + ") termination complete");
            }
        }

        // finally, deregisters JDBC driver manually to prevent Tomcat 7 from complaining about memory leaks
        Enumeration<java.sql.Driver> drivers = java.sql.DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            java.sql.Driver driver = drivers.nextElement();
            _logger.info("<<<<<<<< JDBC Driver(" + driver + ") deregistration starting");
            try {
                java.sql.DriverManager.deregisterDriver(driver);
            } catch (java.sql.SQLException x) {
                _logger.log(Level.WARNING, "Error deregistering driver " + driver, x);
            }
            _logger.info("<<<<<<<< JDBC Driver(" + driver + ") deregistration complete");
        }

        for (Iterator<String> it = _registry.keySet().iterator(); it.hasNext();) {
            if (!it.next().startsWith("x!/")) it.remove();
        }
        _registry.remove("x!/ping");
        _registry.remove("x!/list");
        _registry.remove("x!/desc");
        while (!_applc.empty()) {
            _applc.pop().close();
        }
        wac.close();

        _logger.info("<<<< Service Platform(" + _application + ") destruction complete");
    }
380965
@Override
    protected void cleanUp() {

        m_pageStorage = null;
        m_folderStorage = null;
        m_webAppNames = null;
        m_webappUrl = null;
        super.cleanUp();
    }
662162
public void unsetResourceAdaptorContext() {
        resourceAdaptorContext = null;
        tracer = null;
        eventIdCache = null;
        eventIDFilter = null;
        sleeEndpoint = null;
        eventLookup = null;
        requestLock = null;
        httpRaSbbinterface = null;
    }
583040
@Override
    public void cleanup() throws ResourceException {
        this.session.logout();
        this.session = openSession();
        this.transactions = session.getRepository().transactions();
        this.handles.clear();
    }
519607
protected void deactivate(ComponentContext context) {
        destinationRef.deactivate(context);
        bootstrapContextRef.deactivate(context);
        rrsXAResFactorySvcRef.deactivate(context);
    }
933186
public static synchronized void onDestroy(Context context) {
        if (sRetryReceiver != null) {
            Log.v(TAG, "Unregistering receiver");
            context.unregisterReceiver(sRetryReceiver);
            sRetryReceiver = null;
        }
    }
336330
@Override
    public synchronized void stop(final StopContext context) {
        httpManagementConsumer.accept(null);
        ListenerRegistry lr = listenerRegistrySupplier.get();
        if(lr != null) {
            lr.removeListener(HTTP_MANAGEMENT);
            lr.removeListener(HTTPS_MANAGEMENT);
        }
        if (serverManagement != null) {
            try {
                serverManagement.stop();
            } finally {
                serverManagement = null;

                // Unregister sockets from the SBM
                if (socketBindingManager != null) {
                    ManagedBindingRegistry registry = useUnmanagedBindings ? socketBindingManager.getUnnamedRegistry() : socketBindingManager.getNamedRegistry();
                    if (basicManagedBinding != null) {
                        registry.unregisterBinding(basicManagedBinding);
                        basicManagedBinding = null;
                    }
                    if (secureManagedBinding != null) {
                        registry.unregisterBinding(secureManagedBinding);
                        secureManagedBinding = null;
                    }
                    socketBindingManager = null;
                    useUnmanagedBindings = false;
                }
            }
        }
    }
1022137
protected void deactivate(ComponentContext context) {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
            Tr.event(this, tc, "deactivate", context);
        configAdminRef.deactivate(context);
        variableRegistryRef.deactivate(context);
        metaTypeServiceRef.deactivate(context);
        wsConfigurationHelperRef.deactivate(context);
    }
171918
@Override
    public void stop(StopContext context) {
        Runnable asyncStop = () -> {
            synchronized (stopLock) {
                controlledProcessStateServiceSupplier.get().removePropertyChangeListener(propertyChangeListener);
                SuspendController controller = suspendControllerSupplier != null ? suspendControllerSupplier.get() : null;
                if (controller != null) {
                    controller.removeListener(operationListener);
                }
                runningState = null;
                try {
                    listener.cleanup();
                } catch (RuntimeException t) {
                    CoreManagementLogger.ROOT_LOGGER.processStateCleanupError(t, name);
                } finally {
                    context.complete();
                }
            }
        };
        final ExecutorService executorService = executorServiceSupplier.get();
        try {
            try {
                executorService.execute(asyncStop);
            } catch (RejectedExecutionException e) {
                asyncStop.run();
            }
        } finally {
            context.asynchronous();
        }
    }
681922
private void cleanUpDriverResources() {
    ctrlc.setComplete();
    try {
      Runtime.getRuntime().removeShutdownHook(ctrlc);
    }
    catch (IllegalStateException ignore) {
      // If "Shutdown in progress" exception would be thrown, just ignore and don't bother to remove the hook.
    }
    ctrlc = null;

    try {
      setShutdownRequested();
      driverCallbackSocket.close();
      driverCallbackSocket = null;
    }
    catch (Exception e) {
      System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)"));
      e.printStackTrace();
    }

    try {
      if (! job.isComplete()) {
        System.out.println("ERROR: Job not complete after cleanUpDriverResources()");
      }
    }
    catch (Exception e) {
      System.out.println("ERROR: " + (e.getMessage() != null ? e.getMessage() : "(null)"));
      e.printStackTrace();
    }

    // At this point, resources are released.
    // The hadoop job has completed (job.isComplete() is true),
    // so the cluster memory and cpus are freed.
    // The driverCallbackSocket has been closed so a new one can be made.

    // The callbackManager itself may or may not have finished, but it doesn't
    // matter since the server socket has been closed.
  }
1318568
protected void destroy() {
        ContextLogger.LOG.contextCleared(this);
        final BeanStore beanStore = getBeanStore();
        if (beanStore == null) {
            throw ContextLogger.LOG.noBeanStoreAvailable(this);
        }
        for (BeanIdentifier id : beanStore) {
            destroyContextualInstance(beanStore.get(id));
        }
        beanStore.clear();
    }
512552
protected void removeExpired(Map<Integer, Context> contexts) {
        Iterator<Context> contextsIter = contexts.values().iterator();
        while (contextsIter.hasNext()) {
            Context context = contextsIter.next();
            if (context.completeMoment != null
                    && System.currentTimeMillis() - context.completeMoment > contextTimeout) {
                contextsIter.remove();
            }
        }
    }
980351
protected void cleanup() {

        final String methodName = "cleanup";
        if (TRACE.isEntryEnabled()) {
            SibTr.entry(this, TRACE, methodName);
        }

        super.cleanup();

        if (_successfulMessages.size() > 0) {

            try {

                deleteMessages(getMessageHandles(_successfulMessages), null);

            } catch (final ResourceException exception) {

                FFDCFilter.processException(exception, CLASS_NAME + "."
                        + methodName, FFDC_PROBE_1, this);
                if (TRACE.isEventEnabled()) {
                    SibTr.exception(this, TRACE, exception);
                }

            } finally {

                _successfulMessages.clear();

            }

        }

        if (TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, methodName);
        }

    }