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:it.infn.ct.futuregateway.apiserver.APIContextListener.java

@Override
public final void contextDestroyed(final ServletContextEvent sce) {
    ExecutorService exServ;//ww  w.j av  a  2s  .  c  o m
    try {
        Context ctx = new InitialContext();
        exServ = (ExecutorService) ctx.lookup("java:comp/env/threads/Submitter");
    } catch (NamingException ex) {
        exServ = (ExecutorService) sce.getServletContext().getAttribute("SubmissionThreadPool");
    }
    exServ.shutdown();
    try {
        if (!exServ.awaitTermination(Constants.MAXTHREADWAIT, TimeUnit.MINUTES)) {
            log.warn("Failed to shutdown the submission thread pool.");
        }
    } catch (InterruptedException ex) {
        log.error(ex);
    }
}

From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java

@Override
public void contextDestroyed(ServletContextEvent event) {
    AbstractApplicationContext context = (AbstractApplicationContext) event.getServletContext()
            .getAttribute(ArtifactoryContext.APPLICATION_CONTEXT_KEY);
    try {/*w ww . j  a  va2s.  co  m*/
        getLogger().debug("Context shutdown started");
        if (context != null) {
            if (context instanceof ArtifactoryContext) {
                AddonsManager addonsManager = ((ArtifactoryContext) context).beanForType(AddonsManager.class);
                addonsManager.addonByType(HaCommonAddon.class).shutdown();
            }
            context.destroy();
        }
        if (artifactoryLockFile != null) {
            artifactoryLockFile.release();
        }
        getLogger().debug("Context shutdown Finished");
    } finally {
        event.getServletContext().removeAttribute(ArtifactoryContext.APPLICATION_CONTEXT_KEY);
        event.getServletContext().removeAttribute(ArtifactoryHome.SERVLET_CTX_ATTR);
    }
}

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

/**
 * Inizializzazione di una’applicazione Web.
 * // w  ww  .  jav  a  2 s  .  c o  m
 * @param event Evento.
 */
public void contextInitialized(ServletContextEvent event) {
    UUID applInstanceId;
    ApplicationContext applCtx;
    ServletContext servletCtx = event.getServletContext();
    AttributeMap servletCtxMap;
    EventContext eventCtx = null;

    try {
        applInstanceId = UUIDGenerator.getInstance().newUUID();
    } catch (Exception ex) {
        myLogger.error("Failed to extract UUID.", ex);
        applInstanceId = UUIDGenerator.NIL;
    }

    try {
        servletCtxMap = WebUtils.getSynchronizedAttributeMap(servletCtx);
        servletCtxMap.setAttribute(WebUtils.ATTR_APPLICATIONINSTANCEID, applInstanceId);

        eventCtx = new EventContext(ApplicationContextListener.THREAD_SERVLETCONTEXT_INIT, servletCtx);

        mySpringSvc.contextInitialized(event);
        applCtx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletCtx);
        myApplListeners = applCtx.getBeansOfType(ServletContextListener.class, false, true);
        mySessionListeners = applCtx.getBeansOfType(HttpSessionListener.class, false, true);

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

From source file:org.quartz.ee.servlet.QuartzInitializerListener.java

public void contextInitialized(ServletContextEvent sce) {

    log.info("Quartz Initializer Servlet loaded, initializing Scheduler...");

    ServletContext servletContext = sce.getServletContext();
    StdSchedulerFactory factory;/* w w  w.  j a v a  2s .c o  m*/
    try {

        String configFile = servletContext.getInitParameter("config-file");
        String shutdownPref = servletContext.getInitParameter("shutdown-on-unload");

        if (shutdownPref != null) {
            performShutdown = Boolean.valueOf(shutdownPref).booleanValue();
        }

        // get Properties
        if (configFile != null) {
            factory = new StdSchedulerFactory(configFile);
        } else {
            factory = new StdSchedulerFactory();
        }

        // Always want to get the scheduler, even if it isn't starting, 
        // to make sure it is both initialized and registered.
        scheduler = factory.getScheduler();

        // Should the Scheduler being started now or later
        String startOnLoad = servletContext.getInitParameter("start-scheduler-on-load");

        int startDelay = 0;
        String startDelayS = servletContext.getInitParameter("start-delay-seconds");
        try {
            if (startDelayS != null && startDelayS.trim().length() > 0)
                startDelay = Integer.parseInt(startDelayS);
        } catch (Exception e) {
            log.error("Cannot parse value of 'start-delay-seconds' to an integer: " + startDelayS
                    + ", defaulting to 5 seconds.");
            startDelay = 5;
        }

        /*
         * If the "start-scheduler-on-load" init-parameter is not specified,
         * the scheduler will be started. This is to maintain backwards
         * compatability.
         */
        if (startOnLoad == null || (Boolean.valueOf(startOnLoad).booleanValue())) {
            if (startDelay <= 0) {
                // Start now
                scheduler.start();
                log.info("Scheduler has been started...");
            } else {
                // Start delayed
                scheduler.startDelayed(startDelay);
                log.info("Scheduler will start in " + startDelay + " seconds.");
            }
        } else {
            log.info("Scheduler has not been started. Use scheduler.start()");
        }

        String factoryKey = servletContext.getInitParameter("servlet-context-factory-key");
        if (factoryKey == null) {
            factoryKey = QUARTZ_FACTORY_KEY;
        }

        log.info("Storing the Quartz Scheduler Factory in the servlet context at key: " + factoryKey);
        servletContext.setAttribute(factoryKey, factory);

    } catch (Exception e) {
        log.error("Quartz Scheduler failed to initialize: " + e.toString());
        e.printStackTrace();
    }
}

From source file:org.guzz.web.context.spring.GuzzWithSpringContextLoaderListener.java

public void contextDestroyed(ServletContextEvent event) {
    if (springContext != null) {
        try {//from  w  w  w  .  ja  va  2s  .  co  m
            springContext.contextDestroyed(event);
        } catch (Exception e) {
            log.error(e, e);
        }
        springContext = null;
    }

    if (context != null) {
        context.shutdown(event.getServletContext());
        context = null;
    }
}

From source file:org.scenarioo.rest.application.ScenariooWebApplication.java

@Override
public void contextInitialized(final ServletContextEvent servletContextEvent) {
    LOGGER.info("====================================================");
    LOGGER.info("Scenarioo Viewer is starting up ...");
    LOGGER.info("====================================================");

    initializeApplicationVersion(servletContextEvent.getServletContext());
    loadConfiguration(servletContextEvent);

    LOGGER.info("  Updating documentation content directory (will be done asynchronously ...)");
    ScenarioDocuBuildsManager.INSTANCE.updateAllBuildsAndSubmitNewBuildsForImport();

    LOGGER.info("====================================================");
    LOGGER.info("Scenarioo Viewer started succesfully.");
    LOGGER.info("====================================================");
}

From source file:org.artifactory.webapp.servlet.ArtifactoryContextConfigListener.java

@Override
public void contextInitialized(ServletContextEvent event) {
    final ServletContext servletContext = event.getServletContext();

    setSessionTrackingMode(servletContext);

    final Thread initThread = new Thread("art-init") {
        boolean success = true;

        @SuppressWarnings({ "unchecked" })
        @Override//from   w w  w.  j  a  v a2  s  . c om
        public void run() {
            try {
                //Use custom logger
                String contextId = HttpUtils.getContextId(servletContext);
                //Build a partial config, since we expect the logger-context to exit in the selector cache by only contextId
                LoggerConfigInfo configInfo = new LoggerConfigInfo(contextId);
                LogbackContextSelector.bindConfig(configInfo);
                //No log field since needs to lazy initialize only after logback customization listener has run
                Logger log = getLogger();
                configure(servletContext, log);

                LogbackContextSelector.unbindConfig();
            } catch (Exception e) {
                getLogger().error(
                        "Application could not be initialized: " + ExceptionUtils.getRootCause(e).getMessage(),
                        e);
                success = false;
            } finally {
                if (success) {
                    //Run the waiting filters
                    BlockingQueue<DelayedInit> waitingFiltersQueue = (BlockingQueue<DelayedInit>) servletContext
                            .getAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY);
                    List<DelayedInit> waitingInits = new ArrayList<>();
                    waitingFiltersQueue.drainTo(waitingInits);
                    for (DelayedInit filter : waitingInits) {
                        try {
                            filter.delayedInit();
                        } catch (ServletException e) {
                            getLogger().error("Could not init {}.", filter.getClass().getName(), e);
                            success = false;
                            break;
                        }
                    }
                }
                //Remove the lock and open the app to requests
                servletContext.removeAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY);
            }
        }
    };
    initThread.setDaemon(true);
    servletContext.setAttribute(DelayedInit.APPLICATION_CONTEXT_LOCK_KEY,
            new LinkedBlockingQueue<DelayedInit>());
    initThread.start();
    if (Boolean.getBoolean("artifactory.init.useServletContext")) {
        try {
            getLogger().info("Waiting for servlet context initialization ...");
            initThread.join();
        } catch (InterruptedException e) {
            getLogger().error("Artifactory initialization thread got interrupted", e);
        }
    }
}

From source file:info.magnolia.init.MagnoliaServletContextListener.java

public void contextInitialized(final ServletContextEvent sce, boolean startServer) {
    try {// w w w.  j a  v a 2  s .  co m
        servletContext = sce.getServletContext();

        // Start 'platform' ComponentProvider
        GuiceComponentProviderBuilder builder = new GuiceComponentProviderBuilder();
        builder.withConfiguration(getPlatformComponents());
        builder.inStage(Stage.PRODUCTION);
        builder.exposeGlobally();
        platform = builder.build();

        // Expose server name as a system property, so it can be used in log4j configurations
        // rootPath and webapp are not exposed since there can be different webapps running in the same jvm

        String serverName = platform.getComponent(MagnoliaInitPaths.class).getServerName();
        if (serverName == null) {
            log.warn(
                    "Failed to obtain server name, please check your configuration. Using 'default' as server name instead.");
            serverName = "default";
        }

        System.setProperty("server", serverName);

        // Load module definitions
        moduleManager = platform.getComponent(ModuleManager.class);
        moduleManager.loadDefinitions();

        // Initialize MagnoliaConfigurationProperties
        MagnoliaConfigurationProperties configurationProperties = platform
                .getComponent(MagnoliaConfigurationProperties.class);
        configurationProperties.init();
        log.info("Property sources loaded: {}", configurationProperties.describe());

        // Connect legacy properties to the MagnoliaConfigurationProperties object
        SystemProperty.setMagnoliaConfigurationProperties(configurationProperties);

        // Initialize logging now that properties are available
        Log4jConfigurer.initLogging();

        // Start 'system' ComponentProvider
        builder = new GuiceComponentProviderBuilder();
        builder.withConfiguration(getSystemComponents());
        builder.withParent(platform);
        builder.exposeGlobally();
        system = builder.build();

        // Delegate to ConfigLoader to complete initialization
        loader = system.getComponent(ConfigLoader.class);
        if (startServer) {
            startServer();
        }

    } catch (Throwable t) {
        log.error("Oops, Magnolia could not be started", t);
        t.printStackTrace();
        if (t instanceof Error) {
            throw (Error) t;
        }
        if (t instanceof RuntimeException) {
            throw (RuntimeException) t;
        }
        throw new RuntimeException(t);
    }
}

From source file:com.haulmont.cuba.web.sys.singleapp.SingleAppWebContextLoader.java

/**
 * Here we create servlets and filters manually, to make sure the classes would be loaded using necessary classloader.
 *///ww  w  . j  a  v  a2s.  c o  m
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    super.contextInitialized(servletContextEvent);

    ServletContext servletContext = servletContextEvent.getServletContext();

    registerAppServlet(servletContext);

    registerDispatchServlet(servletContext);

    registerRestApiServlet(servletContext);

    registerCubaHttpFilter(servletContext);

    registerFrontAppServlet(servletContext);

    registerIdpServlet(servletContext);

    registerClassLoaderFilter(servletContext);

    initWebServletContextListener(servletContextEvent, servletContext);
}

From source file:org.exem.flamingo.web.util.ApplicationInformationDisplayContextListener.java

@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    System.setProperty("PID", SystemUtils.getPid());

    Properties properties = new Properties();
    ServletContext context = servletContextEvent.getServletContext();
    InputStream inputStream = null;
    try {//from w  w  w. ja va  2 s  . c o  m
        inputStream = context.getResourceAsStream("/WEB-INF/app.properties");
        properties.load(inputStream);
    } catch (Exception ex) {
        throw new IllegalArgumentException("Cannot load a '/WEB/INF/app.properties' file.", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }

    // See : http://patorjk.com/software/taag/#p=display&f=Slant&t=Flamingo
    StringBuilder builder = new StringBuilder();
    builder.append("    ________                _                 \n"
            + "   / ____/ /___ _____ ___  (_)___  ____ _____ \n"
            + "  / /_  / / __ `/ __ `__ \\/ / __ \\/ __ `/ __ \\\n"
            + " / __/ / / /_/ / / / / / / / / / / /_/ / /_/ /\n"
            + "/_/   /_/\\__,_/_/ /_/ /_/_/_/ /_/\\__, /\\____/ \n"
            + "                                /____/        ");

    printHeader(builder, "Application Information");
    Properties appProps = new Properties();
    appProps.put("Instance", StringUtils.isEmpty(System.getProperty("instance")) ? "** UNKNOWN **"
            : System.getProperty("instance"));
    appProps.put("Version", properties.get("version"));
    appProps.put("Build Date", properties.get("build.timestamp"));
    appProps.put("Build Number", properties.get("build.number"));
    appProps.put("Revision Number", properties.get("revision.number"));
    appProps.put("Organization", properties.get("organization"));
    appProps.put("Homepage", properties.get("homepage"));

    if (context != null) {
        appProps.put("Application Server", context.getServerInfo() + " - Servlet API "
                + context.getMajorVersion() + "." + context.getMinorVersion());
    }

    Properties systemProperties = System.getProperties();
    appProps.put("Java Version", systemProperties.getProperty("java.version", UNKNOWN) + " - "
            + systemProperties.getProperty("java.vendor", UNKNOWN));
    appProps.put("Current Working Directory", systemProperties.getProperty("user.dir", UNKNOWN));

    print(builder, appProps);

    Properties memPros = new Properties();
    final Runtime rt = Runtime.getRuntime();
    final long maxMemory = rt.maxMemory() / MEGA_BYTES;
    final long totalMemory = rt.totalMemory() / MEGA_BYTES;
    final long freeMemory = rt.freeMemory() / MEGA_BYTES;
    final long usedMemory = totalMemory - freeMemory;

    memPros.put("Maximum Allowable Memory", maxMemory + "MB");
    memPros.put("Total Memory", totalMemory + "MB");
    memPros.put("Free Memory", freeMemory + "MB");
    memPros.put("Used Memory", usedMemory + "MB");

    print(builder, memPros);

    printHeader(builder, "Java System Properties");
    Properties sysProps = new Properties();
    for (final Map.Entry<Object, Object> entry : systemProperties.entrySet()) {
        sysProps.put(entry.getKey(), entry.getValue());
    }

    print(builder, sysProps);

    printHeader(builder, "System Environments");
    Map<String, String> envs = System.getenv();
    Properties envProps = new Properties();
    Set<String> strings = envs.keySet();
    for (String key : strings) {
        String message = envs.get(key);
        envProps.put(key, message);
    }

    print(builder, envProps);

    WebLogbackConfigurer.initLogging(servletContextEvent.getServletContext());

    System.out.println(builder.toString());

    logger.info("============================================================");
    logger.info(" Now starting ..... PID: " + SystemUtils.getPid());
    logger.info("============================================================");
}