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:ro.fils.angularspring.controller.ProjectsController.java

@RequestMapping(method = RequestMethod.GET, value = "/downloadXML")
public void downloadXML(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.xml";
    PDFCreator creator = new PDFCreator();
    creator.saveAsXML(projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent(),
            fullPath);/*from w  w w .  ja  v a 2s . co  m*/
    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";
    }
    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();

}

From source file:br.gov.demoiselle.escola.business.AlunoBC.java

public void salvarFoto(Aluno aluno, Foto foto) {
    if (foto != null) {
        try {//  www .  j  a v  a 2  s .  com

            aluno.setFoto(aluno.getId() + "." + FilenameUtils.getExtension(foto.getNome()));
            FacesContext aFacesContext = FacesContext.getCurrentInstance();
            ServletContext context = (ServletContext) aFacesContext.getExternalContext().getContext();

            String path = context.getRealPath(escolaConfig.getUploadPath() + aluno.getFoto());

            File file = new File(path);
            BufferedInputStream bufferedInputStream = new BufferedInputStream(foto.getInputStream());
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            try {
                byte[] buffer = new byte[1024];
                int count;
                while ((count = bufferedInputStream.read(buffer)) > 0)
                    fileOutputStream.write(buffer, 0, count);
            } finally {
                bufferedInputStream.close();
                fileOutputStream.close();
            }
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }
}

From source file:Service.java

/**
 * Method that initializes the server variables. 
 *//*  w w w .  j a v a2  s  .c om*/
public void init() throws ServletException {
    if (!gateInited) { //If GATE has been not initialized.
        try {
            // GATE home is setted, so it can be used by SAGA.
            ServletContext ctx = getServletContext();
            File gateHome = new File(ctx.getRealPath("/WEB-INF"));
            Gate.setGateHome(gateHome);
            // GATE user configuration file is setted. 
            Gate.setUserConfigFile(new File(gateHome, "user-gate.xml"));
            //GATE is initialized as non visible.
            Gate.init();
            // We load the plugins that are going to be used by the SAGA modules.
            // Load ANNIE.
            Gate.getCreoleRegister().registerDirectories(ctx.getResource("/WEB-INF/plugins/ANNIE"));
            // Load processingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/processingResources"));
            // Load webProcessingResources (from SAGA)
            Gate.getCreoleRegister()
                    .registerDirectories(ctx.getResource("/WEB-INF/plugins/webProcessingResources"));
            // Now we create the sentiment analysis modules that are going to be provided by the service.
            // Spanish financial module.
            ArrayList<URL> dictionaries = new ArrayList<URL>();
            dictionaries.add((new Service()).getClass()
                    .getResource("/resources/gazetteer/finances/spanish/paradigma/lists.def"));
            modules.put("spFinancial",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries));
            // Emoticon module.
            ArrayList<URL> dictionaries2 = new ArrayList<URL>();
            dictionaries2
                    .add((new Service()).getClass().getResource("/resources/gazetteer/emoticon/lists.def"));
            modules.put("emoticon",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries2));
            // Spanish financial + emoticon module.
            ArrayList<URL> dictionaries3 = new ArrayList<URL>();
            dictionaries3.add((new Service()).getClass()
                    .getResource("/resources/gazetteer/finances/spanish/paradigma/lists.def"));
            dictionaries3
                    .add((new Service()).getClass().getResource("/resources/gazetteer/emoticon/lists.def"));
            modules.put("spFinancialEmoticon",
                    new DictionaryBasedSentimentAnalyzer("SAGA - Sentiment Analyzer", dictionaries3));
            // GATE has been initialized.
            gateInited = true;
        } catch (Exception ex) {
            throw new ServletException("Exception initialising GATE", ex);
        }
    }
}

From source file:beans.FotoBean.java

public void enviarArquivo(FileUploadEvent event) {
    try {/* w ww  .  j a v a  2  s  .  c o m*/
        arquivo = gerarNome();
        ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext()
                .getContext();
        String pasta = servletContext.getRealPath("") + File.separator + "resources" + File.separator
                + "arquivossalvos";
        File vpasta = new File(pasta);
        if (!vpasta.exists()) {
            vpasta.setWritable(true);
            vpasta.mkdirs();
        }
        String novoarquivo = pasta + File.separator + event.getFile().getFileName();
        File a = new File(novoarquivo);
        a.createNewFile();
        FileUtils.copyInputStreamToFile(event.getFile().getInputstream(), a);
        byte[] fotobyte = FileUtils.readFileToByteArray(a);
        foto.setNome(event.getFile().getFileName());
        foto.setArquivo(fotobyte);
        foto.setDataHora(Calendar.getInstance().getTime());

        if (new FotoController().salvar(foto)) {
            listarArquivos();
            Util.executarJavascript("PF('dlgfoto').hide()");
            Util.criarMensagem("arquivo salvo");
            Util.atualizarComponente("foto");
            a.delete();
        }

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

From source file:org.nuxeo.runtime.deployment.NuxeoStarter.java

protected void findBundles(ServletContext servletContext) throws IOException {
    InputStream bundlesListStream = servletContext.getResourceAsStream("/WEB-INF/" + NUXEO_BUNDLES_LIST);
    if (bundlesListStream != null) {
        File lib = new File(servletContext.getRealPath("/WEB-INF/lib/"));
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(bundlesListStream))) {
            String bundleName;/*from   ww w .  j  a v a  2s  . c o m*/
            while ((bundleName = reader.readLine()) != null) {
                bundleFiles.add(new File(lib, bundleName));
            }
        }
    }
    if (bundleFiles.isEmpty()) { // Fallback on directory scan
        File root = new File(servletContext.getRealPath("/"));
        Set<String> ctxpaths = servletContext.getResourcePaths("/WEB-INF/lib/");
        if (ctxpaths != null) {
            for (String ctxpath : ctxpaths) {
                if (!ctxpath.endsWith(".jar")) {
                    continue;
                }
                bundleFiles.add(new File(root, ctxpath));
            }
        }
    }
}

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

@RequestMapping(method = RequestMethod.GET, value = "/downloadPDF")
public void downloadPDF(HttpServletRequest request, HttpServletResponse response)
        throws FileNotFoundException, IOException, BadElementException {
    ServletContext context = request.getServletContext();
    String appPath = context.getRealPath("");
    String fullPath = appPath + "Projects.pdf";
    PDFCreator creator = new PDFCreator();
    projectConverter = new ProjectConverter();
    creator.saveAsPDF(//from   w w w .ja v  a  2s . co m
            projectConverter.readAll(
                    projectsDocumentRepository.findOne(ConnectionUtils.PROJECTS_COLLECTION).getContent()),
            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";
    }
    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();

}

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

/**
 * This is a pretty heavyweight process. So, we will execute it
 * asynchronously/* ww w  .  j  a  va  2  s  .  c o  m*/
 */
@Transactional
@Async
public void generateSettlementReport(Long sid, RequestContext ctx) {
    // Get hold of the servlet context
    ServletContext context = (ServletContext) ctx.getExternalContext().getNativeContext();
    String settlementReportTemplatePath = context.getRealPath(SETTLEMENT_REPORT_FILE_NAME);
    String expenseReportTemplatePath = context.getRealPath(EXPENSE_REPORT_FILE_NAME);

    byte[] settlementPdfBytes = genSettlementReportInternal(sid, settlementReportTemplatePath);

    // chain expense report
    byte[] expensePdfBytes = genExpenseReportInternal(sid, expenseReportTemplatePath);
    // chain email send
    emailService.sendSettlementEmail(sid, settlementPdfBytes, expensePdfBytes);
    logger.info("Settlement process ended");
}

From source file:com.starr.smartbuilds.service.FileService.java

public String getFile(Build build, ServletContext sc)
        throws FileNotFoundException, IOException, ParseException {

    /*if (fileName == null || fileName.equals("") || fileText == null || fileText.equals("")) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     } else {// www . j a va2s .c o m
     try {*/
    String path = sc.getRealPath("/");
    System.out.println(path);
    File dir = new File(path + "/builds");
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();
    }

    String fileName = path + "/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
    File fileBuild = new File(fileName);
    if (!fileBuild.exists() || fileBuild.isDirectory()) {
        String file_data = buildService.buildData(build, buildService.parseBlocks(build.getBlocks()));
        fileBuild.createNewFile();
        FileOutputStream fos = new FileOutputStream(fileBuild, false);
        fos.write(file_data.getBytes());
        fos.close();
    }

    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    try {
        client.connect("itelit.ftp.ukraine.com.ua");
        client.login("itelit_dor", "154896");

        // Create an InputStream of the file to be uploaded
        fis = new FileInputStream(fileBuild.getAbsolutePath());

        // Store file to server
        client.storeFile("builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json", fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*} catch (IOException ex) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     }
     }*/
    return "http://dor.it-elit.org/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
}

From source file:org.apache.jetspeed.services.resources.VariableResourcesService.java

/**
 * Initializer method that sets up the generic resources.
 *
 * @param confs A Configurations object.
 *///from w ww  .j a va  2  s.  c  o  m
private void initVariables(ServletConfig config) {
    ServletContext ctxt = config.getServletContext();

    String path = ctxt.getRealPath("/");

    // define web app dir
    if (path != null) {
        variables.put(WEBAPP_DIR, normalizePath(path));
    }

    // FIXME. the following code blocks on Tomcat 
    // when loaded on startup
    /*
    path = ctxt.getContext("/").getRealPath("/");
    if (path != null ) {
    variables.put(WEB_DIR, normalizePath(path) );
    }
    */

    // define JVM app dir
    try {
        path = new File(".").getCanonicalPath();
        if (path != null) {
            variables.put(JVM_DIR, normalizePath(path));
        }
    } catch (IOException e) {
        //very unlikely that the JVM can't 
        //resolve its path
        //But logging it anyway...
        logger.error("Exception define JVM app dir", e);
    }

    // load servlet init parameters as variables, they may override
    // the previously defined variables. All param names are folded
    // to lower case

    Enumeration en = config.getInitParameterNames();
    while (en.hasMoreElements()) {
        String paramName = (String) en.nextElement();
        String paramValue = config.getInitParameter(paramName);
        variables.put(paramName.toLowerCase(), paramValue);
    }

}

From source file:managedBeans.informes.InformeMovimientoInventarioMB.java

public void generarReporte() throws IOException, JRException {
    int numero = determinarNumMovimiento();
    List<InvMovimientoDetalle> detalleMovimiento = movimientoDetalleFacade.detalleMovimientoInforme(sedeActual,
            fechaIncial, fechaFinal, productoSeleccionado, movimientoSeleccionado, numero, documentoSoporte);
    List<InformeMovimientoInventario> lista = generarLista(detalleMovimiento);
    JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(lista);
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpServletResponse httpServletResponse = (HttpServletResponse) facesContext.getExternalContext()
            .getResponse();/*w  w w.  j  a v a 2s  . c om*/
    ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
    String rutaReportes = servletContext.getRealPath("/informes/reportes/");//ubicacion para los subreportes
    try (ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream()) {
        httpServletResponse.setContentType("application/pdf");
        servletContext = (ServletContext) facesContext.getExternalContext().getContext();
        String ruta = servletContext.getRealPath("/informes/reportes/informeMovimientoInventario.jasper");
        Map<String, Object> parametros = new HashMap<>();
        if (sedeActual.getLogo() != null) {
            InputStream logo = new ByteArrayInputStream(sedeActual.getLogo());
            parametros.put("logo", logo);
        }
        parametros.put("SUBREPORT_DIR", rutaReportes);
        JasperPrint jasperPrint = JasperFillManager.fillReport(ruta, parametros, beanCollectionDataSource);
        JasperExportManager.exportReportToPdfStream(jasperPrint, servletOutputStream);
        FacesContext.getCurrentInstance().responseComplete();
    }
}