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.tacitknowledge.util.migration.jdbc.JdbcMigrationLauncherFactory.java

/**
 * Used to configure the migration launcher with properties from a servlet
 * context.  You do not need migration.properties to use this method.
 *
 * @param launcher the launcher to configure
 * @param sce      the event to get the context and associated parameters from
 * @throws MigrationException if a problem with the look up in JNDI occurs
 *//*from  w  w  w .  java2s  .c o m*/
private void configureFromServletContext(JdbcMigrationLauncher launcher, ServletContextEvent sce)
        throws MigrationException {
    String readOnly = sce.getServletContext().getInitParameter("migration.readonly");
    launcher.setReadOnly(false);
    if ("true".equals(readOnly)) {
        launcher.setReadOnly(true);
    }

    // See if they want to override the lock after a certain amount of time
    String lockPollRetries = sce.getServletContext().getInitParameter("migration.lockPollRetries");
    if (lockPollRetries != null) {
        launcher.setLockPollRetries(Integer.parseInt(lockPollRetries));
    }

    String patchPath = ConfigurationUtil.getRequiredParam("migration.patchpath", sce, this);
    launcher.setPatchPath(patchPath);

    String postPatchPath = sce.getServletContext().getInitParameter("migration.postpatchpath");
    launcher.setPostPatchPath(postPatchPath);

    String databases = sce.getServletContext().getInitParameter("migration.jdbc.systems");
    String[] databaseNames;
    if ((databases == null) || "".equals(databases)) {
        databaseNames = new String[1];
        databaseNames[0] = "";
        log.debug("jdbc.systems was null or empty, not multi-node");
    } else {
        databaseNames = databases.split(",");
        log.debug("jdbc.systems was set to " + databases + ", configuring multi-node");
    }

    for (int i = 0; i < databaseNames.length; i++) {
        String databaseName = databaseNames[i];
        if (databaseName != "") {
            databaseName = databaseName + ".";
        }
        String databaseType = ConfigurationUtil.getRequiredParam("migration." + databaseName + "databasetype",
                sce, this);
        String systemName = ConfigurationUtil.getRequiredParam("migration.systemname", sce, this);
        String dataSource = ConfigurationUtil.getRequiredParam("migration." + databaseName + "datasource", sce,
                this);

        DataSourceMigrationContext context = getDataSourceMigrationContext();
        context.setSystemName(systemName);
        context.setDatabaseType(new DatabaseType(databaseType));

        try {
            Context ctx = new InitialContext();
            if (ctx == null) {
                throw new IllegalArgumentException(
                        "A jndi context must be " + "present to use this configuration.");
            }
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/" + dataSource);
            context.setDataSource(ds);
            log.debug("adding context with datasource " + dataSource + " of type " + databaseType);
            launcher.addContext(context);
        } catch (NamingException e) {
            throw new MigrationException("Problem with JNDI look up of " + dataSource, e);
        }
    }
}

From source file:org.jdesktop.wonderland.modules.contentrepo.web.servlet.BrowserServlet.java

public void contextDestroyed(ServletContextEvent sce) {
    // register with the admininstration page
    ServletContext sc = sce.getServletContext();
    AdminRegistration.unregister(ar, sc);
}

From source file:org.jdesktop.wonderland.modules.contentrepo.web.servlet.BrowserServlet.java

public void contextInitialized(ServletContextEvent sce) {
    // register with the admininstration page
    ServletContext sc = sce.getServletContext();
    ar = new AdminRegistration("Manage Content", "/content-repository/wonderland-content-repository/browse");
    ar.setFilter(AdminRegistration.ADMIN_FILTER);
    AdminRegistration.register(ar, sc);//  w  w  w.  jav a 2s . c om
}

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

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {/*from  w  ww. j a va  2 s  .co m*/
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils.toString(servletContext.getResourceAsStream("/WEB-INF/web.dependencies"),
                    "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader webClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(webClassLoader);
        Class<?> appContextLoaderClass = webClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:org.sindice.servlet.sparqlqueryservlet.ServletConfigurationContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();
    String contextPath = context.getContextPath().replaceFirst("^/", "");
    if (contextPath.equals("")) {
        // application deployed in ROOT context
        String applicationName = context.getInitParameter("applicationName");
        if (applicationName != null && !applicationName.equals("")) {
            contextPath = "ROOT_" + applicationName;
        } else {/*from w w w.  j  av a  2  s .c  om*/
            contextPath = "ROOT";
        }
        logger.warn("Application deployed in ROOT context.");
    } else {
        logger.info("Application deployed in [" + contextPath + "] context.");
    }
    logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration");

    String servletContextName = context.getServletContextName();
    addEnvToContext(context);

    String sindiceHome = null;
    // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    // check that following directory exists
    // if yes please use it
    if (new File("/etc/" + contextPath + "/config.xml").exists()) {
        sindiceHome = "/etc";
        logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : ["
                + sindiceHome + "]");
    } else {
        logger.info(
                "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome");
    }
    // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    if (sindiceHome == null && context.getAttribute("sindice.home") != null) {
        sindiceHome = (String) context.getAttribute("sindice.home");
        logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) {
        sindiceHome = (String) context.getAttribute("SINDICE_HOME");
        logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null || "".equals(sindiceHome.trim())) {
        String userHome = (String) context.getAttribute("user.home");
        sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice";
        logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome);
    }

    logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]");

    // important to set these two as they are used later in logback.xml
    context.setAttribute("sindice.home", sindiceHome);
    context.setAttribute("app.name", contextPath);

    File configFolder = new File(sindiceHome + File.separatorChar + contextPath);
    if (!(configFolder.exists() && configFolder.isDirectory())) {
        logger.warn("Missing configuration folder {}", configFolder);
        if (configFolder.mkdirs()) {
            logger.warn("Creating default configuration at " + configFolder);

        } else {
            // set logging level to INFO
            configureLogging(context, configFolder);
            return;
        }
    }
    // does a specific folder exist for this servlet context?
    if (servletContextName == null) {
        logger.error("specify display-name element in web.xml !!! ");
    } else {
        File specificFolder = new File(configFolder, servletContextName);
        if (specificFolder.exists() && specificFolder.isDirectory()) {
            configFolder = specificFolder;
        }
    }
    logger.info("loading configuration from folder {}", configFolder);
    configureLogging(context, configFolder);
    final XMLConfiguration config = createXMLConfiguration(context);
    File applicationConfigFile = new File(configFolder, "config.xml");
    if (!applicationConfigFile.exists()) {
        logger.warn("missing application config file {}", applicationConfigFile);
        loadDefaultConfiguration(config, applicationConfigFile);
    } else {
        try {
            config.load(applicationConfigFile);
            logger.info("parsed {}", applicationConfigFile);
        } catch (ConfigurationException e) {
            logger.error("Could not load configuration from {}", applicationConfigFile, e);
            loadDefaultConfiguration(config, null);
        }
    }
    context.setAttribute("config", config);
    logger.info("config now availabe via the following line of code\n"
            + "    XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");");

    logger.info("Starting up {}", servletContextName);
}

From source file:org.sindice.analytics.servlet.ServletConfigurationContextListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    final ServletContext context = sce.getServletContext();
    String contextPath = context.getContextPath().replaceFirst("^/", "");
    if (contextPath.equals("")) {
        // application deployed in ROOT context
        String applicationName = context.getInitParameter("applicationName");
        if (applicationName != null && !applicationName.equals("")) {
            contextPath = "ROOT_" + applicationName;
        } else {/*ww  w  .  j av  a 2s .c  om*/
            contextPath = "ROOT";
        }
        logger.warn("Application deployed in ROOT context.");
    } else {
        logger.info("Application deployed in [" + contextPath + "] context.");
    }
    logger.info("Will use [" + contextPath + "] as a part of a path for reading/storing configuration");

    String servletContextName = context.getServletContextName();
    addEnvToContext(context);

    String sindiceHome = null;
    // FOR DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    // check that following directory exists
    // if yes please use it
    if (new File("/etc/" + contextPath + "/config.xml").exists()) {
        sindiceHome = "/etc";
        logger.info("Found config.xml at [/etc/" + contextPath + "/config.xml]. Setting sindiceHome to : ["
                + sindiceHome + "]");
    } else {
        logger.info(
                "File /etc/" + contextPath + "/config.xml does not exists will try to determine sindiceHome");
    }
    // END DEBIAN PACKAGE LOD2 PROJECT INTEGRATION
    if (sindiceHome == null && context.getAttribute("sindice.home") != null) {
        sindiceHome = (String) context.getAttribute("sindice.home");
        logger.info("Setting sindiceHome from sindice.home env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null && context.getAttribute("SINDICE_HOME") != null) {
        sindiceHome = (String) context.getAttribute("SINDICE_HOME");
        logger.info("Setting sindiceHome from SINDICE_HOME env variable to [" + sindiceHome + "]");
    }
    if (sindiceHome == null || "".equals(sindiceHome.trim())) {
        String userHome = (String) context.getAttribute("user.home");
        sindiceHome = (userHome == null ? "" : userHome) + File.separatorChar + "sindice";
        logger.warn("Neither sindice.home nor SINDICE_HOME are not defined, assuming {}", sindiceHome);
    }

    logger.info("Looking for configuration in [" + sindiceHome + File.separatorChar + contextPath + "]");

    // important to set these two as they are used later in logback.xml
    context.setAttribute("sindice.home", sindiceHome);
    context.setAttribute("app.name", contextPath);

    configFolder = new File(sindiceHome + File.separatorChar + contextPath);
    if (!(configFolder.exists() && configFolder.isDirectory())) {
        logger.warn("Missing configuration folder {}", configFolder);
        if (configFolder.mkdirs()) {
            logger.warn("Creating default configuration at " + configFolder);

        } else {
            // set logging level to INFO
            configureLogging(context, configFolder);
            return;
        }
    }
    // does a specific folder exist for this servlet context?
    if (servletContextName == null) {
        logger.error("specify display-name element in web.xml !!! ");
    } else {
        File specificFolder = new File(configFolder, servletContextName);
        if (specificFolder.exists() && specificFolder.isDirectory()) {
            configFolder = specificFolder;
        }
    }
    logger.info("loading configuration from folder {}", configFolder);
    configureLogging(context, configFolder);
    final XMLConfiguration config = createXMLConfiguration(context);
    File applicationConfigFile = new File(configFolder, "config.xml");
    if (!applicationConfigFile.exists()) {
        logger.warn("missing application config file {}", applicationConfigFile);
        loadDefaultConfiguration(config, applicationConfigFile);
    } else {
        try {
            config.load(applicationConfigFile);
            logger.info("parsed {}", applicationConfigFile);
        } catch (ConfigurationException e) {
            logger.error("Could not load configuration from {}", applicationConfigFile, e);
            loadDefaultConfiguration(config, null);
        }
    }
    context.setAttribute("config", config);
    logger.info("config now availabe via the following line of code\n"
            + "    XMLConfiguration appConfig = (XMLConfiguration) servletContext.getAttribute(\"config\");");

    logger.info("Starting up {}", servletContextName);
}

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

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    if (AbortStartup.isStartupAborted(ctx)) {
        return;//from  ww w  .j  a va2s  . co m
    }

    try {
        Updater updater = new Updater(ctx);
        if (updater.isThereAnythingToDo()) {
            updater.update();
        }
    } catch (Exception e) {
        AbortStartup.abortStartup(ctx);
        log.fatal("Failed to update user accounts information", e);
    }
}

From source file:com.haulmont.cuba.core.sys.singleapp.SingleAppCoreServletListener.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {//from w  w w .  j a  v a  2  s .co m
        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        //need to put the following class to WebAppClassLoader, to share it between for web and core
        contextClassLoader.loadClass("com.haulmont.cuba.core.sys.remoting.LocalServiceDirectory");

        ServletContext servletContext = sce.getServletContext();
        String dependenciesFile;
        try {
            dependenciesFile = IOUtils
                    .toString(servletContext.getResourceAsStream("/WEB-INF/core.dependencies"), "UTF-8");
        } catch (IOException e) {
            throw new RuntimeException("An error occurred while loading dependencies file", e);
        }

        String[] dependenciesNames = dependenciesFile.split("\\n");
        URL[] urls = Arrays.stream(dependenciesNames).map((String name) -> {
            try {
                return servletContext.getResource("/WEB-INF/lib/" + name);
            } catch (MalformedURLException e) {
                throw new RuntimeException("An error occurred while loading dependency " + name, e);
            }
        }).toArray(URL[]::new);
        URLClassLoader coreClassLoader = new CubaSingleAppClassLoader(urls, contextClassLoader);

        Thread.currentThread().setContextClassLoader(coreClassLoader);
        Class<?> appContextLoaderClass = coreClassLoader.loadClass(getAppContextLoaderClassName());
        appContextLoader = appContextLoaderClass.newInstance();

        Method setJarsNamesMethod = ReflectionUtils.findMethod(appContextLoaderClass, "setJarNames",
                String.class);
        ReflectionUtils.invokeMethod(setJarsNamesMethod, appContextLoader, dependenciesFile);

        Method contextInitializedMethod = ReflectionUtils.findMethod(appContextLoaderClass,
                "contextInitialized", ServletContextEvent.class);
        ReflectionUtils.invokeMethod(contextInitializedMethod, appContextLoader, sce);

        Thread.currentThread().setContextClassLoader(contextClassLoader);
    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
        throw new RuntimeException("An error occurred while starting single WAR application", e);
    }
}

From source file:com.jaspersoft.tamanoir.web.ConnectionsRegistrar.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    ConnectionsManager.registerConnection("csv", new CsvConnectionProcessorFactory());
    ConnectionsManager.registerConnection("jdbc", new JdbcConnectionProcessorFactory());
    try {/* www .  j a v  a 2 s. c  o  m*/
        storage = new EhCacheConnectionStorage();
        sessionFactory = new Configuration().configure().buildSessionFactory();
    } catch (Exception e) {
        log.error("Unexpected error occur", e);
    }
    sce.getServletContext().setAttribute(ConnectionsService.class.getName(), new ConnectionsService(storage));
    sce.getServletContext().setAttribute(DomainsService.class.getName(), new DomainsService(sessionFactory));
}

From source file:com.liferay.portal.servlet.PortletContextListener.java

public void contextInitialized(ServletContextEvent sce) {
    try {// w w w  .  j  a v a  2 s  .  c  o m

        // Servlet context

        ServletContext ctx = sce.getServletContext();

        _servletContextName = StringUtil.replace(ctx.getServletContextName(), StringPool.SPACE,
                StringPool.UNDERLINE);

        // Company ids

        _companyIds = StringUtil.split(ctx.getInitParameter("company_id"));

        // Class loader

        ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();

        // Initialize portlets

        String[] xmls = new String[] { Http.URLtoString(ctx.getResource("/WEB-INF/portlet.xml")),
                Http.URLtoString(ctx.getResource("/WEB-INF/liferay-portlet.xml")) };

        _portlets = PortletManagerUtil.initWAR(_servletContextName, xmls);

        // Portlet context wrapper

        Iterator itr1 = _portlets.iterator();

        while (itr1.hasNext()) {
            Portlet portlet = (Portlet) itr1.next();

            javax.portlet.Portlet portletInstance = (javax.portlet.Portlet) contextClassLoader
                    .loadClass(portlet.getPortletClass()).newInstance();

            Indexer indexerInstance = null;
            if (Validator.isNotNull(portlet.getIndexerClass())) {
                indexerInstance = (Indexer) contextClassLoader.loadClass(portlet.getIndexerClass())
                        .newInstance();
            }

            Scheduler schedulerInstance = null;
            if (Validator.isNotNull(portlet.getSchedulerClass())) {
                schedulerInstance = (Scheduler) contextClassLoader.loadClass(portlet.getSchedulerClass())
                        .newInstance();
            }

            PreferencesValidator prefsValidator = null;
            if (Validator.isNotNull(portlet.getPreferencesValidator())) {
                prefsValidator = (PreferencesValidator) contextClassLoader
                        .loadClass(portlet.getPreferencesValidator()).newInstance();

                try {
                    if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.PREFERENCE_VALIDATE_ON_STARTUP))) {

                        prefsValidator.validate(
                                PortletPreferencesSerializer.fromDefaultXML(portlet.getDefaultPreferences()));
                    }
                } catch (Exception e1) {
                    _log.warn("Portlet with the name " + portlet.getPortletId()
                            + " does not have valid default preferences");
                }
            }

            Map resourceBundles = null;

            if (Validator.isNotNull(portlet.getResourceBundle())) {
                resourceBundles = CollectionFactory.getHashMap();

                Iterator itr2 = portlet.getSupportedLocales().iterator();

                while (itr2.hasNext()) {
                    String supportedLocale = (String) itr2.next();

                    Locale locale = new Locale(supportedLocale);

                    try {
                        ResourceBundle resourceBundle = ResourceBundle.getBundle(portlet.getResourceBundle(),
                                locale, contextClassLoader);

                        resourceBundles.put(locale.getLanguage(), resourceBundle);
                    } catch (MissingResourceException mre) {
                        _log.warn(mre.getMessage());
                    }
                }
            }

            Map customUserAttributes = CollectionFactory.getHashMap();

            Iterator itr2 = portlet.getCustomUserAttributes().entrySet().iterator();

            while (itr2.hasNext()) {
                Map.Entry entry = (Map.Entry) itr2.next();

                String attrName = (String) entry.getKey();
                String attrCustomClass = (String) entry.getValue();

                customUserAttributes.put(attrCustomClass,
                        contextClassLoader.loadClass(attrCustomClass).newInstance());
            }

            PortletContextWrapper pcw = new PortletContextWrapper(portlet.getPortletId(), ctx, portletInstance,
                    indexerInstance, schedulerInstance, prefsValidator, resourceBundles, customUserAttributes);

            PortletContextPool.put(portlet.getPortletId(), pcw);
        }

        // Portlet class loader

        String servletPath = ctx.getRealPath("/");
        if (!servletPath.endsWith("/") && !servletPath.endsWith("\\")) {
            servletPath += "/";
        }

        File servletClasses = new File(servletPath + "WEB-INF/classes");
        File servletLib = new File(servletPath + "WEB-INF/lib");

        List urls = new ArrayList();

        if (servletClasses.exists()) {
            urls.add(new URL("file:" + servletClasses + "/"));
        }

        if (servletLib.exists()) {
            String[] jars = FileUtil.listFiles(servletLib);

            for (int i = 0; i < jars.length; i++) {
                urls.add(new URL("file:" + servletLib + "/" + jars[i]));
            }
        }

        URLClassLoader portletClassLoader = new URLClassLoader((URL[]) urls.toArray(new URL[0]),
                contextClassLoader);

        ctx.setAttribute(WebKeys.PORTLET_CLASS_LOADER, portletClassLoader);

        // Portlet display

        String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

        Map newCategories = PortletManagerUtil.getWARDisplay(_servletContextName, xml);

        for (int i = 0; i < _companyIds.length; i++) {
            String companyId = _companyIds[i];

            Map oldCategories = (Map) WebAppPool.get(companyId, WebKeys.PORTLET_DISPLAY);

            Map mergedCategories = PortalUtil.mergeCategories(oldCategories, newCategories);

            WebAppPool.put(companyId, WebKeys.PORTLET_DISPLAY, mergedCategories);
        }

        // Reinitialize portal properties

        PropsUtil.init();
    } catch (Exception e2) {
        Logger.error(this, e2.getMessage(), e2);
    }
}