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:com.glaf.core.context.StartupListener.java

public void contextInitialized(ServletContextEvent event) {
    logger.info("initializing servlet context......");
    ServletContext context = event.getServletContext();
    String root = context.getRealPath("/");
    com.glaf.core.context.ApplicationContext.setAppPath(root);
    com.glaf.core.context.ApplicationContext.setContextPath(event.getServletContext().getContextPath());
    String webAppRootKey = event.getServletContext().getInitParameter("webAppRootKey");
    if (StringUtils.isNotEmpty(webAppRootKey)) {
        System.setProperty(webAppRootKey, SystemProperties.getAppPath());
    } else {/*from  w ww  .  j  a  v  a 2  s. c  om*/
        System.setProperty("webapp.root", SystemProperties.getAppPath());
    }
    for (int i = 1; i <= 20; i++) {
        System.setProperty("webapp" + i + ".root", SystemProperties.getAppPath());
    }
    System.setProperty("app.path", SystemProperties.getAppPath());
    System.setProperty("config.path", SystemProperties.getAppPath() + "/WEB-INF");
    if (DBConnectionFactory.checkConnection()) {
        DatabaseFactory.getInstance().reload();
        this.beforeContextInitialized(context);
        super.contextInitialized(event);
        this.setupContext(context);
    } else {
        logger.error("??");
    }
    if (SystemProperties.getDeploymentSystemName() != null) {
        String deploymentSystemName = SystemProperties.getDeploymentSystemName();
        String path = SystemProperties.getConfigRootPath() + Constants.DEPLOYMENT_JDBC_PATH
                + deploymentSystemName + "/jdbc";
        try {
            FileUtils.mkdirs(path);
        } catch (IOException ex) {
        }
        String log_path = SystemProperties.getConfigRootPath() + "/logs/" + deploymentSystemName;
        try {
            FileUtils.mkdirs(log_path);
        } catch (IOException ex) {
        }
    }

    try {
        File file = new File(SystemProperties.getConfigRootPath() + "/key");
        if (!(file.exists() || file.isFile())) {
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < 32; i++) {
                sb.append(UUID32.getUUID());
            }
            FileUtils.save(SystemProperties.getConfigRootPath() + "/key", sb.toString().getBytes());
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    try {
        ExecutionManager.getInstance().execute();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:org.glimpse.server.LogConfigurator.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext servletContext = sce.getServletContext();

    String confDirPath = System.getProperty("org.glimpse.conf.dir");
    if (StringUtils.isEmpty(confDirPath)) {
        confDirPath = servletContext.getRealPath("/WEB-INF/conf");
    }//  w ww. j  a va2s .  co  m
    File configurationDirectory = new File(confDirPath);

    File logConfig = new File(configurationDirectory, "log4j.properties");

    if (logConfig.exists()) {
        LogManager.resetConfiguration();
        PropertyConfigurator.configure(logConfig.getAbsolutePath());
    }
}

From source file:org.springframework.web.servlet.mvc.UrlTilenameViewController.java

protected String extractOperableUrl(HttpServletRequest request) {
    String uri = request.getRequestURI();
    ServletContext context = request.getSession().getServletContext();
    File rootFile = new File(context.getRealPath("/"));
    String rootContext = rootFile.getName() + "/";

    if (log.isDebugEnabled()) {
        log.debug("Request uri received is " + uri + " in the application context " + rootContext);
    }//from   w  w w.j a  v a2  s. c o m

    if (uri.startsWith("/")) {
        uri = uri.substring(1);
    }
    if (uri.startsWith(rootContext)) {
        uri = uri.substring(rootContext.length());
    }

    return uri;
}

From source file:org.ecocean.ApiAccess.java

public Document initConfig(HttpServletRequest request) {
    if (this.configDoc != null)
        return this.configDoc;
    HttpSession session = request.getSession(true);
    String context = "context0";
    context = ServletUtilities.getContext(request);
    //Shepherd myShepherd = new Shepherd(context);
    ServletContext sc = session.getServletContext();
    File afile = new File(sc.getRealPath("/") + "/WEB-INF/classes/apiaccess.xml");
    System.out.println("reading file??? " + afile.toString());

    // h/t http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/
    try {//from ww w  . j  a v a2s  . c  om
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        this.configDoc = dBuilder.parse(afile);
        this.configDoc.getDocumentElement().normalize();
    } catch (Exception ex) {
        System.out.println("could not read " + afile.toString() + ": " + ex.toString());
        this.configDoc = null;
    }
    return this.configDoc;
}

From source file:com.hastybox.lesscss.compileservice.SimpleWebLessCompileService.java

public String compileFromPath(String path, ServletContext context) {
    LOGGER.debug("Compiling LESS file at {}", path);

    String lessPath = basePath + path;

    String completePath = context.getRealPath(lessPath);

    if (completePath == null) {
        String errorMsg = String
                .format("LESS file not found. Your application might not be exploded to filesystem", lessPath);
        LOGGER.error(errorMsg);//  w ww  .  j  a v a2s.  c  o  m
        throw new CompileException(errorMsg);
    }

    File lessFile = new File(completePath);

    return compileCode(lessFile);

}

From source file:com.eufar.asmm.server.DownloadFunction.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    System.out.println("DownloadFunction - the function started");
    ServletContext context = getServletConfig().getServletContext();
    request.setCharacterEncoding("UTF-8");
    String dir = context.getRealPath("/tmp");
    ;/*from w  ww .j  a  v a  2s  .  co  m*/
    String filename = "";
    File fileDir = new File(dir);
    try {
        System.out.println("DownloadFunction - create the file on server");
        filename = request.getParameterValues("filename")[0];
        String xmltree = request.getParameterValues("xmltree")[0];

        // format xml code to pretty xml code
        Document doc = DocumentHelper.parseText(xmltree);
        StringWriter sw = new StringWriter();
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setIndent(true);
        format.setIndentSize(4);
        XMLWriter xw = new XMLWriter(sw, format);
        xw.write(doc);

        Writer out = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(dir + "/" + filename), "UTF-8"));
        out.append(sw.toString());
        out.flush();
        out.close();
    } catch (Exception ex) {
        System.out.println("ERROR during rendering: " + ex);
    }
    try {
        System.out.println("DownloadFunction - send file to user");
        ServletOutputStream out = response.getOutputStream();
        File file = new File(dir + "/" + filename);
        String mimetype = context.getMimeType(filename);
        response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
        response.setContentLength((int) file.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setHeader("Pragma", "private");
        response.setHeader("Cache-Control", "private, must-revalidate");
        DataInputStream in = new DataInputStream(new FileInputStream(file));
        int length;
        while ((in != null) && ((length = in.read(bbuf)) != -1)) {
            out.write(bbuf, 0, length);
        }
        in.close();
        out.flush();
        out.close();
        FileUtils.cleanDirectory(fileDir);
    } catch (Exception ex) {
        System.out.println("ERROR during downloading: " + ex);
    }
    System.out.println("DownloadFunction - file ready to be donwloaded");
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.ThemeInfoSetup.java

@Override
public void contextInitialized(ServletContextEvent sce) {
    ServletContext ctx = sce.getServletContext();
    StartupStatus ss = StartupStatus.getBean(ctx);

    String themeDirPath = ctx.getRealPath("/themes");
    if (themeDirPath == null) {
        throw new IllegalStateException("Application does not have a /themes directory.");
    }/*from   w  ww  .java  2  s.  c  o  m*/
    File themesBaseDir = new File(themeDirPath);

    List<String> themeNames = getThemeNames(themesBaseDir);
    log.debug("themeNames: " + themeNames);
    if (themeNames.isEmpty()) {
        ss.fatal(this, "The application contains no themes. '" + themesBaseDir.getAbsolutePath()
                + "' has no child directories.");
    }

    String defaultThemeName = "vitro";
    if (!themeNames.contains(defaultThemeName)) {
        defaultThemeName = themeNames.get(0);
    }
    log.debug("defaultThemeName: " + defaultThemeName);

    String currentThemeName = getCurrentThemeName(ctx);
    log.debug("currentThemeName: " + currentThemeName);
    if ((currentThemeName != null) && (!currentThemeName.isEmpty())
            && (!themeNames.contains(currentThemeName))) {
        ss.warning(this,
                "The current theme selection is '" + currentThemeName
                        + "', but that theme is not available. The '" + defaultThemeName
                        + "' theme will be used instead. " + "Go to the Site Admin page and choose "
                        + "\"Site Information\" to select a theme.");
    }

    ApplicationBean.themeInfo = new ThemeInfo(themesBaseDir, defaultThemeName, themeNames);
    ss.info(this, "current theme: " + currentThemeName + ", default theme: " + defaultThemeName
            + ", available themes: " + themeNames);
}

From source file:com.joliciel.jochre.search.web.JochreSearchProperties.java

private JochreSearchProperties(ServletContext servletContext) {
    try {//from   w w  w  .  ja  va 2 s .c om
        this.servletContext = servletContext;
        String cfhPropertiesPath = "/WEB-INF/jochre.properties";
        String realPath = servletContext.getRealPath(cfhPropertiesPath);
        LOG.info("Loading new JochreSearchProperties from " + realPath);
        properties = new Properties();
        FileInputStream inputStream = new FileInputStream(realPath);
        properties.load(inputStream);
        for (Object keyObj : properties.keySet()) {
            String key = (String) keyObj;
            LOG.info(key + "=" + properties.getProperty(key));
        }

    } catch (IOException ioe) {
        LogUtils.logError(LOG, ioe);
        throw new RuntimeException(ioe);
    }

}

From source file:codes.thischwa.c5c.impl.FilemanagerMessageResolver.java

@Override
public void setServletContext(ServletContext servletContext) throws RuntimeException {
    PathBuilder path = new PathBuilder(PropertiesLoader.getFilemanagerPath()).addFolder(langPath);
    File msgFolder = new File(servletContext.getRealPath(path.toString()));
    if (!msgFolder.exists())
        throw new RuntimeException("C5 scripts folder couldn't be found!");

    ObjectMapper mapper = new ObjectMapper();
    try {//w  w  w  . ja  va2s.  co  m
        for (File file : msgFolder.listFiles(jsFilter)) {
            String lang = FilenameUtils.getBaseName(file.getName());
            @SuppressWarnings("unchecked")
            Map<String, String> langData = mapper.readValue(file, Map.class);
            collectLangData(lang, langData);
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.ApplicationModelSetup.java

protected Model readInDisplayModelLoadAtStartup(ServletContext ctx) {
    return getModelFromDir(new File(ctx.getRealPath(DISPLAY_MODEL_LOAD_AT_STARTUP_DIR)));
}