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:nl.strohalm.cyclos.http.LifecycleListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *//* w  ww  .j  a v  a 2  s  . c om*/
@Override
public void contextDestroyed(final ServletContextEvent event) {
    LoggedUser.runAsSystem(new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            try {
                final ServletContext context = event.getServletContext();
                final LocalSettings settings = settingsService == null ? null
                        : settingsService.getLocalSettings();

                // Shutdown the application service
                if (applicationService != null) {
                    applicationService.shutdown();
                }

                final String applicationName = settings == null ? null : settings.getApplicationName();
                context.log(applicationName == null ? "Cyclos" : applicationName + " destroyed");

                // Suggest a GC as probably there were several released resources
                System.gc();

            } catch (final Throwable e) {
                LOG.error("Error on LifecycleListener.contextDestroyed()", e);
                throw new RuntimeException(e);
            }
            return null; // required by compiler
        }
    });
}

From source file:org.red5.server.war.MainServlet.java

/**
 * Main entry point for the Red5 Server as a war
 *///from ww  w.j  a  v a 2s.  c om
// Notification that the web application is ready to process requests
public void contextInitialized(ServletContextEvent sce) {
    System.setProperty("red5.deployment.type", "war");

    if (null != servletContext) {
        return;
    }
    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Loading red5 global context from: " + red5Config);
    logger.info("Path: " + prefix);

    try {
        // Detect root of Red5 configuration and set as system property
        String root;
        String classpath = System.getProperty("java.class.path");
        File fp = new File(prefix + red5Config);
        fp = fp.getCanonicalFile();
        if (!fp.isFile()) {
            // Given file does not exist, search it on the classpath
            String[] paths = classpath.split(System.getProperty("path.separator"));
            for (String element : paths) {
                fp = new File(element + "/" + red5Config);
                fp = fp.getCanonicalFile();
                if (fp.isFile()) {
                    break;
                }
            }
        }
        if (!fp.isFile()) {
            throw new Exception(
                    "could not find configuration file " + red5Config + " on your classpath " + classpath);
        }

        root = fp.getAbsolutePath();
        root = root.replace('\\', '/');
        int idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        // update classpath
        System.setProperty("java.class.path",
                classpath + File.pathSeparatorChar + root + File.pathSeparatorChar + root + "/classes");
        logger.debug("New classpath: " + System.getProperty("java.class.path"));
        // set configuration root
        System.setProperty("red5.config_root", root);
        logger.info("Setting configuation root to " + root);

        // Setup system properties so they can be evaluated
        Properties props = new Properties();
        props.load(new FileInputStream(root + "/red5.properties"));
        for (Object o : props.keySet()) {
            String key = (String) o;
            if (StringUtils.isNotBlank(key)) {
                System.setProperty(key, props.getProperty(key));
            }
        }

        // Store root directory of Red5
        idx = root.lastIndexOf('/');
        root = root.substring(0, idx);
        if (System.getProperty("file.separator").equals("/")) {
            // Workaround for linux systems
            root = "/" + root;
        }
        System.setProperty("red5.root", root);
        logger.info("Setting Red5 root to " + root);

        Class contextClass = org.springframework.web.context.support.XmlWebApplicationContext.class;
        ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) BeanUtils
                .instantiateClass(contextClass);

        String[] strArray = servletContext.getInitParameter(ContextLoader.CONFIG_LOCATION_PARAM)
                .split("[,\\s]");
        logger.info("Config location files: " + strArray.length);
        applicationContext.setConfigLocations(strArray);
        applicationContext.setServletContext(servletContext);
        applicationContext.refresh();

        // set web application context as an attribute of the servlet
        // context so that it may be located via Springs
        // WebApplicationContextUtils
        servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
                applicationContext);

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
        // register default
        // add the context to the parent
        factory.registerSingleton("default.context", applicationContext);

    } catch (Throwable e) {
        logger.error("", e);
    }

    long startupIn = System.currentTimeMillis() - time;
    logger.info("Startup done in: " + startupIn + " ms");

}

From source file:be.fedict.eid.idp.webapp.IdentityProviderServletContextListener.java

private void initIdentityProviderConfiguration(ServletContextEvent event) {

    ServletContext servletContext = event.getServletContext();
    servletContext.setAttribute(//w ww . j  a  va 2 s  .c o m
            IdentityProviderConfigurationFactory.IDENTITY_PROVIDER_CONFIGURATION_CONTEXT_ATTRIBUTE,
            this.identityService);
}

From source file:com.tacitknowledge.util.migration.jdbc.WebAppJNDIMigrationLauncher.java

/**
 * {@inheritDoc}// w  ww. ja  v a2  s. c om
 */
public void contextInitialized(ServletContextEvent sce) {
    try {

        // WEB-INF/classes and WEB-INF/lib are not in the system classpath (as defined by
        // System.getProperty("java.class.path")); add it to the search path here
        if (firstRun) {
            ClassDiscoveryUtil.addResourceListSource(
                    new WebAppResourceListSource(sce.getServletContext().getRealPath("/WEB-INF")));
        }
        firstRun = false;

        // The MigrationLauncher is responsible for handling the interaction
        // between the PatchTable and the underlying MigrationTasks; as each
        // task is executed, the patch level is incremented, etc.
        try {
            MigrationUtil.doMigrations(sce);
        } catch (MigrationException e) {
            // Runtime exceptions coming from a ServletContextListener prevent the
            // application from being deployed.  In this case, the intention is
            // for migration-enabled applications to fail-fast if there are any
            // errors during migration.
            throw new RuntimeException("Migration exception caught during migration", e);
        }
    } catch (RuntimeException e) {
        // Catch all exceptions for the sole reason of logging in
        // as many places as possible - debugging migration
        // problems requires detection first, and that means
        // getting the word of failures out.
        log.error(e);
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.err.println(e.getMessage());
        e.printStackTrace(System.err);

        throw e;
    }
}

From source file:com.manydesigns.portofino.servlets.PortofinoListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    try {/* w w  w . j  a v a 2s  . c  o m*/
        ElementsThreadLocals.setupDefaultElementsContext();
        ServletContext servletContext = servletContextEvent.getServletContext();
        ElementsThreadLocals.setServletContext(servletContext);
        AttributeMap servletContextAttributeMap = AttributeMap.createAttributeMap(servletContext);
        ElementsThreadLocals.getOgnlContext().put(ElementsFilter.SERVLET_CONTEXT_OGNL_ATTRIBUTE,
                servletContextAttributeMap);
        init(servletContextEvent);
    } catch (Throwable e) {
        logger.error("Could not start ManyDesigns Portofino", e);
        throw new Error(e);
    } finally {
        ElementsThreadLocals.removeElementsContext();
    }
}

From source file:org.alfresco.repo.web.util.AbstractJettyComponent.java

protected void configure(WebAppContext webAppContext) {
    try {/*  w  ww . j a  v a 2s.co m*/
        ClassLoader classLoader = BaseApplicationContextHelper.buildClassLoader(classLocations);
        webAppContext.setClassLoader(classLoader);
    } catch (IOException e) {
        throw new ExceptionInInitializerError(e);
    }

    webAppContext.addEventListener(new ServletContextListener() {
        public void contextInitialized(ServletContextEvent sce) {
            // create a Spring web application context, wrapping and providing access to
            // the application context
            try {
                ServletContext servletContext = sce.getServletContext();

                // initialise web application context
                WebApplicationContextLoader.getApplicationContext(servletContext, configLocations,
                        classLocations);

                if (logger.isDebugEnabled()) {
                    logger.debug("contextInitialized " + sce);
                }
            } catch (Throwable t) {
                logger.error("Failed to start Jetty server: " + t);
                throw new AlfrescoRuntimeException("Failed to start Jetty server", t);
            }
        }

        public void contextDestroyed(ServletContextEvent sce) {
            if (logger.isDebugEnabled()) {
                logger.debug("contextDestroyed " + sce);
            }
        }
    });

    // with a login-config in web.xml, jetty seems to require this in order to start successfully
    webAppContext.getSecurityHandler().setLoginService(new HashLoginService());

    // arbitrary temporary file location
    File tmp = new File(TempFileProvider.getSystemTempDir(), String.valueOf(System.currentTimeMillis()));
    webAppContext.setResourceBase(tmp.getAbsolutePath());
}

From source file:org.kuali.rice.core.framework.config.module.WebModuleLoaderListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    List<String> springFileLocations = getSpringFileLocations();
    if (CollectionUtils.isNotEmpty(springFileLocations)) {
        LOG.info("Initializing " + getClass().getSimpleName() + " with spring files: " + springFileLocations);
        SpringResourceLoader resourceLoader = new SpringResourceLoader(RESOURCE_LOADER_NAME,
                springFileLocations, event.getServletContext());
        try {//from w  w  w .  j  a  v  a 2 s.  c om
            resourceLoader.start();
        } catch (Exception e) {
            throw new ConfigurationException("Failed to load web module spring configuration", e);
        }
        GlobalResourceLoader.addResourceLoader(resourceLoader);
    }
}

From source file:org.apache.marmotta.platform.core.servlet.MarmottaPreStartupListener.java

/**
 * * Notification that the web application initialization
 * * process is starting./*from   www.  j  a  v  a 2 s.c o m*/
 * * All ServletContextListeners are notified of context
 * * initialization before any filter or servlet in the web
 * * application is initialized.
 */
@Override
public void contextInitialized(ServletContextEvent sce) {

    if (startupService == null) {
        startupService = CDIContext.getInstance(MarmottaStartupService.class);
    }

    // we check for the presence of the configuration.override init parameter; if it exists, we load this
    // configuration file and pass it as configuration override to the startup
    PropertiesConfiguration override = null;

    if (sce.getServletContext().getInitParameter("configuration.override") != null) {
        try {
            override = new PropertiesConfiguration(
                    sce.getServletContext().getInitParameter("configuration.override"));
        } catch (ConfigurationException e) {
            log.warn("could not load configuration override file from {}",
                    sce.getServletContext().getInitParameter("configuration.override"));
        }
    }

    startupService.startupConfiguration(null, override, sce.getServletContext());

}

From source file:com.tacitknowledge.util.migration.jdbc.WebAppMigrationLauncher.java

/**
 * {@inheritDoc}/*from w w w. ja  v a2s .c  om*/
 */
public void contextInitialized(ServletContextEvent sce) {
    try {

        // WEB-INF/classes and WEB-INF/lib are not in the system classpath (as defined by
        // System.getProperty("java.class.path")); add it to the search path here
        if (firstRun) {
            ClassDiscoveryUtil.addResourceListSource(
                    new WebAppResourceListSource(sce.getServletContext().getRealPath("/WEB-INF")));
        }
        firstRun = false;

        String systemName = ConfigurationUtil.getRequiredParam("migration.systemname", sce, this);
        String settings = ConfigurationUtil.getOptionalParam("migration.settings", sce, this);

        // The MigrationLauncher is responsible for handling the interaction
        // between the PatchTable and the underlying MigrationTasks; as each
        // task is executed, the patch level is incremented, etc.
        try {
            MigrationUtil.doMigrations(systemName, settings);
        } catch (MigrationException e) {
            // Runtime exceptions coming from a ServletContextListener prevent the
            // application from being deployed.  In this case, the intention is
            // for migration-enabled applications to fail-fast if there are any
            // errors during migration.
            throw new RuntimeException("Migration exception caught during migration", e);
        }
    } catch (RuntimeException e) {
        // Catch all exceptions for the sole reason of logging in
        // as many places as possible - debugging migration
        // problems requires detection first, and that means
        // getting the word of failures out.
        log.error(e);
        System.out.println(e.getMessage());
        e.printStackTrace(System.out);
        System.err.println(e.getMessage());
        e.printStackTrace(System.err);

        throw e;
    }
}

From source file:io.kahu.hawaii.util.logger.Log4jConfigListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    String config = System.getenv("log4j.configuration");
    if (StringUtils.isBlank(config)) {
        config = System.getProperty("log4j.configuration");
    }//from  ww w  .  ja  v a 2 s. c  om
    if (StringUtils.isNotEmpty(config)) {
        String overrideConfig = StringUtils.replace(config, ".xml", ".local.xml");
        if (!configureAndWatch(overrideConfig)) {
            configureAndWatch(config);
            sce.getServletContext().log("Configured to watch log configuration '" + config + "'");
        } else {
            sce.getServletContext().log("Configured to watch log configuration '" + overrideConfig + "'");
        }
    }
}