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.kuali.ext.mm.web.listener.StandaloneInitializeListener.java

/**
 * ServletContextListener interface implementation that schedules the start of the lifecycle
 *//*from www . jav  a  2s .c o m*/
public void contextInitialized(ServletContextEvent sce) {
    long startInit = System.currentTimeMillis();
    try {
        Properties p = new Properties();
        p.load(getClass().getClassLoader().getResourceAsStream(DEFAULT_LOG4J_CONFIG));
        PropertyConfigurator.configure(p);
    } catch (Exception e) {
        throw new WorkflowRuntimeException(e);
    }

    LOG.info("Initializing Organization Of Interest...");

    sce.getServletContext().setAttribute("Constants", new JSTLConstants(KEWConstants.class));

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

    String bootstrapSpringBeans = DEFAULT_SPRING_BEANS;
    if (!StringUtils.isBlank(System.getProperty(KEWConstants.BOOTSTRAP_SPRING_FILE))) {
        bootstrapSpringBeans = System.getProperty(KEWConstants.BOOTSTRAP_SPRING_FILE);
    } else if (!StringUtils
            .isBlank(sce.getServletContext().getInitParameter(KEWConstants.BOOTSTRAP_SPRING_FILE))) {
        String bootstrapSpringInitParam = sce.getServletContext()
                .getInitParameter(KEWConstants.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);
        }
    }
    try {
        String basePath = findBasePath(sce.getServletContext());
        Properties baseProps = new Properties();
        baseProps.putAll(getContextParameters(sce.getServletContext()));
        baseProps.putAll(System.getProperties());
        baseProps.setProperty(RICE_BASE, basePath);
        // HACK: need to determine best way to do this...
        // if the additional config locations property is empty then we need
        // to explicitly set it so that if we use it in a root config
        // a value (an empty value) can be found, and the config parser
        // won't blow up because "additional.config.locations" property
        // cannot be resolved
        // An alternative to doing this at the application/module level would
        // be to push this functionality down into the Rice ConfigFactoryBean
        // e.g., by writing a simple ResourceFactoryBean that would conditionally
        // expose the resource, and then plugging the Resource into the ConfigFactoryBean
        // However, currently, the ConfigFactoryBean operates on String locations, not
        // Resources. Spring can coerce string <value>s into Resources, but not vice-versa
        if (StringUtils.isEmpty(additionalConfigLocations)) {
            baseProps.setProperty(KEWConstants.ADDITIONAL_CONFIG_LOCATIONS_PARAM, "");
        }
        SimpleConfig config = new SimpleConfig(baseProps);
        config.parseConfig();
        ConfigContext.init(config);

        URL[] urls = ((URLClassLoader) ClassLoader.getSystemClassLoader()).getURLs();
        StringBuffer classpath = new StringBuffer("Classpath is:\n");
        for (URL clp : urls) {
            classpath.append(clp.getFile() + ";");
        }
        LOG.info(classpath.toString());
        context = new ClassPathXmlApplicationContext(bootstrapSpringBeans);
        context.start();

        if (shouldExecuteMessageFetcher()) {
            // execute the MessageFetcher to grab any messages that were being processed
            // when the system shut down originally
            MessageFetcher messageFetcher = new MessageFetcher((Integer) null);
            KSBServiceLocator.getThreadPool().execute(messageFetcher);
        }
    } catch (Exception e) {
        LOG.fatal("Organization of Interest startup failed!", e);
        throw new RuntimeException("Startup failed.  Exiting.", e);
    }
    long endInit = System.currentTimeMillis();
    LOG.info("...Organization of Interest successfully initialized, startup took " + (endInit - startInit)
            + " ms.");
}

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

/**
 * Main entry point for the Red5 Server as a war
 *//*from w ww. j  ava2 s  .  c  o  m*/
// Notification that the web application is ready to process requests
@Override
public void contextInitialized(ServletContextEvent sce) {
    if (null != servletContext) {
        return;
    }
    instance = this;
    System.setProperty("red5.deployment.type", "war");

    myClassloader = getClass().getClassLoader();

    servletContext = sce.getServletContext();
    String prefix = servletContext.getRealPath("/");

    servletContext.setAttribute("root.classloader", myClassloader);

    initRegistry(servletContext);

    long time = System.currentTimeMillis();

    logger.info("RED5 Server (http://www.osflash.org/red5)");
    logger.info("Root context loader");
    logger.debug("Path: " + prefix);

    try {
        // instance the context loader
        ContextLoader loader = createContextLoader();
        applicationContext = (ConfigurableWebApplicationContext) loader
                .initWebApplicationContext(servletContext);
        logger.debug("Root context path: " + applicationContext.getServletContext().getContextPath());

        ConfigurableBeanFactory factory = applicationContext.getBeanFactory();

        // register default
        factory.registerSingleton("default.context", applicationContext);

        // get the main factory
        parentFactory = (DefaultListableBeanFactory) factory.getParentBeanFactory();

        // create a wrapper around our primary context
        BeanFactoryReference beanfactoryRef = new ContextBeanFactoryReference(applicationContext);

        // set it in the root servlet context
        servletContext.setAttribute("bean.factory.ref", beanfactoryRef);

        // set a remoting codec factory for AMF use
        servletContext.setAttribute("remoting.codec.factory", parentFactory.getBean("remotingCodecFactory"));

        server = (Server) parentFactory.getBean("red5.server");

        clientRegistry = (ClientRegistry) factory.getBean("global.clientRegistry");

        globalInvoker = (ServiceInvoker) factory.getBean("global.serviceInvoker");

        globalStrategy = (MappingStrategy) factory.getBean("global.mappingStrategy");

        global = (GlobalScope) factory.getBean("global.scope");
        logger.debug("GlobalScope: " + global);
        global.setServer(server);
        global.register();
        global.start();

        globalResolver = new ScopeResolver();
        globalResolver.setGlobalScope(global);

        logger.debug("About to grab Webcontext bean for Global");
        Context globalContext = (Context) factory.getBean("global.context");
        globalContext.setCoreBeanFactory(parentFactory);
        globalContext.setClientRegistry(clientRegistry);
        globalContext.setServiceInvoker(globalInvoker);
        globalContext.setScopeResolver(globalResolver);
        globalContext.setMappingStrategy(globalStrategy);

        logger.debug("About to grab Webcontext bean for ROOT");
        Context webContext = (Context) factory.getBean("web.context");
        webContext.setCoreBeanFactory(parentFactory);
        webContext.setClientRegistry(clientRegistry);
        webContext.setServiceInvoker(globalInvoker);
        webContext.setScopeResolver(globalResolver);
        webContext.setMappingStrategy(globalStrategy);

        WebScope scope = (WebScope) factory.getBean("web.scope");
        scope.setServer(server);
        scope.setParent(global);
        scope.register();
        scope.start();

        // grab the scope list (other war/webapps)
        IRemotableList remote = (IRemotableList) Naming
                .lookup("rmi://localhost:" + rmiPort + "/subContextList");
        logger.debug("Children: " + remote.numChildren());
        if (remote.hasChildren()) {
            logger.debug("Children were detected");
            for (int i = 0; i < remote.numChildren(); i++) {
                logger.debug("Enumerating children");
                WebSettings settings = remote.getAt(i);
                registerSubContext(settings.getWebAppKey());
            }
            logger.debug("End of children...");
        }

    } catch (Throwable t) {
        logger.error(t);
    } finally {
        timer = new Timer();
        checkScopeList = new CheckScopeListTask();
        timer.scheduleAtFixedRate(checkScopeList, 1000, 30000);
    }

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

}

From source file:org.parancoe.web.plugin.PluginHelper.java

protected void copyJspResources(ApplicationContextPlugin plugin, ServletContextEvent evt) throws IOException {
    List<String> jspResources = plugin.getJspResources();
    if (jspResources.isEmpty()) {
        log.info("No JSP resources to copy for this plugin.");
    } else {// ww  w  .  ja v a2s  . c  om
        String jspBasePath = Constants.DEFAULT_JSP_BASE_PATH;
        if (ctx.containsBean(Constants.JSP_BASE_PATH_BEAN_NAME)) {
            jspBasePath = (String) ctx.getBean(Constants.JSP_BASE_PATH_BEAN_NAME);
        }
        String realPath = evt.getServletContext().getRealPath(jspBasePath);
        if (realPath == null) {
            log.warn("Can't copy JSP resources to " + jspBasePath
                    + ". Is the application deployed as a WAR or in an inaccessible location?");
        } else {
            log.info("Copying JSP resources to " + realPath + " ...");
            for (String jspResource : jspResources) {
                log.info("  Copying " + jspResource + " ...");
                Resource[] resources = ctx.getResources(jspResource);
                int i = 0;
                for (Resource resource : resources) {
                    String resourceURI = resource.getURI().toString();
                    String baseName = extractJspResourceBaseName(resourceURI, plugin.getJspPrefix());
                    String destination = realPath + baseName;
                    File destinationFile = new File(destination);
                    if (destinationFile.exists()) {
                        log.warn("    Not copying " + resourceURI + " to " + destination
                                + " as it already exists.");
                    } else {
                        log.info("    Copying " + resourceURI + " to " + destination + " .");
                        destinationFile.getParentFile().mkdirs();
                        InputStream in = resource.getInputStream();
                        FileOutputStream out = new FileOutputStream(destinationFile);
                        try {
                            IOUtils.copy(in, out);
                        } finally {
                            IOUtils.closeQuietly(in);
                            IOUtils.closeQuietly(out);
                        }
                    }
                }
            }
        }
    }
}

From source file:edu.stanford.epad.epadws.listener.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    // Skip, if we are using same APP
    if (!Main.separateWebServicesApp)
        return;/* ww w.j a  va  2s . c om*/
    log.info("#####################################################");
    log.info("############# Starting ePAD Web Service #############");
    log.info("#####################################################");

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

    ServletContext servletContext = event.getServletContext();
    appContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    webAppPath = servletContext.getRealPath("/");
    try {
        URL url = servletContext.getResource("/");
        webAppURL = "http:/" + url.getPath(); // Does not look correct
        System.out.println("Context initialized , webAppUrl=" + webAppURL + " webappPath=" + webAppPath);
    } catch (Exception x) {
    }
    Main.checkPropertiesFile();
    Main.checkResourcesFolders();
    Main.checkPluginsFile();
    RemotePACService.checkPropertiesFile();
    Main.initializePlugins();
    Main.startSupportThreads();
    Main.loadPluginClasses();
    new ServerStatusHandler(); // Sets startup time
}

From source file:de.xwic.sandbox.server.ServletLifecycleListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    HibernateDAOProvider hbnDP = new HibernateDAOProvider();

    DAOFactory factory = CommonConfiguration.createCommonDaoFactory(hbnDP);

    DAOSystem.setDAOFactory(factory);/*from  w  w  w.ja  va  2 s .  co  m*/
    DAOSystem.setSecurityManager(new ServerSecurityManager());
    DAOSystem.setUseCaseService(new DefaultUseCaseService(hbnDP));
    DAOSystem.setFileHandler(new HbnFileOracleFixDAO());

    SandboxModelConfig.register(factory);
    StartModelConfig.register(factory);

    DemoAppModelConfig.register(factory);

    final ServletContext context = event.getServletContext();
    SandboxModelConfig.setWebRootDirectory(new File(context.getRealPath("/")));

    final String rootPath = context.getRealPath("");

    final File path = new File(rootPath + "/config");
    Setup setup;
    try {
        setup = XmlConfigLoader.loadSetup(path.toURI().toURL());
    } catch (Exception e) {
        log.error("Error loading product configuration", e);
        throw new RuntimeException("Error loading product configuration: " + e, e);
    }
    ConfigurationManager.setSetup(setup);

    if (!HibernateUtil.isInitialized()) {
        Configuration configuration = new Configuration();
        configuration.configure(); // load configuration settings from hbm file.
        // load properties
        Properties prop = new Properties();
        InputStream in = context.getResourceAsStream("WEB-INF/hibernate.properties");
        if (in == null) {
            in = context.getResourceAsStream("/WEB-INF/hibernate.properties");
        }
        if (in != null) {
            try {
                prop.load(in);
                configuration.setProperties(prop);
            } catch (IOException e) {
                log.error("Error loading hibernate.properties. Skipping this step! : " + e);
            }
        }
        HibernateUtil.initialize(configuration);
    }

    File prefStorePath = new File(new File(rootPath), "WEB-INF/prefstore");
    if (!prefStorePath.exists() && !prefStorePath.mkdirs()) {
        throw new IllegalStateException("Error initializing preference store: can not create directory "
                + prefStorePath.getAbsolutePath());
    }
    Platform.initialize(new StorageProvider(prefStorePath), new UserContextPreferenceProvider());

}

From source file:org.killbill.billing.server.listeners.KillbillPlatformGuiceListener.java

protected void initializeMetrics(final ServletContextEvent event) {

    final MetricRegistry metricRegistry = injector.getInstance(MetricRegistry.class);
    final LoggerContext factory = (LoggerContext) LoggerFactory.getILoggerFactory();
    final ch.qos.logback.classic.Logger root = factory.getLogger(Logger.ROOT_LOGGER_NAME);

    final InstrumentedAppender metrics = new InstrumentedAppender(metricRegistry);
    metrics.setContext(root.getLoggerContext());
    metrics.start();/*from w w  w . j a va 2s.  com*/
    root.addAppender(metrics);

    event.getServletContext().setAttribute(HealthCheckServlet.HEALTH_CHECK_REGISTRY,
            injector.getInstance(HealthCheckRegistry.class));
    event.getServletContext().setAttribute(MetricsServlet.METRICS_REGISTRY, metricRegistry);
}

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

public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    StartupStatus ss = StartupStatus.getBean(ctx);

    boolean migrationChangesMade = false;

    try {/* w  ww. ja v a 2 s  . c  o  m*/
        UpdateSettings settings = new UpdateSettings();
        putReportingPathsIntoSettings(ctx, settings);
        putNonReportingPathsIntoSettings(ctx, settings);

        try {
            ApplicationUtils.instance().getTBoxReasonerModule().waitForTBoxReasoning();
        } catch (Exception e) {
            // Should mean that the reasoner is not even started yet.
        }

        WebappDaoFactory wadf = ModelAccess.on(ctx).getWebappDaoFactory();
        settings.setDefaultNamespace(wadf.getDefaultNamespace());
        settings.setAssertionOntModelSelector(ModelAccess.on(ctx).getOntModelSelector(ASSERTIONS_ONLY));
        settings.setInferenceOntModelSelector(ModelAccess.on(ctx).getOntModelSelector(INFERENCES_ONLY));
        settings.setUnionOntModelSelector(ModelAccess.on(ctx).getOntModelSelector());

        Path homeDir = ApplicationUtils.instance().getHomeDirectory().getPath();
        settings.setDisplayModel(ModelAccess.on(ctx).getOntModel(DISPLAY));
        OntModel oldTBoxModel = loadModelFromDirectory(ctx.getRealPath(oldTBoxModelDir()));
        settings.setOldTBoxModel(oldTBoxModel);
        OntModel newTBoxModel = loadModelFromDirectory(
                createDirectory(homeDir, "rdf", "tbox", "filegraph").toString());
        settings.setNewTBoxModel(newTBoxModel);
        OntModel oldTBoxAnnotationsModel = loadModelFromDirectory(ctx.getRealPath(oldTBoxAnnotationsDir()));
        settings.setOldTBoxAnnotationsModel(oldTBoxAnnotationsModel);
        OntModel newTBoxAnnotationsModel = loadModelFromDirectory(
                createDirectory(homeDir, "rdf", "tbox", "firsttime").toString());
        settings.setNewTBoxAnnotationsModel(newTBoxAnnotationsModel);
        settings.setRDFService(ModelAccess.on(ctx).getRDFService());

        boolean tryMigrateDisplay = true;
        try {
            //Display model tbox and display metadata 
            //old display model tbox model
            OntModel oldDisplayModelTboxModel = loadModelFromFile(ctx.getRealPath(oldDisplayModelTBoxPath()));
            settings.setOldDisplayModelTboxModel(oldDisplayModelTboxModel);
            //new display model tbox model
            OntModel newDisplayModelTboxModel = loadModelFromFile(ctx.getRealPath(NEW_DISPLAYMODEL_TBOX_PATH));
            settings.setNewDisplayModelTboxModel(newDisplayModelTboxModel);
            //old display model display model metadata
            OntModel oldDisplayModelDisplayMetadataModel = loadModelFromFile(
                    ctx.getRealPath(oldDisplayModelDisplayMetadataPath()));
            settings.setOldDisplayModelDisplayMetadataModel(oldDisplayModelDisplayMetadataModel);
            //new display model display model metadata
            OntModel newDisplayModelDisplayMetadataModel = loadModelFromFile(
                    ctx.getRealPath(NEW_DISPLAYMODEL_DISPLAYMETADATA_PATH));
            settings.setNewDisplayModelDisplayMetadataModel(newDisplayModelDisplayMetadataModel);
            //Get new display model
            OntModel newDisplayModelFromFile = loadModelFromFile(ctx.getRealPath(NEW_DISPLAYMODEL_PATH));
            settings.setNewDisplayModelFromFile(newDisplayModelFromFile);
            OntModel loadedAtStartupFiles = loadModelFromDirectory(
                    ctx.getRealPath(LOADED_STARTUPT_DISPLAYMODEL_DIR));
            settings.setLoadedAtStartupDisplayModel(loadedAtStartupFiles);
            OntModel oldDisplayModelVivoListView = loadModelFromFile(
                    ctx.getRealPath(oldDisplayModelVivoListViewPath()));
            settings.setVivoListViewConfigDisplayModel(oldDisplayModelVivoListView);
        } catch (ModelFileNotFoundException e) {
            // expected if no display migration was intended
            tryMigrateDisplay = false;
        } catch (Exception e) {
            log.info("Unable to read display model migration files. ", e);
            tryMigrateDisplay = false;
        }

        KnowledgeBaseUpdater ontologyUpdater = new KnowledgeBaseUpdater(settings);
        boolean requiredUpdate = ontologyUpdater.updateRequired(ctx);

        if (requiredUpdate && !JenaDataSourceSetupBase.isFirstStartup()) {
            try {
                ctx.setAttribute(KBM_REQURIED_AT_STARTUP, Boolean.TRUE);
                migrationChangesMade = ontologyUpdater.update(ctx);
                if (tryMigrateDisplay) {
                    try {
                        migrateDisplayModel(settings);
                        log.info("Migrated display model");
                    } catch (Exception e) {
                        log.warn("unable to successfully update display model: " + e.getMessage());
                    }
                }
                // reload the display model since the TBoxUpdater may have 
                // modified it
                new ConfigurationModelsSetup().contextInitialized(sce);
            } catch (Exception ioe) {
                ss.fatal(parent, "Exception updating knowledge base for ontology changes: ", ioe);
            }
        }

        removeBadRestrictions(settings.getAssertionOntModelSelector().getTBoxModel());

        log.info("Simple reasoner connected for the ABox");
        if (JenaDataSourceSetupBase.isFirstStartup() || (migrationChangesMade && requiredUpdate)) {
            SimpleReasonerSetup.setRecomputeRequired(ctx, SimpleReasonerSetup.RecomputeMode.FOREGROUND);
        } else if (migrationChangesMade) {
            SimpleReasonerSetup.setRecomputeRequired(ctx, SimpleReasonerSetup.RecomputeMode.BACKGROUND);
        }

    } catch (Throwable t) {
        ss.fatal(parent, "Exception updating knowledge base for ontology changes: ", t);
    }

}

From source file:com.cws.esolutions.security.listeners.SecurityServiceListener.java

/**
 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
 *///from   ww  w.  ja  v a2  s. co  m
public void contextInitialized(final ServletContextEvent sContextEvent) {
    final String methodName = SecurityServiceListener.CNAME
            + "#contextInitialized(final ServletContextEvent sContextEvent)";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("ServletContextEvent: {}", sContextEvent);
    }

    URL xmlURL = null;
    JAXBContext context = null;
    Unmarshaller marshaller = null;
    SecurityConfigurationData configData = null;

    final ServletContext sContext = sContextEvent.getServletContext();
    final ClassLoader classLoader = SecurityServiceListener.class.getClassLoader();

    if (DEBUG) {
        DEBUGGER.debug("ServletContext: {}", sContext);
        DEBUGGER.debug("ClassLoader: {}", classLoader);
    }

    try {
        if (sContext != null) {
            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSLOGGING_FILE)) {
                System.err.println("Logging configuration not found. No logging enabled !");
            } else {
                DOMConfigurator.configure(Loader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSLOGGING_FILE)));
            }

            if (StringUtils.isBlank(SecurityServiceListener.INIT_SYSCONFIG_FILE)) {
                xmlURL = classLoader
                        .getResource(sContext.getInitParameter(SecurityServiceListener.INIT_SYSCONFIG_FILE));

            } else {
                ERROR_RECORDER.error("System configuration not found. Shutting down !");

                throw new SecurityServiceException(
                        "System configuration file location not provided by application. Cannot continue.");
            }

            if (DEBUG) {
                DEBUGGER.debug("xmlURL: {}", xmlURL);
            }

            if (xmlURL != null) {
                context = JAXBContext.newInstance(SecurityConfigurationData.class);
                marshaller = context.createUnmarshaller();
                configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL);

                SecurityServiceListener.svcBean.setConfigData(configData);

                Context initContext = new InitialContext();
                Context envContext = (Context) initContext.lookup(SecurityServiceConstants.DS_CONTEXT);

                DAOInitializer.configureAndCreateAuthConnection(
                        new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())),
                        false, SecurityServiceListener.svcBean);

                Map<String, DataSource> dsMap = new HashMap<String, DataSource>();

                for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) {
                    dsMap.put(mgr.getDsName(), (DataSource) envContext.lookup(mgr.getDataSource()));
                }

                SecurityServiceListener.svcBean.setDataSources(dsMap);
            } else {
                throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
            }
        } else {
            throw new SecurityServiceException("Unable to load configuration. Cannot continue.");
        }
    } catch (NamingException nx) {
        ERROR_RECORDER.error(nx.getMessage(), nx);
    } catch (SecurityServiceException ssx) {
        ERROR_RECORDER.error(ssx.getMessage(), ssx);
    } catch (JAXBException jx) {
        ERROR_RECORDER.error(jx.getMessage(), jx);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);
    }
}

From source file:com.boylesoftware.web.AbstractWebApplication.java

@Override
public void contextDestroyed(final ServletContextEvent sce) {

    sce.getServletContext().removeAttribute(WEBAPP_ATTNAME);

    this.servletContext = null;
}

From source file:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextInitialized(final ServletContextEvent sce) {
    log.info("Creation of the Hibernate SessionFactory for the context");
    try {/*  www  . j  av  a 2  s. com*/
        entityManagerFactory = Persistence
                .createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.container");
    } catch (Exception ex) {
        log.warn("Resource 'jdbc/FutureGatewayDB' not accessuible or"
                + " not properly configured for the application. An"
                + " alternative resource is created on the fly.");
        entityManagerFactory = Persistence.createEntityManagerFactory("it.infn.ct.futuregateway.apiserver.app");
    }
    sce.getServletContext().setAttribute(Constants.SESSIONFACTORY, entityManagerFactory);
    String path = sce.getServletContext().getInitParameter("CacheDir");
    if (path == null || path.isEmpty()) {
        path = sce.getServletContext().getRealPath("/") + ".." + FileSystems.getDefault().getSeparator() + ".."
                + FileSystems.getDefault().getSeparator() + "FutureGatewayData";
    }
    log.info("Created the cache directory: " + path);
    sce.getServletContext().setAttribute(Constants.CACHEDIR, path);
    try {
        Files.createDirectories(Paths.get(path));
        log.info("Cache dir enabled");
    } catch (FileAlreadyExistsException faee) {
        log.debug("Message for '" + path + "':" + faee.getMessage());
        log.info("Cache dir enabled");
    } catch (Exception e) {
        log.error("Impossible to initialise the temporary store");
    }
    ExecutorService tpe;
    try {
        Context ctx = new InitialContext();
        tpe = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        log.warn("Submitter thread not defined in the container. A thread "
                + "pool is created using provided configuration parameters " + "and defaults values");
        int threadPoolSize = Constants.DEFAULTTHREADPOOLSIZE;
        try {
            threadPoolSize = Integer
                    .parseInt(sce.getServletContext().getInitParameter("SubmissioneThreadPoolSize"));
        } catch (NumberFormatException nfe) {
            log.info("Parameter 'SubmissioneThreadPoolSize' has a wrong"
                    + " value or it is not present. Default value " + "10 is used");
        }
        tpe = ThreadPoolFactory.getThreadPool(threadPoolSize, Constants.MAXTHREADPOOLSIZETIMES * threadPoolSize,
                Constants.MAXTHREADIDLELIFE);
    }
    sce.getServletContext().setAttribute(Constants.SUBMISSIONPOOL, tpe);
}