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:net.jawr.web.bundle.processor.BundleProcessor.java

/**
 * Launch the bundle processing//  ww  w .  ja  va2s.c  o  m
 * 
 * @param baseDirPath
 *            the base directory path
 * @param tmpDirPath
 *            the temp directory path
 * @param destDirPath
 *            the destination directory path
 * @param springConfigFiles
 *            the spring config file to initialize
 * @param propertyPlaceHolderFile
 *            the path to the property place holder file
 * @param servletNames
 *            the list of the name of servlets to initialized
 * @param generateCdnFiles
 *            the flag indicating if we should generate the CDN files or not
 * @param keepUrlMapping
 *            the flag indicating if we should keep the URL mapping or not.
 * @param servletApiVersion
 *            the servlet API version (ex: "2.3" or "2.5")
 * @throws Exception
 *             if an exception occurs
 */
public void process(String baseDirPath, String tmpDirPath, String destDirPath, String springConfigFiles,
        List<String> servletsToInitialize, boolean generateCdnFiles, boolean keepUrlMapping,
        String servletApiVersion) throws Exception {

    // Creates the web app class loader
    ClassLoader webAppClassLoader = initClassLoader(baseDirPath);

    // Retrieve the parameters from baseDir+"/WEB-INF/web.xml"
    Document doc = getWebXmlDocument(baseDirPath);

    ServletContext servletContext = initServletContext(doc, baseDirPath, tmpDirPath, springConfigFiles,
            servletApiVersion);

    List<ServletDefinition> servletDefinitions = getWebXmlServletDefinitions(doc, servletContext,
            servletsToInitialize, webAppClassLoader);

    // Initialize the servlets and retrieve the jawr servlet definitions
    List<ServletDefinition> jawrServletDefinitions = initServlets(servletDefinitions);
    if (jawrServletDefinitions.isEmpty()) {

        logger.debug("No Jawr Servlet defined in web.xml");
        if (servletContext.getInitParameter(CONFIG_LOCATION_PARAM) != null) {
            logger.debug("Spring config location defined. Try loading spring context");
            jawrServletDefinitions = initJawrSpringControllers(servletContext);
        }
    }

    // Copy the temporary directory in the dest directory
    FileUtils.copyDirectory(new File(tmpDirPath), new File(destDirPath));

    if (generateCdnFiles) {
        // Process the Jawr servlet to generate the bundles
        String cdnDestDirPath = destDirPath + CDN_DIR_NAME;
        processJawrServlets(cdnDestDirPath, jawrServletDefinitions, keepUrlMapping);
    }

}

From source file:info.magnolia.cms.beans.config.PropertiesInitializer.java

/**
 * Returns the property files configuration string passed, replacing all the needed values: ${servername} will be
 * reaplced with the name of the server, ${webapp} will be replaced with webapp name, ${systemProperty/*} will be
 * replaced with the corresponding system property, ${env/*} will be replaced with the corresponding environment property,
 * and ${contextAttribute/*} and ${contextParam/*} will be replaced with the corresponding attributes or parameters
 * taken from servlet context.//  ww  w .ja v a2 s .c  o  m
 * This can be very useful for all those application servers that has multiple instances on the same server, like
 * WebSphere. Typical usage in this case:
 * <code>WEB-INF/config/${servername}/${contextAttribute/com.ibm.websphere.servlet.application.host}/magnolia.properties</code>
 *
 * @param context Servlet context
 * @param servername Server name
 * @param webapp Webapp name
 * @param propertiesFilesString a comma separated list of paths.
 * @return Property file configuration string with everything replaced.
 *
 * @deprecated since 4.5, this is done by {@link info.magnolia.init.DefaultMagnoliaPropertiesResolver#DefaultMagnoliaPropertiesResolver}.
 * Note: when remove this class and method, this code will need to be cleaned up and moved to info.magnolia.init.DefaultMagnoliaPropertiesResolver
 */
public static String processPropertyFilesString(ServletContext context, String servername, String webapp,
        String propertiesFilesString, String contextPath) {
    // Replacing basic properties.
    propertiesFilesString = StringUtils.replace(propertiesFilesString, "${servername}", servername); //$NON-NLS-1$
    propertiesFilesString = StringUtils.replace(propertiesFilesString, "${webapp}", webapp); //$NON-NLS-1$
    propertiesFilesString = StringUtils.replace(propertiesFilesString, "${contextPath}", contextPath);

    // Replacing servlet context attributes (${contextAttribute/something})
    String[] contextAttributeNames = getNamesBetweenPlaceholders(propertiesFilesString,
            CONTEXT_ATTRIBUTE_PLACEHOLDER_PREFIX);
    if (contextAttributeNames != null) {
        for (String ctxAttrName : contextAttributeNames) {
            if (ctxAttrName != null) {
                // Some implementation may not accept a null as attribute key, but all should accept an empty
                // string.
                final String originalPlaceHolder = PLACEHOLDER_PREFIX + CONTEXT_ATTRIBUTE_PLACEHOLDER_PREFIX
                        + ctxAttrName + PLACEHOLDER_SUFFIX;
                final Object attrValue = context.getAttribute(ctxAttrName);
                if (attrValue != null) {
                    propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder,
                            attrValue.toString());
                }
            }
        }
    }

    // Replacing servlet context parameters (${contextParam/something})
    String[] contextParamNames = getNamesBetweenPlaceholders(propertiesFilesString,
            CONTEXT_PARAM_PLACEHOLDER_PREFIX);
    if (contextParamNames != null) {
        for (String ctxParamName : contextParamNames) {
            if (ctxParamName != null) {
                // Some implementation may not accept a null as param key, but an empty string? TODO Check.
                final String originalPlaceHolder = PLACEHOLDER_PREFIX + CONTEXT_PARAM_PLACEHOLDER_PREFIX
                        + ctxParamName + PLACEHOLDER_SUFFIX;
                final String paramValue = context.getInitParameter(ctxParamName);
                if (paramValue != null) {
                    propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue);
                }
            }
        }
    }

    // Replacing system property (${systemProperty/something})
    String[] systemPropertiesNames = getNamesBetweenPlaceholders(propertiesFilesString,
            SYSTEM_PROPERTY_PLACEHOLDER_PREFIX);
    if (systemPropertiesNames != null) {
        for (String sysPropName : systemPropertiesNames) {
            if (StringUtils.isNotBlank(sysPropName)) {
                final String originalPlaceHolder = PLACEHOLDER_PREFIX + SYSTEM_PROPERTY_PLACEHOLDER_PREFIX
                        + sysPropName + PLACEHOLDER_SUFFIX;
                final String paramValue = System.getProperty(sysPropName);
                if (paramValue != null) {
                    propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue);
                }
            }
        }
    }

    // Replacing environment property (${env/something})
    String[] envPropertiesNames = getNamesBetweenPlaceholders(propertiesFilesString,
            ENV_PROPERTY_PLACEHOLDER_PREFIX);
    if (envPropertiesNames != null) {
        for (String envPropName : envPropertiesNames) {
            if (StringUtils.isNotBlank(envPropName)) {
                final String originalPlaceHolder = PLACEHOLDER_PREFIX + ENV_PROPERTY_PLACEHOLDER_PREFIX
                        + envPropName + PLACEHOLDER_SUFFIX;
                final String paramValue = System.getenv(envPropName);
                if (paramValue != null) {
                    propertiesFilesString = propertiesFilesString.replace(originalPlaceHolder, paramValue);
                }
            }
        }
    }

    return propertiesFilesString;
}

From source file:se.jiderhamn.classloader.leak.prevention.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 .  ja  va  2  s .  c om*/
    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());

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread
        java.security.Security.getProviders();

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

        // Christopher: Uncommented as it will not work on some containers as google app engine  
        //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
        }
    } catch (Throwable ex) {
        error(ex);
    } finally {
        // Reset original classloader
        Thread.currentThread().setContextClassLoader(contextClassLoader);
    }
}

From source file:org.debux.webmotion.server.call.ServerContext.java

/**
 * Initialize the context./*  www . j  av  a  2 s. c o m*/
 * 
 * @param servletContext servlet context
 */
public void contextInitialized(ServletContext servletContext) {
    this.servletContext = servletContext;
    this.attributes = new HashMap<String, Object>();
    this.handlers = new SingletonFactory<WebMotionHandler>();
    this.controllers = new SingletonFactory<WebMotionController>();
    this.globalControllers = new HashMap<String, Class<? extends WebMotionController>>();
    this.injectors = new ArrayList<Injector>();

    this.beanUtil = BeanUtilsBean.getInstance();
    this.converter = beanUtil.getConvertUtils();

    // Register MBeans
    this.serverStats = new ServerStats();
    this.handlerStats = new HandlerStats();
    this.serverManager = new ServerContextManager(this);

    this.serverStats.register();
    this.handlerStats.register();
    this.serverManager.register();

    this.webappPath = servletContext.getRealPath("/");

    // Read the mapping in the current project
    MappingParser[] parsers = getMappingParsers();
    for (MappingParser parser : parsers) {
        mapping = parser.parse(mappingFileNames);
        if (mapping != null) {
            break;
        }
    }

    String skipConvensionScan = servletContext.getInitParameter("wm.skip.conventionScan");
    if (!"true".equals(skipConvensionScan)) {

        // Scan to generate mapping by convention
        ConventionScan[] conventions = getMappingConventions();
        for (ConventionScan conventionScan : conventions) {
            Mapping convention = conventionScan.scan();

            if (!convention.getActionRules().isEmpty() || !convention.getFilterRules().isEmpty()) {

                if (mapping == null) {
                    mapping = convention;
                } else {
                    mapping.getExtensionsRules().add(convention);
                }
            }
        }
    }

    if (mapping == null) {
        throw new WebMotionException("No mapping found for " + Arrays.toString(mappingFileNames) + " in "
                + Arrays.toString(mappingParsers));
    }

    // Fire onStart
    listeners = new ArrayList<WebMotionServerListener>();
    onStartServerListener(mapping);

    // Load mapping
    loadMapping();

    // Check mapping
    checkMapping();

    log.info("WebMotion is started");
}

From source file:org.red5.server.tomcat.TomcatLoader.java

/**
 * Starts a web application and its red5 (spring) component. This is
 * basically a stripped down version of init().
 * /*from   w w w . j  a  v a 2s.  c o m*/
 * @return true on success
 */
public boolean startWebApplication(String applicationName) {
    log.info("Starting Tomcat - Web application");
    boolean result = false;

    //get a reference to the current threads classloader
    final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();

    log.debug("Webapp root: {}", webappFolder);

    // application directory
    String contextName = '/' + applicationName;

    Container ctx = null;

    if (webappFolder == null) {
        // Use default webapps directory
        webappFolder = System.getProperty("red5.root") + "/webapps";
    }
    System.setProperty("red5.webapp.root", webappFolder);
    log.info("Application root: {}", webappFolder);

    // scan for additional webapp contexts

    // Root applications directory
    File appDirBase = new File(webappFolder);

    // check if the context already exists for the host
    if ((ctx = host.findChild(contextName)) == null) {
        log.debug("Context did not exist in host");
        String webappContextDir = FileUtil.formatPath(appDirBase.getAbsolutePath(), applicationName);
        log.debug("Webapp context directory (full path): {}", webappContextDir);
        // set the newly created context as the current container
        ctx = addContext(contextName, webappContextDir);
    } else {
        log.debug("Context already exists in host");
    }

    final ServletContext servletContext = ((Context) ctx).getServletContext();
    log.debug("Context initialized: {}", servletContext.getContextPath());

    String prefix = servletContext.getRealPath("/");
    log.debug("Path: {}", prefix);

    try {
        Loader cldr = ctx.getLoader();
        log.debug("Loader delegate: {} type: {}", cldr.getDelegate(), cldr.getClass().getName());
        if (cldr instanceof WebappLoader) {
            log.debug("WebappLoader class path: {}", ((WebappLoader) cldr).getClasspath());
        }
        final ClassLoader webClassLoader = cldr.getClassLoader();
        log.debug("Webapp classloader: {}", webClassLoader);

        // get the (spring) config file path
        final String contextConfigLocation = servletContext.getInitParameter("contextConfigLocation") == null
                ? defaultSpringConfigLocation
                : servletContext.getInitParameter("contextConfigLocation");
        log.debug("Spring context config location: {}", contextConfigLocation);

        // get the (spring) parent context key
        final String parentContextKey = servletContext.getInitParameter("parentContextKey") == null
                ? defaultParentContextKey
                : servletContext.getInitParameter("parentContextKey");
        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()) {
            @SuppressWarnings("cast")
            public void run() {
                //set current threads classloader to the webapp classloader
                Thread.currentThread().setContextClassLoader(webClassLoader);

                // create a spring web application context
                XmlWebApplicationContext appctx = new XmlWebApplicationContext();
                appctx.setClassLoader(webClassLoader);
                appctx.setConfigLocations(new String[] { contextConfigLocation });

                // check for red5 context bean
                ApplicationContext parentAppCtx = null;

                if (applicationContext.containsBean(defaultParentContextKey)) {
                    parentAppCtx = (ApplicationContext) applicationContext.getBean(defaultParentContextKey);
                } else {
                    log.warn("{} bean was not found in context: {}", defaultParentContextKey,
                            applicationContext.getDisplayName());
                    // lookup context loader and attempt to get what we need from it
                    if (applicationContext.containsBean("context.loader")) {
                        ContextLoader contextLoader = (ContextLoader) applicationContext
                                .getBean("context.loader");
                        parentAppCtx = contextLoader.getContext(defaultParentContextKey);
                    } else {
                        log.debug("Context loader was not found, trying JMX");
                        MBeanServer mbs = JMXFactory.getMBeanServer();
                        // get the ContextLoader from jmx
                        ObjectName oName = JMXFactory.createObjectName("type", "ContextLoader");
                        ContextLoaderMBean proxy = null;
                        if (mbs.isRegistered(oName)) {
                            proxy = (ContextLoaderMBean) MBeanServerInvocationHandler.newProxyInstance(mbs,
                                    oName, ContextLoaderMBean.class, true);
                            log.debug("Context loader was found");
                            parentAppCtx = proxy.getContext(defaultParentContextKey);
                        } else {
                            log.warn("Context loader was not found");
                        }
                    }
                }
                if (log.isDebugEnabled()) {
                    if (appctx.getParent() != null) {
                        log.debug("Parent application context: {}", appctx.getParent().getDisplayName());
                    }
                }

                appctx.setParent(parentAppCtx);

                appctx.setServletContext(servletContext);
                // 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.refresh();
            }
        };
        thread.setDaemon(true);
        thread.start();

        result = true;
    } 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);
    }

    return result;
}

From source file:org.apache.tapestry.request.RequestContext.java

/**
 * Writes the state of the context to the writer, typically for inclusion
 * in a HTML page returned to the user. This is useful
 * when debugging.  The Inspector uses this as well.
 *
 **//*from   w  w  w . j  a va2s  .  c  o  m*/

public void write(IMarkupWriter writer) {
    // Create a box around all of this stuff ...

    writer.begin("table");
    writer.attribute("class", "request-context-border");
    writer.begin("tr");
    writer.begin("td");

    // Get the session, if it exists, and display it.

    HttpSession session = getSession();

    if (session != null) {
        object(writer, "Session");
        writer.begin("table");
        writer.attribute("class", "request-context-object");

        section(writer, "Properties");
        header(writer, "Name", "Value");

        pair(writer, "id", session.getId());
        datePair(writer, "creationTime", session.getCreationTime());
        datePair(writer, "lastAccessedTime", session.getLastAccessedTime());
        pair(writer, "maxInactiveInterval", session.getMaxInactiveInterval());
        pair(writer, "new", session.isNew());

        List names = getSorted(session.getAttributeNames());
        int count = names.size();

        for (int i = 0; i < count; i++) {
            if (i == 0) {
                section(writer, "Attributes");
                header(writer, "Name", "Value");
            }

            String name = (String) names.get(i);
            pair(writer, name, session.getAttribute(name));
        }

        writer.end(); // Session

    }

    object(writer, "Request");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    // Parameters ...

    List parameters = getSorted(_request.getParameterNames());
    int count = parameters.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Parameters");
            header(writer, "Name", "Value(s)");
        }

        String name = (String) parameters.get(i);
        String[] values = _request.getParameterValues(name);

        writer.begin("tr");
        writer.attribute("class", getRowClass());
        writer.begin("th");
        writer.print(name);
        writer.end();
        writer.begin("td");

        if (values.length > 1)
            writer.begin("ul");

        for (int j = 0; j < values.length; j++) {
            if (values.length > 1)
                writer.beginEmpty("li");

            writer.print(values[j]);

        }

        writer.end("tr");
    }

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "authType", _request.getAuthType());
    pair(writer, "characterEncoding", _request.getCharacterEncoding());
    pair(writer, "contentLength", _request.getContentLength());
    pair(writer, "contentType", _request.getContentType());
    pair(writer, "method", _request.getMethod());
    pair(writer, "pathInfo", _request.getPathInfo());
    pair(writer, "pathTranslated", _request.getPathTranslated());
    pair(writer, "protocol", _request.getProtocol());
    pair(writer, "queryString", _request.getQueryString());
    pair(writer, "remoteAddr", _request.getRemoteAddr());
    pair(writer, "remoteHost", _request.getRemoteHost());
    pair(writer, "remoteUser", _request.getRemoteUser());
    pair(writer, "requestedSessionId", _request.getRequestedSessionId());
    pair(writer, "requestedSessionIdFromCookie", _request.isRequestedSessionIdFromCookie());
    pair(writer, "requestedSessionIdFromURL", _request.isRequestedSessionIdFromURL());
    pair(writer, "requestedSessionIdValid", _request.isRequestedSessionIdValid());
    pair(writer, "requestURI", _request.getRequestURI());
    pair(writer, "scheme", _request.getScheme());
    pair(writer, "serverName", _request.getServerName());
    pair(writer, "serverPort", _request.getServerPort());
    pair(writer, "contextPath", _request.getContextPath());
    pair(writer, "servletPath", _request.getServletPath());

    // Now deal with any headers

    List headers = getSorted(_request.getHeaderNames());
    count = headers.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Headers");
            header(writer, "Name", "Value");
        }

        String name = (String) headers.get(i);
        String value = _request.getHeader(name);

        pair(writer, name, value);
    }

    // Attributes

    List attributes = getSorted(_request.getAttributeNames());
    count = attributes.size();

    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) attributes.get(i);

        pair(writer, name, _request.getAttribute(name));
    }

    // Cookies ...

    Cookie[] cookies = _request.getCookies();

    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {

            if (i == 0) {
                section(writer, "Cookies");
                header(writer, "Name", "Value");
            }

            Cookie cookie = cookies[i];

            pair(writer, cookie.getName(), cookie.getValue());

        } // Cookies loop
    }

    writer.end(); // Request

    object(writer, "Servlet");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "servlet", _servlet);
    pair(writer, "name", _servlet.getServletName());
    pair(writer, "servletInfo", _servlet.getServletInfo());

    ServletConfig config = _servlet.getServletConfig();

    List names = getSorted(config.getInitParameterNames());
    count = names.size();

    for (int i = 0; i < count; i++) {

        if (i == 0) {
            section(writer, "Init Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        ;
        pair(writer, name, config.getInitParameter(name));

    }

    writer.end(); // Servlet

    ServletContext context = config.getServletContext();

    object(writer, "Servlet Context");
    writer.begin("table");
    writer.attribute("class", "request-context-object");

    section(writer, "Properties");
    header(writer, "Name", "Value");

    pair(writer, "majorVersion", context.getMajorVersion());
    pair(writer, "minorVersion", context.getMinorVersion());
    pair(writer, "serverInfo", context.getServerInfo());

    names = getSorted(context.getInitParameterNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Initial Parameters");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getInitParameter(name));
    }

    names = getSorted(context.getAttributeNames());
    count = names.size();
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            section(writer, "Attributes");
            header(writer, "Name", "Value");
        }

        String name = (String) names.get(i);
        pair(writer, name, context.getAttribute(name));
    }

    writer.end(); // Servlet Context

    writeSystemProperties(writer);

    writer.end("table"); // The enclosing border
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Returns the application properties/*from  www  . j ava  2 s .  c  om*/
 * 
 * @param context
 * @param props
 * @return
 */
public synchronized static Map initViewerProps(ServletContext context, Map props) {
    // initialize map
    if (props == null)
        props = new HashMap();

    // get config file
    String file = context.getInitParameter(INIT_PARAM_CONFIG_FILE);
    if (file == null || file.trim().length() <= 0)
        file = IBirtConstants.DEFAULT_VIEWER_CONFIG_FILE;

    try {

        InputStream is = null;
        if (isRelativePath(file)) {
            // realtive path
            if (!file.startsWith("/")) //$NON-NLS-1$
                file = "/" + file; //$NON-NLS-1$

            is = context.getResourceAsStream(file);
        } else {
            // absolute path
            is = new FileInputStream(file);
        }

        // parse the properties file
        PropertyResourceBundle bundle = new PropertyResourceBundle(is);
        if (bundle != null) {
            Enumeration<String> keys = bundle.getKeys();
            while (keys != null && keys.hasMoreElements()) {
                String key = keys.nextElement();
                String value = (String) bundle.getObject(key);
                if (key != null && value != null)
                    props.put(key, value);
            }
        }
    } catch (Exception e) {
    }

    return props;
}

From source file:org.apache.ofbiz.content.data.DataEvents.java

/** Streams ImageDataResource data to the output. */
// TODO: remove this method in favor of serveObjectData
public static String serveImage(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession();
    ServletContext application = session.getServletContext();

    Delegator delegator = (Delegator) request.getAttribute("delegator");
    Map<String, Object> parameters = UtilHttp.getParameterMap(request);

    Debug.logInfo("Img UserAgent - " + request.getHeader("User-Agent"), module);

    String dataResourceId = (String) parameters.get("imgId");
    if (UtilValidate.isEmpty(dataResourceId)) {
        String errorMsg = "Error getting image record from db: " + " dataResourceId is empty";
        Debug.logError(errorMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errorMsg);
        return "error";
    }//from  w  w w .  j  a  va  2  s . c om

    try {
        GenericValue dataResource = EntityQuery.use(delegator).from("DataResource")
                .where("dataResourceId", dataResourceId).cache().queryOne();
        if (!"Y".equals(dataResource.getString("isPublic"))) {
            // now require login...
            GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
            if (userLogin == null) {
                String errorMsg = "You must be logged in to download the Data Resource with ID ["
                        + dataResourceId + "]";
                Debug.logError(errorMsg, module);
                request.setAttribute("_ERROR_MESSAGE_", errorMsg);
                return "error";
            }

            // make sure the logged in user can download this content; otherwise is a pretty big security hole for DataResource records...
            // TODO: should we restrict the roleTypeId?
            long contentAndRoleCount = EntityQuery.use(delegator).from("ContentAndRole")
                    .where("partyId", userLogin.get("partyId"), "dataResourceId", dataResourceId).queryCount();
            if (contentAndRoleCount == 0) {
                String errorMsg = "You do not have permission to download the Data Resource with ID ["
                        + dataResourceId + "], ie you are not associated with it.";
                Debug.logError(errorMsg, module);
                request.setAttribute("_ERROR_MESSAGE_", errorMsg);
                return "error";
            }
        }

        String mimeType = DataResourceWorker.getMimeType(dataResource);

        // hack for IE and mime types
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.indexOf("MSIE") > -1) {
            Debug.logInfo("Found MSIE changing mime type from - " + mimeType, module);
            mimeType = "application/octet-stream";
        }

        if (mimeType != null) {
            response.setContentType(mimeType);
        }
        OutputStream os = response.getOutputStream();
        Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "",
                application.getInitParameter("webSiteId"), UtilHttp.getLocale(request),
                application.getRealPath("/"), false);
        os.write(IOUtils.toByteArray((ByteArrayInputStream) resourceData.get("stream")));
        os.flush();
    } catch (GenericEntityException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (GeneralException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    } catch (IOException e) {
        String errMsg = "Error downloading digital product content: " + e.toString();
        Debug.logError(e, errMsg, module);
        request.setAttribute("_ERROR_MESSAGE_", errMsg);
        return "error";
    }

    return "success";
}

From source file:org.apache.click.ClickServlet.java

/**
 * Create a Click application ConfigService instance.
 *
 * @param servletContext the Servlet Context
 * @return a new application ConfigService instance
 * @throws Exception if an initialization error occurs
 *///from  www .  j  a  v a  2  s  .  co  m
@SuppressWarnings("unchecked")
ConfigService createConfigService(ServletContext servletContext) throws Exception {

    Class<? extends ConfigService> serviceClass = XmlConfigService.class;

    String classname = servletContext.getInitParameter(CONFIG_SERVICE_CLASS);
    if (StringUtils.isNotBlank(classname)) {
        serviceClass = ClickUtils.classForName(classname);
    }

    return serviceClass.newInstance();
}

From source file:org.eclipse.birt.report.utility.ParameterAccessor.java

/**
 * Initial the parameters class. Web.xml is in UTF-8 format. No need to do
 * encoding convertion.//from  ww  w  .j  a va2 s . c o  m
 * 
 * @param context
 *            Servlet Context
 */

public synchronized static void initParameters(ServletContext context) {
    if (isInitContext)
        return;

    if ("true".equalsIgnoreCase(System.getProperty(IBirtConstants.SYS_PROP_BIRT_ISDESIGNER))) //$NON-NLS-1$
        isDesigner = true;

    String workingPath = "${" + IBirtConstants.SYS_PROP_WORKING_PATH + "}/"; //$NON-NLS-1$//$NON-NLS-2$

    // Working folder setting
    workingFolder = processWorkingFolder(context, context.getInitParameter(INIT_PARAM_WORKING_DIR));

    // Document folder setting
    String initDocumentFolder = context.getInitParameter(INIT_PARAM_DOCUMENT_FOLDER);
    if (isDesigner && initDocumentFolder == null)
        initDocumentFolder = workingPath + IBirtConstants.DEFAULT_DOCUMENT_FOLDER;
    String documentFolder = processRealPath(context, initDocumentFolder, IBirtConstants.DEFAULT_DOCUMENT_FOLDER,
            true);

    // Image folder setting
    String initImageFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_IMAGE_DIR);
    if (isDesigner && initImageFolder == null)
        initImageFolder = workingPath + IBirtConstants.DEFAULT_IMAGE_FOLDER;
    String imageFolder = processRealPath(context, initImageFolder, IBirtConstants.DEFAULT_IMAGE_FOLDER, true);

    // Log folder setting
    String initLogFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_DIR);
    if (isDesigner && initLogFolder == null)
        initLogFolder = workingPath + IBirtConstants.DEFAULT_LOGS_FOLDER;
    logFolder = processRealPath(context, initLogFolder, IBirtConstants.DEFAULT_LOGS_FOLDER, true);

    // Log level setting
    logLevel = context.getInitParameter(ParameterAccessor.INIT_PARAM_LOG_LEVEL);
    if (logLevel == null)
        logLevel = IBirtConstants.DEFAULT_LOGS_LEVEL;

    String rootPath = "${" + IBirtConstants.SYS_PROP_ROOT_PATH + "}/"; //$NON-NLS-1$//$NON-NLS-2$      
    // Script lib folder setting
    String initScriptlibFolder = context.getInitParameter(ParameterAccessor.INIT_PARAM_SCRIPTLIB_DIR);
    if (isDesigner && initScriptlibFolder == null)
        initScriptlibFolder = rootPath + IBirtConstants.DEFAULT_SCRIPTLIB_FOLDER;
    scriptLibDir = processRealPath(context, initScriptlibFolder, IBirtConstants.DEFAULT_SCRIPTLIB_FOLDER,
            false);

    // WebApp Locale setting
    webAppLocale = getLocaleFromString(context.getInitParameter(INIT_PARAM_LOCALE));
    if (webAppLocale == null)
        webAppLocale = Locale.getDefault();

    webAppTimeZone = getTimeZoneFromString(context.getInitParameter(INIT_PARAM_TIMEZONE));

    isWorkingFolderAccessOnly = Boolean.valueOf(context.getInitParameter(INIT_PARAM_WORKING_FOLDER_ACCESS_ONLY))
            .booleanValue();

    urlReportPathPolicy = context.getInitParameter(INIT_PARAM_URL_REPORT_PATH_POLICY);

    // Get preview report max rows parameter from ServletContext
    String s_maxRows = context.getInitParameter(INIT_PARAM_VIEWER_MAXROWS);
    try {
        maxRows = Integer.valueOf(s_maxRows).intValue();
    } catch (NumberFormatException e) {
        maxRows = -1;
    }

    // Get preview report max cube fetch levels parameter from
    // ServletContext
    String s_maxRowLevels = context.getInitParameter(INIT_PARAM_VIEWER_MAXCUBE_ROWLEVELS);
    try {
        maxCubeRowLevels = Integer.valueOf(s_maxRowLevels).intValue();
    } catch (NumberFormatException e) {
        maxCubeRowLevels = -1;
    }

    String s_maxColumnLevels = context.getInitParameter(INIT_PARAM_VIEWER_MAXCUBE_COLUMNLEVELS);
    try {
        maxCubeColumnLevels = Integer.valueOf(s_maxColumnLevels).intValue();
    } catch (NumberFormatException e) {
        maxCubeColumnLevels = -1;
    }

    // Get cube memory size parameter from ServletContext
    String s_cubeMemSize = context.getInitParameter(INIT_PARAM_VIEWER_CUBEMEMSIZE);
    try {
        cubeMemorySize = Integer.valueOf(s_cubeMemSize).intValue();
    } catch (NumberFormatException e) {
        cubeMemorySize = 0;
    }

    // default resource path
    String initResourceFolder = context.getInitParameter(INIT_PARAM_BIRT_RESOURCE_PATH);
    if (isDesigner && initResourceFolder == null)
        initResourceFolder = "${" + IBirtConstants.SYS_PROP_RESOURCE_PATH + "}"; //$NON-NLS-1$ //$NON-NLS-2$
    birtResourceFolder = processRealPath(context, initResourceFolder, null, false);

    if (isDesigner) {
        // workaround for Bugzilla bug 231715
        // (must be removed once the web.xml is used for the designer)
        isOverWrite = true;
    } else {
        // get the overwrite flag
        String s_overwrite = DataUtil.trimString(context.getInitParameter(INIT_PARAM_OVERWRITE_DOCUMENT));
        if ("true".equalsIgnoreCase(s_overwrite)) //$NON-NLS-1$
        {
            isOverWrite = true;
        } else {
            isOverWrite = false;
        }
    }

    // initialize the application properties
    initProps = initViewerProps(context, initProps);

    if (loggers == null) {
        loggers = new HashMap();
    }

    // retrieve the logger names from the application properties
    for (Iterator i = initProps.keySet().iterator(); i.hasNext();) {
        String name = (String) i.next();
        if (name.startsWith("logger.")) //$NON-NLS-1$
        {
            String loggerName = name.replaceFirst("logger.", //$NON-NLS-1$
                    "" //$NON-NLS-1$
            );
            String levelName = (String) initProps.get(name);

            loggers.put(loggerName, levelName);

            i.remove();
        }
    }

    // print on the server side
    String flag = DataUtil.trimString(context.getInitParameter(INIT_PARAM_PRINT_SERVERSIDE));
    if (IBirtConstants.VAR_ON.equalsIgnoreCase(flag)) {
        isSupportedPrintOnServer = true;
    } else if (IBirtConstants.VAR_OFF.equalsIgnoreCase(flag)) {
        isSupportedPrintOnServer = false;
    }

    // get agent style flag
    String s_agentstyle = context.getInitParameter(INIT_PARAM_AGENTSTYLE_ENGINE);
    if ("false".equalsIgnoreCase(s_agentstyle)) //$NON-NLS-1$
        isAgentStyle = false;

    // try from servlet context
    String exportFilenameGeneratorClassName = context.getInitParameter(INIT_PARAM_FILENAME_GENERATOR_CLASS);
    if (exportFilenameGeneratorClassName != null) {
        Object generatorInstance = null;
        try {
            Class generatorClass = Class.forName(exportFilenameGeneratorClassName);
            generatorInstance = generatorClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (generatorInstance != null) {
            if (generatorInstance instanceof IFilenameGeneratorFactory) {
                exportFilenameGenerator = ((IFilenameGeneratorFactory) generatorInstance)
                        .createFilenameGenerator(context);
            } else if (generatorInstance instanceof IFilenameGenerator) {
                exportFilenameGenerator = (IFilenameGenerator) generatorInstance;
            }
        }
    }

    if (exportFilenameGenerator == null) {
        exportFilenameGenerator = new DefaultFilenameGenerator();
    }

    initViewingSessionConfig(documentFolder, imageFolder);

    // Finish init context
    isInitContext = true;
}