Example usage for javax.servlet ServletContext removeAttribute

List of usage examples for javax.servlet ServletContext removeAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext removeAttribute.

Prototype

public void removeAttribute(String name);

Source Link

Document

Removes the attribute with the given name from this ServletContext.

Usage

From source file:org.jasig.springframework.web.portlet.context.PortletContextLoader.java

/**
 * Close Spring's web application context for the given portlet context. If
 * the default {@link #loadParentContext(PortletContext)} implementation,
 * which uses ContextSingletonBeanFactoryLocator, has loaded any shared
 * parent context, release one reference to that shared parent context.
 * <p>If overriding {@link #loadParentContext(PortletContext)}, you may have
 * to override this method as well./*from   w w  w . j a va2s.c  o  m*/
 * @param servletContext the PortletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
    servletContext.log("Closing Spring root PortletApplicationContext");
    try {
        if (this.context instanceof ConfigurablePortletApplicationContext) {
            ((ConfigurablePortletApplicationContext) this.context).close();
        }
    } finally {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == PortletContextLoader.class.getClassLoader()) {
            currentContext = null;
        } else if (ccl != null) {
            currentContextPerThread.remove(ccl);
        }
        servletContext.removeAttribute(PortletApplicationContext.ROOT_PORTLET_APPLICATION_CONTEXT_ATTRIBUTE);
        if (this.parentContextRef != null) {
            this.parentContextRef.release();
        }
    }
}

From source file:org.springframework.web.context.ContextLoader.java

/**
 * Close Spring's web application context for the given servlet context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well./*  w  ww .ja  va 2  s .c o m*/
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
    servletContext.log("Closing Spring root WebApplicationContext");
    try {
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ((ConfigurableWebApplicationContext) this.context).close();
        }
    } finally {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == ContextLoader.class.getClassLoader()) {
            currentContext = null;
        } else if (ccl != null) {
            currentContextPerThread.remove(ccl);
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }
}

From source file:org.mifos.framework.ApplicationInitializer.java

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    ServletContext ctx = servletContextEvent.getServletContext();
    logger.info("shutting down scheduler");
    final MifosScheduler mifosScheduler = (MifosScheduler) ctx.getAttribute(MifosScheduler.class.getName());
    ctx.removeAttribute(MifosScheduler.class.getName());
    try {/*from   www .ja  v a2 s  .c o m*/
        if (mifosScheduler != null) {
            mifosScheduler.shutdown();
        }
    } catch (Exception e) {
        logger.error("error while shutting down scheduler", e);
    }

    // WebApplicationContext applicationContext = null;
    //  if (ctx != null) {
    //     applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
    // }

    StaticHibernateUtil.shutdown();
    unregisterMySQLDriver();
    cancelMySQLStatement();
    logger.info("destroyed context");
}

From source file:com.dhcc.framework.web.context.DhccContextLoader.java

/**
 * Close Spring's web application context for the given servlet context. If
 * the default {@link #loadParentContext(ServletContext)} implementation,
 * which uses ContextSingletonBeanFactoryLocator, has loaded any shared
 * parent context, release one reference to that shared parent context.
 * <p>If overriding {@link #loadParentContext(ServletContext)}, you may have
 * to override this method as well.//from   www .j  a  v a  2  s .  c  o  m
 * @param servletContext the ServletContext that the WebApplicationContext runs in
 */
public void closeWebApplicationContext(ServletContext servletContext) {
    servletContext.log("Closing Spring root WebApplicationContext");
    try {
        if (this.context instanceof ConfigurableWebApplicationContext) {
            ((ConfigurableWebApplicationContext) this.context).close();
        }
    } finally {
        ClassLoader ccl = Thread.currentThread().getContextClassLoader();
        if (ccl == DhccContextLoader.class.getClassLoader()) {
            currentContext = null;
        } else if (ccl != null) {
            currentContextPerThread.remove(ccl);
        }
        servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
        if (this.parentContextRef != null) {
            this.parentContextRef.release();
        }
    }
}

From source file:fll.web.setup.CreateDB.java

protected void processRequest(final HttpServletRequest request, final HttpServletResponse response,
        final ServletContext application, final HttpSession session) throws IOException, ServletException {
    String redirect;//from ww w .  j a  v  a  2  s .  c o  m
    final StringBuilder message = new StringBuilder();
    InitFilter.initDataSource(application);
    final DataSource datasource = ApplicationAttributes.getDataSource(application);
    Connection connection = null;
    try {
        connection = datasource.getConnection();

        // must be first to ensure the form parameters are set
        UploadProcessor.processUpload(request);

        if (null != request.getAttribute("chooseDescription")) {
            final String description = (String) request.getAttribute("description");
            try {
                final URL descriptionURL = new URL(description);
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(descriptionURL.openStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";

            } catch (final MalformedURLException e) {
                throw new FLLInternalException("Could not parse URL from choosen description: " + description,
                        e);
            }
        } else if (null != request.getAttribute("reinitializeDatabase")) {
            // create a new empty database from an XML descriptor
            final FileItem xmlFileItem = (FileItem) request.getAttribute("xmldocument");

            if (null == xmlFileItem || xmlFileItem.getSize() < 1) {
                message.append("<p class='error'>XML description document not specified</p>");
                redirect = "/setup";
            } else {
                final Document document = ChallengeParser
                        .parse(new InputStreamReader(xmlFileItem.getInputStream(), Utilities.DEFAULT_CHARSET));

                GenerateDB.generateDB(document, connection);

                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database</i></p>");
                redirect = "/admin/createUsername.jsp";
            }
        } else if (null != request.getAttribute("createdb")) {
            // import a database from a dump
            final FileItem dumpFileItem = (FileItem) request.getAttribute("dbdump");

            if (null == dumpFileItem || dumpFileItem.getSize() < 1) {
                message.append("<p class='error'>Database dump not specified</p>");
                redirect = "/setup";
            } else {

                ImportDB.loadFromDumpIntoNewDB(new ZipInputStream(dumpFileItem.getInputStream()), connection);

                // remove application variables that depend on the database
                application.removeAttribute(ApplicationAttributes.CHALLENGE_DOCUMENT);

                message.append("<p id='success'><i>Successfully initialized database from dump</i></p>");
                redirect = "/admin/createUsername.jsp";
            }

        } else {
            message.append(
                    "<p class='error'>Unknown form state, expected form fields not seen: " + request + "</p>");
            redirect = "/setup";
        }

    } catch (final FileUploadException fue) {
        message.append("<p class='error'>Error handling the file upload: " + fue.getMessage() + "</p>");
        LOG.error(fue, fue);
        redirect = "/setup";
    } catch (final IOException ioe) {
        message.append("<p class='error'>Error reading challenge descriptor: " + ioe.getMessage() + "</p>");
        LOG.error(ioe, ioe);
        redirect = "/setup";
    } catch (final SQLException sqle) {
        message.append("<p class='error'>Error loading data into the database: " + sqle.getMessage() + "</p>");
        LOG.error(sqle, sqle);
        redirect = "/setup";
    } finally {
        SQLFunctions.close(connection);
    }

    session.setAttribute("message", message.toString());
    response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + redirect));

}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Stop this component, finalizing our associated class loader.
 *
 * @exception LifecycleException if a lifecycle error occurs
 *///from  www . j  a va 2  s  . c o m
public void stop() throws LifecycleException {

    // Validate and update our current component state
    if (!started)
        throw new LifecycleException(sm.getString("webappLoader.notStarted"));
    if (log.isDebugEnabled())
        log.debug(sm.getString("webappLoader.stopping"));
    lifecycle.fireLifecycleEvent(STOP_EVENT, null);
    started = false;

    // Remove context attributes as appropriate
    if (container instanceof Context) {
        ServletContext servletContext = ((Context) container).getServletContext();
        servletContext.removeAttribute(Globals.CLASS_PATH_ATTR);
    }

    // Throw away our current class loader
    if (classLoader instanceof Lifecycle)
        ((Lifecycle) classLoader).stop();
    DirContextURLStreamHandler.unbind((ClassLoader) classLoader);
    classLoader = null;

    destroy();

}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Adds a feature to the Parameter attribute of the ApplicationPrefs object
 *
 * @param context      The feature to be added to the Parameter attribute
 * @param param        The feature to be added to the Parameter attribute
 * @param value        The feature to be added to the Parameter attribute
 * @param defaultValue The feature to be added to the Parameter attribute
 *//* ww w .  j a  v  a  2  s.co  m*/
private void addParameter(ServletContext context, String param, String value, String defaultValue) {
    if (value != null) {
        context.setAttribute(param, value);
    } else {
        if (defaultValue != null) {
            context.setAttribute(param, defaultValue);
        } else {
            context.removeAttribute(param);
        }
    }
}

From source file:com.concursive.connect.web.listeners.ContextListener.java

/**
 * All objects that should not be persistent can be removed from the context
 * before the next reload//  ww  w .  j a va2  s .  c o m
 *
 * @param event Description of the Parameter
 */
public void contextDestroyed(ServletContextEvent event) {
    ServletContext context = event.getServletContext();
    LOG.info("Shutting down");

    // Remove scheduler
    try {
        Scheduler scheduler = (Scheduler) context.getAttribute(Constants.SCHEDULER);
        if (scheduler != null) {
            // Remove the App connection pool
            ConnectionPool appCP = (ConnectionPool) scheduler.getContext().get("ConnectionPool");
            // Interrupt any interruptable jobs
            scheduler.interrupt("directoryIndexer",
                    (String) scheduler.getContext().get(ScheduledJobs.CONTEXT_SCHEDULER_GROUP));
            // Cleanup the scheduler
            scheduler.getContext().remove(appCP);
            int count = scheduler.getCurrentlyExecutingJobs().size();
            if (count > 0) {
                LOG.info("Waiting for scheduler jobs to finish executing... (" + count + ")");
            }
            scheduler.shutdown(true);
            LOG.info("Scheduler shutdown");
            if (appCP != null) {
                appCP.closeAllConnections();
                appCP.destroy();
            }
            context.removeAttribute(Constants.SCHEDULER);
        }
    } catch (Exception e) {
        LOG.error("Scheduler error", e);
    }

    // Remove the tracker
    context.removeAttribute(Constants.USER_SESSION_TRACKER);

    // Stop the object hook manager
    ObjectHookManager hookManager = (ObjectHookManager) context.getAttribute(Constants.OBJECT_HOOK_MANAGER);
    if (hookManager != null) {
        hookManager.reset();
        hookManager.shutdown();
        context.removeAttribute(Constants.OBJECT_HOOK_MANAGER);
    }

    // Stop the work flow manager
    WorkflowManager wfManager = (WorkflowManager) context.getAttribute(Constants.WORKFLOW_MANAGER);
    if (wfManager != null) {
        context.removeAttribute(Constants.WORKFLOW_MANAGER);
    }

    // Unregister the remote wsrp producer
    ProducerRegistry producerRegistry = ProducerRegistryImpl.getInstance();
    ProducerImpl producer = (ProducerImpl) producerRegistry
            .getProducer(PortletManager.CONCURSIVE_WSRP_PRODUCER_ID);
    if (producer != null) {
        try {
            producer.deregister();
            LOG.info("Successfully deregistered remote wsrp producer");
        } catch (WSRPException e) {
            LOG.error("Unable to de-register the remote wsrp producer");
        }
    }

    // Stop the portlet container
    PortletContainer container = (PortletContainer) context.getAttribute(Constants.PORTLET_CONTAINER);
    if (container != null) {
        try {
            container.destroy();
        } catch (Exception e) {
            LOG.error("PortletContainer error", e);
        }
        context.removeAttribute(Constants.PORTLET_CONTAINER);
    }

    // Remove the cache manager
    CacheManager.getInstance().shutdown();

    // TODO: Create a connection pool array
    // Remove the connection pool
    ConnectionPool cp = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL);
    if (cp != null) {
        cp.closeAllConnections();
        cp.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL);
    }

    // Remove the RSS connection pool
    ConnectionPool rssCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL_RSS);
    if (rssCP != null) {
        rssCP.closeAllConnections();
        rssCP.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL_RSS);
    }

    // Remove the API connection pool
    ConnectionPool apiCP = (ConnectionPool) context.getAttribute(Constants.CONNECTION_POOL_API);
    if (apiCP != null) {
        apiCP.closeAllConnections();
        apiCP.destroy();
        context.removeAttribute(Constants.CONNECTION_POOL_API);
    }

    // Shutdown the indexer service
    IIndexerService indexer = IndexerFactory.getInstance().getIndexerService();
    if (indexer != null) {
        try {
            indexer.shutdown();
        } catch (Exception e) {
            LOG.error("Error shutting down indexer", e);
        }
    }

    // Remove system settings
    context.removeAttribute(Constants.SYSTEM_SETTINGS);

    // Remove the logger
    ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
    LogFactory.release(contextClassLoader);

    LOG.info("Shutdown complete");
}

From source file:com.jsmartframework.web.manager.BeanHandler.java

private void finalizeWebBean(Object bean, ServletContext servletContext) {
    if (bean != null) {
        executePreDestroy(bean);/* w w w  .  j a va 2s .com*/
        finalizeInjection(bean, servletContext);
        WebBean webBean = bean.getClass().getAnnotation(WebBean.class);
        servletContext.removeAttribute(HELPER.getClassName(webBean, bean.getClass()));
    }
}

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
 *///  www.  ja  v a 2  s . c  om
@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();
        }
    }
}