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:edu.lternet.pasta.portal.DesktopCleanerServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)/*from w  w  w  .  j  av  a  2 s. c om*/
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    String dataPath = servletContext.getRealPath(HarvesterServlet.DESKTOP_DATA_DIR);
    String ttlString = TTL_IN_MINUTES; // number of minutes for desktop data to live

    if (ttlString != null && !ttlString.isEmpty()) {
        Long ttl = Long.valueOf(ttlString) * 60000L; // Convert minutes to ms
        cleanExpiredData(dataPath, ttl);
    }

}

From source file:net.jforum.core.tags.ImportFileTag.java

/**
 * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag()
 *//*from w w  w.  ja v  a2  s .  c o m*/
@Override
public void doTag() throws JspException, IOException {
    // check the URL
    if (StringUtils.isEmpty(url))
        throw new NullAttributeException("import", "url");

    String jsp = this.getFile(url);

    ServletRequest request = this.request();
    ServletResponse respose = this.response();
    HttpSession session = ((HttpServletRequest) request).getSession();
    ServletContext servletContext = session.getServletContext();

    String jspPath = servletContext.getRealPath(jsp);
    File jspFile = new File(jspPath);
    if (!jspFile.exists())
        return;

    respose.flushBuffer();
    RequestDispatcher rd = this.pageContext().getRequest().getRequestDispatcher(jsp);
    try {
        // include the resource, using our custom wrapper
        ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) respose);
        irw.setCharacterEncoding(charEncoding);
        rd.include(request, irw);
        // disallow inappropriate response codes per JSTL spec
        if (irw.getStatus() < 200 || irw.getStatus() > 299) {
            throw new JspTagException(irw.getStatus() + " " + jsp);
        }

        // recover the response String from our wrapper
        pageContext().getOut().print(irw.getString());
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:org.restcomm.sbc.Bootstrapper.java

private String home(final ServletConfig config) {
    final ServletContext context = config.getServletContext();
    final String path = context.getRealPath("/");
    if (path.endsWith("/")) {
        return path.substring(0, path.length() - 1);
    } else {/*from  w  ww.  j  a va  2  s . co m*/
        return path;
    }
}

From source file:org.jboss.datagrid.LoadXMLServlet.java

public void init(ServletConfig config) throws ServletException {

    File folder;//  w ww .  j a v a  2 s. c  o  m
    ServletContext ctx = config.getServletContext();
    folder = new File(ctx.getRealPath(Resources.xmlDataDir()));
    //folder = new File(Resources.xmlDataDir());
    logger.info("Using absolute path: " + folder.getAbsolutePath());
    File[] listOfFiles = folder.listFiles(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.toLowerCase().endsWith(".xml");
        }
    });

    if (listOfFiles == null || listOfFiles.length == 0)
        logger.info("Did not find any XML files in the " + Resources.jdgProperty(Resources.XML_DIRECTORY)
                + " directory");
    else {
        logger.info("Found " + listOfFiles.length + " files!");

        for (File file : listOfFiles) {
            if (file.isFile()) {
                //System.out.println(file.getName());
                try {
                    String content = FileUtils.readFileToString(file, "UTF-8");
                    logger.info("Putting contents from file " + file.getName()
                            + " into the cache, content length=" + content.length());
                    cache.put(file.getName(), content);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    Set<String> set = cache.keySet();
    logger.info("Warming up the cache....");

    for (String key : set) {
        for (int i = 0; i < 1000; ++i)
            cache.get(key);
    }

}

From source file:com.concursive.connect.config.ApplicationPrefs.java

/**
 * Gets the war attribute of the ApplicationPrefs class
 *
 * @param context Description of the Parameter
 * @return The war value// w ww  .j av a 2  s . c  o m
 */
public static boolean isWar(ServletContext context) {
    String realPath = context.getRealPath("/");
    String fs = System.getProperty("file.separator");
    if (realPath == null) {
        return true;
    } else if (realPath.endsWith(".war")) {
        return true;
    } else if (realPath.endsWith(".war" + fs)) {
        return true;
    } else if (realPath.indexOf("Instance") > -1) {
        return true;
    } else {
        return false;
    }
}

From source file:com.geodan.ngr.serviceintegration.listener.ApplicationListener.java

public void contextInitialized(ServletContextEvent servletContextEvent) {
    log.debug("context initializing..");
    ServletContext servletContext = servletContextEvent.getServletContext();
    String ctxName = servletContext.getServletContextName();
    String realP = servletContext.getRealPath(ctxName);
    String fixedRealPath = realP.substring(0, realP.lastIndexOf(ctxName));
    log.debug("realpath: " + fixedRealPath);
    RealPath.init(fixedRealPath);//from w  ww.  j  a va  2s  .co  m
    log.debug("context initialized");
}

From source file:org.restcomm.connect.http.cors.CorsFilter.java

private void initLazily(ServletRequest request) {
    if (lazyServletContext == null) {
        ServletContext context = request.getServletContext();
        String rootPath = context.getRealPath("/");
        rootPath = StringUtils.stripEnd(rootPath, "/"); // remove trailing "/" character
        String restcommXmlPath = rootPath + "/WEB-INF/conf/restcomm.xml";

        // ok, found restcomm.xml. Now let's get rcmlserver/base-url configuration setting
        File restcommXmlFile = new File(restcommXmlPath);
        // Create apache configuration
        XMLConfiguration apacheConf = new XMLConfiguration();
        apacheConf.setDelimiterParsingDisabled(true);
        apacheConf.setAttributeSplittingDisabled(true);
        try {/* w ww.  j a v a2 s .  c o m*/
            apacheConf.load(restcommXmlPath);
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        // Create high-level configuration
        ConfigurationSource source = new ApacheConfigurationSource(apacheConf);
        RcmlserverConfigurationSet rcmlserverConfig = new RcmlserverConfigurationSetImpl(source);
        // initialize allowedOrigin
        String baseUrl = rcmlserverConfig.getBaseUrl();
        if (baseUrl != null && (!baseUrl.trim().equals(""))) {
            // baseUrl is set. We need to return CORS allow headers
            allowedOrigin = baseUrl;
        }

        lazyServletContext = context;

        logger.info("Initialized (lazily) CORS servlet response filter. allowedOrigin: " + allowedOrigin);
    }
}

From source file:org.pau.assetmanager.viewmodel.chart.ResourceImageGenerator.java

@Override
public String apply(JFreeChart jfchart) {
    String tempFileName = "";
    try {//from  ww w.  j a  va 2 s  . co m
        ServletContext servletContext = Sessions.getCurrent().getWebApp().getServletContext();
        String tempDirPath = servletContext.getRealPath("") + File.separator + "TMP";
        File tempDir = new File(tempDirPath);
        if (!tempDir.exists()) {
            tempDir.mkdir();
        } else {
            cleanTempFolder(tempDir);
        }
        File tempFile = File.createTempFile("tmp", ".png", tempDir);
        tempFileName = tempFile.getName();
        FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
        ChartUtilities.writeChartAsPNG(fileOutputStream, jfchart, 1200, 500);
    } catch (Throwable t) {
        logger.error("Error generating chart.", t);
    }
    Clients.clearBusy();
    return "TMP" + File.separator + tempFileName;
}

From source file:org.openmrs.web.CopyLegacyUiContentToWebInf.java

@Override
public void setServletContext(ServletContext servletContext) {

    String basePath = servletContext.getRealPath("");

    try {//from  ww w  . java  2s  .  c o  m
        List<File> toIgnore = new ArrayList<>();
        toIgnore.add(new File(basePath + "/index.jsp".replace("/", File.separator)));

        String[] jspsToCopy = { "errorhandler", "memoryUsage" };
        //copy these files to root of the webapp
        for (String jsp : jspsToCopy) {
            File dest = new File(basePath + "/" + jsp + ".jsp".replace("/", File.separator));
            File src = new File(basePath + MODULE_ROOT_DIR + "/" + jsp + ".jsp".replace("/", File.separator));
            FileUtils.copyFile(src, dest);
            toIgnore.add(src);
        }
        //Copy only the jsps under webapp to /WEB-INF/view
        File destDir = new File(basePath + "/WEB-INF/view".replace("/", File.separator));
        File srcDir = new File(basePath + MODULE_ROOT_DIR.replace("/", File.separator));
        FileUtils.copyDirectory(srcDir, destDir,
                toCopy -> toCopy.getName().endsWith(".jsp") && !toIgnore.contains(toCopy));

        //copy scripts
        destDir = new File(basePath + "/WEB-INF/view/scripts".replace("/", File.separator));
        srcDir = new File(basePath + MODULE_ROOT_DIR + "/resources/scripts".replace("/", File.separator));
        FileUtils.copyDirectory(srcDir, destDir);

        //copy openmrs.js
        File destFile = new File(basePath + "/openmrs.js".replace("/", File.separator));
        File srcFile = new File(
                basePath + MODULE_ROOT_DIR + "/resources/scripts/openmrs.js".replace("/", File.separator));
        FileUtils.copyFile(srcFile, destFile);

        //copy images
        destDir = new File(basePath + "/images".replace("/", File.separator));
        srcDir = new File(basePath + MODULE_ROOT_DIR + "/resources/images".replace("/", File.separator));
        FileUtils.copyDirectory(srcDir, destDir);

        //copy css
        destDir = new File(basePath);
        srcDir = new File(basePath + MODULE_ROOT_DIR + "/resources/css".replace("/", File.separator));
        FileUtils.copyDirectory(srcDir, destDir);

        //Later we need to ignore everything in resources folder
        toIgnore.add(new File(basePath + MODULE_ROOT_DIR + "/resources".replace("/", File.separator)));

        //copy tags
        destDir = new File(basePath + "/WEB-INF/tags".replace("/", File.separator));
        srcDir = new File(basePath + "/WEB-INF/tags/module/legacyui".replace("/", File.separator));
        FileUtils.copyDirectory(srcDir, destDir);

        //copy these directories to WEB-INF
        String[] directoriesToCopy = { "taglibs", "template" };
        for (String dir : directoriesToCopy) {
            File dest = new File(basePath + "/WEB-INF/" + dir.replace("/", File.separator));
            File src = new File(basePath + MODULE_ROOT_DIR + "/" + dir.replace("/", File.separator));
            FileUtils.copyDirectory(src, dest);
            toIgnore.add(src);
        }

        //copy all other un copied folders to WEB-INF/view
        destDir = new File(basePath + "/WEB-INF/view".replace("/", File.separator));
        srcDir = new File(basePath + MODULE_ROOT_DIR.replace("/", File.separator));
        final File src = srcDir;
        FileUtils.copyDirectory(src, destDir, toCopy -> !toIgnore.contains(toCopy)
                && (toCopy.isDirectory() || !toCopy.getParentFile().equals(src)));
    } catch (IOException ex) {
        log.error("Failed to copy legacy ui files", ex);
    }
}

From source file:com.googlecode.psiprobe.controllers.apps.ViewXMLConfController.java

protected ModelAndView handleContext(String contextName, Context context, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (displayTarget == null) {
        throw new RuntimeException("Display target is not set for " + getClass().getName());
    }/*from  w  ww .  java2 s .  co  m*/

    String xmlPath;
    File xmlFile = null;
    ModelAndView mv = new ModelAndView(getViewName());

    if (TARGET_WEB_XML.equals(displayTarget)) {
        ServletContext sctx = context.getServletContext();
        xmlPath = sctx.getRealPath("/WEB-INF/web.xml");
        xmlFile = new File(xmlPath);
        mv.addObject("fileDesc",
                getMessageSourceAccessor().getMessage("probe.src.app.viewxmlconf.webxml.desc"));
    } else if (TARGET_CONTEXT_XML.equals(displayTarget)) {
        xmlFile = getContainerWrapper().getTomcatContainer().getConfigFile(context);
        if (xmlFile != null) {
            xmlPath = xmlFile.getPath();
        } else {
            xmlPath = null;
        }
        mv.addObject("fileDesc",
                getMessageSourceAccessor().getMessage("probe.src.app.viewxmlconf.contextxml.desc"));
    } else {
        throw new RuntimeException("Unknown display target " + getDisplayTarget());
    }

    mv.addObject("displayTarget", displayTarget);
    mv.addObject("downloadUrl", downloadUrl);

    if (xmlFile != null) {
        mv.addObject("fileName", xmlFile.getName());
        if (xmlFile.exists()) {
            FileInputStream fis = new FileInputStream(xmlFile);
            try {
                String encoding = System.getProperty("file.encoding");
                mv.addObject("content", Utils.highlightStream("web.xml", fis, "xml",
                        encoding == null ? "ISO-8859-1" : encoding));
            } finally {
                fis.close();
            }
        } else {
            logger.debug("File " + xmlPath + " of " + contextName + " application does not exists.");
        }
    } else {
        logger.debug(
                "Cannot determine path to " + getDisplayTarget() + " file of " + contextName + " application.");
    }

    return mv;
}