Example usage for javax.servlet ServletContext getRealPath

List of usage examples for javax.servlet ServletContext getRealPath

Introduction

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

Prototype

public String getRealPath(String path);

Source Link

Document

Gets the real path corresponding to the given virtual path.

Usage

From source file:org.tinygroup.jspengine.compiler.JspRuntimeContext.java

/**
 * Create a JspRuntimeContext for a web application context.
 * /* w w  w. j  a  v a 2s  .co m*/
 * Loads in any previously generated dependencies from file.
 * 
 * @param context
 *            ServletContext for web application
 */
public JspRuntimeContext(ServletContext context, Options options) {

    System.setErr(new SystemLogHandler(System.err));

    this.context = context;
    this.options = options;

    int hashSize = options.getInitialCapacity();
    jsps = new ConcurrentHashMap<String, JspServletWrapper>(hashSize);

    bytecodes = new ConcurrentHashMap<String, byte[]>(hashSize);
    bytecodeBirthTimes = new ConcurrentHashMap<String, Long>(hashSize);

    // Get the parent class loader
    parentClassLoader = Thread.currentThread().getContextClassLoader();
    if (parentClassLoader == null) {
        parentClassLoader = this.getClass().getClassLoader();
    }

    if (log.isTraceEnabled()) {
        if (parentClassLoader != null) {
            log.trace(Localizer.getMessage("jsp.message.parent_class_loader_is", parentClassLoader.toString()));
        } else {
            log.trace(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>"));
        }
    }

    initClassPath();

    if (context instanceof org.tinygroup.jspengine.servlet.JspCServletContext) {
        return;
    }

    if (Constants.IS_SECURITY_ENABLED) {
        initSecurity();
    }

    // If this web application context is running from a
    // directory, start the background compilation thread
    String appBase = context.getRealPath("/");
    if (!options.getDevelopment() && appBase != null && options.getCheckInterval() > 0) {
        if (appBase.endsWith(File.separator)) {
            appBase = appBase.substring(0, appBase.length() - 1);
        }
        String directory = appBase.substring(appBase.lastIndexOf(File.separator));
        threadName = threadName + "[" + directory + "]";
        threadStart();
    }
}

From source file:org.apache.catalina.loader.WebappLoader.java

/**
 * Configure associated class loader permissions.
 *///from  w w w .ja  v a2 s.c o m
private void setPermissions() {

    if (System.getSecurityManager() == null)
        return;
    if (!(container instanceof Context))
        return;

    // Tell the class loader the root of the context
    ServletContext servletContext = ((Context) container).getServletContext();

    // Assigning permissions for the work directory
    File workDir = (File) servletContext.getAttribute(Globals.WORK_DIR_ATTR);
    if (workDir != null) {
        try {
            String workDirPath = workDir.getCanonicalPath();
            classLoader.addPermission(new FilePermission(workDirPath, "read,write"));
            classLoader
                    .addPermission(new FilePermission(workDirPath + File.separator + "-", "read,write,delete"));
        } catch (IOException e) {
            // Ignore
        }
    }

    try {

        URL rootURL = servletContext.getResource("/");
        classLoader.addPermission(rootURL);

        String contextRoot = servletContext.getRealPath("/");
        if (contextRoot != null) {
            try {
                contextRoot = (new File(contextRoot)).getCanonicalPath();
                classLoader.addPermission(contextRoot);
            } catch (IOException e) {
                // Ignore
            }
        }

        URL classesURL = servletContext.getResource("/WEB-INF/classes/");
        classLoader.addPermission(classesURL);
        URL libURL = servletContext.getResource("/WEB-INF/lib/");
        classLoader.addPermission(libURL);

        if (contextRoot != null) {

            if (libURL != null) {
                File rootDir = new File(contextRoot);
                File libDir = new File(rootDir, "WEB-INF/lib/");
                try {
                    String path = libDir.getCanonicalPath();
                    classLoader.addPermission(path);
                } catch (IOException e) {
                }
            }

        } else {

            if (workDir != null) {
                if (libURL != null) {
                    File libDir = new File(workDir, "WEB-INF/lib/");
                    try {
                        String path = libDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
                if (classesURL != null) {
                    File classesDir = new File(workDir, "WEB-INF/classes/");
                    try {
                        String path = classesDir.getCanonicalPath();
                        classLoader.addPermission(path);
                    } catch (IOException e) {
                    }
                }
            }

        }

    } catch (MalformedURLException e) {
    }

}

From source file:org.springframework.web.context.support.ServletContextResourcePatternResolver.java

/**
 * Recursively retrieve ServletContextResources that match the given pattern,
 * adding them to the given result set./*from  w ww  . j  a v a 2  s . c o  m*/
 * @param servletContext the ServletContext to work on
 * @param fullPattern the pattern to match against,
 * with preprended root directory path
 * @param dir the current directory
 * @param result the Set of matching Resources to add to
 * @throws IOException if directory contents could not be retrieved
 * @see ServletContextResource
 * @see javax.servlet.ServletContext#getResourcePaths
 */
protected void doRetrieveMatchingServletContextResources(ServletContext servletContext, String fullPattern,
        String dir, Set<Resource> result) throws IOException {

    Set<String> candidates = servletContext.getResourcePaths(dir);
    if (candidates != null) {
        boolean dirDepthNotFixed = fullPattern.contains("**");
        int jarFileSep = fullPattern.indexOf(ResourceUtils.JAR_URL_SEPARATOR);
        String jarFilePath = null;
        String pathInJarFile = null;
        if (jarFileSep > 0 && jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length() < fullPattern.length()) {
            jarFilePath = fullPattern.substring(0, jarFileSep);
            pathInJarFile = fullPattern.substring(jarFileSep + ResourceUtils.JAR_URL_SEPARATOR.length());
        }
        for (String currPath : candidates) {
            if (!currPath.startsWith(dir)) {
                // Returned resource path does not start with relative directory:
                // assuming absolute path returned -> strip absolute path.
                int dirIndex = currPath.indexOf(dir);
                if (dirIndex != -1) {
                    currPath = currPath.substring(dirIndex);
                }
            }
            if (currPath.endsWith("/") && (dirDepthNotFixed || StringUtils.countOccurrencesOf(currPath,
                    "/") <= StringUtils.countOccurrencesOf(fullPattern, "/"))) {
                // Search subdirectories recursively: ServletContext.getResourcePaths
                // only returns entries for one directory level.
                doRetrieveMatchingServletContextResources(servletContext, fullPattern, currPath, result);
            }
            if (jarFilePath != null && getPathMatcher().match(jarFilePath, currPath)) {
                // Base pattern matches a jar file - search for matching entries within.
                String absoluteJarPath = servletContext.getRealPath(currPath);
                if (absoluteJarPath != null) {
                    doRetrieveMatchingJarEntries(absoluteJarPath, pathInJarFile, result);
                }
            }
            if (getPathMatcher().match(fullPattern, currPath)) {
                result.add(new ServletContextResource(servletContext, currPath));
            }
        }
    }
}

From source file:org.openbravo.client.kernel.StyleSheetResourceComponent.java

@Override
public String generate() {
    final List<Module> modules = KernelUtils.getInstance().getModulesOrderedByDependency();
    final ServletContext context = (ServletContext) getParameters().get(KernelConstants.SERVLET_CONTEXT);
    final StringBuffer sb = new StringBuffer();

    final String appName = getApplicationName();

    final boolean makeCssDataUri = getParameters().get("_cssDataUri") != null
            && getParameters().get("_cssDataUri").equals("true");

    final String skinParam;
    if (getParameters().containsKey(KernelConstants.SKIN_PARAMETER)) {
        skinParam = (String) getParameters().get(KernelConstants.SKIN_PARAMETER);
    } else {/*from  w w  w. j  ava 2s . c  o m*/
        skinParam = KernelConstants.SKIN_DEFAULT;
    }

    for (Module module : modules) {
        for (ComponentProvider provider : componentProviders) {
            final List<ComponentResource> resources = provider.getGlobalComponentResources();
            if (resources == null || resources.size() == 0) {
                continue;
            }

            if (provider.getModule().getId().equals(module.getId())) {
                for (ComponentResource resource : resources) {

                    if (resource.getType() == ComponentResourceType.Stylesheet
                            && resource.isValidForApp(appName)) {

                        log.debug("Processing resource: " + resource);

                        String resourcePath = resource.getPath();

                        // Skin version handling
                        if (resourcePath.contains(KernelConstants.SKIN_PARAMETER)) {
                            resourcePath = resourcePath.replaceAll(KernelConstants.SKIN_PARAMETER, skinParam);
                        }

                        try {
                            final String realResourcePath = context.getRealPath(resourcePath);
                            final File file = new File(realResourcePath);
                            if (!file.exists() || !file.canRead()) {
                                log.error(file.getAbsolutePath() + " cannot be read");
                                continue;
                            }
                            String resourceContents = FileUtils.readFileToString(file, "UTF-8");

                            final String contextPath = getContextUrl()
                                    + resourcePath.substring(0, resourcePath.lastIndexOf("/"));
                            String realPath = "";
                            if (realResourcePath.lastIndexOf("/") != -1) {
                                realPath = realResourcePath.substring(0, realResourcePath.lastIndexOf("/"));
                            } else if (realResourcePath.lastIndexOf("\\") != -1) {
                                realPath = realResourcePath.substring(0, realResourcePath.lastIndexOf("\\"));
                            }

                            // repair urls
                            resourceContents = resourceContents.replace("url(./", "url(" + IMGURLHOLDER + "/");
                            resourceContents = resourceContents.replace("url(images",
                                    "url(" + IMGURLHOLDER + "/images");
                            resourceContents = resourceContents.replace("url(\"images",
                                    "url(\"" + IMGURLHOLDER + "/images");
                            resourceContents = resourceContents.replace("url('images",
                                    "url('" + IMGURLHOLDER + "/images");
                            resourceContents = resourceContents.replace("url('./",
                                    "url('" + IMGURLHOLDER + "/");
                            resourceContents = resourceContents.replace("url(\"./",
                                    "url(\"" + IMGURLHOLDER + "/");

                            if (!module.isInDevelopment()) {
                                // CSSMinimizer have problems dealing with selectors like url('data:image/....')
                                // and it needs to be with double quotes in order to work ok
                                resourceContents = resourceContents.replaceAll("(url\\()(')(.*)(')(.*)",
                                        "$1\"$3\"$5");

                                resourceContents = CSSMinimizer.formatString(resourceContents);
                                if (makeCssDataUri) {
                                    String resourceContentsLine;
                                    BufferedReader resourceContentsReader = new BufferedReader(
                                            new StringReader(resourceContents));
                                    StringBuffer resourceContentsBuffer = new StringBuffer();

                                    int indexOfUrl;
                                    String imgUrl, imgExt, imgDataUri, newUrlParam;
                                    while ((resourceContentsLine = resourceContentsReader.readLine()) != null) {
                                        indexOfUrl = 0;
                                        while ((indexOfUrl = resourceContentsLine.indexOf("url(",
                                                indexOfUrl)) != -1) {
                                            imgUrl = resourceContentsLine.substring(indexOfUrl + 4,
                                                    resourceContentsLine.indexOf(")", indexOfUrl));
                                            if (imgUrl.indexOf("\"") == 0 || imgUrl.indexOf("'") == 0) {
                                                imgUrl = imgUrl.substring(1, imgUrl.length());
                                            }
                                            if (imgUrl.indexOf("\"") == imgUrl.length() - 1
                                                    || imgUrl.indexOf("'") == imgUrl.length() - 1) {
                                                imgUrl = imgUrl.substring(0, imgUrl.length() - 1);
                                            }
                                            imgExt = imgUrl.substring(imgUrl.lastIndexOf(".") + 1,
                                                    imgUrl.length());
                                            imgExt = imgExt.toLowerCase();
                                            if (imgExt.equals("jpg")) {
                                                imgExt = "jpeg";
                                            }
                                            if (imgExt.equals("jpeg") || imgExt.equals("png")
                                                    || imgExt.equals("gif")) {
                                                imgDataUri = filePathToBase64(
                                                        imgUrl.replace(IMGURLHOLDER, realPath));
                                            } else {
                                                imgDataUri = "";
                                            }
                                            if (imgDataUri != "") {
                                                newUrlParam = "data:image/" + imgExt + ";base64," + imgDataUri;
                                                resourceContentsLine = resourceContentsLine.replace(imgUrl,
                                                        newUrlParam);
                                            }
                                            indexOfUrl = indexOfUrl + 1;
                                        }
                                        resourceContentsBuffer.append(resourceContentsLine).append("\n");
                                    }
                                    resourceContents = resourceContentsBuffer.toString();
                                }
                            }
                            resourceContents = resourceContents.replace(IMGURLHOLDER, contextPath);
                            sb.append(resourceContents);
                        } catch (Exception e) {
                            log.error("Error reading file: " + resource, e);
                        }
                    }
                }
            }
        }
    }

    return sb.toString();
}

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  va2  s  .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);
}

From source file:org.codelibs.fess.job.CrawlJob.java

protected void executeCrawler() {
    final List<String> cmdList = new ArrayList<>();
    final String cpSeparator = SystemUtils.IS_OS_WINDOWS ? ";" : ":";
    final ServletContext servletContext = ComponentUtil.getComponent(ServletContext.class);
    final SystemHelper systemHelper = ComponentUtil.getSystemHelper();
    final ProcessHelper processHelper = ComponentUtil.getProcessHelper();
    final FessConfig fessConfig = ComponentUtil.getFessConfig();

    cmdList.add(fessConfig.getJavaCommandPath());

    // -cp//from w w  w .  j  a v  a2 s.  co m
    cmdList.add("-cp");
    final StringBuilder buf = new StringBuilder(100);
    ResourceUtil.getOverrideConfPath().ifPresent(p -> {
        buf.append(p);
        buf.append(cpSeparator);
    });
    final String confPath = System.getProperty(Constants.FESS_CONF_PATH);
    if (StringUtil.isNotBlank(confPath)) {
        buf.append(confPath);
        buf.append(cpSeparator);
    }
    // WEB-INF/env/crawler/resources
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("env");
    buf.append(File.separator);
    buf.append("crawler");
    buf.append(File.separator);
    buf.append("resources");
    buf.append(cpSeparator);
    // WEB-INF/classes
    buf.append("WEB-INF");
    buf.append(File.separator);
    buf.append("classes");
    // target/classes
    final String userDir = System.getProperty("user.dir");
    final File targetDir = new File(userDir, "target");
    final File targetClassesDir = new File(targetDir, "classes");
    if (targetClassesDir.isDirectory()) {
        buf.append(cpSeparator);
        buf.append(targetClassesDir.getAbsolutePath());
    }
    // WEB-INF/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/lib")),
            "WEB-INF" + File.separator + "lib" + File.separator);
    // WEB-INF/env/crawler/lib
    appendJarFile(cpSeparator, buf, new File(servletContext.getRealPath("/WEB-INF/env/crawler/lib")), "WEB-INF"
            + File.separator + "env" + File.separator + "crawler" + File.separator + "lib" + File.separator);
    final File targetLibDir = new File(targetDir, "fess" + File.separator + "WEB-INF" + File.separator + "lib");
    if (targetLibDir.isDirectory()) {
        appendJarFile(cpSeparator, buf, targetLibDir, targetLibDir.getAbsolutePath() + File.separator);
    }
    cmdList.add(buf.toString());

    if (useLocalElasticsearch) {
        final String httpAddress = System.getProperty(Constants.FESS_ES_HTTP_ADDRESS);
        if (StringUtil.isNotBlank(httpAddress)) {
            cmdList.add("-D" + Constants.FESS_ES_HTTP_ADDRESS + "=" + httpAddress);
        }
    }

    final String systemLastaEnv = System.getProperty("lasta.env");
    if (StringUtil.isNotBlank(systemLastaEnv)) {
        if (systemLastaEnv.equals("web")) {
            cmdList.add("-Dlasta.env=crawler");
        } else {
            cmdList.add("-Dlasta.env=" + systemLastaEnv);
        }
    } else if (StringUtil.isNotBlank(lastaEnv)) {
        cmdList.add("-Dlasta.env=" + lastaEnv);
    }

    addSystemProperty(cmdList, Constants.FESS_CONF_PATH, null, null);
    cmdList.add("-Dfess.crawler.process=true");
    cmdList.add("-Dfess.log.path=" + (logFilePath != null ? logFilePath : systemHelper.getLogFilePath()));
    addSystemProperty(cmdList, "fess.log.name", "fess-crawler", "-crawler");
    if (logLevel == null) {
        addSystemProperty(cmdList, "fess.log.level", null, null);
    } else {
        cmdList.add("-Dfess.log.level=" + logLevel);
        if (logLevel.equalsIgnoreCase("debug")) {
            cmdList.add("-Dorg.apache.tika.service.error.warn=true");
        }
    }
    stream(fessConfig.getJvmCrawlerOptionsAsArray())
            .of(stream -> stream.filter(StringUtil::isNotBlank).forEach(value -> cmdList.add(value)));

    File ownTmpDir = null;
    final String tmpDir = System.getProperty("java.io.tmpdir");
    if (fessConfig.isUseOwnTmpDir() && StringUtil.isNotBlank(tmpDir)) {
        ownTmpDir = new File(tmpDir, "fessTmpDir_" + sessionId);
        if (ownTmpDir.mkdirs()) {
            cmdList.add("-Djava.io.tmpdir=" + ownTmpDir.getAbsolutePath());
            cmdList.add("-Dpdfbox.fontcache=" + ownTmpDir.getAbsolutePath());
        } else {
            ownTmpDir = null;
        }
    }

    cmdList.add(ComponentUtil.getThumbnailManager().getThumbnailPathOption());

    if (StringUtil.isNotBlank(jvmOptions)) {
        split(jvmOptions, " ").of(stream -> stream.filter(StringUtil::isNotBlank).forEach(s -> cmdList.add(s)));
    }

    cmdList.add(Crawler.class.getCanonicalName());

    cmdList.add("--sessionId");
    cmdList.add(sessionId);
    cmdList.add("--name");
    cmdList.add(namespace);

    if (webConfigIds != null && webConfigIds.length > 0) {
        cmdList.add("-w");
        cmdList.add(StringUtils.join(webConfigIds, ','));
    }
    if (fileConfigIds != null && fileConfigIds.length > 0) {
        cmdList.add("-f");
        cmdList.add(StringUtils.join(fileConfigIds, ','));
    }
    if (dataConfigIds != null && dataConfigIds.length > 0) {
        cmdList.add("-d");
        cmdList.add(StringUtils.join(dataConfigIds, ','));
    }
    if (documentExpires >= -1) {
        cmdList.add("-e");
        cmdList.add(Integer.toString(documentExpires));
    }

    File propFile = null;
    try {
        cmdList.add("-p");
        propFile = File.createTempFile("crawler_", ".properties");
        cmdList.add(propFile.getAbsolutePath());
        try (FileOutputStream out = new FileOutputStream(propFile)) {
            final Properties prop = new Properties();
            prop.putAll(ComponentUtil.getSystemProperties());
            prop.store(out, cmdList.toString());
        }

        final File baseDir = new File(servletContext.getRealPath("/WEB-INF")).getParentFile();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: \nDirectory=" + baseDir + "\nOptions=" + cmdList);
        }

        final JobProcess jobProcess = processHelper.startProcess(sessionId, cmdList, pb -> {
            pb.directory(baseDir);
            pb.redirectErrorStream(true);
        });

        final InputStreamThread it = jobProcess.getInputStreamThread();
        it.start();

        final Process currentProcess = jobProcess.getProcess();
        currentProcess.waitFor();
        it.join(5000);

        final int exitValue = currentProcess.exitValue();

        if (logger.isInfoEnabled()) {
            logger.info("Crawler: Exit Code=" + exitValue + " - Crawler Process Output:\n" + it.getOutput());
        }
        if (exitValue != 0) {
            throw new FessSystemException("Exit Code: " + exitValue + "\nOutput:\n" + it.getOutput());
        }
    } catch (final FessSystemException e) {
        throw e;
    } catch (final InterruptedException e) {
        logger.warn("Crawler Process interrupted.");
    } catch (final Exception e) {
        throw new FessSystemException("Crawler Process terminated.", e);
    } finally {
        try {
            processHelper.destroyProcess(sessionId);
        } finally {
            if (propFile != null && !propFile.delete()) {
                logger.warn("Failed to delete {}.", propFile.getAbsolutePath());
            }
            deleteTempDir(ownTmpDir);
        }
    }
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public void init(ServletConfig config) throws ServletException {
    final ServletContext sc = config.getServletContext();
    log.debug("Init");
    final String depName = (String) sc.getAttribute("deployment.name");
    final Properties rtProps = (Properties) sc.getAttribute("meta.properties");
    log.debug("RT configs retrieved for application '" + depName + "'");
    srvlt_config = config;/*from  w w w .  ja va 2 s  . c o  m*/
    this.config = new Properties();
    final Enumeration enumVar = config.getInitParameterNames();
    while (enumVar.hasMoreElements()) {
        final String s = (String) enumVar.nextElement();
        this.config.put(s, config.getInitParameter(s));
        log.debug(s + ": " + config.getInitParameter(s));
    }

    /*
     * Issue a warning if webmail.basepath and/or webmail.imagebase are not
     * set.
     */
    if (config.getInitParameter("webmail.basepath") == null) {
        log.warn("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        basepath = "";
    } else {
        basepath = config.getInitParameter("webmail.basepath");
    }
    if (config.getInitParameter("webmail.imagebase") == null) {
        log.error("webmail.basepath initArg should be set to the WebMail " + "Servlet's base path");
        imgbase = "";
    } else {
        imgbase = config.getInitParameter("webmail.imagebase");
    }

    /*
     * Try to get the pathnames from the URL's if no path was given in the
     * initargs.
     */
    if (config.getInitParameter("webmail.data.path") == null) {
        this.config.put("webmail.data.path", sc.getRealPath("/data"));
    }
    if (config.getInitParameter("webmail.lib.path") == null) {
        this.config.put("webmail.lib.path", sc.getRealPath("/lib"));
    }
    if (config.getInitParameter("webmail.template.path") == null) {
        this.config.put("webmail.template.path", sc.getRealPath("/lib/templates"));
    }
    if (config.getInitParameter("webmail.xml.path") == null) {
        this.config.put("webmail.xml.path", sc.getRealPath("/lib/xml"));
    }
    if (config.getInitParameter("webmail.log.facility") == null) {
        this.config.put("webmail.log.facility", "net.wastl.webmail.logger.ServletLogger");
    }

    // Override settings with webmail.* meta.properties
    final Enumeration rte = rtProps.propertyNames();
    int overrides = 0;
    String k;
    while (rte.hasMoreElements()) {
        k = (String) rte.nextElement();
        if (!k.startsWith("webmail.")) {
            continue;
        }
        overrides++;
        this.config.put(k, rtProps.getProperty(k));
    }
    log.debug(Integer.toString(overrides) + " settings passed to WebMailServer, out of " + rtProps.size()
            + " RT properties");

    /*
     * Call the WebMailServer's initialization method and forward all
     * Exceptions to the ServletServer
     */
    try {
        doInit();
    } catch (final Exception e) {
        log.error("Could not intialize", e);
        throw new ServletException("Could not intialize: " + e.getMessage(), e);
    }
    Helper.logThreads("Bottom of WebMailServlet.init()");
}

From source file:org.pentaho.platform.web.http.context.SolutionContextListener.java

public void contextInitialized(final ServletContextEvent event) {

    ServletContext context = event.getServletContext();

    String encoding = context.getInitParameter("encoding"); //$NON-NLS-1$
    if (encoding != null) {
        LocaleHelper.setSystemEncoding(encoding);
    }//from  ww w .ja v a2 s.c o  m

    String textDirection = context.getInitParameter("text-direction"); //$NON-NLS-1$
    if (textDirection != null) {
        LocaleHelper.setTextDirection(textDirection);
    }

    String localeLanguage = context.getInitParameter("locale-language"); //$NON-NLS-1$
    String localeCountry = context.getInitParameter("locale-country"); //$NON-NLS-1$
    boolean localeSet = false;
    if ((localeLanguage != null) && !"".equals(localeLanguage) && (localeCountry != null)
            && !"".equals(localeCountry)) { //$NON-NLS-1$ //$NON-NLS-2$
        Locale[] locales = Locale.getAvailableLocales();
        if (locales != null) {
            for (Locale element : locales) {
                if (element.getLanguage().equals(localeLanguage)
                        && element.getCountry().equals(localeCountry)) {
                    LocaleHelper.setLocale(element);
                    localeSet = true;
                    break;
                }
            }
        }
    }
    if (!localeSet) {
        // do this thread in the default locale
        LocaleHelper.setLocale(Locale.getDefault());
    }
    LocaleHelper.setDefaultLocale(LocaleHelper.getLocale());
    // log everything that goes on here
    Logger.info(SolutionContextListener.class.getName(),
            Messages.getInstance().getString("SolutionContextListener.INFO_INITIALIZING")); //$NON-NLS-1$
    Logger.info(SolutionContextListener.class.getName(),
            Messages.getInstance().getString("SolutionContextListener.INFO_SERVLET_CONTEXT") + context); //$NON-NLS-1$
    SolutionContextListener.contextPath = context.getRealPath(""); //$NON-NLS-1$
    Logger.info(SolutionContextListener.class.getName(),
            Messages.getInstance().getString("SolutionContextListener.INFO_CONTEXT_PATH") //$NON-NLS-1$
                    + SolutionContextListener.contextPath);

    SolutionContextListener.solutionPath = PentahoHttpSessionHelper.getSolutionPath(context);
    if (StringUtils.isEmpty(SolutionContextListener.solutionPath)) {
        String errorMsg = Messages.getInstance()
                .getErrorString("SolutionContextListener.ERROR_0001_NO_ROOT_PATH"); //$NON-NLS-1$
        Logger.error(getClass().getName(), errorMsg);
        /*
         * Since we couldn't find solution repository path there is no point in going forward and the user should know
         * that a major config setting was not found. So we are throwing in a RunTimeException with the requisite message.
         */
        throw new RuntimeException(errorMsg);
    }

    Logger.info(getClass().getName(), Messages.getInstance().getString("SolutionContextListener.INFO_ROOT_PATH")
            + SolutionContextListener.solutionPath); //$NON-NLS-1$

    String fullyQualifiedServerUrl = context.getInitParameter("fully-qualified-server-url"); //$NON-NLS-1$
    if (fullyQualifiedServerUrl == null) {
        // assume this is a demo installation
        // TODO: Create a servlet that's loaded on startup to set this value
        fullyQualifiedServerUrl = "http://localhost:8080/pentaho/"; //$NON-NLS-1$
    }

    IApplicationContext applicationContext = new WebApplicationContext(SolutionContextListener.solutionPath,
            fullyQualifiedServerUrl, context.getRealPath(""), context); //$NON-NLS-1$

    /*
     * Copy out all the initParameter values from the servlet context and put them in the application context.
     */
    Properties props = new Properties();
    Enumeration<?> initParmNames = context.getInitParameterNames();
    String initParmName;
    while (initParmNames.hasMoreElements()) {
        initParmName = (String) initParmNames.nextElement();
        props.setProperty(initParmName, context.getInitParameter(initParmName));
    }
    ((WebApplicationContext) applicationContext).setProperties(props);

    setSystemCfgFile(context);
    setObjectFactory(context);

    boolean initOk = PentahoSystem.init(applicationContext);

    this.showInitializationMessage(initOk, fullyQualifiedServerUrl);
}

From source file:org.wapama.web.EditorHandler.java

/**
 * Initiate the compression of the environment.
 * @param context/*from w  w  w.ja v  a 2 s  .c om*/
 * @throws IOException
 */
private void initEnvFiles(ServletContext context) throws IOException {
    // only do it the first time the servlet starts
    try {
        JSONObject obj = new JSONObject(readEnvFiles(context));

        JSONArray array = obj.getJSONArray("files");
        for (int i = 0; i < array.length(); i++) {
            _envFiles.add(array.getString(i));
        }
    } catch (JSONException e) {
        _logger.error("invalid js_files.json");
        _logger.error(e.getMessage(), e);
        throw new RuntimeException("Error initializing the " + "environment of the editor");
    }

    // generate script to setup the languages
    //_envFiles.add("i18n/translation_ja.js");
    if (System.getProperty(DEV) == null) {
        StringWriter sw = new StringWriter();
        for (String file : _envFiles) {
            sw.append("/* ").append(file).append(" */\n");
            InputStream input = new FileInputStream(new File(getServletContext().getRealPath(file)));
            try {
                JavaScriptCompressor compressor = new JavaScriptCompressor(new InputStreamReader(input), null);
                compressor.compress(sw, -1, false, false, false, false);
            } catch (EvaluatorException e) {
                _logger.error(e.getMessage(), e);
            } catch (IOException e) {
                _logger.error(e.getMessage(), e);
            } finally {
                try {
                    input.close();
                } catch (IOException e) {
                }
            }

            sw.append("\n");
        }
        try {
            FileWriter w = new FileWriter(context.getRealPath("jsc/env_combined.js"));
            w.write(sw.toString());
            w.close();
        } catch (IOException e) {
            _logger.error(e.getMessage(), e);
        }
    } else {
        if (_logger.isInfoEnabled()) {
            _logger.info("The diagram editor is running in development mode. "
                    + "Javascript will be served uncompressed");
        }
    }
}

From source file:org.geoserver.platform.GeoServerResourceLoader.java

/**
 * Determines the location of the geoserver data directory based on the following lookup
 * mechanism://w  w  w. j a  va 2  s .com
 *  
 * 1) Java environment variable
 * 2) Servlet context variable
 * 3) System variable 
 *
 * For each of these, the methods checks that
 * 1) The path exists
 * 2) Is a directory
 * 3) Is writable
 * 
 * @param servContext The servlet context.
 * @return String The absolute path to the data directory, or <code>null</code> if it could not
 * be found. 
 */
public static String lookupGeoServerDataDirectory(ServletContext servContext) {

    final String[] typeStrs = { "Java environment variable ", "Servlet context parameter ",
            "System environment variable " };

    String requireFileVar = "GEOSERVER_REQUIRE_FILE";
    requireFile(System.getProperty(requireFileVar), typeStrs[0] + requireFileVar);
    requireFile(servContext.getInitParameter(requireFileVar), typeStrs[1] + requireFileVar);
    requireFile(System.getenv(requireFileVar), typeStrs[2] + requireFileVar);

    final String[] varStrs = { "GEOSERVER_DATA_DIR", "GEOSERVER_DATA_ROOT" };

    String dataDirStr = null;
    String msgPrefix = null;

    // Loop over variable names
    for (int i = 0; i < varStrs.length && dataDirStr == null; i++) {

        // Loop over variable access methods
        for (int j = 0; j < typeStrs.length && dataDirStr == null; j++) {
            String value = null;
            String varStr = varStrs[i];
            String typeStr = typeStrs[j];

            // Lookup section
            switch (j) {
            case 0:
                value = System.getProperty(varStr);
                break;
            case 1:
                value = servContext.getInitParameter(varStr);
                break;
            case 2:
                value = System.getenv(varStr);
                break;
            }

            if (value == null || value.equalsIgnoreCase("")) {
                LOGGER.finer("Found " + typeStr + varStr + " to be unset");
                continue;
            }

            // Verify section
            File fh = new File(value);

            // Being a bit pessimistic here
            msgPrefix = "Found " + typeStr + varStr + " set to " + value;

            if (!fh.exists()) {
                LOGGER.warning(msgPrefix + " , but this path does not exist");
                continue;
            }
            if (!fh.isDirectory()) {
                LOGGER.warning(msgPrefix + " , which is not a directory");
                continue;
            }
            if (!fh.canWrite()) {
                LOGGER.warning(msgPrefix + " , which is not writeable");
                continue;
            }

            // Sweet, we can work with this
            dataDirStr = value;
        }
    }

    // fall back to embedded data dir
    if (dataDirStr == null) {
        dataDirStr = servContext.getRealPath("/data");
        LOGGER.info("Falling back to embedded data directory: " + dataDirStr);
    }

    return dataDirStr;
}