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.doculibre.constellio.filters.LocalRequestFilter.java

private boolean isFileRequest(ServletRequest request) {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpSession httpSession = httpRequest.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    String contextPath = httpRequest.getContextPath();
    String requestURI = httpRequest.getRequestURI();
    String contextRelativePath = requestURI.substring(contextPath.length());
    String possibleFilePath = servletContext.getRealPath(contextRelativePath);
    return new File(possibleFilePath).exists();
}

From source file:org.kie.workbench.common.stunner.backend.service.DiagramServiceImpl.java

private void deployAppDiagrams(final String path) {
    ServletContext servletContext = RpcContext.getServletRequest().getServletContext();
    if (null != servletContext) {
        String dir = servletContext.getRealPath(path);
        if (dir != null && new File(dir).exists()) {
            dir = dir.replaceAll("\\\\", "/");
            findAndDeployDiagrams(dir);/*ww  w.j a  v  a  2s.  c o  m*/
        }
    } else {
        LOG.warn("No servlet context available. Cannot deploy the application diagrams.");
    }
}

From source file:org.deegree.client.core.renderer.InputFileRenderer.java

private File getTargetFile(ServletContext sc, String target, String fileName) throws IOException {
    File targetFile = null;//from ww  w.  ja  va2s  .c o m
    if (target != null) {
        if (!target.endsWith("/")) {
            target += "/";
        }
        targetFile = new File(sc.getRealPath(target + fileName));
    } else {
        // use deegree's temp directory
        File tempDir = TempFileManager.getBaseDir();
        targetFile = File.createTempFile("upload", "", tempDir);
    }

    LOG.info("Uploading file '" + fileName + "' to: '" + targetFile + "'");
    return targetFile;
}

From source file:beans.FotoBean.java

public void tirarFoto(CaptureEvent captureEvent) throws IOException {
    arquivo = gerarNome();/*from  www  .jav  a 2  s.  co m*/
    byte[] data = captureEvent.getData();

    ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
            .getContext();
    String pasta = servletContext.getRealPath("") + File.separator + "resources" + File.separator
            + "fotossalvas";
    File vpasta = new File(pasta);
    if (!vpasta.exists()) {
        vpasta.setWritable(true);
        vpasta.mkdirs();
    }
    String novoarquivo = pasta + File.separator + arquivo + ".jpeg";
    System.out.println(novoarquivo);
    fotosalva = new File(novoarquivo);
    fotosalva.createNewFile();
    FileImageOutputStream imageOutput;
    try {
        imageOutput = new FileImageOutputStream(fotosalva);
        imageOutput.write(data, 0, data.length);
        imageOutput.close();

    } catch (IOException e) {
        Util.criarMensagemErro(e.toString());

    }
}

From source file:com.exp.tracker.services.impl.JasperReportGenerationService.java

public void generateExpenseReport(Long sid, RequestContext ctx) {
    // Get hold of the servlet context
    ServletContext context = (ServletContext) ctx.getExternalContext().getNativeContext();
    String expenseReportTemplatePath = context.getRealPath(EXPENSE_REPORT_FILE_NAME);

    genExpenseReportInternal(sid, expenseReportTemplatePath);
}

From source file:com.wavemaker.spinup.web.WavemakerStudioApplicationArchiveFactory.java

private void downloadStudioWar(ServletContext servletContext, boolean replaceExisting) {
    InputStream reader = null;/*  w  w w.j a  v  a2s.c  o m*/
    OutputStream out = null;
    String path = null;
    int ByteRead = 0;
    try {
        String uploadDirName = servletContext.getRealPath(SpinupConstants.STUDIOD_UPLOAD_DIR);
        File uploadPath = new File(uploadDirName);
        uploadPath.mkdirs();
        File localStudioWar = new File(uploadPath, SpinupConstants.STUDIO_FILE);
        if (!localStudioWar.exists() || replaceExisting) {
            try {
                byte[] buffer = new byte[5242880]; //5mb

                String customURL = CloudFoundryUtils.getEnvironmentVariable("studio_war_url", "");
                if (customURL.isEmpty()) {
                    path = SpinupConstants.STUDIO_URL + SpinupConstants.STUDIO_FILE;
                } else {
                    path = customURL;
                }
                if (this.logger.isInfoEnabled()) {
                    this.logger.info("Downloading studio from: " + path);
                }
                URL url = new URL(path);
                url.openConnection();
                reader = url.openStream();
                out = new BufferedOutputStream(new FileOutputStream(localStudioWar));
                while ((ByteRead = reader.read(buffer)) != -1) {
                    out.write(buffer, 0, ByteRead);
                }
            } catch (IOException e) {
                e.printStackTrace();
                throw new IllegalStateException(e);
            } catch (Exception e) {
                throw new WMRuntimeException(e);
            } finally {
                try {
                    reader.close();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            if (this.logger.isInfoEnabled()) {
                this.logger.info("Using existing studio WAR");
            }
        }
        this.namingStrategy.getCurrentVersion(this.servletContext);
        this.studioWarFile = localStudioWar;

        Assert.state(studioWarFile.exists(),
                "Studio resource '" + studioWarFile.getPath() + "' does not exist");
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Studio War is " + studioWarFile.getPath());
        }
    } catch (Exception e) {
        throw new WMRuntimeException(e);
    }
}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

private String createLanguageDir() {
    ServletContext context = getServletConfig().getServletContext();
    String path = context.getRealPath("/");

    boolean serveronwindows = !path.startsWith("/");

    String root = "";
    int idx = path.lastIndexOf("NEDAdminConsole");
    root = path.substring(0, idx);// ww w .  j  ava 2 s. c o m
    root += "ROOT\\";

    String directory = root + "\\locales\\";

    if (!serveronwindows) {
        directory = directory.replace('\\', '/');
    }

    return directory;
}

From source file:org.ned.server.nedadminconsole.server.NedFileUploadServlet.java

private String createDirectory(String libId) {
    ServletContext context = getServletConfig().getServletContext();
    String path = context.getRealPath("/");

    boolean serveronwindows = !path.startsWith("/");

    String root = "";
    int idx = path.lastIndexOf("NEDAdminConsole");
    root = path.substring(0, idx);//from   ww  w  . j  av a2  s. c o  m
    root += "ROOT\\";

    String directory = root + libId + "\\nokiaecd\\videos\\";

    if (!serveronwindows) {
        directory = directory.replace('\\', '/');
    }

    return directory;
}

From source file:com.google.ratel.util.RatelUtils.java

/**
 * Returns true if Click resources (JavaScript, CSS, images etc) packaged in jars can be deployed to the root directory of the webapp,
 * false otherwise.//from   w w  w .ja v a 2  s.  c  om
 * <p/>
 * This method will return false in restricted environments where write access to the underlying file system is disallowed. Examples
 * where write access is not allowed include the WebLogic JEE server (this can be changed though) and Google App Engine.
 *
 * @param servletContext the application servlet context
 * @return true if writes are allowed, false otherwise
 */
public static boolean isResourcesDeployable(ServletContext servletContext) {
    try {
        boolean canWrite = (servletContext.getRealPath("/") != null);
        if (!canWrite) {
            return false;
        }

        // Since Google App Engine returns a value for getRealPath, check
        // SecurityManager if writes are allowed
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite("/");
        }
        return true;
    } catch (Throwable e) {
        return false;
    }
}

From source file:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXSLT")
public void downloadXSLT(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xsl";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXSLT(XSLTFile.xsltString, fullPath);
    System.out.println("appPath = " + appPath);

    File downloadFile = new File(fullPath);
    FileInputStream inputStream = new FileInputStream(downloadFile);

    // get MIME type of the file
    String mimeType = context.getMimeType(fullPath);
    if (mimeType == null) {
        // set to binary type if MIME mapping not found
        mimeType = "application/octet-stream";
    }/*  w  w  w.  jav a  2  s  . c om*/
    System.out.println("MIME type: " + mimeType);

    // set content attributes for the response
    response.setContentType(mimeType);
    response.setContentLength((int) downloadFile.length());

    // set headers for the response
    String headerKey = "Content-Disposition";
    String headerValue = String.format("attachment; filename=\"%s\"", downloadFile.getName());
    response.setHeader(headerKey, headerValue);

    // get output stream of the response
    OutputStream outStream = response.getOutputStream();

    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = -1;

    // write bytes read from the input stream into the output stream
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outStream.write(buffer, 0, bytesRead);
    }

    inputStream.close();
    outStream.close();

}