Example usage for javax.servlet ServletContextEvent getServletContext

List of usage examples for javax.servlet ServletContextEvent getServletContext

Introduction

In this page you can find the example usage for javax.servlet ServletContextEvent getServletContext.

Prototype

public ServletContext getServletContext() 

Source Link

Document

Return the ServletContext that changed.

Usage

From source file:org.sakaiproject.context.util.LocatorServletContextListener.java

public void contextInitialized(ServletContextEvent sce) {
    try {/*from   ww w  . j  a v  a2 s. c  o  m*/
        locator = (ServletContextLocator) ComponentManager.getInstance().get(ServletContextLocator.class);
        if (locator == null) {
            M_log.error(error);
            return;
        }
    } catch (Exception e) {
        M_log.error(error, e);
    }

    ServletContext context = sce.getServletContext();
    String name = context.getInitParameter("sakai-context-name");
    if (name == null) {
        name = ServletUtil.computeContextName(context);
        name = name.substring(0, name.length() - 1);
    }
    locator.registerContext(name, context);
    contextName = name;
}

From source file:org.hdiv.listener.InitListener.java

/**
 * Initialize servlet context objects./*from   w w  w .j av  a  2s  .c  o m*/
 * 
 * @param servletContextEvent
 *            servlet context created event
 * @since HDIV 2.1.0
 */
public void contextInitialized(ServletContextEvent servletContextEvent) {

    ServletContext servletContext = servletContextEvent.getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(servletContext);

    if (wac != null) {
        this.initServletContext(servletContext);
    } else {
        if (log.isWarnEnabled()) {
            log.warn("Hdiv's InitListener is registered before Spring's ContextLoaderListener.");
        }
    }
}

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  v a  2  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.ContextControl.java

@Override
public void contextDestroyed(ServletContextEvent event) {
    HANDLER.destroy(event.getServletContext());
    CONTEXT_LOADER.closeWebApplicationContext(event.getServletContext());
}

From source file:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 *//*from   w ww . j ava  2s  . c  om*/
@Override
public void contextInitialized(final ServletContextEvent event) {
    LoggedUser.runAsSystem(new Callable<Void>() {
        @Override
        public Void call() {
            try {
                final ServletContext context = event.getServletContext();

                final WebApplicationContext applicationContext = WebApplicationContextUtils
                        .getWebApplicationContext(context);
                SpringHelper.injectBeans(applicationContext, LifecycleListener.this);

                applicationService.initialize();

                context.setAttribute("systemOnline", applicationService.isOnline());
                context.setAttribute("cyclosVersion", applicationService.getCyclosVersion());

                // Run web initializations
                final Collection<LocalWebInitialization> initializations = applicationContext
                        .getBeansOfType(LocalWebInitialization.class).values();
                runAll(initializations);

                final LocalSettings settings = settingsService.getLocalSettings();
                context.log(settings.getApplicationName() + " initialized");

                // Suggest a GC in order to keep the heap low right after a startup
                System.gc();
            } catch (final Throwable e) {
                LOG.error("Error on LifecycleListener.contextInitialized()", e);
                throw new RuntimeException(e);
            }
            return null; // required by compiler
        }
    });
}

From source file:com.nec.harvest.servlet.listener.WebApplicationContextLoaderListener.java

/**
 * Initialize the root web application context
 *//* w  w w.j a  va 2  s .  com*/
@Override
public void contextInitialized(ServletContextEvent event) {
    super.contextInitialized(event);

    // Starting Harvest environment initialization...
    if (logger.isDebugEnabled()) {
        logger.debug("Starting Harvest environment initialization...");
    }

    /// You can get Servlet Context
    ServletContext servletContext = event.getServletContext();
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    String jasperReportPath = getReportPath(webApplicationContext);

    // Create new a folder to store all of reports
    logger.info("Trying to create a new local storage {} folder for all reports", jasperReportPath);

    File folder = new File(jasperReportPath);
    if (!folder.exists()) {
        folder.mkdirs();
    }

    // ????
    logger.info("Successfully created a report storage folder to store all of temporary reports");

    // 
    logger.info("Context instance: {}", webApplicationContext);
    logger.info("Application name: {} && path: {}", webApplicationContext.getApplicationName(),
            servletContext.getContextPath());
}

From source file:it.scoppelletti.programmerpower.web.spring.ApplicationContextListener.java

/**
 * Termine di un&rsquo;applicazione Web.
 * /*from   w w  w . j a v a 2s .c  o  m*/
 * @param event Evento.
 */
public void contextDestroyed(ServletContextEvent event) {
    EventContext eventCtx = null;

    try {
        eventCtx = new EventContext(ApplicationContextListener.THREAD_SERVLETCONTEXT_DESTROY,
                event.getServletContext());

        if (myApplListeners != null) {
            for (Map.Entry<String, ServletContextListener> entry : myApplListeners.entrySet()) {
                myLogger.trace("Calling method contextDestroyed of " + "ServletContextListener {}.",
                        entry.getKey());
                try {
                    entry.getValue().contextDestroyed(event);
                } catch (Exception ex) {
                    myLogger.error(entry.getKey(), ex);
                }
            }
        }

        mySpringSvc.contextDestroyed(event);
    } finally {
        if (eventCtx != null) {
            eventCtx.dispose();
            eventCtx = null;
        }
    }
}

From source file:org.tobarsegais.webapp.ServletContextListenerImpl.java

public void contextInitialized(ServletContextEvent sce) {
    ServletContext application = sce.getServletContext();
    Map<String, String> bundles = new HashMap<String, String>();
    Map<String, Toc> contents = new LinkedHashMap<String, Toc>();
    List<IndexEntry> keywords = new ArrayList<IndexEntry>();
    Directory index = new RAMDirectory();
    Analyzer analyzer = new StandardAnalyzer(LUCENE_VERSON);
    IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_VERSON, analyzer);
    IndexWriter indexWriter;/*from  w  w  w .j a v a  2 s .c om*/
    try {
        indexWriter = new IndexWriter(index, indexWriterConfig);
    } catch (IOException e) {
        application.log("Cannot create search index. Search will be unavailable.", e);
        indexWriter = null;
    }
    for (String path : (Set<String>) application.getResourcePaths(BUNDLE_PATH)) {
        if (path.endsWith(".jar")) {
            String key = path.substring("/WEB-INF/bundles/".length(), path.lastIndexOf(".jar"));
            application.log("Parsing " + path);
            URLConnection connection = null;
            try {
                URL url = new URL("jar:" + application.getResource(path) + "!/");
                connection = url.openConnection();
                if (!(connection instanceof JarURLConnection)) {
                    application.log(path + " is not a jar file, ignoring");
                    continue;
                }
                JarURLConnection jarConnection = (JarURLConnection) connection;
                JarFile jarFile = jarConnection.getJarFile();
                Manifest manifest = jarFile.getManifest();
                if (manifest != null) {
                    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
                    if (symbolicName != null) {
                        int i = symbolicName.indexOf(';');
                        if (i != -1) {
                            symbolicName = symbolicName.substring(0, i);
                        }
                        bundles.put(symbolicName, key);
                        key = symbolicName;
                    }
                }

                JarEntry pluginEntry = jarFile.getJarEntry("plugin.xml");
                if (pluginEntry == null) {
                    application.log(path + " does not contain a plugin.xml file, ignoring");
                    continue;
                }
                Plugin plugin = Plugin.read(jarFile.getInputStream(pluginEntry));

                Extension tocExtension = plugin.getExtension("org.eclipse.help.toc");
                if (tocExtension == null || tocExtension.getFile("toc") == null) {
                    application.log(path + " does not contain a 'org.eclipse.help.toc' extension, ignoring");
                    continue;
                }
                JarEntry tocEntry = jarFile.getJarEntry(tocExtension.getFile("toc"));
                if (tocEntry == null) {
                    application.log(path + " is missing the referenced toc: " + tocExtension.getFile("toc")
                            + ", ignoring");
                    continue;
                }
                Toc toc;
                try {
                    toc = Toc.read(jarFile.getInputStream(tocEntry));
                } catch (IllegalStateException e) {
                    application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                    continue;
                }
                contents.put(key, toc);

                Extension indexExtension = plugin.getExtension("org.eclipse.help.index");
                if (indexExtension != null && indexExtension.getFile("index") != null) {
                    JarEntry indexEntry = jarFile.getJarEntry(indexExtension.getFile("index"));
                    if (indexEntry != null) {
                        try {
                            keywords.addAll(Index.read(key, jarFile.getInputStream(indexEntry)).getChildren());
                        } catch (IllegalStateException e) {
                            application.log("Could not parse " + path + " due to " + e.getMessage(), e);
                        }
                    } else {
                        application.log(
                                path + " is missing the referenced index: " + indexExtension.getFile("index"));
                    }

                }
                application.log(path + " successfully parsed and added as " + key);
                if (indexWriter != null) {
                    application.log("Indexing content of " + path);
                    Set<String> files = new HashSet<String>();
                    Stack<Iterator<? extends TocEntry>> stack = new Stack<Iterator<? extends TocEntry>>();
                    stack.push(Collections.singleton(toc).iterator());
                    while (!stack.empty()) {
                        Iterator<? extends TocEntry> cur = stack.pop();
                        if (cur.hasNext()) {
                            TocEntry entry = cur.next();
                            stack.push(cur);
                            if (!entry.getChildren().isEmpty()) {
                                stack.push(entry.getChildren().iterator());
                            }
                            String file = entry.getHref();
                            if (file == null) {
                                continue;
                            }
                            int hashIndex = file.indexOf('#');
                            if (hashIndex != -1) {
                                file = file.substring(0, hashIndex);
                            }
                            if (files.contains(file)) {
                                // already indexed
                                // todo work out whether to just pull the section
                                continue;
                            }
                            Document document = new Document();
                            document.add(new Field("title", entry.getLabel(), Field.Store.YES,
                                    Field.Index.ANALYZED));
                            document.add(new Field("href", key + "/" + entry.getHref(), Field.Store.YES,
                                    Field.Index.NO));
                            JarEntry docEntry = jarFile.getJarEntry(file);
                            if (docEntry == null) {
                                // ignore missing file
                                continue;
                            }
                            InputStream inputStream = null;
                            try {
                                inputStream = jarFile.getInputStream(docEntry);
                                org.jsoup.nodes.Document docDoc = Jsoup.parse(IOUtils.toString(inputStream));
                                document.add(new Field("contents", docDoc.body().text(), Field.Store.NO,
                                        Field.Index.ANALYZED));
                                indexWriter.addDocument(document);
                            } finally {
                                IOUtils.closeQuietly(inputStream);
                            }
                        }
                    }
                }
            } catch (XMLStreamException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (MalformedURLException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } catch (IOException e) {
                application.log("Could not parse " + path + " due to " + e.getMessage(), e);
            } finally {
                if (connection instanceof HttpURLConnection) {
                    // should never be the case, but we should try to be sure
                    ((HttpURLConnection) connection).disconnect();
                }
            }
        }
    }
    if (indexWriter != null) {
        try {
            indexWriter.close();
        } catch (IOException e) {
            application.log("Cannot create search index. Search will be unavailable.", e);
        }
        application.setAttribute("index", index);
    }

    application.setAttribute("toc", Collections.unmodifiableMap(contents));
    application.setAttribute("keywords", new Index(keywords));
    application.setAttribute("bundles", Collections.unmodifiableMap(bundles));
    application.setAttribute("analyzer", analyzer);
    application.setAttribute("contentsQueryParser", new QueryParser(LUCENE_VERSON, "contents", analyzer));
}

From source file:com.haulmont.cuba.core.sys.AbstractWebAppContextLoader.java

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    ApplicationContext applicationContext = AppContext.getApplicationContext();

    applicationContext.getBean(Events.class).publish(
            new ServletContextDestroyedEvent(servletContextEvent.getServletContext(), applicationContext));

    AppContext.Internals.stopContext();// w  w  w.  j  av a  2s.c  om
    AppContext.Internals.setApplicationContext(null);

    if (LoggerFactory.getILoggerFactory() instanceof LoggerContext) {
        ((LoggerContext) LoggerFactory.getILoggerFactory()).stop();
    }
}

From source file:com.netsteadfast.greenstep.sys.WebMessagePublishListener.java

@SuppressWarnings("unchecked")
@Override// w w w  .  ja  v a  2  s .  c  o  m
public void contextInitialized(ServletContextEvent event) {
    if (null == sysMsgNoticeConfigService) {
        this.sysMsgNoticeConfigService = (ISysMsgNoticeConfigService<SysMsgNoticeConfigVO, TbSysMsgNoticeConfig, String>) AppContext
                .getBean("core.service.SysMsgNoticeConfigService");
    }
    event.getServletContext().setAttribute("asyncContexts", asyncContexts);
    this.webMessagePublishRunnable = new WebMessagePublishRunnable(this.asyncContexts);
    this.webMessagePublishThread = new Thread(this.webMessagePublishRunnable);
    this.webMessagePublishThread.start();
}