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.iterx.miru.support.servlet.dispatcher.context.BootstrapServletContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {

    try {/*  w w w. j a  v  a 2  s . com*/
        DispatcherApplicationContext applicationContext;
        ApplicationContext parentApplicationContext;
        ServletContext servletContext;
        String parameter;
        String path;
        int next;

        parentApplicationContext = null;
        servletContext = servletContextEvent.getServletContext();

        path = resolveContextPath(servletContext);
        next = path.length();
        while ((next = path.lastIndexOf('/', next - 1)) > -1) {
            if ((parentApplicationContext = (ApplicationContext) contexts.get(path.substring(0, next))) != null)
                break;
        }

        applicationContext = ((parentApplicationContext != null)
                ? new ServletDispatcherApplicationContext(parentApplicationContext, servletContext)
                : new ServletDispatcherApplicationContext(servletContext));

        if ((parameter = servletContext.getInitParameter(ServletDispatcherApplicationContext.BEANS)) != null
                && applicationContext instanceof Loadable) {
            URL url;

            if ((url = (servletContext.getResource(parameter))) != null)
                ((Loadable) applicationContext).load(new UriStreamResource(url.toURI()));
            else
                throw new IOException("Invalid stream [" + parameter + "]");

        }
        if (inheritable) {
            synchronized (contexts) {
                contexts.put(path, applicationContext);
            }
        }

        servletContext.setAttribute((DispatcherApplicationContext.class).getName(), applicationContext);
    } catch (Exception e) {
        e.printStackTrace();
        LOGGER.error("Initialisation failed.", e);
        throw new RuntimeException("Initialisation failed.", e);
    }

}

From source file:eu.openanalytics.rsb.config.BootstrapConfigurationServletContextListener.java

File getWritableConfigurationDirectory(final ServletContextEvent sce) {
    File rsbConfigurationDirectory = new File(ConfigurationFactory.RSB_CONFIGURATION_DIRECTORY);
    if (rsbConfigurationDirectory.isDirectory() && rsbConfigurationDirectory.canWrite()) {
        return rsbConfigurationDirectory;
    }/*from ww w. j a  v a 2s  .c o m*/

    final String path = sce.getServletContext().getRealPath("/WEB-INF/classes");
    if (StringUtils.isNotBlank(path)) {
        rsbConfigurationDirectory = new File(path);
        if (rsbConfigurationDirectory.isDirectory() && rsbConfigurationDirectory.canWrite()) {
            return rsbConfigurationDirectory;
        }
    }

    return null;
}

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

private void init(ServletContextEvent servletContextEvent) {
    // clear the Mapping Diagnostic Context for logging
    MDC.clear();//from ww  w.  j  a  v  a2  s.c  om

    servletContext = servletContextEvent.getServletContext();

    serverInfo = new ServerInfo(servletContext);
    servletContext.setAttribute(BaseModule.SERVLET_CONTEXT, servletContext);
    servletContext.setAttribute(BaseModule.SERVER_INFO, serverInfo);

    setupCommonsConfiguration();

    elementsConfiguration = ElementsProperties.getConfiguration();
    servletContext.setAttribute(BaseModule.ELEMENTS_CONFIGURATION, elementsConfiguration);

    try {
        loadConfiguration();
    } catch (ConfigurationException e) {
        logger.error("Could not load configuration", e);
        throw new Error(e);
    }
    servletContext.setAttribute(BaseModule.APPLICATION_DIRECTORY, applicationDirectory);
    servletContext.setAttribute(BaseModule.PORTOFINO_CONFIGURATION, configuration);
    // hongliangpan add
    BaseContextUtils.setApplicationDirectory(applicationDirectory);

    logger.debug("Setting blobs directory");
    File appBlobsDir;
    if (configuration.containsKey(PortofinoProperties.BLOBS_DIR_PATH)) {
        appBlobsDir = new File(configuration.getString(PortofinoProperties.BLOBS_DIR_PATH));
    } else {
        File appDir = (File) servletContext.getAttribute(BaseModule.APPLICATION_DIRECTORY);
        appBlobsDir = new File(appDir, "blobs");
    }
    String blobsDirPath = appBlobsDir.getAbsolutePath();
    elementsConfiguration.setProperty(ElementsProperties.BLOBS_DIR, blobsDirPath);
    logger.info("Blobs directory: " + blobsDirPath);

    File groovyClasspath = new File(applicationDirectory, "groovy");
    logger.info("Initializing Groovy script engine with classpath: " + groovyClasspath.getAbsolutePath());
    ElementsFileUtils.ensureDirectoryExistsAndWarnIfNotWritable(groovyClasspath);

    logger.debug("Registering Groovy class loader");
    GroovyScriptEngine groovyScriptEngine = createScriptEngine(groovyClasspath);
    GroovyClassLoader classLoader = groovyScriptEngine.getGroovyClassLoader();
    servletContext.setAttribute(BaseModule.GROOVY_CLASS_PATH, groovyClasspath);
    servletContext.setAttribute(BaseModule.CLASS_LOADER, classLoader);
    servletContext.setAttribute(BaseModule.GROOVY_SCRIPT_ENGINE, groovyScriptEngine);
    // hongliangpan add
    BaseContextUtils.setGroovyClasspath(groovyClasspath);
    BaseContextUtils.setGroovyScriptEngine(groovyScriptEngine);
    BaseContextUtils.setClassLoader(classLoader);

    logger.debug("Installing I18n ResourceBundleManager");
    ResourceBundleManager resourceBundleManager = new ResourceBundleManager();
    try {
        Enumeration<URL> messagesSearchPaths = classLoader.getResources(PORTOFINO_MESSAGES_FILE_NAME);
        while (messagesSearchPaths.hasMoreElements()) {
            resourceBundleManager.addSearchPath(messagesSearchPaths.nextElement().toString());
        }
        File appMessages = new File(applicationDirectory, PORTOFINO_MESSAGES_FILE_NAME);
        resourceBundleManager.addSearchPath(appMessages.getAbsolutePath());
    } catch (IOException e) {
        logger.warn("Could not initialize resource bundle manager", e);
    }
    servletContext.setAttribute(BaseModule.RESOURCE_BUNDLE_MANAGER, resourceBundleManager);

    logger.info("Servlet API version is " + serverInfo.getServletApiVersion());
    if (serverInfo.getServletApiMajor() < 3) {
        String msg = "Servlet API version should be >= 3.0.";
        logger.warn(msg);
    }

    logger.info("Loading modules...");
    moduleRegistry = new ModuleRegistry(configuration);
    discoverModules(moduleRegistry, classLoader);
    servletContext.setAttribute(BaseModule.MODULE_REGISTRY, moduleRegistry);
    moduleRegistry.migrateAndInit(servletContext);
    logger.info("All modules loaded.");
    moduleRegistry.start();

    String encoding = configuration.getString(PortofinoProperties.URL_ENCODING,
            PortofinoProperties.URL_ENCODING_DEFAULT);
    logger.info("URL character encoding is set to " + encoding
            + ". Make sure the web server uses the same encoding to parse URLs.");
    if (!Charset.isSupported(encoding)) {
        logger.error("The encoding is not supported by the JVM!");
    }
    if (!"UTF-8".equals(encoding)) {
        logger.warn(
                "URL encoding is not UTF-8, but the Stripes framework always generates UTF-8 encoded URLs. URLs with non-ASCII characters may not work.");
    }

    String lineSeparator = System.getProperty("line.separator", "\n");
    logger.info(
            lineSeparator + SEPARATOR + lineSeparator + "--- ManyDesigns Portofino started successfully"
                    + lineSeparator + "--- Context path: {}" + lineSeparator + "--- Real path: {}"
                    + lineSeparator + SEPARATOR,
            new String[] { serverInfo.getContextPath(), serverInfo.getRealPath() });
}

From source file:com.bbc.remarc.servlet.ResourceServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    log.debug("contextInitialized");

    String resourcesPath = System.getenv(Configuration.ENV_DATA_DIR_OPENSHIFT);

    if (resourcesPath == null || "".equals(resourcesPath)) {
        log.info("Not running on OpenShift. Falling back to local resource path");

        resourcesPath = System.getenv(Configuration.ENV_DATA_DIR_LOCAL);
    }//from   w w w  .  j a v  a2s  .  c o  m

    createResourceFolders(resourcesPath);

    event.getServletContext().setAttribute(Configuration.ATT_DATA_DIR, resourcesPath);
}

From source file:com.chilmers.configbootstrapper.ConfigServletContextListener.java

/**
 * Configures the when the servlet context is initialized.
 * {@inheritDoc} //from  w w  w  .  j a  v  a 2  s.  co  m
 */
public void contextInitialized(ServletContextEvent sce) {
    overrideDefaults(sce.getServletContext());
    String configLocation = getApplicationConfigurationLocation(sce.getServletContext());
    if (!configLocation.startsWith("classpath:") && !configLocation.startsWith("file:")) {
        configLocation = "file:" + configLocation;
        logToSystemOut("The application config location neither starts with classpath: nor file:, "
                + "assuming " + configLocation);
    }
    setSystemProperty(this.configLocationPropertyKey, configLocation);

    PropertyResourceBundle config = configHelper.getApplicationConfiguration(configLocation);
    if (config != null) {
        loadApplicationConfigurationSystemProperties(config);
        loadLoggingConfiguration(config);
    }
}

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

private void initProtocolServices(ServletContextEvent event) {

    ServletContext servletContext = event.getServletContext();
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    List<IdentityProviderProtocolType> identityProviderProtocolTypes = this.protocolServiceManager
            .getProtocolServices();//from w  w  w.  j a  v  a  2s.  co m

    Map<String, String> wsEndpointsMap = new HashMap<String, String>();

    for (IdentityProviderProtocolType identityProviderProtocolType : identityProviderProtocolTypes) {
        String name = identityProviderProtocolType.getName();
        LOG.debug("initializing protocol service: " + name);

        // register endpoints
        EndpointsType endpoints = identityProviderProtocolType.getEndpoints();
        if (null != endpoints) {
            for (EndpointType endpoint : endpoints.getEndpoint()) {
                String contextPath = endpoint.getContextPath();
                String servletClassName = endpoint.getServletClass();
                LOG.debug("initializing on context path: " + contextPath + " servlet " + servletClassName);
                Class<?> servletClass;
                try {
                    servletClass = classLoader.loadClass(servletClassName);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException("could not load the servlet class: " + servletClassName);
                }
                if (!Servlet.class.isAssignableFrom(servletClass)) {
                    throw new RuntimeException("not a servlet class: " + servletClassName);
                }
                String servletName = name + contextPath;
                LOG.debug("servlet name: " + servletName);
                @SuppressWarnings("unchecked")
                Dynamic dynamic = servletContext.addServlet(servletName,
                        (Class<? extends Servlet>) servletClass);
                String urlPattern = IdentityProviderProtocolService.ENDPOINT_CONTEXT_PATH + contextPath;
                dynamic.addMapping(urlPattern);
            }
        }

        // WS endpoints
        WSEndpointsType wsEndpoints = identityProviderProtocolType.getWSEndpoints();
        if (null != wsEndpoints) {
            for (WSEndpointType wsEndpoint : wsEndpoints.getWSEndpoint()) {

                String contextPath = wsEndpoint.getContextPath();
                String wsImplClass = wsEndpoint.getWSImplClass();
                LOG.debug("WS Endpoint: path=" + contextPath + " impl=" + wsImplClass);
                wsEndpointsMap.put(contextPath, wsImplClass);
            }
        }

        // initialize protocol specific attribute URIs
        LOG.debug("initializing protocol specific attribute URIs");
        IdentityProviderProtocolService protocolService = this.protocolServiceManager
                .getProtocolService(identityProviderProtocolType);

        for (AttributeEntity attribute : this.attributeService.listAttributes()) {

            this.attributeService.createAttributeUri(protocolService.getId(), attribute.getUri(),
                    protocolService.findAttributeUri(attribute.getUri()));
        }
    }

    // register JAX-WS runtime if necessary
    if (!wsEndpointsMap.isEmpty()) {

        // WSServlet class
        Class<?> wsServletClass;
        try {
            wsServletClass = classLoader.loadClass("com.sun.xml.ws.transport.http.servlet.WSServlet");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
        @SuppressWarnings("unchecked")
        Dynamic dynamic = servletContext.addServlet("WSServlet", (Class<? extends Servlet>) wsServletClass);
        String urlPattern = IdentityProviderProtocolService.WS_ENDPOINT_CONTEXT_PATH + "/*";
        dynamic.setLoadOnStartup(1);
        dynamic.addMapping(urlPattern);

        // intialize WS endpoints
        initWsEndpoints(servletContext, wsEndpointsMap);

    }
}

From source file:com.icesoft.faces.util.event.servlet.ContextEventRepeater.java

public void contextInitialized(final ServletContextEvent event) {
    servletContextConfiguration = new ServletContextConfiguration("com.icesoft.faces",
            event.getServletContext());
    SessionDispatcherListener.contextInitialized(event);
}

From source file:ubic.gemma.web.listener.StartupListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    StartupListener.log.info("Initializing Gemma web context ...");
    StopWatch sw = new StopWatch();
    sw.start();//from ww w  . j  a  v  a2  s  .c o m

    // call Spring's context ContextLoaderListener to initialize
    // all the context files specified in web.xml
    super.contextInitialized(event);

    ServletContext servletContext = event.getServletContext();

    Map<String, Object> config = this.initializeConfiguration(servletContext);

    this.loadTheme(servletContext, config);

    this.loadVersionInformation(config);

    this.loadTrackerInformation(config);

    ApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);

    servletContext.setAttribute(Constants.CONFIG, config);

    this.initializeHomologene(ctx);

    this.configureScheduler(ctx);

    sw.stop();

    double time = sw.getTime() / 1000.00;
    StartupListener.log.info("Initialization of Gemma Spring web context in " + time + " s ");
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.FileGraphSetup.java

@Override
public void contextInitialized(ServletContextEvent sce) {

    boolean aboxChanged = false; // indicates whether any ABox file graph model has changed
    boolean tboxChanged = false; // indicates whether any TBox file graph model has changed

    ServletContext ctx = sce.getServletContext();

    try {/* ww  w . j  a  v a  2s.  co  m*/
        OntDocumentManager.getInstance().setProcessImports(true);
        Dataset dataset = ModelAccess.on(ctx).getDataset();
        RDFService rdfService = ModelAccess.on(ctx).getRDFService(CONTENT);

        // ABox files
        Set<Path> paths = getFilegraphPaths(ctx, RDF, ABOX, FILEGRAPH);

        cleanupDB(dataset, pathsToURIs(paths, ABOX), ABOX);

        // Just update the ABox filegraphs in the DB; don't attach them to a base model.
        aboxChanged = readGraphs(paths, rdfService, ABOX, /* aboxBaseModel */ null);

        // TBox files
        paths = getFilegraphPaths(ctx, RDF, TBOX, FILEGRAPH);

        cleanupDB(dataset, pathsToURIs(paths, TBOX), TBOX);

        OntModel tboxBaseModel = ModelAccess.on(ctx).getOntModel(ModelNames.TBOX_ASSERTIONS);
        tboxChanged = readGraphs(paths, rdfService, TBOX, tboxBaseModel);
    } catch (ClassCastException cce) {
        String errMsg = "Unable to cast servlet context attribute to the appropriate type "
                + cce.getLocalizedMessage();
        log.error(errMsg);
        throw new ClassCastException(errMsg);
    } catch (Throwable t) {
        log.error(t, t);
    } finally {
        OntDocumentManager.getInstance().setProcessImports(false);
    }

    if ((aboxChanged || tboxChanged) && !isUpdateRequired(ctx)) {
        log.info("a full recompute of the Abox will be performed because"
                + " the filegraph abox(s) and/or tbox(s) have changed or are being read for the first time.");
        SimpleReasonerSetup.setRecomputeRequired(ctx, SimpleReasonerSetup.RecomputeMode.BACKGROUND);
    }
}

From source file:org.openspaces.pu.container.jee.context.BootstrapWebApplicationContextListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    Boolean bootstraped = (Boolean) servletContext.getAttribute(BOOTSTRAP_CONTEXT_KEY);
    if (bootstraped != null && bootstraped) {
        logger.debug("Already performed bootstrap, ignoring");
        return;// ww w  .  jav  a  2  s .  c o  m
    }
    servletContext.setAttribute(BOOTSTRAP_CONTEXT_KEY, true);

    logger.info("Booting OpenSpaces Web Application Support");
    logger.info(ClassLoaderUtils.getCurrentClassPathString("Web Class Loader"));
    final ProcessingUnitContainerConfig config = new ProcessingUnitContainerConfig();

    InputStream is = servletContext.getResourceAsStream(MARSHALLED_CLUSTER_INFO);
    if (is != null) {
        try {
            config.setClusterInfo((ClusterInfo) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.CLUSTER_INFO_CONTEXT,
                    config.getClusterInfo());
        } catch (Exception e) {
            logger.warn("Failed to read cluster info from " + MARSHALLED_CLUSTER_INFO, e);
        }
    } else {
        logger.debug("No cluster info found at " + MARSHALLED_CLUSTER_INFO);
    }
    is = servletContext.getResourceAsStream(MARSHALLED_BEAN_LEVEL_PROPERTIES);
    if (is != null) {
        try {
            config.setBeanLevelProperties(
                    (BeanLevelProperties) objectFromByteBuffer(FileCopyUtils.copyToByteArray(is)));
            servletContext.setAttribute(JeeProcessingUnitContainerProvider.BEAN_LEVEL_PROPERTIES_CONTEXT,
                    config.getBeanLevelProperties());
        } catch (Exception e) {
            logger.warn("Failed to read bean level properties from " + MARSHALLED_BEAN_LEVEL_PROPERTIES, e);
        }
    } else {
        logger.debug("No bean level properties found at " + MARSHALLED_BEAN_LEVEL_PROPERTIES);
    }

    Resource resource = null;
    String realPath = servletContext.getRealPath("/META-INF/spring/pu.xml");
    if (realPath != null) {
        resource = new FileSystemResource(realPath);
    }
    if (resource != null && resource.exists()) {
        logger.debug("Loading [" + resource + "]");
        // create the Spring application context
        final ResourceApplicationContext applicationContext = new ResourceApplicationContext(
                new Resource[] { resource }, null, config);
        // "start" the application context
        applicationContext.refresh();

        servletContext.setAttribute(JeeProcessingUnitContainerProvider.APPLICATION_CONTEXT_CONTEXT,
                applicationContext);
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (applicationContext.getType(beanName) != null)
                servletContext.setAttribute(beanName, applicationContext.getBean(beanName));
        }

        if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
            final String key = config.getClusterInfo().getUniqueName();

            SharedServiceData.addServiceDetails(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceDetails> serviceDetails = new ArrayList<ServiceDetails>();
                    Map map = applicationContext.getBeansOfType(ServiceDetailsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceDetails[] details = ((ServiceDetailsProvider) it.next()).getServicesDetails();
                        if (details != null) {
                            for (ServiceDetails detail : details) {
                                serviceDetails.add(detail);
                            }
                        }
                    }
                    return serviceDetails.toArray(new Object[serviceDetails.size()]);
                }
            });

            SharedServiceData.addServiceMonitors(key, new Callable() {
                public Object call() throws Exception {
                    ArrayList<ServiceMonitors> serviceMonitors = new ArrayList<ServiceMonitors>();
                    Map map = applicationContext.getBeansOfType(ServiceMonitorsProvider.class);
                    for (Iterator it = map.values().iterator(); it.hasNext();) {
                        ServiceMonitors[] monitors = ((ServiceMonitorsProvider) it.next())
                                .getServicesMonitors();
                        if (monitors != null) {
                            for (ServiceMonitors monitor : monitors) {
                                serviceMonitors.add(monitor);
                            }
                        }
                    }
                    return serviceMonitors.toArray(new Object[serviceMonitors.size()]);
                }
            });

            Map map = applicationContext.getBeansOfType(MemberAliveIndicator.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final MemberAliveIndicator memberAliveIndicator = (MemberAliveIndicator) it.next();
                if (memberAliveIndicator.isMemberAliveEnabled()) {
                    SharedServiceData.addMemberAliveIndicator(key, new Callable<Boolean>() {
                        public Boolean call() throws Exception {
                            return memberAliveIndicator.isAlive();
                        }
                    });
                }
            }

            map = applicationContext.getBeansOfType(ProcessingUnitUndeployingListener.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                final ProcessingUnitUndeployingListener listener = (ProcessingUnitUndeployingListener) it
                        .next();
                SharedServiceData.addUndeployingEventListener(key, new Callable() {
                    public Object call() throws Exception {
                        listener.processingUnitUndeploying();
                        return null;
                    }
                });
            }

            map = applicationContext.getBeansOfType(InternalDumpProcessor.class);
            for (Iterator it = map.values().iterator(); it.hasNext();) {
                SharedServiceData.addDumpProcessors(key, it.next());
            }
        }
    } else {
        logger.debug("No [" + ApplicationContextProcessingUnitContainerProvider.DEFAULT_PU_CONTEXT_LOCATION
                + "] to load");
    }

    // load jee specific context listener
    if (config.getBeanLevelProperties() != null) {
        String jeeContainer = JeeProcessingUnitContainerProvider
                .getJeeContainer(config.getBeanLevelProperties());
        String className = "org.openspaces.pu.container.jee." + jeeContainer + "."
                + StringUtils.capitalize(jeeContainer) + "WebApplicationContextListener";
        Class clazz = null;
        try {
            clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
        } catch (ClassNotFoundException e) {
            // no class, ignore
        }
        if (clazz != null) {
            try {
                jeeContainerContextListener = (ServletContextListener) clazz.newInstance();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Failed to create JEE specific context listener [" + clazz.getName() + "]", e);
            }
            jeeContainerContextListener.contextInitialized(servletContextEvent);
        }
    }

    // set the class loader used so the service bean can use it
    if (config.getClusterInfo() != null && SystemBoot.isRunningWithinGSC()) {
        SharedServiceData.putWebAppClassLoader(config.getClusterInfo().getUniqueName(),
                Thread.currentThread().getContextClassLoader());
    }
}