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:net.shopxx.util.ImageUtil.java

/**
 * ?/*from   w  ww  .jav a 2s  .  co m*/
 * @param imageFile 
 * @return     
 */
public static String copyImageFile(ServletContext servletContext, File imageFile) {
    if (imageFile == null) {
        return null;
    }
    String formatName = getFormatName(imageFile);
    if (formatName == null) {
        throw new IllegalArgumentException("imageFile format error!");
    }
    String destImagePath = SettingUtil.getSetting().getImageUploadRealPath() + "/" + CommonUtil.getUUID() + "."
            + formatName;
    File destImageFile = new File(servletContext.getRealPath(destImagePath));
    File destImageParentFile = destImageFile.getParentFile();
    if (!destImageParentFile.isDirectory()) {
        destImageParentFile.mkdirs();
    }
    try {
        FileUtils.copyFile(imageFile, destImageFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return destImagePath;
}

From source file:org.sakaiproject.tool.assessment.qti.util.XmlUtil.java

/**
 * Read document from ServletContext/context path
 *
 * @param context ServletContext/*  w w  w.  ja v  a 2 s  .com*/
 * @param path path
 *
 * @return Document
 */
public static Document readDocument(ServletContext context, String path) {
    if (log.isDebugEnabled()) {
        log.debug("readDocument(String " + path + ")");
    }

    Document document = null;
    InputStream inputStream = context.getResourceAsStream(path);
    String fullpath = context.getRealPath(path);
    log.debug("readDocument(full path) " + fullpath + ")");
    DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    try {
        setDocumentBuilderFactoryFeatures(builderFactory);
        DocumentBuilder documentBuilder = builderFactory.newDocumentBuilder();
        document = documentBuilder.parse(inputStream);
    } catch (ParserConfigurationException e) {
        log.error(e.getMessage(), e);
    } catch (SAXException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    }

    return document;
}

From source file:com.kolich.havalo.components.RepositoryManagerComponent.java

private static final RepositoryManager getRepositoryManager(final ServletContext context) {
    String repositoryBase = getRepositoryBase();
    if (repositoryBase == null) {
        logger__.warn("Config property '" + HAVALO_REPO_BASE_CONFIG_PROPERTY
                + "' was not set, using default repository base: " + REPO_BASE_DEFAULT);
        repositoryBase = REPO_BASE_DEFAULT;
    }//from w w w .  j a  v a2 s .c o  m
    // If the provided repository base path starts with a slash, then
    // interpret the location as an absolute path on disk.  Otherwise,
    // no preceding slash indicates a path relative to the web application
    // root directory.
    final File realPath;
    if (repositoryBase.startsWith("/")) {
        realPath = new File(repositoryBase);
    } else {
        realPath = new File(context.getRealPath("/" + repositoryBase));
    }
    logger__.info("Using repository root at: " + realPath.getAbsolutePath());
    final int maxFilenameLength = getMaxFilenameLength();
    logger__.info("Max repository object filename length: " + maxFilenameLength);
    return new RepositoryManager(realPath, maxFilenameLength);
}

From source file:com.kolich.blog.components.GitRepository.java

private static final File getRepoDir(final ServletContext context) {
    final File repoDir;
    if (isDevMode__) {
        // If in "development mode", the clone path is the local copy of the repo on disk.
        repoDir = new File(userDir__);
    } else {//from   w  w  w . j  av a 2s.  c o m
        // Otherwise, it could be somewhere else either in an absolute location (/...) or somewhere
        // under the Servlet container when relative.
        repoDir = (clonePath__.startsWith(File.separator)) ?
        // If the specified clone path in the application configuration is "absolute", then use that path raw.
                new File(clonePath__) :
                // Otherwise, the clone path is relative to the container Servlet context of this application.
                new File(context.getRealPath(File.separator + clonePath__));
    }
    return repoDir;
}

From source file:password.pwm.http.servlet.resource.ResourceFileServlet.java

private static FileResource handleWebjarURIs(final ServletContext servletContext, final String resourcePathUri)
        throws PwmUnrecoverableException {
    if (resourcePathUri.startsWith(WEBJAR_BASE_URL_PATH)) {
        // This allows us to override a webjar file, if needed.  Mostly helpful during development.
        final File file = new File(servletContext.getRealPath(resourcePathUri));
        if (file.exists()) {
            return new RealFileResource(file);
        }// w ww.  ja  v a 2s.  com

        final String remainingPath = resourcePathUri.substring(WEBJAR_BASE_URL_PATH.length(),
                resourcePathUri.length());

        final String webJarName;
        final String webJarPath;
        {
            final int slashIndex = remainingPath.indexOf("/");
            if (slashIndex < 0) {
                return null;
            }
            webJarName = remainingPath.substring(0, slashIndex);
            webJarPath = remainingPath.substring(slashIndex + 1, remainingPath.length());
        }

        final String versionString = WEB_JAR_VERSION_MAP.get(webJarName);
        if (versionString == null) {
            return null;
        }

        final String fullPath = WEBJAR_BASE_FILE_PATH + "/" + webJarName + "/" + versionString + "/"
                + webJarPath;
        if (WEB_JAR_ASSET_LIST.contains(fullPath)) {
            final ClassLoader classLoader = servletContext.getClassLoader();
            final InputStream inputStream = classLoader.getResourceAsStream(fullPath);

            if (inputStream != null) {
                return new InputStreamFileResource(inputStream, fullPath);
            }
        }
    }

    return null;
}

From source file:org.apache.myfaces.webapp.StartupServletContextListener.java

public static void initFaces(ServletContext servletContext) {
    try {//from  w  w w  .  j  a va 2s  . c  om
        Boolean b = (Boolean) servletContext.getAttribute(FACES_INIT_DONE);

        if (b == null || b.booleanValue() == false) {
            log.trace("Initializing MyFaces");

            //Load the configuration
            ExternalContext externalContext = new ServletExternalContextImpl(servletContext, null, null);

            //And configure everything
            new FacesConfigurator(externalContext).configure();

            if ("true".equals(servletContext.getInitParameter(FacesConfigValidator.VALIDATE_CONTEXT_PARAM))
                    || "true".equals(servletContext
                            .getInitParameter(FacesConfigValidator.VALIDATE_CONTEXT_PARAM.toLowerCase()))) {
                List list = FacesConfigValidator.validate(externalContext, servletContext.getRealPath("/"));

                Iterator iterator = list.iterator();

                while (iterator.hasNext())
                    log.warn(iterator.next());

            }

            // parse web.xml
            WebXml.init(externalContext);

            servletContext.setAttribute(FACES_INIT_DONE, Boolean.TRUE);
        } else {
            log.info("MyFaces already initialized");
        }
    } catch (Exception ex) {
        log.error("Error initializing ServletContext", ex);
        ex.printStackTrace();
    }
    log.info("ServletContext '" + servletContext.getRealPath("/") + "' initialized.");

    if (servletContext.getInitParameter(StateUtils.INIT_SECRET) != null
            || servletContext.getInitParameter(StateUtils.INIT_SECRET.toLowerCase()) != null)
        StateUtils.initSecret(servletContext);
}

From source file:net.ontopia.topicmaps.webed.impl.utils.TagUtils.java

public static Map getSchemaRegistry(ServletContext servletContext) {
    Map schemas = (Map) servletContext.getAttribute(Constants.AA_SCHEMAS);
    if (schemas != null)
        return schemas;

    // Read in schemas for the topicmaps and provide them to the app context
    String schemasRootDir = servletContext.getInitParameter(Constants.SCTXT_SCHEMAS_ROOTDIR);
    if (schemasRootDir != null)
        schemasRootDir = servletContext.getRealPath(schemasRootDir);

    schemas = new HashMap();
    if (schemasRootDir == null) {
        servletContext.setAttribute(Constants.AA_SCHEMAS, schemas);
        log.debug("No schema directory configured; registry empty");
        return schemas;
    }/* w  w w . j a v  a2  s.com*/

    log.debug("Reading schemas from " + schemasRootDir);
    TopicMapRepositoryIF repository = NavigatorUtils.getTopicMapRepository(servletContext);
    Collection refkeys = repository.getReferenceKeys();
    Iterator iter = refkeys.iterator();
    while (iter.hasNext()) {
        String refkey = (String) iter.next();
        TopicMapReferenceIF reference = repository.getReferenceByKey(refkey);
        String tmid = reference.getId();
        try {
            OSLSchemaReader reader = new OSLSchemaReader(new File(schemasRootDir, tmid + ".osl"));
            OSLSchema schema = (OSLSchema) reader.read();
            schemas.put(tmid, schema);
            log.info("Loaded schema for " + tmid);
        } catch (java.io.IOException e) {
            log.info("Warning: " + e.getMessage());
        } catch (SchemaSyntaxException e) {
            log.error("Schema syntax error: " + e.getMessage());
            Locator loc = e.getErrorLocation();
            log.error("Location: " + loc.getSystemId() + ":" + loc.getLineNumber() + ":" + loc.getColumnNumber()
                    + ".");
        }
    }

    servletContext.setAttribute(Constants.AA_SCHEMAS, schemas);
    return schemas;
}

From source file:org.pentaho.platform.web.http.PentahoHttpSessionHelper.java

public static String getSolutionPath(final ServletContext context) {
    File pentahoSolutions;/*from  w  ww.j a v  a 2  s  . c o  m*/

    // first try the web.xml setting
    String rootPath = context.getInitParameter("solution-path"); //$NON-NLS-1$
    if (StringUtils.isNotBlank(rootPath)) {
        pentahoSolutions = new File(rootPath);
        if (pentahoSolutions.exists() && pentahoSolutions.isDirectory()) {
            return rootPath;
        }
    }

    for (String element : DEFAULT_LOCATIONS) {
        pentahoSolutions = new File(element);
        if (pentahoSolutions.exists() && pentahoSolutions.isDirectory()) {
            try {
                return pentahoSolutions.getCanonicalPath();
            } catch (IOException e) {
                return pentahoSolutions.getAbsolutePath();
            }
        }
    }

    // now try the path to the WEB-INF to see if we find
    File file = new File(context.getRealPath("")); //$NON-NLS-1$
    while (file != null) {
        if (file.exists() && file.isDirectory()) {
            pentahoSolutions = new File(file.getAbsolutePath() + File.separator + "pentaho-solutions"); //$NON-NLS-1$
            if (pentahoSolutions.exists() && pentahoSolutions.isDirectory()) {
                try {
                    return pentahoSolutions.getCanonicalPath();
                } catch (IOException e) {
                    return pentahoSolutions.getAbsolutePath();
                }
            }
        }
        file = file.getParentFile();
    }
    return null;
}

From source file:com.qualogy.qafe.web.ContextLoader.java

private static void create(ServletContext servletContext) throws MalformedURLException, URISyntaxException {
    String configLocation = servletContext.getInitParameter(CONFIG_FILE_PARAM);
    String contextPath = getContextPath(servletContext);
    QafeConfigurationManager contextInitialiser = new QafeConfigurationManager(contextPath);
    ApplicationContext springContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);
    contextInitialiser.setSpringContext(springContext);
    qafeContext.putInstance(QafeConfigurationManager.class.getName(), contextInitialiser);

    StopWatch watch = new StopWatch();
    watch.start();//w w  w.  j av a  2s  . c om
    ApplicationContextLoader.unload();

    // The default way: works on JBoss/Tomcat/Jetty
    String configFileLocation = servletContext.getRealPath("/WEB-INF/");
    if (configFileLocation != null) {
        configFileLocation += File.separator + configLocation;
        logger.log(Level.INFO, "URL to config file on disk :" + configFileLocation + ")");
        ApplicationContextLoader.load(configFileLocation, true);
    } else {
        // This is how a weblogic explicitly wants the fetching of resources.
        URL url = servletContext.getResource("/WEB-INF/" + configLocation);
        logger.log(Level.INFO, "Fallback scenario" + url.toString());
        if (url != null) {
            logger.log(Level.INFO, "URL to config file " + url.toString());
            ApplicationContextLoader.load(url.toURI(), true);
        } else {
            throw new RuntimeException(
                    "Strange Error: /WEB-INF/ cannot be found. Check the appserver or installation directory.");
        }
    }

    watch.stop();
    logger.log(Level.INFO,
            "Root WebApplicationContext: initialization completed in " + watch.getTime() + " ms");
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Return the real path of the given path within the web application,
 * as provided by the servlet container.
 * <p>Prepends a slash if the path does not already start with a slash,
 * and throws a FileNotFoundException if the path cannot be resolved to
 * a resource (in contrast to ServletContext's {@code getRealPath},
 * which returns null).//w  ww. jav  a  2 s  .  c om
 * @param servletContext the servlet context of the web application
 * @param path the path within the web application
 * @return the corresponding real path
 * @throws FileNotFoundException if the path cannot be resolved to a resource
 * @see javax.servlet.ServletContext#getRealPath
 */
public static String getRealPath(ServletContext servletContext, String path) throws FileNotFoundException {
    Assert.notNull(servletContext, "ServletContext must not be null");
    // Interpret location as relative to the web application root directory.
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    String realPath = servletContext.getRealPath(path);
    if (realPath == null) {
        throw new FileNotFoundException("ServletContext resource [" + path
                + "] cannot be resolved to absolute file path - " + "web application archive not expanded?");
    }
    return realPath;
}