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:com.boylesoftware.web.AbstractWebApplication.java

@Override
public void contextInitialized(final ServletContextEvent sce) {

    this.servletContext = sce.getServletContext();

    sce.getServletContext().setAttribute(WEBAPP_ATTNAME, this);
}

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

/**
 * Clearing the in-memory configuration parameters, we will receive
 * notification that the servlet context is about to be shut down
 *///from w w  w. j a  va 2  s .c om
@Override
public void contextDestroyed(ServletContextEvent sce) {
    synchronized (instance) {
        logger.info("Webapp shutdown");
        // XXX Paul: grabbed this from
        // http://opensource.atlassian.com/confluence/spring/display/DISC/Memory+leak+-+classloader+won%27t+let+go
        // in hopes that we can clear all the issues with J2EE containers
        // during shutdown
        try {
            ServletContext ctx = sce.getServletContext();
            // if the ctx being destroyed is root then kill the timer
            if (ctx.getContextPath().equals("/ROOT")) {
                timer.cancel();
            } else {
                // remove from registered list
                registeredContexts.remove(ctx);
            }
            // prepare spring for shutdown
            Introspector.flushCaches();
            // dereg any drivers
            for (Enumeration e = DriverManager.getDrivers(); e.hasMoreElements();) {
                Driver driver = (Driver) e.nextElement();
                if (driver.getClass().getClassLoader() == getClass().getClassLoader()) {
                    DriverManager.deregisterDriver(driver);
                }
            }
            // shutdown jmx
            JMXAgent.shutdown();
            // shutdown spring
            Object attr = ctx.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
            if (attr != null) {
                // get web application context from the servlet context
                ConfigurableWebApplicationContext applicationContext = (ConfigurableWebApplicationContext) attr;
                ConfigurableBeanFactory factory = applicationContext.getBeanFactory();
                // for (String scope : factory.getRegisteredScopeNames()) {
                // logger.debug("Registered scope: " + scope);
                // }
                try {
                    for (String singleton : factory.getSingletonNames()) {
                        logger.debug("Registered singleton: " + singleton);
                        factory.destroyScopedBean(singleton);
                    }
                } catch (RuntimeException e) {
                }
                factory.destroySingletons();

                ctx.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
                applicationContext.close();
            }
            instance.getContextLoader().closeWebApplicationContext(ctx);
        } catch (Throwable e) {
            e.printStackTrace();
        } finally {
            // http://jakarta.apache.org/commons/logging/guide.html#Classloader_and_Memory_Management
            // http://wiki.apache.org/jakarta-commons/Logging/UndeployMemoryLeak?action=print
            LogFactory.release(Thread.currentThread().getContextClassLoader());
        }
    }
}

From source file:org.openmrs.web.Listener.java

/**
 * Called when the webapp is shut down properly Must call Context.shutdown() and then shutdown
 * all the web layers of the modules/*from ww  w  . j av  a2s  .  c  o m*/
 *
 * @see org.springframework.web.context.ContextLoaderListener#contextDestroyed(javax.servlet.ServletContextEvent)
 */
@SuppressWarnings("squid:S1215")
@Override
public void contextDestroyed(ServletContextEvent event) {

    try {
        Context.openSession();

        Context.shutdown();

        WebModuleUtil.shutdownModules(event.getServletContext());

    } catch (Exception e) {
        // don't print the unhelpful "contextDAO is null" message
        if (!"contextDAO is null".equals(e.getMessage())) {
            // not using log.error here so it can be garbage collected
            System.out.println("Listener.contextDestroyed: Error while shutting down openmrs: ");
            log.error(e);
        }
    } finally {
        if ("true".equalsIgnoreCase(System.getProperty("FUNCTIONAL_TEST_MODE"))) {
            //Delete the temporary file created for functional testing and shutdown the mysql daemon
            String filename = WebConstants.WEBAPP_NAME + "-test-runtime.properties";
            File file = new File(OpenmrsUtil.getApplicationDataDirectory(), filename);
            System.out.println(filename + " delete=" + file.delete());
            //new com.mysql.management.MysqldResource(new File("../openmrs/target/database")).shutdown();
        }
        // remove the user context that we set earlier
        Context.closeSession();
    }

    // commented out because we are not init'ing it in the contextInitialization anymore
    // super.contextDestroyed(event);

    try {
        for (Enumeration<Driver> e = DriverManager.getDrivers(); e.hasMoreElements();) {
            Driver driver = e.nextElement();
            ClassLoader classLoader = driver.getClass().getClassLoader();
            // only unload drivers for this webapp
            if (classLoader == null || classLoader == getClass().getClassLoader()) {
                DriverManager.deregisterDriver(driver);
            } else {
                System.err.println("Didn't remove driver class: " + driver.getClass() + " with classloader of: "
                        + driver.getClass().getClassLoader());
            }
        }
    } catch (Exception e) {
        System.err.println("Listener.contextDestroyed: Failed to cleanup drivers in webapp");
        log.error(e);
    }

    MemoryLeakUtil.shutdownMysqlCancellationTimer();
    MemoryLeakUtil.shutdownKeepAliveTimer();

    OpenmrsClassLoader.onShutdown();

    LogManager.shutdown();

    // just to make things nice and clean.
    // Suppressing sonar issue squid:S1215
    System.gc();
    System.gc();
}

From source file:com.alfaariss.oa.OAContextListener.java

/**
 * Starts the engine before all servlets are initialized.
 * // w w  w.jav  a 2s.  c  om
 * Searches for the properties needed for the configuration in:
 * <code>[Servlet context dir]/WEB-INF/[PROPERTIES_FILENAME]</code>
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent oServletContextEvent) {
    Properties pConfig = new Properties();
    try {
        _logger.info("Starting Asimba");

        Package pCurrent = OAContextListener.class.getPackage();

        String sSpecVersion = pCurrent.getSpecificationVersion();
        if (sSpecVersion != null)
            _logger.info("Specification-Version: " + sSpecVersion);

        String sImplVersion = pCurrent.getImplementationVersion();
        if (sImplVersion != null)
            _logger.info("Implementation-Version: " + sImplVersion);

        ServletContext oServletContext = oServletContextEvent.getServletContext();

        Enumeration enumContextAttribs = oServletContext.getInitParameterNames();
        while (enumContextAttribs.hasMoreElements()) {
            String sName = (String) enumContextAttribs.nextElement();
            pConfig.put(sName, oServletContext.getInitParameter(sName));
        }

        if (pConfig.size() > 0) {
            _logger.info("Using configuration items found in servlet context: " + pConfig);
        }

        // Add MountingPoint to PathTranslator
        PathTranslator.getInstance().addKey(MP_WEBAPP_ROOT, oServletContext.getRealPath(""));

        // Try to see whether there is a system property with the location of the properties file:
        String sPropertiesFilename = System.getProperty(PROPERTIES_FILENAME_PROPERTY);
        if (null != sPropertiesFilename && !"".equals(sPropertiesFilename)) {
            File fConfig = new File(sPropertiesFilename);
            if (fConfig.exists()) {
                _logger.info("Reading Asimba properties from " + fConfig.getAbsolutePath());
                pConfig.putAll(getProperties(fConfig));
            }
        }

        String sWebInf = oServletContext.getRealPath("WEB-INF");
        if (sWebInf != null) {
            _logger.info("Cannot find path in ServletContext for WEB-INF");
            StringBuffer sbConfigFile = new StringBuffer(sWebInf);
            if (!sbConfigFile.toString().endsWith(File.separator))
                sbConfigFile.append(File.separator);
            sbConfigFile.append(PROPERTIES_FILENAME);

            File fConfig = new File(sbConfigFile.toString());
            if (fConfig.exists()) {
                _logger.info("Updating configuration items with the items in file: " + fConfig.toString());
                pConfig.putAll(getProperties(fConfig));
            } else {
                _logger.info("No optional configuration properties (" + PROPERTIES_FILENAME
                        + ") file found at: " + fConfig.toString());
            }
        }
        //Search for PROPERTIES_FILENAME file in servlet context classloader classpath 
        //it looks first at this location: ./<context>/web-inf/classes/[PROPERTIES_FILENAME]
        //if previous location didn't contain PROPERTIES_FILENAME then checking: 
        //./tomcat/common/classes/PROPERTIES_FILENAME
        URL urlProperties = oServletContext.getClass().getClassLoader().getResource(PROPERTIES_FILENAME);
        if (urlProperties != null) {
            String sProperties = urlProperties.getFile();
            _logger.debug("Found '" + PROPERTIES_FILENAME + "' file in classpath: " + sProperties);
            File fProperties = new File(sProperties);
            if (fProperties != null && fProperties.exists()) {
                _logger.info("Updating configuration items with the items in file: "
                        + fProperties.getAbsolutePath());
                pConfig.putAll(getProperties(fProperties));
            } else
                _logger.info("Could not resolve: " + fProperties.getAbsolutePath());
        } else
            _logger.info("No optional '" + PROPERTIES_FILENAME
                    + "' configuration file found in servlet context classpath");

        if (!pConfig.containsKey("configuration.handler.filename")) {
            StringBuffer sbOAConfigFile = new StringBuffer(sWebInf);
            if (!sbOAConfigFile.toString().endsWith(File.separator))
                sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("conf");
            sbOAConfigFile.append(File.separator);
            sbOAConfigFile.append("asimba.xml");
            File fOAConfig = new File(sbOAConfigFile.toString());
            if (fOAConfig.exists()) {
                pConfig.put("configuration.handler.filename", sbOAConfigFile.toString());
                _logger.info(
                        "Setting 'configuration.handler.filename' configuration property with configuration file found at: "
                                + fOAConfig.toString());
            }
        }

        _oEngineLauncher.start(pConfig);

        _logger.info("Started Engine with OAContextListener");
    } catch (Exception e) {
        _logger.error("Can't start Engine with OAContextListener", e);

        _logger.debug("try stopping the server");
        _oEngineLauncher.stop();
    }

}

From source file:org.j2free.config.ConfigurationListener.java

/**
 *
 * @param event/* w w  w .j  av a2  s . co m*/
 */
public synchronized void contextInitialized(ServletContextEvent event) {
    context = event.getServletContext();

    // Get the configuration file
    String configPathTemp = (String) context.getInitParameter(INIT_PARAM_CONFIG_PATH);

    // Use the default path if it wasn't specified
    if (StringUtils.isBlank(configPathTemp))
        configPathTemp = DEFAULT_CONFIG_PATH;

    // Finalize the config path (needs to be final for inner-Runnable below)
    final String configPath = configPathTemp;
    context.setAttribute(CONTEXT_ATTR_CONFIG_PATH, configPath);

    try {
        // Load the configuration
        DefaultConfigurationBuilder configBuilder = new DefaultConfigurationBuilder();
        configBuilder.setFileName(configPath);

        final CombinedConfiguration config = configBuilder.getConfiguration(true);

        // Save the config where we can get at it later
        context.setAttribute(CONTEXT_ATTR_CONFIG, config);
        Global.put(CONTEXT_ATTR_CONFIG, config);

        // Determine the localhost
        String localhost = config.getString(PROP_LOCALHOST, "ip");
        if (localhost.equalsIgnoreCase("ip")) {
            try {
                localhost = InetAddress.getLocalHost().getHostAddress();
                log.info("Using localhost: " + localhost);
            } catch (Exception e) {
                log.warn("Error determining localhost", e);
                localhost = "localhost";
            }
        }

        context.setAttribute(CONTEXT_ATTR_LOCALHOST, localhost);
        Global.put(CONTEXT_ATTR_LOCALHOST, localhost);
        loadedConfigPropKeys.add(CONTEXT_ATTR_LOCALHOST);

        // Set application context attributes for all config properties
        String prop, value;
        Iterator itr = config.getKeys();
        while (itr.hasNext()) {
            prop = (String) itr.next();
            value = config.getString(prop);

            // Anything with the value "localhost" will be set to the IP if possible
            value = (value.equals("localhost") ? localhost : value);

            log.debug("Config: " + prop + " = " + value);
            context.setAttribute(prop, value);
            loadedConfigPropKeys.add(prop);
        }

        // Run Mode configuration
        String runMode = config.getString(PROP_RUNMODE);
        try {
            RUN_MODE = RunMode.valueOf(runMode);
        } catch (Exception e) {
            log.warn("Error setting runmode, invalid value: " + runMode);
        }

        context.setAttribute("devMode", RUN_MODE != RunMode.PRODUCTION);
        loadedConfigPropKeys.add("devMode");

        // Fragment Cache Configuration
        if (config.getBoolean(FragmentCache.Properties.ENABLED, false)) {
            log.info("Enabling fragment caching...");
            FragmentCacheTag.enable();

            // This is expected to be in seconds
            long temp = config.getLong(FragmentCache.Properties.REQUEST_TIMEOUT, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag request timeout: " + temp);
                FragmentCacheTag.setRequestTimeout(temp);
            }

            // The property is in seconds, but WARNING_COMPUTE_DURATION does NOT use a TimeUnit, so it's in ms
            temp = config.getLong(FragmentCache.Properties.WARNING_DURATION, -1l);
            if (temp != -1) {
                log.info("Setting FragmentCacheTag warning duration: " + temp);
                FragmentCacheTag.setWarningComputeDuration(temp * 1000);
            }

            // Get the fragment cache names
            String[] cacheNames = config.getStringArray(FragmentCache.Properties.ENGINE_NAMES);
            for (String cacheName : cacheNames) {
                String cacheClassName = config
                        .getString(String.format(FragmentCache.Properties.ENGINE_CLASS_TEMPLATE, cacheName));
                try {
                    // Load up the class
                    Class<? extends FragmentCache> cacheClass = (Class<? extends FragmentCache>) Class
                            .forName(cacheClassName);

                    // Look for a constructor that takes a config
                    Constructor<? extends FragmentCache> constructor = null;
                    try {
                        constructor = cacheClass.getConstructor(Configuration.class);
                    } catch (Exception e) {
                    }

                    FragmentCache cache;

                    // If we found the configuration constructor, use it
                    if (constructor != null)
                        cache = constructor.newInstance(config);
                    else {
                        // otherwise use a default no-args constructor
                        log.warn("Could not find a " + cacheClass.getSimpleName()
                                + " constructor that takes a Configuration, defaulting to no-args constructor");
                        cache = cacheClass.newInstance();
                    }

                    // register the cache with the FragmentCacheTag using the config strategy-name, or the engineName
                    // if a strategy-name is not specified
                    log.info("Registering FragmentCache strategy: [name=" + cacheName + ", class="
                            + cacheClass.getName() + "]");
                    FragmentCacheTag.registerStrategy(cacheName, cache);
                } catch (Exception e) {
                    log.error("Error enabling FragmentCache engine: " + cacheName, e);
                }
            }

        } else {
            // Have to call this here, because reconfiguration could turn
            // the cache off after it was previously enabled.
            FragmentCacheTag.disable();
        }

        // For Task execution
        ScheduledExecutorService taskExecutor;

        if (config.getBoolean(PROP_TASK_EXECUTOR_ON, false)) {
            int threads = config.getInt(PROP_TASK_EXECUTOR_THREADS, DEFAULT_TASK_EXECUTOR_THREADS);

            if (threads == 1)
                taskExecutor = Executors.newSingleThreadScheduledExecutor();
            else
                taskExecutor = Executors.newScheduledThreadPool(threads);

            context.setAttribute(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
            loadedConfigPropKeys.add(CONTEXT_ATTR_TASK_MANAGER);

            Global.put(CONTEXT_ATTR_TASK_MANAGER, taskExecutor);
        } else {
            // Not allowed to shutdown the taskExecutor if dynamic reconfig is enabled
            if (reconfigTask == null) {
                // Shutdown and remove references to the taskManager previously created
                taskExecutor = (ScheduledExecutorService) Global.get(CONTEXT_ATTR_TASK_MANAGER);
                if (taskExecutor != null) {
                    taskExecutor.shutdown(); // will block until all tasks complete
                    taskExecutor = null;
                    Global.remove(CONTEXT_ATTR_TASK_MANAGER);
                }
            } else {
                // We could just log a warning that you can't do this, but the user
                // might not see that, so we're going to refuse to reset a configuration
                // that cannot be loaded in whole successfully.
                throw new ConfigurationException(
                        "Cannot disable task execution service, dynamic reconfiguration is enabled!");
            }
        }

        // Email Service
        if (config.getBoolean(PROP_MAIL_SERVICE_ON, false)) {
            if (!SimpleEmailService.isEnabled()) {
                // Get the SMTP properties
                Properties props = System.getProperties();
                props.put(PROP_SMTP_HOST, config.getString(PROP_SMTP_HOST));
                props.put(PROP_SMTP_PORT, config.getString(PROP_SMTP_PORT));
                props.put(PROP_SMTP_AUTH, config.getString(PROP_SMTP_AUTH));

                Session session;

                if (config.getBoolean(PROP_SMTP_AUTH)) {
                    final String user = config.getString(PROP_SMTP_USER);
                    final String pass = config.getString(PROP_SMTP_PASS);

                    Authenticator auth = new Authenticator() {
                        @Override
                        public PasswordAuthentication getPasswordAuthentication() {
                            return new PasswordAuthentication(user, pass);
                        }
                    };
                    session = Session.getInstance(props, auth);

                } else {
                    session = Session.getInstance(props);
                }

                // Get the global headers
                Iterator headerNames = config.getKeys(PROP_MAIL_HEADER_PREFIX);
                List<KeyValuePair<String, String>> headers = new LinkedList<KeyValuePair<String, String>>();

                String headerName;
                while (headerNames.hasNext()) {
                    headerName = (String) headerNames.next();
                    headers.add(new KeyValuePair<String, String>(headerName, config.getString(headerName)));
                }

                // Initialize the service
                SimpleEmailService.init(session);
                SimpleEmailService.setGlobalHeaders(headers);

                // Set whether we actually send the e-mails
                SimpleEmailService.setDummyMode(config.getBoolean(PROP_MAIL_DUMMY_MODE, false));

                // Set the failure policy
                String policy = config.getString(PROP_MAIL_ERROR_POLICY);
                if (policy != null) {
                    if (policy.equals(VALUE_MAIL_POLICY_DISCARD)) {
                        SimpleEmailService.setErrorPolicy(new SimpleEmailService.DiscardPolicy());
                    } else if (policy.equals(VALUE_MAIL_POLICY_REQUEUE)) {
                        Priority priority = null;
                        try {
                            priority = Priority.valueOf(config.getString(PROP_MAIL_REQUEUE_PRIORITY));
                        } catch (Exception e) {
                            log.warn("Error reading requeue policy priority: "
                                    + config.getString(PROP_MAIL_REQUEUE_PRIORITY, "") + ", using default");
                        }

                        if (priority == null)
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy());
                        else
                            SimpleEmailService.setErrorPolicy(new SimpleEmailService.RequeuePolicy(priority));
                    }
                }

                // Parse templates
                String emailTemplateDir = config.getString(PROP_MAIL_TEMPLATE_DIR);

                // If the template
                if (StringUtils.isBlank(emailTemplateDir))
                    emailTemplateDir = DEFAULT_EMAIL_TEMPLATE_DIR;

                log.debug("Looking for e-mail templates in: " + emailTemplateDir);
                Set<String> templates = context.getResourcePaths(emailTemplateDir);

                // E-mail templates
                if (templates != null && !templates.isEmpty()) {
                    log.debug("Found " + templates.size() + " templates");

                    String key;
                    String defaultTemplate = config.getString(PROP_MAIL_DEFAULT_TEMPLATE, EMPTY);

                    InputStream in;
                    StringBuilder builder;
                    Scanner scanner;

                    try {
                        Template template;
                        String[] parts;

                        ContentType contentType;

                        for (String path : templates) {
                            path = path.trim();
                            parts = path.split("\\.");

                            contentType = ContentType.valueOfExt(parts[1]);

                            try {
                                in = context.getResourceAsStream(path.trim());

                                if (in != null && in.available() > 0) {
                                    scanner = new Scanner(in);
                                    builder = new StringBuilder();

                                    while (scanner.hasNextLine()) {
                                        builder.append(scanner.nextLine());
                                        if (contentType == ContentType.PLAIN) {
                                            builder.append("\n");
                                        }
                                    }

                                    template = new Template(builder.toString(), contentType);

                                    key = parts[0].replace(emailTemplateDir, EMPTY);
                                    SimpleEmailService.registerTemplate(key, template,
                                            key.equals(defaultTemplate));
                                }
                            } catch (IOException ioe) {
                                log.error("Error loading e-mail template: " + path, ioe);
                            }
                        }
                    } catch (Exception e) {
                        log.error("Error loading e-mail templates", e);
                    }
                } else
                    log.debug("No e-mail templates found.");
            }
        } else if (SimpleEmailService.isEnabled()) {
            boolean shutdown = false;
            try {
                shutdown = SimpleEmailService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while shutting down SimpleEmailService");
            }

            if (!shutdown)
                SimpleEmailService.shutdown();
        }

        // QueuedHttpCallService
        if (config.getBoolean(PROP_HTTP_SRVC_ON, false)) {
            if (!SimpleHttpService.isEnabled()) // Don't double init...
            {
                int defaultThreadCount = Runtime.getRuntime().availableProcessors() + 1; // threads to use if unspecified
                SimpleHttpService.init(config.getInt(PROP_HTTP_SRVC_CORE_POOL, defaultThreadCount),
                        config.getInt(PROP_HTTP_SRVC_MAX_POOL, defaultThreadCount),
                        config.getLong(PROP_HTTP_SRVC_POOL_IDLE, DEFAULT_HTTP_SRVC_THREAD_IDLE),
                        config.getInt(PROP_HTTP_SRVC_CONNECT_TOUT, DEFAULT_HTTP_SRVC_CONNECT_TOUT),
                        config.getInt(PROP_HTTP_SRVE_SOCKET_TOUT, DEFAULT_HTTP_SRVE_SOCKET_TOUT));
            }
        } else if (SimpleHttpService.isEnabled()) {
            boolean shutdown = false;
            try {
                // Try to shutdown the service while letting currently waiting tasks complete
                shutdown = SimpleHttpService.shutdown(30, TimeUnit.SECONDS);
            } catch (InterruptedException ie) {
                log.warn("Interrupted while waiting for SimpleHttpService to shutdown");
            }
            if (!shutdown) {
                // But if that doesn't finish in 60 seconds, just cut it off
                int count = SimpleHttpService.shutdown().size();
                log.warn("SimpleHttpService failed to shutdown in 60 seconds, so it was terminated with "
                        + count + " tasks waiting");
            }
        }

        // Spymemcached Client
        if (config.getBoolean(PROP_SPYMEMCACHED_ON, false)) {
            String addresses = config.getString(PROP_SPYMEMCACHED_ADDRESSES);
            if (addresses == null) {
                log.error("Error configuring spymemcached; enabled but no addresses!");
            } else {
                try {
                    // Reflect our way to the constructor, this is all so that the
                    // spymemcached jar does not need to be included in a J2Free app
                    // unless it is actually to be used.
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Constructor constructor = klass.getConstructor(List.class);

                    klass = Class.forName("net.spy.memcached.AddrUtil");
                    Method method = klass.getMethod("getAddresses", String.class);

                    Object client = constructor.newInstance(method.invoke(null, addresses));

                    context.setAttribute(CONTEXT_ATTR_SPYMEMCACHED, client);
                    loadedConfigPropKeys.add(CONTEXT_ATTR_SPYMEMCACHED);

                    Global.put(CONTEXT_ATTR_SPYMEMCACHED, client);

                    log.info("Spymemcached client created, connected to " + addresses);
                } catch (Exception e) {
                    log.error("Error creating memcached client [addresses=" + addresses + "]", e);
                }
            }
        } else {
            // If a spymemcached client was previous created
            Object client = Global.get(CONTEXT_ATTR_SPYMEMCACHED);
            if (client != null) {
                try {
                    // Reflect our way to the shutdown method
                    Class klass = Class.forName("net.spy.memcached.MemcachedClient");
                    Method method = klass.getMethod("shutdown");

                    method.invoke(null, client); // and shut it down

                    log.info("Spymemcached client shutdown");
                } catch (Exception e) {
                    log.error("Error shutting down spymemcached client", e);
                }

                // Then remove any references
                Global.remove(CONTEXT_ATTR_SPYMEMCACHED);
                client = null;
            }
        }
    } catch (ConfigurationException ce) {
        log.error("Error configuring app", ce);
    }
}

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

protected void initializeGuice(final ServletContextEvent event) {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    guiceModules = ImmutableList.<Module>of(getServletModule(), getJacksonModule(),
            new JMXModule(KillbillHealthcheck.class, NotificationQueueService.class, PersistentBus.class),
            new StatsModule(METRICS_SERVLETS_PATHS.get(0), METRICS_SERVLETS_PATHS.get(1),
                    METRICS_SERVLETS_PATHS.get(2), METRICS_SERVLETS_PATHS.get(3),
                    ImmutableList.<Class<? extends HealthCheck>>of(KillbillHealthcheck.class)),
            getModule(event.getServletContext()));

    // Start the Guice machinery
    super.contextInitialized(event);

    injector = injector(event);//w w w.  ja  v a 2 s.c o  m
    event.getServletContext().setAttribute(Injector.class.getName(), injector);

    // Already started at this point - we just need the instance for shutdown
    embeddedDB = injector.getInstance(EmbeddedDB.class);

    killbillLifecycle = injector.getInstance(Lifecycle.class);
    killbillBusService = injector.getInstance(BusService.class);
}

From source file:org.mifos.framework.ApplicationInitializer.java

@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
    ServletContext ctx = servletContextEvent.getServletContext();
    logger.info("shutting down scheduler");
    final MifosScheduler mifosScheduler = (MifosScheduler) ctx.getAttribute(MifosScheduler.class.getName());
    ctx.removeAttribute(MifosScheduler.class.getName());
    try {//ww w  .j a va2 s  .  c  om
        if (mifosScheduler != null) {
            mifosScheduler.shutdown();
        }
    } catch (Exception e) {
        logger.error("error while shutting down scheduler", e);
    }

    // WebApplicationContext applicationContext = null;
    //  if (ctx != null) {
    //     applicationContext = WebApplicationContextUtils.getRequiredWebApplicationContext(ctx);
    // }

    StaticHibernateUtil.shutdown();
    unregisterMySQLDriver();
    cancelMySQLStatement();
    logger.info("destroyed context");
}

From source file:org.openmrs.web.Listener.java

/**
 * This method is called when the servlet context is initialized(when the Web Application is
 * deployed). You can initialize servlet context related data here.
 *
 * @param event/*from  w  w  w  .  j av  a  2 s. c o  m*/
 */
@Override
public void contextInitialized(ServletContextEvent event) {
    Log log = LogFactory.getLog(Listener.class);

    log.debug("Starting the OpenMRS webapp");

    try {
        // validate the current JVM version
        OpenmrsUtil.validateJavaVersion();

        ServletContext servletContext = event.getServletContext();

        // pulled from web.xml.
        loadConstants(servletContext);

        // erase things in the dwr file
        clearDWRFile(servletContext);

        // Try to get the runtime properties
        Properties props = getRuntimeProperties();
        if (props != null) {
            // the user has defined a runtime properties file
            setRuntimePropertiesFound(true);
            // set props to the context so that they can be
            // used during sessionFactory creation
            Context.setRuntimeProperties(props);
        }

        Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

        if (!setupNeeded()) {
            // must be done after the runtime properties are
            // found but before the database update is done
            copyCustomizationIntoWebapp(servletContext, props);

            //super.contextInitialized(event);
            // also see commented out line in contextDestroyed

            /** This logic is from ContextLoader.initWebApplicationContext.
             * Copied here instead of calling that so that the context is not cached
             * and hence not garbage collected
             */
            XmlWebApplicationContext context = (XmlWebApplicationContext) createWebApplicationContext(
                    servletContext);
            configureAndRefreshWebApplicationContext(context, servletContext);
            servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, context);

            WebDaemon.startOpenmrs(event.getServletContext());
        } else {
            setupNeeded = true;
        }

    } catch (Exception e) {
        setErrorAtStartup(e);
        log.fatal("Got exception while starting up: ", e);
    }

}

From source file:org.mifos.framework.ApplicationInitializer.java

public void init(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();
    try {/* ww w  .  j  a  v  a 2s . c  o m*/
        // prevent ehcache "phone home"
        System.setProperty("net.sf.ehcache.skipUpdateCheck", "true");
        // prevent quartz "phone home"
        System.setProperty("org.terracotta.quartz.skipUpdateCheck", "true");

        synchronized (ApplicationInitializer.class) {
            ApplicationContext applicationContext = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(servletContext);
            if (servletContext != null) {
                dbUpgrade(applicationContext);

            }
            initJNDIforPentaho(applicationContext);
            setAttributesOnContext(servletContext);
            copyResources(servletContext);
        }
    } catch (Exception e) {
        String errMsgStart = "unable to start Mifos web application";
        if (null == logger) {
            System.err.println(errMsgStart + " and logger is not available!");
            e.printStackTrace();
        } else {
            logger.error(errMsgStart, e);
        }
        throw new Error(e);
    }
    logger.info("Mifos is ready.");
}

From source file:org.viafirma.nucleo.Nucleo.java

/**
 * Oyente de Contexto que se activa al arrancar la aplicacin.
 * /*from w  ww .j ava  2s .  c o  m*/
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
@Override
public void contextInitialized(ServletContextEvent event) {
    System.out.println("*******************************************\n\t\tIniciando Viafirma\n" + this
            + "\n*******************************************");
    init(event.getServletContext());
    loadProperties(event.getServletContext());
}