Example usage for javax.servlet ServletContext getInitParameter

List of usage examples for javax.servlet ServletContext getInitParameter

Introduction

In this page you can find the example usage for javax.servlet ServletContext getInitParameter.

Prototype

public String getInitParameter(String name);

Source Link

Document

Returns a String containing the value of the named context-wide initialization parameter, or null if the parameter does not exist.

Usage

From source file:com.bstek.dorado.web.loader.DoradoLoader.java

public synchronized void preload(ServletContext servletContext, boolean processOriginContextConfigLocation)
        throws Exception {
    if (preloaded) {
        throw new IllegalStateException("Dorado base configurations already loaded.");
    }/* www  . j av  a 2 s.  c  o  m*/
    preloaded = true;

    // ?
    ConsoleUtils.outputLoadingInfo("Initializing " + DoradoAbout.getProductTitle() + " engine...");
    ConsoleUtils.outputLoadingInfo("[Vendor: " + DoradoAbout.getVendor() + "]");

    ConfigureStore configureStore = Configure.getStore();
    doradoHome = System.getenv("DORADO_HOME");

    // ?DoradoHome
    String intParam;
    intParam = servletContext.getInitParameter("doradoHome");
    if (intParam != null) {
        doradoHome = intParam;
    }
    if (doradoHome == null) {
        doradoHome = DEFAULT_DORADO_HOME;
    }

    configureStore.set(HOME_PROPERTY, doradoHome);
    ConsoleUtils.outputLoadingInfo("[Home: " + StringUtils.defaultString(doradoHome, "<not assigned>") + "]");

    // ResourceLoader
    ResourceLoader resourceLoader = new ServletContextResourceLoader(servletContext) {
        @Override
        public Resource getResource(String resourceLocation) {
            if (resourceLocation != null && resourceLocation.startsWith(HOME_LOCATION_PREFIX)) {
                resourceLocation = ResourceUtils.concatPath(doradoHome,
                        resourceLocation.substring(HOME_LOCATION_PREFIX_LEN));
            }
            return super.getResource(resourceLocation);
        }
    };

    String runMode = null;
    if (StringUtils.isNotEmpty(doradoHome)) {
        String configureLocation = HOME_LOCATION_PREFIX + "configure.properties";
        loadConfigureProperties(configureStore, resourceLoader, configureLocation, false);
    }

    runMode = configureStore.getString("core.runMode");

    if (StringUtils.isNotEmpty(runMode)) {
        loadConfigureProperties(configureStore, resourceLoader,
                CORE_PROPERTIES_LOCATION_PREFIX + "configure-" + runMode + ".properties", true);

        if (StringUtils.isNotEmpty(doradoHome)) {
            loadConfigureProperties(configureStore, resourceLoader,
                    HOME_LOCATION_PREFIX + "configure-" + runMode + ".properties", true);
        }
    }

    ConsoleUtils.outputConfigureItem("core.runMode");
    ConsoleUtils.outputConfigureItem("core.addonLoadMode");

    File tempDir;
    String tempDirPath = configureStore.getString("core.tempDir");
    if (StringUtils.isNotBlank(tempDirPath)) {
        tempDir = new File(tempDirPath);
    } else {
        tempDir = new File(WebUtils.getTempDir(servletContext), ".dorado");
    }

    boolean supportsTempFile = configureStore.getBoolean("core.supportsTempFile");
    TempFileUtils.setSupportsTempFile(supportsTempFile);
    if (supportsTempFile) {
        if ((tempDir.exists() && tempDir.isDirectory()) || tempDir.mkdir()) {
            TempFileUtils.setTempDir(tempDir);
        }
        ConsoleUtils.outputLoadingInfo("[TempDir: " + TempFileUtils.getTempDir().getPath() + "]");
    } else {
        ConsoleUtils.outputLoadingInfo("Temp file is forbidden.");
    }

    // 
    File storeDir;
    String storeDirSettring = configureStore.getString("core.storeDir");
    if (StringUtils.isNotEmpty(storeDirSettring)) {
        storeDir = new File(storeDirSettring);
        File testFile = new File(storeDir, ".test");
        if (!testFile.mkdirs()) {
            throw new IllegalStateException(
                    "Store directory [" + storeDir.getAbsolutePath() + "] is not writable in actually.");
        }
        testFile.delete();
    } else {
        storeDir = new File(tempDir, "dorado-store");
        configureStore.set("core.storeDir", storeDir.getAbsolutePath());
    }
    ConsoleUtils.outputConfigureItem("core.storeDir");

    // gothrough packages
    String addonLoadMode = Configure.getString("core.addonLoadMode");
    String[] enabledAddons = StringUtils.split(Configure.getString("core.enabledAddons"), ",; \n\r");
    String[] disabledAddon = StringUtils.split(Configure.getString("core.disabledAddon"), ",; \n\r");

    Collection<PackageInfo> packageInfos = PackageManager.getPackageInfoMap().values();
    int addonNumber = 0;
    for (PackageInfo packageInfo : packageInfos) {
        String packageName = packageInfo.getName();
        if (packageName.equals("dorado-core")) {
            continue;
        }

        if (addonNumber > 9999) {
            packageInfo.setEnabled(false);
        } else if (StringUtils.isEmpty(addonLoadMode) || "positive".equals(addonLoadMode)) {
            packageInfo.setEnabled(!ArrayUtils.contains(disabledAddon, packageName));
        } else {
            // addonLoadMode == negative
            packageInfo.setEnabled(ArrayUtils.contains(enabledAddons, packageName));
        }

        if (packageInfo.isEnabled()) {
            addonNumber++;
        }
    }

    // print packages
    int i = 0;
    for (PackageInfo packageInfo : packageInfos) {
        ConsoleUtils.outputLoadingInfo(
                StringUtils.rightPad(String.valueOf(++i) + '.', 4) + "Package [" + packageInfo.getName() + " - "
                        + StringUtils.defaultIfBlank(packageInfo.getVersion(), "<Unknown Version>") + "] found."
                        + ((packageInfo.isEnabled() ? "" : " #DISABLED# ")));
    }

    // load packages
    for (PackageInfo packageInfo : packageInfos) {
        if (!packageInfo.isEnabled()) {
            pushLocations(contextLocations, packageInfo.getComponentLocations());
            continue;
        }

        PackageListener packageListener = packageInfo.getListener();
        if (packageListener != null) {
            packageListener.beforeLoadPackage(packageInfo, resourceLoader);
        }

        PackageConfigurer packageConfigurer = packageInfo.getConfigurer();

        if (StringUtils.isNotEmpty(packageInfo.getPropertiesLocations())) {
            for (String location : org.springframework.util.StringUtils.tokenizeToStringArray(
                    packageInfo.getPropertiesLocations(),
                    ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS)) {
                loadConfigureProperties(configureStore, resourceLoader, location, false);
            }
        }

        String[] locations;
        if (packageConfigurer != null) {
            locations = packageConfigurer.getPropertiesConfigLocations(resourceLoader);
            if (locations != null) {
                for (String location : locations) {
                    loadConfigureProperties(configureStore, resourceLoader, location, false);
                }
            }
        }

        // ?Spring?
        pushLocations(contextLocations, packageInfo.getContextLocations());
        if (packageConfigurer != null) {
            locations = packageConfigurer.getContextConfigLocations(resourceLoader);
            if (locations != null) {
                for (String location : locations) {
                    pushLocation(contextLocations, location);
                }
            }
        }

        pushLocations(servletContextLocations, packageInfo.getServletContextLocations());
        if (packageConfigurer != null) {
            locations = packageConfigurer.getServletContextConfigLocations(resourceLoader);
            if (locations != null) {
                for (String location : locations) {
                    pushLocation(servletContextLocations, location);
                }
            }
        }

        packageInfo.setLoaded(true);
    }

    // ?dorado-homepropertiesaddon
    if (StringUtils.isNotEmpty(doradoHome)) {
        String configureLocation = HOME_LOCATION_PREFIX + "configure.properties";
        loadConfigureProperties(configureStore, resourceLoader, configureLocation, true);
        if (StringUtils.isNotEmpty(runMode)) {
            loadConfigureProperties(configureStore, resourceLoader,
                    CORE_PROPERTIES_LOCATION_PREFIX + "configure-" + runMode + ".properties", true);
            loadConfigureProperties(configureStore, resourceLoader,
                    HOME_LOCATION_PREFIX + "configure-" + runMode + ".properties", true);
        }
    }

    Resource resource;

    // context
    if (processOriginContextConfigLocation) {
        intParam = servletContext.getInitParameter(CONTEXT_CONFIG_LOCATION);
        if (intParam != null) {
            pushLocations(contextLocations, intParam);
        }
    }

    resource = resourceLoader.getResource(HOME_CONTEXT_XML);
    if (resource.exists()) {
        pushLocations(contextLocations, HOME_CONTEXT_XML);
    }

    if (StringUtils.isNotEmpty(runMode)) {
        String extHomeContext = HOME_CONTEXT_PREFIX + '-' + runMode + CONTEXT_FILE_EXT;
        resource = resourceLoader.getResource(extHomeContext);
        if (resource.exists()) {
            pushLocations(contextLocations, extHomeContext);
        }
    }

    // servlet-context
    intParam = servletContext.getInitParameter(SERVLET_CONTEXT_CONFIG_LOCATION);
    if (intParam != null) {
        pushLocations(servletContextLocations, intParam);
    }
    resource = resourceLoader.getResource(HOME_SERVLET_CONTEXT_XML);
    if (resource.exists()) {
        pushLocations(servletContextLocations, HOME_SERVLET_CONTEXT_XML);
    }

    if (StringUtils.isNotEmpty(runMode)) {
        String extHomeContext = HOME_SERVLET_CONTEXT_PREFIX + '-' + runMode + CONTEXT_FILE_EXT;
        resource = resourceLoader.getResource(extHomeContext);
        if (resource.exists()) {
            pushLocations(servletContextLocations, extHomeContext);
        }
    }

    ConsoleUtils.outputConfigureItem(RESOURCE_LOADER_PROPERTY);
    ConsoleUtils.outputConfigureItem(BYTE_CODE_PROVIDER_PROPERTY);

    String contextLocationsFromProperties = configureStore.getString(CONTEXT_CONFIG_PROPERTY);
    if (contextLocationsFromProperties != null) {
        pushLocations(contextLocations, contextLocationsFromProperties);
    }
    configureStore.set(CONTEXT_CONFIG_PROPERTY, StringUtils.join(getRealResourcesPath(contextLocations), ';'));
    ConsoleUtils.outputConfigureItem(CONTEXT_CONFIG_PROPERTY);

    String serlvetContextLocationsFromProperties = configureStore.getString(SERVLET_CONTEXT_CONFIG_PROPERTY);
    if (serlvetContextLocationsFromProperties != null) {
        pushLocations(servletContextLocations, serlvetContextLocationsFromProperties);
    }
    configureStore.set(SERVLET_CONTEXT_CONFIG_PROPERTY,
            StringUtils.join(getRealResourcesPath(servletContextLocations), ';'));
    ConsoleUtils.outputConfigureItem(SERVLET_CONTEXT_CONFIG_PROPERTY);

    // ?WebContext
    DoradoContext context = DoradoContext.init(servletContext, false);
    Context.setFailSafeContext(context);
}

From source file:net.bull.javamelody.TestMonitoringFilter.java

/**
 * Initialisation./* w  w  w  .  j  ava  2s . co  m*/
 * @throws ServletException e
 */
@Before
public void setUp() throws ServletException {
    try {
        final Field field = MonitoringFilter.class.getDeclaredField("instanceCreated");
        field.setAccessible(true);
        field.set(null, false);
    } catch (final IllegalAccessException e) {
        throw new IllegalStateException(e);
    } catch (final NoSuchFieldException e) {
        throw new IllegalStateException(e);
    }
    final FilterConfig config = createNiceMock(FilterConfig.class);
    final ServletContext context = createNiceMock(ServletContext.class);
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getFilterName()).andReturn(FILTER_NAME).anyTimes();
    // anyTimes sur getInitParameter car TestJdbcDriver a pu fixer la proprit systme  false
    expect(context.getInitParameter(Parameters.PARAMETER_SYSTEM_PREFIX + Parameter.DISABLED.getCode()))
            .andReturn(null).anyTimes();
    expect(config.getInitParameter(Parameter.DISABLED.getCode())).andReturn(null).anyTimes();
    expect(context.getMajorVersion()).andReturn(2).anyTimes();
    expect(context.getMinorVersion()).andReturn(5).anyTimes();
    expect(context.getServletContextName()).andReturn("test webapp").anyTimes();
    // mockJetty pour avoir un applicationServerIconName dans JavaInformations
    expect(context.getServerInfo()).andReturn("mockJetty").anyTimes();
    // dependencies pour avoir des dpendances dans JavaInformations
    final Set<String> dependencies = new LinkedHashSet<String>(
            Arrays.asList("/WEB-INF/lib/jrobin.jar", "/WEB-INF/lib/javamelody.jar"));
    // et flags pour considrer que les ressources pom.xml et web.xml existent
    JavaInformations.setWebXmlExistsAndPomXmlExists(true, true);
    expect(context.getResourcePaths("/WEB-INF/lib/")).andReturn(dependencies).anyTimes();
    expect(context.getContextPath()).andReturn(CONTEXT_PATH).anyTimes();
    monitoringFilter = new MonitoringFilter();
    monitoringFilter.setApplicationType("Test");
    replay(config);
    replay(context);
    monitoringFilter.init(config);
    verify(config);
    verify(context);
}

From source file:org.red5.server.winstone.WinstoneLoader.java

/**
 * Initialization.// www  . j a v a 2  s .c o  m
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void init() {
    log.info("Loading Winstone context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    // configure the webapps folder, make sure we have one
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // create one embedded (server) and use it everywhere
    Map args = new HashMap();
    //args.put("webroot", webappFolder + "/root");
    args.put("webappsDir", webappFolder);
    // Start server
    try {
        log.info("Starting Winstone servlet engine");
        Launcher.initLogger(args);
        // spawns threads, so your application doesn't block
        embedded = new StoneLauncher(args);
        log.trace("Classloader for embedded: {} TCL: {}", Launcher.class.getClassLoader(), originalClassLoader);
        // get the default host
        HostConfiguration host = embedded.getHostGroup().getHostByName(null);
        // set the primary application loader
        LoaderBase.setApplicationLoader(new WinstoneApplicationLoader(host, applicationContext));
        // get root first, we may want to start a spring config internally but for now skip it
        WebAppConfiguration root = host.getWebAppByURI("/");
        log.trace("Root: {}", root);
        // scan the sub directories to determine our context names
        buildContextNameList(webappFolder);
        // loop the other contexts
        for (String contextName : contextNames) {
            WebAppConfiguration ctx = host.getWebAppByURI(contextName);
            // get access to the servlet context
            final ServletContext servletContext = ctx.getContext(contextName);
            log.debug("Context initialized: {}", servletContext.getContextPath());
            //set the hosts id
            servletContext.setAttribute("red5.host.id", host.getHostname());
            // get the path
            String prefix = servletContext.getRealPath("/");
            log.debug("Path: {}", prefix);
            try {
                final ClassLoader cldr = ctx.getLoader();
                log.debug("Loader type: {}", cldr.getClass().getName());
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                //set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(cldr);
                //create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(cldr);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        //web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, cldr);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class.", e);
                        }
                        appctx.setConfigLocations(new String[] { contextConfigLocation });
                        appctx.setServletContext(servletContext);
                        //set parent context or use current app context
                        if (parentContext != null) {
                            appctx.setParent(parentContext);
                        } else {
                            appctx.setParent(applicationContext);
                        }
                        // set the root webapp ctx attr on the each servlet context so spring can find it later
                        servletContext.setAttribute(
                                WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                        //refresh the factory
                        log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                        appctx.refresh();
                        if (log.isDebugEnabled()) {
                            log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                    appctx.isRunning());
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading Winstone, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading Winstone", e);
        }
    } finally {
        registerJMX();
    }

}

From source file:com.sun.faces.config.ConfigureListener.java

/**
 * <p>Determines if a particular feature, configured via the web
 * deployment descriptor as a <code>true/false</code> value, is
 * enabled or not.</p>/*from   w ww  .j av  a  2s. c  o  m*/
 * @param context the <code>ServletContext</code> of the application
 * @param paramName the name of the context init paramName to check
 *
 * @return <code>true</code> if the feature in question is enabled, otherwise
 *  <code>false</code>
 */
protected boolean isFeatureEnabled(ServletContext context, String paramName) {
    String paramValue = context.getInitParameter(paramName);
    if (paramValue != null) {
        paramValue = paramValue.trim();
        if (!(paramValue.equals("true")) && !(paramValue.equals("false"))) {

            if (log.isWarnEnabled()) {
                log.warn(Util.getExceptionMessageString(Util.INVALID_INIT_PARAM_ERROR_MESSAGE_ID,
                        new Object[] { paramValue, "validateXml" }));
            }
        }
    }

    return Boolean.valueOf(paramValue).booleanValue();
}

From source file:org.red5.server.undertow.UndertowLoader.java

/**
 * Initialization./*from w ww  .j  av a2 s . c  o  m*/
 */
public void start() {
    log.info("Loading undertow context");
    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
    // root location for servlet container
    String serverRoot = System.getProperty("red5.root");
    log.info("Server root: {}", serverRoot);
    String confRoot = System.getProperty("red5.config_root");
    log.info("Config root: {}", confRoot);
    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = FileUtil.formatPath(System.getProperty("red5.root"), "/webapps");
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);
    // scan the sub directories to determine our context paths
    buildContextPathList(webappFolder);
    try {
        // create our servlet container
        container = ServletContainer.Factory.newInstance();
        // create a root path handler
        final PathHandler rootHandler = new PathHandler();
        // create one server and use it everywhere
        Undertow.Builder builder = Undertow.builder();
        // loop through connectors adding listeners to the builder
        for (UndertowConnector undertowConnector : connectors) {
            InetSocketAddress addr = undertowConnector.getSocketAddress();
            builder.addListener(addr.getPort(), addr.getHostName(),
                    (undertowConnector.isSecure() ? ListenerType.HTTPS : ListenerType.HTTP));
        }
        log.trace("Classloader for undertow: {} TCL: {}", Undertow.class.getClassLoader(), originalClassLoader);
        // create references for later lookup
        LoaderBase.setApplicationLoader(new UndertowApplicationLoader(container, applicationContext));
        // loop the other contexts
        for (String contextPath : contextPaths) {
            // create a class loader for the context
            ClassLoader classLoader = buildWebClassLoader(originalClassLoader, webappFolder, contextPath);
            // create deployment info
            DeploymentInfo info = deployment().setClassLoader(classLoader)
                    .setContextPath(contextPath.equalsIgnoreCase("/ROOT") ? "/" : contextPath)
                    .setDefaultEncoding("UTF-8").setDeploymentName(contextPath.substring(1) + ".war")
                    .setUrlEncoding("UTF-8");
            // parse the web.xml and configure the context
            parseWebXml(webappFolder, contextPath, info);
            if (log.isDebugEnabled()) {
                log.debug("Deployment info - name: {} servlets: {} filters: {}", new Object[] {
                        info.getDisplayName(), info.getServlets().size(), info.getFilters().size() });
            }
            // add the new deployment to the servlet container
            DeploymentManager manager = container.addDeployment(info);
            // set a reference to the manager and deploy the context
            LoaderBase.setRed5ApplicationContext(contextPath, new UndertowApplicationContext(manager));
            // deploy
            manager.deploy();
            // add path
            rootHandler.addPrefixPath(info.getContextPath(), manager.start());
            // get deployment
            Deployment deployment = manager.getDeployment();
            // get servlet context
            final ServletContext servletContext = deployment.getServletContext();
            log.debug("Context initialized: {}", servletContext.getContextPath());
            try {
                log.debug("Context: {}", servletContext);
                final ClassLoader webClassLoader = info.getClassLoader();
                log.debug("Webapp classloader: {}", webClassLoader);
                // get the (spring) config file path
                final String contextConfigLocation = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM) == null
                                ? defaultSpringConfigLocation
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.CONFIG_LOCATION_PARAM);
                log.debug("Spring context config location: {}", contextConfigLocation);
                // get the (spring) parent context key
                final String parentContextKey = servletContext.getInitParameter(
                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM) == null
                                ? defaultParentContextKey
                                : servletContext.getInitParameter(
                                        org.springframework.web.context.ContextLoader.LOCATOR_FACTORY_KEY_PARAM);
                log.debug("Spring parent context key: {}", parentContextKey);
                // set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);
                // create a thread to speed-up application loading
                Thread thread = new Thread("Launcher:" + servletContext.getContextPath()) {
                    public void run() {
                        //set thread context classloader to web classloader
                        Thread.currentThread().setContextClassLoader(webClassLoader);
                        //get the web app's parent context
                        ApplicationContext parentContext = null;
                        if (applicationContext.containsBean(parentContextKey)) {
                            parentContext = (ApplicationContext) applicationContext.getBean(parentContextKey);
                        } else {
                            log.warn("Parent context was not found: {}", parentContextKey);
                        }
                        // create a spring web application context
                        final String contextClass = servletContext.getInitParameter(
                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM) == null
                                        ? XmlWebApplicationContext.class.getName()
                                        : servletContext.getInitParameter(
                                                org.springframework.web.context.ContextLoader.CONTEXT_CLASS_PARAM);
                        // web app context (spring)
                        ConfigurableWebApplicationContext appctx = null;
                        try {
                            Class<?> clazz = Class.forName(contextClass, true, webClassLoader);
                            appctx = (ConfigurableWebApplicationContext) clazz.newInstance();
                            // set the root webapp ctx attr on the each servlet context so spring can find it later
                            servletContext.setAttribute(
                                    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, appctx);
                            appctx.setConfigLocations(new String[] { contextConfigLocation });
                            appctx.setServletContext(servletContext);
                            // set parent context or use current app context
                            if (parentContext != null) {
                                appctx.setParent(parentContext);
                            } else {
                                appctx.setParent(applicationContext);
                            }
                            // refresh the factory
                            log.trace("Classloader prior to refresh: {}", appctx.getClassLoader());
                            appctx.refresh();
                            if (log.isDebugEnabled()) {
                                log.debug("Red5 app is active: {} running: {}", appctx.isActive(),
                                        appctx.isRunning());
                            }
                            appctx.start();
                        } catch (Throwable e) {
                            throw new RuntimeException("Failed to load webapplication context class", e);
                        }
                    }
                };
                thread.setDaemon(true);
                thread.start();
            } catch (Throwable t) {
                log.error("Error setting up context: {} due to: {}", servletContext.getContextPath(),
                        t.getMessage());
                t.printStackTrace();
            } finally {
                //reset the classloader
                Thread.currentThread().setContextClassLoader(originalClassLoader);
            }
        }
        // Dump deployments list
        if (log.isDebugEnabled()) {
            for (String deployment : container.listDeployments()) {
                log.debug("Container deployment: {}", deployment);
            }
        }
        // if everything is ok at this point then call the rtmpt and rtmps beans so they will init
        //         if (applicationContext.containsBean("rtmpt.server")) {
        //            log.debug("Initializing RTMPT");
        //            applicationContext.getBean("rtmpt.server");
        //            log.debug("Finished initializing RTMPT");
        //         } else {
        //            log.info("Dedicated RTMPT server configuration was not specified");
        //         }
        //         if (applicationContext.containsBean("rtmps.server")) {
        //            log.debug("Initializing RTMPS");
        //            applicationContext.getBean("rtmps.server");
        //            log.debug("Finished initializing RTMPS");
        //         } else {
        //            log.debug("Dedicated RTMPS server configuration was not specified");
        //         }
        // add a root handler
        builder.setHandler(rootHandler);
        // build the server instance
        server = builder.build();
        log.info("Starting Undertow");
        server.start();
    } catch (Exception e) {
        if (e instanceof BindException || e.getMessage().indexOf("BindException") != -1) {
            log.error(
                    "Error loading undertow, unable to bind connector. You may not have permission to use the selected port",
                    e);
        } else {
            log.error("Error loading undertow", e);
        }
    } finally {
        registerJMX();
    }
    log.debug("Undertow init exit");
}

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

/**
 * Decides which application configuration file to use and sets the location in the system properties.
 * By default the location will be set in the property with key "application.config.location" but this 
 * can be overridden by configuration//  w  w  w .ja va 2 s. c  om
 */
private String getApplicationConfigurationLocation(ServletContext ctx) {
    logToSystemOut("Servlet context initialized, checking for configuration location parameters...");
    logToSystemOut("Checking for system property " + this.configLocationPropertyKey);
    String configLocation = System.getProperty(this.configLocationPropertyKey);
    if (configLocation == null) {
        logToSystemOut("Didn't find system property " + this.configLocationPropertyKey
                + " holding application configuration location, checking environment variable "
                + this.configLocationPropertyKey);
        configLocation = System.getenv(this.configLocationPropertyKey);
    }
    if (configLocation == null) {
        logToSystemOut("Didn't find environment variable " + this.configLocationPropertyKey
                + " holding application configuration location, checking servlet context-param "
                + this.configLocationPropertyKey);
        configLocation = ctx.getInitParameter(this.configLocationPropertyKey);
    }
    if (configLocation == null) {
        logToSystemOut("Didn't find servlet-context variable " + this.configLocationPropertyKey
                + " holding application configuration location, " + "using fallback configuration location: "
                + this.fallbackConfigLocation);
        configLocation = this.fallbackConfigLocation;
    }

    return configLocation;
}

From source file:org.accada.epcis.repository.RepositoryContextListener.java

/**
 * {@inheritDoc}/*from   w  w  w .j a v  a2  s .c om*/
 * 
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent event) {
    ServletContext ctx = event.getServletContext();

    /*
     * Note: logging is initialized automatically by reading
     * logging.properties and log4j.properties from the classpath.
     * logging.properties is used to tell commons-logging to use LOG4J as
     * its underlying logging toolkit; log4j.properties is used to configure
     * LOG4J. To initialize LOG4J manually from LOG4J_CONFIG_LOCATION,
     * un-comment the following code (LOG4J_CONFIG_LOCATION =
     * "log4jConfigLocation") ...
     */
    // "log4jConfigLocation";
    // String path = ctx.getRealPath("/");
    // String log4jCfg = ctx.getInitParameter(LOG4J_CONFIG_LOCATION);
    // // initialize Log4j
    // if (log4jCfg != null) {
    // // if no log4j properties file found, then do not try
    // // to load it (the application runs without logging)
    // PropertyConfigurator.configure(path + log4jCfg);
    // }
    // log = LogFactory.getLog(this.getClass());

    // set a system property to configure CXF to use LOG4J
    System.setProperty("org.apache.cxf.Logger", "org.apache.cxf.common.logging.Log4jLogger");

    LOG.info("Starting Accada EPCIS Repository application");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Logging application context init-parameters:");
        Enumeration<?> e = ctx.getInitParameterNames();
        while (e.hasMoreElements()) {
            String param = (String) e.nextElement();
            LOG.debug(param + "=" + ctx.getInitParameter(param));
        }
    }
}

From source file:org.fosstrak.epcis.repository.RepositoryContextListener.java

/**
 * {@inheritDoc}/*from  www  . j ava2 s .c o m*/
 * 
 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
 */
public void contextInitialized(ServletContextEvent event) {
    ServletContext ctx = event.getServletContext();

    /*
     * Note: logging is initialized automatically by reading
     * logging.properties and log4j.properties from the classpath.
     * logging.properties is used to tell commons-logging to use LOG4J as
     * its underlying logging toolkit; log4j.properties is used to configure
     * LOG4J. To initialize LOG4J manually from LOG4J_CONFIG_LOCATION,
     * un-comment the following code (LOG4J_CONFIG_LOCATION =
     * "log4jConfigLocation") ...
     */
    // "log4jConfigLocation";
    // String path = ctx.getRealPath("/");
    // String log4jCfg = ctx.getInitParameter(LOG4J_CONFIG_LOCATION);
    // // initialize Log4j
    // if (log4jCfg != null) {
    // // if no log4j properties file found, then do not try
    // // to load it (the application runs without logging)
    // PropertyConfigurator.configure(path + log4jCfg);
    // }
    // log = LogFactory.getLog(this.getClass());

    // set a system property to configure CXF to use LOG4J
    System.setProperty("org.apache.cxf.Logger", "org.apache.cxf.common.logging.Log4jLogger");

    LOG.info("Starting Fosstrak EPCIS Repository application");

    if (LOG.isDebugEnabled()) {
        LOG.debug("Logging application context init-parameters:");
        Enumeration<?> e = ctx.getInitParameterNames();
        while (e.hasMoreElements()) {
            String param = (String) e.nextElement();
            LOG.debug(param + "=" + ctx.getInitParameter(param));
        }
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    final ServletContext servletContext = servletContextEvent.getServletContext();
    stopThreads = !"false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads"));
    stopTimerThreads = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads"));
    executeShutdownHooks = !"false"
            .equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks"));
    threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs",
            THREAD_WAIT_MS_DEFAULT);/*from w w w  .j  a  va2  s .com*/
    shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs",
            SHUTDOWN_HOOK_WAIT_MS_DEFAULT);

    info("Settings for " + this.getClass().getName() + " (CL: 0x"
            + Integer.toHexString(System.identityHashCode(getWebApplicationClassLoader())) + "):");
    info("  stopThreads = " + stopThreads);
    info("  stopTimerThreads = " + stopTimerThreads);
    info("  executeShutdownHooks = " + executeShutdownHooks);
    info("  threadWaitMs = " + threadWaitMs + " ms");
    info("  shutdownHookWaitMs = " + shutdownHookWaitMs + " ms");

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

    try {
        // If package org.jboss is found, we may be running under JBoss
        mayBeJBoss = (contextClassLoader.getResource("org/jboss") != null);
    } catch (Exception ex) {
        // Do nothing
    }

    info("Initializing context by loading some known offenders with system classloader");

    // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener  
    // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup
    try {
        // Switch to system classloader in before we load/call some JRE stuff that will cause 
        // the current classloader to be available for garbage collection
        Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());

        java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread

        java.security.Security.getProviders();

        java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader

        javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext()

        try {
            Class.forName("javax.security.auth.Policy").getMethod("getPolicy").invoke(null);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (ClassNotFoundException e) {
            // Ignore silently - class is deprecated
        }

        try {
            javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        } catch (Exception ex) { // Example: ParserConfigurationException
            error(ex);
        }

        try {
            Class.forName("javax.xml.bind.DatatypeConverterImpl"); // Since JDK 1.6. May throw java.lang.Error
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        try {
            Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader());
        } catch (ClassNotFoundException e) {
            // Do nothing
        }

        // This probably does not affect classloaders, but prevents some problems with .jar files
        try {
            // URL needs to be well-formed, but does not need to exist
            new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false);
        } catch (Exception ex) {
            error(ex);
        }

        /////////////////////////////////////////////////////
        // Load Sun specific classes that may cause leaks

        final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun");

        try {
            Class.forName("com.sun.jndi.ldap.LdapPoolManager");
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        }

        try {
            Class.forName("sun.java2d.Disposer"); // Will start a Thread
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE && !mayBeJBoss) // JBoss blocks this package/class, so don't warn
                error(cnfex);
        }

        try {
            Class<?> gcClass = Class.forName("sun.misc.GC");
            final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class);
            requestLatency.invoke(null, 3600000L);
        } catch (ClassNotFoundException cnfex) {
            if (isSunJRE)
                error(cnfex);
        } catch (NoSuchMethodException nsmex) {
            error(nsmex);
        } catch (IllegalAccessException iaex) {
            error(iaex);
        } catch (InvocationTargetException itex) {
            error(itex);
        }

        // Cause oracle.jdbc.driver.OracleTimeoutPollingThread to be started with contextClassLoader = system classloader  
        try {
            Class.forName("oracle.jdbc.driver.OracleTimeoutThreadPerVM");
        } catch (ClassNotFoundException e) {
            // Ignore silently - class not present
        }
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * This method returns a File that points to the location of the toaster scripts...
 *//*  w w w  . j a  v  a2s . c  om*/
private File getScriptDirectory() throws Exception {

    ServletContext context = getServletContext();
    String tmpScriptPath;
    File scriptDirectory;

    /* Check if the servlet initialisation parameter defines the script path... */
    tmpScriptPath = context.getInitParameter(SCRIPT_PATH_INIT_PARAM);

    if (tmpScriptPath != null) {
        scriptDirectory = checkScriptPath(tmpScriptPath);
        if (scriptDirectory != null) {
            return (scriptDirectory);
        }
    }

    /* Get the system path to the web directory... check for the toaster scripts */
    /* under this.                                                               */
    tmpScriptPath = context.getRealPath("/");
    if (tmpScriptPath == null) {
        /* null means that we cannot get the system directory... which probably */
        /* means that the servlet is running from a WAR file.                   */
        throw new Exception("Could not get the directory that the XMLToaster scripts are in.");
    }

    /* If a directory called "services" exists under the web directory.. then use that... */
    String tmpScriptPathWithToaster = tmpScriptPath + File.separator + "services";
    scriptDirectory = checkScriptPath(tmpScriptPathWithToaster);

    if (scriptDirectory != null) {
        return (scriptDirectory);
    }

    /* If the "services" directory does not exist then use the web directory... */
    scriptDirectory = checkScriptPath(tmpScriptPath);
    if (scriptDirectory != null) {
        return (scriptDirectory);
    }

    /* We have run out of options... */
    return (null);
}