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.jasig.cas.web.init.SafeContextLoaderListener.java

public void contextInitialized(final ServletContextEvent sce) {
    try {//from www  . jav a 2  s  .  co  m
        this.delegate.contextInitialized(sce);
    } catch (Throwable t) {
        /*
         * no matter what went wrong, our role is to capture this error and
         * prevent it from blocking initialization of the context. logging
         * overkill so that our deployer will find a record of this problem
         * even if unfamiliar with Commons Logging and properly configuring
         * it.
         */

        final String message = "SafeContextLoaderListener: \n"
                + "The Spring ContextLoaderListener we wrap threw on contextInitialized.\n"
                + "But for our having caught this error, the web application context would not have initialized.";

        // log it via Commons Logging
        log.fatal(message, t);

        // log it to System.err
        System.err.println(message);
        t.printStackTrace();

        // log it to the ServletContext
        ServletContext context = sce.getServletContext();
        context.log(message, t);

        /*
         * record the error so that the application has access to later
         * display a proper error message based on the exception.
         */
        context.setAttribute(CAUGHT_THROWABLE_KEY, t);
    }
}

From source file:com.meltmedia.cadmium.servlets.guice.CadmiumListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    //Force the use of slf4j logger in all JBoss log uses in this wars context!!!
    jboss = ContainerUtils.isJBoss();/*from w w  w . j  av  a 2  s. co m*/
    if (jboss) {
        oldJBoss = ContainerUtils.isOldJBoss();
    }
    if (oldJBoss) {
        System.setProperty("org.jboss.logging.provider", "slf4j");
    }

    failOver = servletContextEvent.getServletContext().getRealPath("/");
    MaintenanceFilter.siteDown.start();
    context = servletContextEvent.getServletContext();

    configManager = new ConfigManager(context);

    Properties cadmiumProperties = configManager.getPropertiesByContext(context, "/WEB-INF/cadmium.properties");

    Properties configProperties = new Properties();
    configProperties = configManager.getSystemProperties();
    configProperties.putAll(cadmiumProperties);

    sharedContentRoot = sharedContextRoot(configProperties, context, log);

    // compute the directory for this application, based on the war name.
    warName = WarUtils.getWarName(context);

    vHostName = getVHostName(context);

    applicationContentRoot = applicationContentRoot(sharedContentRoot, warName, log);

    executor = new ScheduledThreadPoolExecutor(1);
    executor.setContinueExistingPeriodicTasksAfterShutdownPolicy(false);
    executor.setExecuteExistingDelayedTasksAfterShutdownPolicy(false);
    executor.setKeepAliveTime(5, TimeUnit.MINUTES);
    executor.setMaximumPoolSize(Math.min(Runtime.getRuntime().availableProcessors(), 4));

    configProperties = configManager.appendProperties(configProperties,
            new File(applicationContentRoot, CONFIG_PROPERTIES_FILE));

    configManager.setDefaultProperties(configProperties);
    configManager.setDefaultPropertiesFile(new File(applicationContentRoot, CONFIG_PROPERTIES_FILE));

    try {
        LogUtils.configureLogback(servletContextEvent.getServletContext(), applicationContentRoot,
                getVHostName(servletContextEvent.getServletContext()), log);
    } catch (IOException e) {
        log.error("Failed to reconfigure logging", e);
    }

    if ((sshDir = getSshDir(configProperties, sharedContentRoot, log)) != null) {
        GitService.setupSsh(sshDir.getAbsolutePath());
    }

    String repoDir = servletContextEvent.getServletContext().getInitParameter("repoDir");
    if (repoDir != null && repoDir.trim().length() > 0) {
        this.repoDir = repoDir;
    }
    String contentDir = servletContextEvent.getServletContext().getInitParameter("contentDir");
    if (contentDir != null && contentDir.trim().length() > 0) {
        this.contentDir = contentDir;
    }
    if (configProperties.containsKey(LAST_UPDATED_DIR)) {
        File cntDir = new File(configProperties.getProperty(LAST_UPDATED_DIR));
        if (cntDir.exists() && cntDir.canRead()) {
            this.contentDir = cntDir.getName();
        }
    }
    File repoFile = new File(this.applicationContentRoot, this.repoDir);
    if (repoFile.isDirectory() && repoFile.canWrite()) {
        this.repoDir = repoFile.getAbsoluteFile().getAbsolutePath();
    } else {
        log.warn("The repo directory may not have been initialized yet.");
        this.repoDir = repoFile.getAbsoluteFile().getAbsolutePath();
    }

    File contentFile = new File(this.applicationContentRoot, this.contentDir);
    if (contentFile.exists() && contentFile.isDirectory() && contentFile.canWrite()) {
        this.contentDir = contentFile.getAbsoluteFile().getAbsolutePath();
    } else {
        log.warn("The content directory may not have been initialized yet.");
        this.contentDir = contentFile.getAbsoluteFile().getAbsolutePath();
    }

    String channelCfgUrl = configProperties.getProperty(JGROUPS_CHANNEL_CONFIG_URL);
    //String channelCfgUrl = System.getProperty(JGROUPS_CHANNEL_CONFIG_URL);
    if (channelCfgUrl != null) {
        File channelCfgFile = null;
        URL fileUrl = null;
        try {
            fileUrl = new URL(channelCfgUrl);
        } catch (Exception e) {
            channelCfgFile = new File(channelCfgUrl);
        }
        if (fileUrl == null && channelCfgFile != null) {
            if (!channelCfgFile.isAbsolute() && !channelCfgFile.exists()) {
                channelCfgFile = new File(this.sharedContentRoot, channelCfgUrl);
                if (channelCfgFile.exists()) {
                    this.channelConfigUrl = "file://" + channelCfgFile.getAbsoluteFile().getAbsolutePath();
                }
            } else {
                this.channelConfigUrl = "file://" + channelCfgFile.getAbsoluteFile().getAbsolutePath();
            }
        } else if (fileUrl != null) {
            this.channelConfigUrl = fileUrl.toString();
        }
    }
    Vfs.addDefaultURLTypes(new JBossVfsUrlType());
    reflections = Reflections.collect();
    Module modules[] = new Module[] { createServletModule(), createModule() };
    InternalInjectorCreator guiceCreator = new InternalInjectorCreator().stage(Stage.DEVELOPMENT)
            .addModules(Arrays.asList(modules));
    try {
        injector = guiceCreator.build();

        //injector = Guice.createInjector(createServletModule(), createModule());

        // run the postConstruct methods.
        jsr250Executor = Jsr250Utils.createJsr250Executor(injector, log, Scopes.SINGLETON);
        jsr250Executor.postConstruct();

        super.contextInitialized(servletContextEvent);
        File graphFile = new File(applicationContentRoot, "injector.dot");
        graphGood(graphFile, injector);
    } catch (Throwable t) {
        try {
            log.error("Failed to initialize...", t);
            Method primaryInjector = InternalInjectorCreator.class.getDeclaredMethod("primaryInjector");
            primaryInjector.setAccessible(true);
            injector = (Injector) primaryInjector.invoke(guiceCreator);
            if (injector == null) {
                log.error("Injector must not have been created.");
            } else {
                log.error("Found injector {}", injector);
            }
        } catch (Throwable e) {
            log.error("Failed to retrieve injector that failed to initialize.", e);
        }
        throw new RuntimeException("Failed to Initialize", t);
    }
}

From source file:org.kuali.rice.core.web.listener.KualiInitializeListener.java

/**
 * ServletContextListener interface implementation that schedules the start of the lifecycle
 *//*  w  w  w. j a  va2  s.  c  om*/
@Override
public void contextInitialized(ServletContextEvent sce) {
    long startInit = System.currentTimeMillis();
    LOG.info("Initializing Kuali Rice Application...");

    // Stop Quartz from "phoning home" on every startup
    System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");

    List<String> configLocations = new ArrayList<String>();
    String additionalConfigLocations = System.getProperty(KewApiConstants.ADDITIONAL_CONFIG_LOCATIONS_PARAM);
    if (!StringUtils.isBlank(additionalConfigLocations)) {
        String[] additionalConfigLocationArray = additionalConfigLocations.split(",");
        for (String additionalConfigLocation : additionalConfigLocationArray) {
            configLocations.add(additionalConfigLocation);
        }
    }

    String bootstrapSpringBeans = "";
    if (!StringUtils.isBlank(System.getProperty(WEB_BOOTSTRAP_SPRING_FILE))) {
        bootstrapSpringBeans = System.getProperty(WEB_BOOTSTRAP_SPRING_FILE);
    } else if (!StringUtils.isBlank(sce.getServletContext().getInitParameter(WEB_BOOTSTRAP_SPRING_FILE))) {
        String bootstrapSpringInitParam = sce.getServletContext().getInitParameter(WEB_BOOTSTRAP_SPRING_FILE);
        // if the value comes through as ${bootstrap.spring.beans}, we ignore it
        if (!DEFAULT_SPRING_BEANS_REPLACEMENT_VALUE.equals(bootstrapSpringInitParam)) {
            bootstrapSpringBeans = bootstrapSpringInitParam;
            LOG.info("Found bootstrap Spring Beans file defined in servlet context: " + bootstrapSpringBeans);
        }
    }

    Properties baseProps = new Properties();
    baseProps.putAll(getContextParameters(sce.getServletContext()));
    baseProps.putAll(System.getProperties());
    JAXBConfigImpl config = new JAXBConfigImpl(baseProps);
    ConfigContext.init(config);

    context = new XmlWebApplicationContext();
    if (!StringUtils.isEmpty(bootstrapSpringBeans)) {
        context.setConfigLocation(bootstrapSpringBeans);
    }
    context.setServletContext(sce.getServletContext());

    // Provide an optional method for bootstrapping a Spring property source
    Optional<PropertySource<?>> ps = PropertySources.getPropertySource(sce, "web.bootstrap.spring.psc");
    if (ps.isPresent()) {
        PropertySources.addFirst(context, ps.get());
    }

    try {
        context.refresh();
    } catch (RuntimeException e) {
        LOG.error("problem during context.refresh()", e);

        throw e;
    }

    context.start();
    long endInit = System.currentTimeMillis();
    LOG.info("...Kuali Rice Application successfully initialized, startup took " + (endInit - startInit)
            + " ms.");
}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

@Override
public void contextInitialized(ServletContextEvent event) {

    startupTime = System.currentTimeMillis();
    startupWithTrust(Jahia.isEnterpriseEdition() ? (Jahia.getBuildNumber() + "." + Jahia.getEEBuildNumber())
            : String.valueOf(Jahia.getBuildNumber()));

    logger.info("Starting up Digital Experience Manager, please wait...");

    servletContext = event.getServletContext();

    Jahia.setContextPath(servletContext.getContextPath());

    initWebAppRoot();/*from w  w  w.ja v  a 2  s .c  o m*/

    if (System.getProperty("jahia.config") == null) {
        setSystemProperty("jahia.config", "");
    }
    if (System.getProperty("jahia.license") == null) {
        setSystemProperty("jahia.license", "");
    }

    try {
        // verify supported Java version
        Jahia.verifyJavaVersion(servletContext.getInitParameter("supported_jdk_versions"));
    } catch (JahiaInitializationException e) {
        throw new JahiaRuntimeException(e);
    }

    detectPID(servletContext);

    GroovyPatcher.executeScripts(servletContext, "beforeContextInitializing");

    // initialize VFS file system (solves classloader issue: https://issues.apache.org/jira/browse/VFS-228 )
    try {
        VFS.getManager();
    } catch (FileSystemException e) {
        throw new JahiaRuntimeException(e);
    }

    try {
        long timer = System.currentTimeMillis();
        logger.info("Start initializing Spring root application context");

        running = true;

        super.contextInitialized(event);

        logger.info("Spring Root application context initialized in {} ms",
                (System.currentTimeMillis() - timer));

        // initialize services registry
        ServicesRegistry.getInstance().init();

        // fire Spring event that the root context is initialized
        WebApplicationContext rootCtx = ContextLoader.getCurrentWebApplicationContext();
        rootCtx.publishEvent(new RootContextInitializedEvent(rootCtx));

        if (Jahia.isEnterpriseEdition()) {
            requireLicense();
        }

        boolean isProcessingServer = SettingsBean.getInstance().isProcessingServer();

        // execute patches after root context initialization
        if (isProcessingServer) {
            GroovyPatcher.executeScripts(servletContext, "rootContextInitialized");
        }

        // start OSGi container
        FrameworkService.getInstance().start();

    } catch (JahiaException e) {
        running = false;
        logger.error(e.getMessage(), e);
        throw new JahiaRuntimeException(e);
    } catch (RuntimeException e) {
        running = false;
        throw e;
    } finally {
        JCRSessionFactory.getInstance().closeAllSessions();
    }
}

From source file:com.clican.pluto.cms.ui.listener.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    super.contextInitialized(event);
    try {/* w ww  .j a  v  a2s  . c  om*/
        Velocity.init(
                Thread.currentThread().getContextClassLoader().getResource("velocity.properties").getPath());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    ApplicationContext ctx = null;
    JndiUtils.setJndiFactory(MockContextFactory.class.getName());
    Hashtable<String, String> ht = new Hashtable<String, String>();
    ht.put(Context.INITIAL_CONTEXT_FACTORY, MockContextFactory.class.getName());
    try {
        ctx = (ApplicationContext) JndiUtils.lookupObject(ApplicationContext.class.getName());
        if (ctx == null) {
            log.warn("Cannot get ApplicationContext from JNDI");
        }
    } catch (Exception e) {
        log.warn("Cannot get ApplicationContext from JNDI");
    }
    if (ctx == null) {
        ctx = (new ClassPathXmlApplicationContext(new String[] { "classpath*:META-INF/ui-*.xml", }));
    }
    XmlWebApplicationContext wac = (XmlWebApplicationContext) WebApplicationContextUtils
            .getRequiredWebApplicationContext(event.getServletContext());
    wac.setParent(ctx);
    wac.refresh();
    event.getServletContext().setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
    Constants.ctx = wac;
}

From source file:org.apache.syncope.ext.saml2lsp.agent.SAML2SPAgentSetup.java

@Override
public void contextInitialized(final ServletContextEvent sce) {
    // read saml2spagent.properties
    Properties props = PropertyUtils.read(getClass(), SAML2SP_AGENT_PROPERTIES, "conf.directory").getLeft();

    String anonymousUser = props.getProperty("anonymousUser");
    assertNotNull(anonymousUser, "<anonymousUser>");
    String anonymousKey = props.getProperty("anonymousKey");
    assertNotNull(anonymousKey, "<anonymousKey>");

    String scheme = props.getProperty("scheme");
    assertNotNull(scheme, "<scheme>");
    String host = props.getProperty("host");
    assertNotNull(host, "<host>");
    String port = props.getProperty("port");
    assertNotNull(port, "<port>");
    String rootPath = props.getProperty("rootPath");
    assertNotNull(rootPath, "<rootPath>");
    String useGZIPCompression = props.getProperty("useGZIPCompression");
    assertNotNull(useGZIPCompression, "<useGZIPCompression>");

    SyncopeClientFactoryBean clientFactory = new SyncopeClientFactoryBean()
            .setAddress(scheme + "://" + host + ":" + port + "/" + rootPath)
            .setUseCompression(BooleanUtils.toBoolean(useGZIPCompression));

    sce.getServletContext().setAttribute(Constants.SYNCOPE_CLIENT_FACTORY, clientFactory);
    sce.getServletContext().setAttribute(Constants.SYNCOPE_ANONYMOUS_CLIENT,
            clientFactory.create(new AnonymousAuthenticationHandler(anonymousUser, anonymousKey)));
}

From source file:org.jahia.bin.listeners.JahiaContextLoaderListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {

    if (!running) {
        return;// ww  w.j a va2 s.  c o  m
    }

    contextInitialized = false;
    running = false;

    logger.info("Shutting down scheduler, wait for running jobs");
    ServicesRegistry.getInstance().getSchedulerService().stop();

    if (isEventInterceptorActivated("interceptServletContextListenerEvents")) {
        SpringContextSingleton.getInstance()
                .publishEvent(new ServletContextDestroyedEvent(event.getServletContext()));
    }

    long timer = System.currentTimeMillis();
    logger.info("Stopping OSGi platform service");

    try {
        FrameworkService.getInstance().stop();
    } catch (Exception e) {
        logger.error("Error stopping OSGi platform service. Cause: " + e.getMessage(), e);
    }

    logger.info("OSGi platform service stopped in {} ms", (System.currentTimeMillis() - timer));

    timer = System.currentTimeMillis();
    logger.info("Shutting down Spring root application context");

    super.contextDestroyed(event);

    removeAddedSystemProperties();

    logger.info("Spring Root application context shut down in {} ms", (System.currentTimeMillis() - timer));
}

From source file:com.sun.faces.config.ConfigureListener.java

public void contextDestroyed(ServletContextEvent sce) {

    ServletContext context = sce.getServletContext();
    if (log.isDebugEnabled()) {
        log.debug("contextDestroyed(" + context.getServletContextName() + ')');
    }/*from   w  w w  .j a  va2  s. co  m*/

    // Release any allocated application resources
    FactoryFinder.releaseFactories();
    tlsExternalContext.set(new ServletContextAdapter(context));
    ApplicationAssociate.clearInstance((ExternalContext) tlsExternalContext.get());
    tlsExternalContext.set(null);

    // Release the initialization mark on this web application
    release();

}

From source file:com.sun.faces.config.ConfigureListener.java

public void contextInitialized(ServletContextEvent sce) {
    // Prepare local variables we will need
    Digester digester = null;// ww w  .  jav  a 2 s .c  o m
    FacesConfigBean fcb = new FacesConfigBean();
    ServletContext context = sce.getServletContext();

    // store the servletContext instance in Thread local Storage.
    // This enables our Application's ApplicationAssociate to locate
    // it so it can store the ApplicationAssociate in the
    // ServletContext.
    tlsExternalContext.set(new ServletContextAdapter(context));

    // see if we're operating in the unit test environment
    try {
        if (RIConstants.IS_UNIT_TEST_MODE) {
            // if so, put the fcb in the servletContext
            context.setAttribute(FACES_CONFIG_BEAN_KEY, fcb);
        }
    } catch (Exception e) {
        if (log.isDebugEnabled()) {
            log.debug("Can't query for test environment");
        }
    }

    // see if we need to disable our TLValidator
    RIConstants.HTML_TLV_ACTIVE = isFeatureEnabled(context, ENABLE_HTML_TLV);

    URL url = null;
    if (log.isDebugEnabled()) {
        log.debug("contextInitialized(" + context.getServletContextName() + ")");
    }

    // Ensure that we initialize a particular application ony once
    if (initialized()) {
        return;
    }

    // Step 1, configure a Digester instance we can use
    digester = digester(isFeatureEnabled(context, VALIDATE_XML));

    // Step 2, parse the RI configuration resource
    url = Util.getCurrentLoader(this).getResource(JSF_RI_CONFIG);
    parse(digester, url, fcb);

    // Step 3, parse any "/META-INF/faces-config.xml" resources
    Iterator resources;
    try {
        List list = new LinkedList();
        Enumeration items = Util.getCurrentLoader(this).getResources(META_INF_RESOURCES);
        while (items.hasMoreElements()) {
            list.add(0, items.nextElement());
        }
        resources = list.iterator();
    } catch (IOException e) {
        String message = null;
        try {
            message = Util.getExceptionMessageString(Util.CANT_PARSE_FILE_ERROR_MESSAGE_ID,
                    new Object[] { META_INF_RESOURCES });
        } catch (Exception ee) {
            message = "Can't parse configuration file:" + META_INF_RESOURCES;
        }
        log.warn(message, e);
        throw new FacesException(message, e);
    }
    while (resources.hasNext()) {
        url = (URL) resources.next();
        parse(digester, url, fcb);
    }

    // Step 4, parse any context-relative resources specified in
    // the web application deployment descriptor
    String paths = context.getInitParameter(FacesServlet.CONFIG_FILES_ATTR);
    if (paths != null) {
        for (StringTokenizer t = new StringTokenizer(paths.trim(), ","); t.hasMoreTokens();) {

            url = getContextURLForPath(context, t.nextToken().trim());
            if (url != null) {
                parse(digester, url, fcb);
            }

        }
    }

    // Step 5, parse "/WEB-INF/faces-config.xml" if it exists
    url = getContextURLForPath(context, WEB_INF_RESOURCE);
    if (url != null) {
        parse(digester, url, fcb);
    }

    // Step 6, use the accumulated configuration beans to configure the RI
    try {
        configure(context, fcb);
    } catch (FacesException e) {
        e.printStackTrace();
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        throw new FacesException(e);
    }

    // Step 7, verify that all the configured factories are available
    // and optionall that configured objects can be created
    verifyFactories();
    if (isFeatureEnabled(context, VERIFY_OBJECTS)) {
        verifyObjects(context, fcb);
    }

    tlsExternalContext.set(null);
}