Example usage for javax.servlet ServletOutputStream flush

List of usage examples for javax.servlet ServletOutputStream flush

Introduction

In this page you can find the example usage for javax.servlet ServletOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/convertTiffToPdf", method = RequestMethod.POST)
@ResponseBody/*from  www .j  a  v  a 2  s. com*/
public void convertTiffToPdf(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for extract fuzzy DB for given HOCR file");
    String respStr = "";
    String workingDir = "";
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
            if (!fileMap.keySet().isEmpty()) {
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.endsWith(FileType.TIF.getExtensionWithDot())
                            || fileName.endsWith(FileType.TIFF.getExtensionWithDot())) {
                    } else {
                        respStr = "Invalid file. Please passed the valid tif/tiff file";
                        break;
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    final File file = new File(workingDir + File.separator + fileName);
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }

                    if (outStream != null) {
                        outStream.close();
                    }
                }
            } else {
                respStr = "Please passed the input files for processing";
            }

            if (respStr.isEmpty()) {
                String inputParams = WebServiceUtil.EMPTY_STRING;
                String outputParams = WebServiceUtil.EMPTY_STRING;
                String pdfGeneratorEngine = WebServiceUtil.EMPTY_STRING;
                for (final Enumeration<String> params = multiPartRequest.getParameterNames(); params
                        .hasMoreElements();) {
                    final String paramName = params.nextElement();
                    if (paramName.equalsIgnoreCase("inputParams")) {
                        inputParams = multiPartRequest.getParameter(paramName);
                        logger.info("Value for batchClassIdentifier parameter is " + inputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase("outputParams")) {
                        outputParams = multiPartRequest.getParameter(paramName);
                        logger.info("Value for hocrFile parameter is " + outputParams);
                        continue;
                    }
                    if (paramName.equalsIgnoreCase("pdfGeneratorEngine")) {
                        pdfGeneratorEngine = multiPartRequest.getParameter(paramName);
                        logger.info("Value for hocrFile parameter is " + pdfGeneratorEngine);
                        continue;
                    }
                }

                respStr = WebServiceUtil.validateConvertTiffToPdfAPI(pdfGeneratorEngine, inputParams,
                        outputParams);

                if (respStr.isEmpty()) {
                    Set<String> outputFileList = new HashSet<String>();
                    File file = new File(workingDir);
                    String[] fileList = file.list(new CustomFileFilter(false,
                            FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot()));

                    BatchInstanceThread batchInstanceThread = new BatchInstanceThread(workingDir);

                    for (String inputFile : fileList) {
                        String[] fileArray = new String[2];
                        String outputFile = inputFile.substring(0, inputFile.lastIndexOf(WebServiceUtil.DOT))
                                + FileType.PDF.getExtensionWithDot();
                        fileArray[0] = workingDir + File.separator + inputFile;
                        fileArray[1] = workingDir + File.separator + outputFile;
                        outputFileList.add(outputFile);
                        imService.createTifToPDF(pdfGeneratorEngine, fileArray, batchInstanceThread,
                                inputParams, outputParams);
                    }

                    batchInstanceThread.execute();

                    for (String outputFile : outputFileList) {
                        FileUtils.copyFile(new File(workingDir + File.separator + outputFile),
                                new File(outputDir + File.separator + outputFile));
                    }

                    ServletOutputStream out = null;
                    ZipOutputStream zout = null;
                    final String zipFileName = WebServiceUtil.serverOutputFolderName;
                    resp.setContentType("application/x-zip\r\n");
                    resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                            + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                    try {
                        out = resp.getOutputStream();
                        zout = new ZipOutputStream(out);
                        FileUtils.zipDirectory(outputDir, zout, zipFileName);
                        resp.setStatus(HttpServletResponse.SC_OK);
                    } catch (final IOException e) {
                        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                                "Error in creating output zip file.Please try again." + e.getMessage());
                    } finally {
                        if (zout != null) {
                            zout.close();
                        }
                        if (out != null) {
                            out.flush();
                        }
                        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    }
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!respStr.isEmpty()) {
        try {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/createSearchablePDF", method = RequestMethod.POST)
@ResponseBody/*  w ww .j a v  a 2s .c o  m*/
public void createSearchablePDF(final HttpServletRequest request, final HttpServletResponse response) {
    logger.info("Start processing web service for create searchable pdf");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (request instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;
            final DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            final BatchInstanceThread batchInstanceThread = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());

            final String isColorImage = request.getParameter("isColorImage");
            final String isSearchableImage = request.getParameter("isSearchableImage");
            final String outputPDFFileName = request.getParameter("outputPDFFileName");
            final String projectFile = request.getParameter("projectFile");
            String results = WebServiceUtil.validateSearchableAPI(outputPDFFileName, projectFile,
                    FileType.PDF.getExtensionWithDot(), isSearchableImage, isColorImage);
            if (!results.isEmpty()) {
                respStr = results;
            } else {
                logger.info("Value of isColorImage" + isColorImage);
                logger.info("Value of isSearchableImage" + isSearchableImage);
                logger.info("Value of outputPDFFileName" + outputPDFFileName);
                logger.info("Value of projectFile" + projectFile);

                final MultiValueMap<String, MultipartFile> fileMap = multipartRequest.getMultiFileMap();
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.toLowerCase().indexOf(WebServiceUtil.RSP_EXTENSION) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIF.getExtension()) > -1
                            || fileName.toLowerCase().indexOf(FileType.TIFF.getExtension()) > -1) {
                        // only tiffs and RSP file is expected
                        final MultipartFile f = multipartRequest.getFile(fileName);
                        instream = f.getInputStream();
                        final File file = new File(workingDir + File.separator + fileName);
                        outStream = new FileOutputStream(file);
                        final byte[] buf = new byte[WebServiceUtil.bufferSize];
                        int len;
                        while ((len = instream.read(buf)) > 0) {
                            outStream.write(buf, 0, len);
                        }
                        if (instream != null) {
                            instream.close();
                        }
                        if (outStream != null) {
                            outStream.close();
                        }
                    } else {
                        respStr = "Only tiff, tif and rsp files expected.";
                        break;
                    }
                }
                if (respStr.isEmpty()) {
                    String[] imageFiles = null;
                    final File file = new File(workingDir);

                    imageFiles = file.list(new CustomFileFilter(false, FileType.TIFF.getExtensionWithDot(),
                            FileType.TIF.getExtensionWithDot()));

                    if (imageFiles == null || imageFiles.length == 0) {
                        respStr = "No tif/tiff file found for processing.";
                    }

                    String rspProjectFile = workingDir + File.separator + projectFile;

                    File rspFile = new File(rspProjectFile);

                    if (rspProjectFile == null || !rspFile.exists()) {
                        respStr = "Invalid project file. Please verify the project file.";
                    }

                    if (respStr.isEmpty()) {
                        final String[] pages = new String[imageFiles.length + 1];
                        int index = 0;
                        for (final String imageFileName : imageFiles) {
                            pages[index] = workingDir + File.separator + imageFileName;
                            index++;

                            if (WebServiceUtil.TRUE.equalsIgnoreCase(isColorImage)) {
                                try {
                                    logger.info("Generating png image files");
                                    imService.generatePNGForImage(
                                            new File(workingDir + File.separator + imageFileName));
                                    final String pngFileName = imageFileName.substring(0,
                                            imageFileName.lastIndexOf(WebServiceUtil.DOT))
                                            + FileType.PNG.getExtensionWithDot();
                                    recostarService.createOCR(projectFile, workingDir, WebServiceUtil.ON_STRING,
                                            pngFileName, batchInstanceThread, workingDir);
                                } catch (final DCMAException e) {
                                    FileUtils.deleteDirectoryAndContentsRecursive(
                                            new File(workingDir).getParentFile());
                                    respStr = "Error in generating plugin output." + imageFileName + ". " + e;
                                }
                            } else {
                                try {
                                    recostarService.createOCR(projectFile, workingDir,
                                            WebServiceUtil.OFF_STRING, imageFileName, batchInstanceThread,
                                            workingDir);
                                } catch (final DCMAException e) {
                                    FileUtils.deleteDirectoryAndContentsRecursive(
                                            new File(workingDir).getParentFile());
                                    respStr = "Error in generating plugin output." + imageFileName + ". " + e;
                                }
                            }
                        }
                        try {
                            logger.info("Generating HOCR file for input images.");
                            batchInstanceThread.execute();
                            batchInstanceThread.remove();
                            final String outputPDFFile = workingDir + File.separator + outputPDFFileName;
                            pages[index] = outputPDFFile;
                            imService.createSearchablePDF(isColorImage, isSearchableImage, workingDir, pages,
                                    batchInstanceThread, WebServiceUtil.DOCUMENTID);
                            batchInstanceThread.execute();
                            logger.info("Copying output searchable file");
                            FileUtils.copyFile(new File(outputPDFFile),
                                    new File(outputDir + File.separator + outputPDFFileName));
                        } catch (final DCMAApplicationException e) {
                            batchInstanceThread.remove();
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            respStr = "Error in generating searchable pdf." + e;
                        }
                        ServletOutputStream out = null;
                        ZipOutputStream zout = null;
                        final String zipFileName = WebServiceUtil.serverOutputFolderName;
                        response.setContentType("application/x-zip\r\n");
                        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                                + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                        try {
                            out = response.getOutputStream();
                            zout = new ZipOutputStream(out);
                            FileUtils.zipDirectory(outputDir, zout, zipFileName);
                            response.setStatus(HttpServletResponse.SC_OK);
                        } catch (final IOException e) {
                            respStr = "Unable to process web service request.Please try again." + e;
                        } finally {
                            // clean up code
                            if (zout != null) {
                                zout.close();
                            }
                            if (out != null) {
                                out.flush();
                            }
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                        }
                    }
                }

            }
        } catch (Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/createOCR", method = RequestMethod.POST)
@ResponseBody/*  w  ww .j a  v  a 2  s. c  o  m*/
public void createOCR(final HttpServletRequest req, final HttpServletResponse resp) {
    logger.info("Start processing web service for create OCRing");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        try {
            final String webServiceFolderPath = bsService.getWebServicesFolderPath();
            workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
            final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

            InputStream instream = null;
            OutputStream outStream = null;

            final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

            final BatchInstanceThread batchInstanceThread = new BatchInstanceThread(
                    new File(workingDir).getName() + Math.random());

            final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();

            if (!(fileMap.size() >= 2 && fileMap.size() <= 3)) {
                respStr = "Invalid number of files. We are supposed only 3 files.";
            }
            if (respStr.isEmpty()) {
                String xmlFileName = WebServiceUtil.EMPTY_STRING;
                for (final String fileName : fileMap.keySet()) {
                    if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                        xmlFileName = fileName;
                    }
                    final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                    instream = multiPartFile.getInputStream();
                    final File file = new File(workingDir + File.separator + fileName);
                    outStream = new FileOutputStream(file);
                    final byte[] buf = new byte[WebServiceUtil.bufferSize];
                    int len;
                    while ((len = instream.read(buf)) > 0) {
                        outStream.write(buf, 0, len);
                    }
                    if (instream != null) {
                        instream.close();
                    }

                    if (outStream != null) {
                        outStream.close();
                    }
                }

                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);
                Source source = XMLUtil.createSourceFromStream(inputStream);
                final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao.getJAXB2Template()
                        .getJaxb2Marshaller().unmarshal(source);

                List<Param> paramList = webServiceParams.getParams().getParam();
                if (paramList == null || paramList.isEmpty()) {
                    FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                    respStr = "Improper input to server. Parameter XML is incorrect. Returning without processing the results.";
                } else {
                    String ocrEngine = WebServiceUtil.EMPTY_STRING;
                    String colorSwitch = WebServiceUtil.EMPTY_STRING;
                    String projectFile = WebServiceUtil.EMPTY_STRING;
                    String tesseractVersion = WebServiceUtil.EMPTY_STRING;
                    String cmdLanguage = WebServiceUtil.EMPTY_STRING;
                    for (final Param param : paramList) {
                        if (param.getName().equalsIgnoreCase("ocrEngine")) {
                            ocrEngine = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("colorSwitch")) {
                            colorSwitch = param.getValue();
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("projectFile")) {
                            projectFile = param.getValue();
                            logger.info("Project file for recostar is :" + projectFile);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("tesseractVersion")) {
                            tesseractVersion = param.getValue();
                            logger.info("Tesseract version is: " + tesseractVersion);
                            continue;
                        }
                        if (param.getName().equalsIgnoreCase("cmdLanguage")) {
                            // supported values are "eng" and "tha" for now provided tesseract engine is learnt.
                            cmdLanguage = param.getValue();
                            logger.info("cmd langugage is :" + cmdLanguage);
                            continue;
                        }
                    }

                    String results = WebServiceUtil.validateCreateOCRAPI(workingDir, ocrEngine, colorSwitch,
                            projectFile, tesseractVersion, cmdLanguage);
                    if (!results.isEmpty()) {
                        respStr = results;
                    } else {
                        String[] fileNames = null;
                        final File file = new File(workingDir);
                        if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                            logger.info("Picking up the png file for processing.");
                            fileNames = file
                                    .list(new CustomFileFilter(false, FileType.PNG.getExtensionWithDot()));
                        } else {
                            logger.info("Picking up the tif file for processing.");
                            fileNames = file.list(new CustomFileFilter(false,
                                    FileType.TIF.getExtensionWithDot(), FileType.TIFF.getExtensionWithDot()));
                        }
                        logger.info("Number of file is:" + fileNames.length);
                        logger.info("OcrEngine used for generating ocr is :" + ocrEngine);
                        if (ocrEngine.equalsIgnoreCase("recostar")) {
                            if (fileNames != null && fileNames.length > 0) {
                                for (final String fileName : fileNames) {
                                    try {
                                        logger.info("File processing for recostar is :" + fileName);
                                        recostarService.createOCR(projectFile, workingDir, colorSwitch,
                                                fileName, batchInstanceThread, outputDir);
                                    } catch (final DCMAException e) {
                                        respStr = "Error occuring while creating OCR file using recostar. Please try again."
                                                + e;
                                        break;
                                    }
                                }
                            } else {
                                respStr = "Improper input to server. No tiff/png files provided.";
                            }
                        } else if (ocrEngine.equalsIgnoreCase("tesseract")) {
                            if (fileNames != null && fileNames.length > 0) {
                                for (final String fileName : fileNames) {
                                    try {
                                        logger.info("File processing for ocr with tesseract is :" + fileName);
                                        tesseractService.createOCR(workingDir, colorSwitch, fileName,
                                                batchInstanceThread, outputDir, cmdLanguage, tesseractVersion);
                                    } catch (final DCMAException e) {
                                        respStr = "Error occuring while creating OCR file using tesseract. Please try again."
                                                + e;
                                        break;
                                    }
                                }
                            } else {
                                respStr = "Improper input to server. No tiff/png files provided.";

                            }
                        } else {
                            respStr = "Please select valid tool for generating OCR file.";
                        }
                        if (respStr.isEmpty()) {
                            try {
                                batchInstanceThread.execute();
                                if (ocrEngine.equalsIgnoreCase("recostar")) {
                                    for (final String fileName : fileNames) {
                                        final String recostarXMLFileName = fileName.substring(0,
                                                fileName.lastIndexOf(WebServiceUtil.DOT))
                                                + FileType.XML.getExtensionWithDot();
                                        try {
                                            FileUtils.copyFile(
                                                    new File(workingDir + File.separator + recostarXMLFileName),
                                                    new File(outputDir + File.separator + recostarXMLFileName));
                                        } catch (final Exception e) {
                                            respStr = "Error while generating copying result file." + e;
                                            break;
                                        }
                                    }
                                }
                            } catch (final DCMAApplicationException e) {
                                respStr = "Exception while generating ocr using threadpool" + e;
                            }

                            ServletOutputStream out = null;
                            ZipOutputStream zout = null;
                            final String zipFileName = WebServiceUtil.serverOutputFolderName;
                            resp.setContentType("application/x-zip\r\n");
                            resp.setHeader("Content-Disposition", "attachment; filename=\"" + zipFileName
                                    + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                            try {
                                out = resp.getOutputStream();
                                zout = new ZipOutputStream(out);
                                FileUtils.zipDirectory(outputDir, zout, zipFileName);
                                resp.setStatus(HttpServletResponse.SC_OK);
                            } catch (final IOException e) {
                                respStr = "Error in creating output zip file.Please try again." + e;
                            } finally {
                                if (zout != null) {
                                    zout.close();
                                }
                                if (out != null) {
                                    out.flush();
                                }
                                FileUtils.deleteDirectoryAndContentsRecursive(
                                        new File(workingDir).getParentFile());
                            }
                        }
                    }
                }
            }
        } catch (final XmlMappingException xmle) {
            respStr = "Error in mapping input XML in the desired format. Please send it in the specified format. Detailed exception is "
                    + xmle;
        } catch (final DCMAException dcmae) {
            respStr = "Error in processing request. Detailed exception is " + dcmae;
        } catch (final Exception e) {
            respStr = "Internal Server error.Please check logs for further details." + e;
            if (!workingDir.isEmpty()) {
                FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
            }
        }
    } else {
        respStr = "Improper input to server. Expected multipart request. Returning without processing the results.";
    }
    if (!workingDir.isEmpty()) {
        FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:de.sub.goobi.forms.ProzessverwaltungForm.java

/**
 * Generate result as PDF.//  w  w w  . java2  s.  co  m
 */
public void generateResultAsPdf() {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    if (!facesContext.getResponseComplete()) {

        /*
         * Vorbereiten der Header-Informationen
         */
        HttpServletResponse response = (HttpServletResponse) facesContext.getExternalContext().getResponse();
        try {
            ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
            String contentType = servletContext.getMimeType("search.pdf");
            response.setContentType(contentType);
            response.setHeader("Content-Disposition", "attachment;filename=\"search.pdf\"");
            ServletOutputStream out = response.getOutputStream();

            SearchResultGeneration sr = new SearchResultGeneration(this.filter, this.showClosedProcesses,
                    this.showArchivedProjects);
            HSSFWorkbook wb = sr.getResult();
            List<List<HSSFCell>> rowList = new ArrayList<List<HSSFCell>>();
            HSSFSheet mySheet = wb.getSheetAt(0);
            Iterator<Row> rowIter = mySheet.rowIterator();
            while (rowIter.hasNext()) {
                HSSFRow myRow = (HSSFRow) rowIter.next();
                Iterator<Cell> cellIter = myRow.cellIterator();
                List<HSSFCell> row = new ArrayList<HSSFCell>();
                while (cellIter.hasNext()) {
                    HSSFCell myCell = (HSSFCell) cellIter.next();
                    row.add(myCell);
                }
                rowList.add(row);
            }
            Document document = new Document();
            Rectangle a4quer = new Rectangle(PageSize.A3.getHeight(), PageSize.A3.getWidth());
            PdfWriter.getInstance(document, out);
            document.setPageSize(a4quer);
            document.open();
            if (rowList.size() > 0) {
                Paragraph p = new Paragraph(rowList.get(0).get(0).toString());

                document.add(p);
                PdfPTable table = new PdfPTable(9);
                table.setSpacingBefore(20);
                for (int i = 1; i < rowList.size(); i++) {

                    List<HSSFCell> row = rowList.get(i);
                    for (int j = 0; j < row.size(); j++) {
                        HSSFCell myCell = row.get(j);
                        // TODO aufhbschen und nicht toString() nutzen

                        String stringCellValue = myCell.toString();
                        table.addCell(stringCellValue);
                    }

                }
                document.add(table);
            }

            document.close();
            out.flush();
            facesContext.responseComplete();

        } catch (Exception e) {
        }
    }
}

From source file:de.fau.amos.ChartRenderer.java

/**
 * /*from   w  w  w .j a v a 2  s.  c  o m*/
 * Reads Information from request and returns respective chart (.png-type) in response
 * 
 * @param request Request from website. Contains info about what should be displayed in chart.
 * @param response Contains .png-file with ready-to-use chart.
 * 
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("image/png");

    ServletOutputStream os = response.getOutputStream();

    //<img src="../ChartRenderer?selectedChartType=<%=chartType%>&time=<%out.println(time+(timeGranularity==3?"&endTime="+endTime:""));%>&timeGranularity=<%=timeGranularity%>&countType=<%=countType%>&groupParameters=<%out.println(ChartPreset.createParameterString(request));%>" />

    JFreeChart chart = null;

    // Parameters from URL
    String chartType = request.getParameter("selectedChartType");
    if (chartType != null) {
        chartType = chartType.trim();
    } else {
        chartType = "";
    }
    String startTime = request.getParameter("startTime");
    String endTime = request.getParameter("endTime");
    String timeGranularity = request.getParameter("timeGranularity");
    String stringTimeGranularity = timeGranularityToString(timeGranularity);
    String countType = countTypeToString(request.getParameter("countType"));
    String groupLocationParameters = encodeGroupParameters(request.getParameter("groupLocationParameters"));
    String groupFormatParameters = encodeGroupParameters(request.getParameter("groupFormatParameters"));
    String unit = request.getParameter("unit");

    int width = 100;
    try {
        width = Integer.parseInt(request.getParameter("w"));
    } catch (NumberFormatException e) {
    }
    int height = 100;
    try {
        height = Integer.parseInt(request.getParameter("h"));
    } catch (NumberFormatException e) {
    }

    if (chartType.equals("1")) {
        //show time chart
        // Create TimeSeriesCollection from URL-Parameters. This includes the SQL Query
        TimeSeriesCollection dataset = null;
        dataset = createTimeCollection(stringTimeGranularity, startTime, endTime, countType,
                groupLocationParameters, unit);

        // Create Chart from TimeSeriesCollection and do graphical modifications.
        if (timeGranularity.equals("0")) {
            chart = createTimeLineChart(dataset, timeGranularity, startTime, unit);
        } else {
            chart = createTimeBarChart(dataset, timeGranularity, startTime, unit);
        }
    } else if (chartType.equals("2")) {

        //show location-format chart
        DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType,
                groupLocationParameters, groupFormatParameters, unit, chartType);
        chart = createLocationFormatChart(dataset, unit);

    } else if (chartType.equals("3")) {

        //show location-format chart
        DefaultCategoryDataset dataset = createLocationFormatCollection(startTime, endTime, countType,
                groupLocationParameters, groupFormatParameters, unit, chartType);
        chart = createLocationFormatChart(dataset, unit);

    } else if (chartType.equals("forecast")) {

        TimeSeriesCollection dataset = createForecastCollection(request.getParameter("forecastYear"),
                request.getParameter("forecastPlant"), request.getParameter("forecastMethod"),
                request.getParameter("forecastUnits"));
        chart = createForecastChart(dataset, "2004-01-01 00:00:00", "1");
    }

    //create Image and clear output stream
    RenderedImage chartImage = chart.createBufferedImage(width, height);
    ImageIO.write(chartImage, "png", os);
    os.flush();
    os.close();

}

From source file:com.ephesoft.dcma.workflow.service.webservices.EphesoftWebServiceAPI.java

@RequestMapping(value = "/extractFixedForm", method = RequestMethod.POST)
@ResponseBody/*  ww w  .j ava 2  s. c  o  m*/
public void extractFixedForm(final HttpServletRequest req, final HttpServletResponse resp) throws Exception {
    logger.info("Start processing web service for extract fixed form");
    String respStr = WebServiceUtil.EMPTY_STRING;
    String workingDir = WebServiceUtil.EMPTY_STRING;
    com.ephesoft.dcma.batch.schema.Documents documents = null;
    if (req instanceof DefaultMultipartHttpServletRequest) {
        final String webServiceFolderPath = bsService.getWebServicesFolderPath();
        workingDir = WebServiceUtil.createWebServiceWorkingDir(webServiceFolderPath);
        final String outputDir = WebServiceUtil.createWebServiceOutputDir(workingDir);

        InputStream instream = null;
        OutputStream outStream = null;

        final DefaultMultipartHttpServletRequest multiPartRequest = (DefaultMultipartHttpServletRequest) req;

        final MultiValueMap<String, MultipartFile> fileMap = multiPartRequest.getMultiFileMap();
        String xmlFileName = WebServiceUtil.EMPTY_STRING;

        if (fileMap.size() != 3) {
            respStr = "Invalid number of files. We are supposed only 3 files.";
        }

        if (respStr.isEmpty()) {
            for (final String fileName : fileMap.keySet()) {
                if (fileName.endsWith(FileType.XML.getExtensionWithDot())) {
                    xmlFileName = fileName;
                }

                final MultipartFile multiPartFile = multiPartRequest.getFile(fileName);
                instream = multiPartFile.getInputStream();
                final File file = new File(workingDir + File.separator + fileName);
                outStream = new FileOutputStream(file);
                final byte[] buf = new byte[WebServiceUtil.bufferSize];
                int len;
                while ((len = instream.read(buf)) > 0) {
                    outStream.write(buf, 0, len);
                }
                if (instream != null) {
                    instream.close();
                }

                if (outStream != null) {
                    outStream.close();
                }
            }

            if (xmlFileName.isEmpty()) {
                respStr = "XML file is not found. Returning without processing the results.";
            }

            if (respStr.isEmpty()) {
                final File xmlFile = new File(workingDir + File.separator + xmlFileName);
                final FileInputStream inputStream = new FileInputStream(xmlFile);

                Source source = null;
                try {
                    source = XMLUtil.createSourceFromStream(inputStream);
                    if (respStr.isEmpty()) {
                        final WebServiceParams webServiceParams = (WebServiceParams) batchSchemaDao
                                .getJAXB2Template().getJaxb2Marshaller().unmarshal(source);

                        List<Param> paramList = null;

                        if (webServiceParams != null && webServiceParams.getParams() != null) {
                            paramList = webServiceParams.getParams().getParam();
                        } else {
                            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
                            respStr = "Invalid xml file mapped. Returning without processing the results.";
                        }

                        if (respStr.isEmpty()) {
                            String colorSwitch = WebServiceUtil.EMPTY_STRING;
                            String projectFile = WebServiceUtil.EMPTY_STRING;
                            if (paramList == null || paramList.size() <= 0) {
                                respStr = "Improper input to server. Returning without processing the results.";
                            } else {
                                for (final Param param : paramList) {
                                    if (param.getName().equalsIgnoreCase("colorSwitch")) {
                                        colorSwitch = param.getValue();
                                        logger.info("Color Switch for recostar is :" + colorSwitch);
                                        continue;
                                    }
                                    if (param.getName().equalsIgnoreCase("projectFile")) {
                                        projectFile = param.getValue();
                                        logger.info("Project file for recostar is :" + projectFile);
                                        continue;
                                    }
                                }
                            }

                            String[] fileNames = null;
                            final File file = new File(workingDir);
                            respStr = WebServiceUtil.validateExtractFixedFormAPI(workingDir, projectFile,
                                    colorSwitch);

                            if (respStr.isEmpty()) {
                                if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                                    logger.info("Picking up the png file for processing.");
                                    fileNames = file.list(
                                            new CustomFileFilter(false, FileType.PNG.getExtensionWithDot()));
                                } else {
                                    logger.info("Picking up the tif file for processing.");
                                    fileNames = file.list(
                                            new CustomFileFilter(false, FileType.TIF.getExtensionWithDot(),
                                                    FileType.TIFF.getExtensionWithDot()));
                                }
                                logger.info("Number of file is:" + fileNames.length);

                                if (fileNames != null && fileNames.length > 0) {
                                    for (final String fileName : fileNames) {
                                        logger.info("File processing for recostar is :" + fileName);
                                        documents = recostarExtractionService.extractDocLevelFieldsForRspFile(
                                                projectFile, workingDir, colorSwitch, fileName, workingDir);
                                    }
                                } else {
                                    if (colorSwitch.equalsIgnoreCase(WebServiceUtil.ON_STRING)) {
                                        respStr = "Image file of png type is not found for processing";
                                    } else {
                                        respStr = "Image file of tif type is not found for processing";
                                    }
                                }

                                if (respStr.isEmpty() && documents != null) {
                                    File outputxmlFile = new File(outputDir + File.separator + "OutputXML.xml");
                                    FileOutputStream stream = new FileOutputStream(outputxmlFile);
                                    StreamResult result = new StreamResult(stream);
                                    batchSchemaDao.getJAXB2Template().getJaxb2Marshaller().marshal(documents,
                                            result);

                                    ServletOutputStream out = null;
                                    ZipOutputStream zout = null;
                                    final String zipFileName = WebServiceUtil.serverOutputFolderName;
                                    resp.setContentType("application/x-zip\r\n");
                                    resp.setHeader("Content-Disposition", "attachment; filename=\""
                                            + zipFileName + FileType.ZIP.getExtensionWithDot() + "\"\r\n");
                                    try {
                                        out = resp.getOutputStream();
                                        zout = new ZipOutputStream(out);
                                        FileUtils.zipDirectory(outputDir, zout, zipFileName);
                                        resp.setStatus(HttpServletResponse.SC_OK);
                                    } catch (final IOException e) {
                                        respStr = "Error in creating output zip file.Please try again." + e;
                                    } finally {
                                        if (zout != null) {
                                            zout.close();
                                        }
                                        if (out != null) {
                                            out.flush();
                                        }
                                    }
                                }
                            }
                        }
                    }
                } catch (final DCMAException e) {
                    respStr = "Error occuring while creating OCR file using recostar. Please try later. " + e;
                } catch (final Exception e) {
                    respStr = "Improper input to server. Returning without processing the results." + e;
                }
            }
        }
        if (!workingDir.isEmpty()) {
            FileUtils.deleteDirectoryAndContentsRecursive(new File(workingDir).getParentFile());
        }
    }
    if (!respStr.isEmpty()) {
        try {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, respStr);
        } catch (final IOException ioe) {

        }
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.coordinator.ManageFinalDegreeWorkDispatchAction.java

public ActionForward proposalsXLS(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws FenixActionException, FenixServiceException {

    final ExecutionDegree executionDegree = getExecutionDegree(request);
    final ExecutionYear executionYear = executionDegree.getExecutionYear();
    final String yearString = executionYear.getNextYearsYearString().replace('/', '_');

    try {/* www .j  a  v  a  2  s .  c o  m*/
        response.setContentType("text/plain");
        response.setHeader("Content-disposition", "attachment; filename=proposals_" + yearString + ".xls");

        final HSSFWorkbook workbook = new HSSFWorkbook();
        final ExcelStyle excelStyle = new ExcelStyle(workbook);
        final ServletOutputStream writer = response.getOutputStream();

        final Spreadsheet proposalsSpreadsheet = new Spreadsheet("Proposals " + yearString);
        setProposalsHeaders(proposalsSpreadsheet);
        fillProposalsSpreadSheet(executionDegree, proposalsSpreadsheet);
        proposalsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(),
                excelStyle.getStringStyle());

        final Spreadsheet groupsSpreadsheet = new Spreadsheet("Groups " + yearString);
        fillGroupsSpreadSheet(executionDegree, groupsSpreadsheet);
        groupsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(), excelStyle.getStringStyle());

        final Scheduleing scheduleing = executionDegree.getScheduling();

        final Set<ExecutionDegree> allExecutionDegrees = new HashSet<ExecutionDegree>();
        for (final ExecutionDegree otherExecutionDegree : scheduleing.getExecutionDegreesSet()) {
            for (final FinalDegreeWorkGroup group : otherExecutionDegree
                    .getAssociatedFinalDegreeWorkGroupsSet()) {
                if (!group.getGroupProposalsSet().isEmpty()) {
                    for (final GroupStudent groupStudent : group.getGroupStudentsSet()) {
                        final Registration registration = groupStudent.getRegistration();
                        final StudentCurricularPlan studentCurricularPlan = registration
                                .getLastStudentCurricularPlan();
                        final DegreeCurricularPlan degreeCurricularPlan = studentCurricularPlan
                                .getDegreeCurricularPlan();
                        final ExecutionDegree executionDegreeByYear = degreeCurricularPlan
                                .getExecutionDegreeByYear(otherExecutionDegree.getExecutionYear());
                        if (executionDegreeByYear != null) {
                            allExecutionDegrees.add(executionDegreeByYear);
                        }
                    }
                }
            }
        }

        // for (final ExecutionDegree otherExecutionDegree :
        // scheduleing.getExecutionDegreesSet()) {
        for (final ExecutionDegree otherExecutionDegree : allExecutionDegrees) {
            final DegreeCurricularPlan degreeCurricularPlan = otherExecutionDegree.getDegreeCurricularPlan();
            final Spreadsheet studentsSpreadsheet = new Spreadsheet(
                    "Alunos " + degreeCurricularPlan.getName() + " " + yearString);
            fillStudentsSpreadSheet(otherExecutionDegree, scheduleing, studentsSpreadsheet);
            studentsSpreadsheet.exportToXLSSheet(workbook, excelStyle.getHeaderStyle(),
                    excelStyle.getStringStyle());
        }

        workbook.write(writer);

        writer.flush();
        response.flushBuffer();
    } catch (IOException e) {
        throw new FenixServiceException();
    }
    return null;
}

From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java

public void exportVSDToXMLAction(HttpServletRequest request, HttpServletResponse response) {
    String selectedvalueset = null;
    String multiplematches = HTTPUtils.cleanXSS((String) request.getParameter("multiplematches"));
    if (multiplematches != null) {
        selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("valueset"));
    } else {//from   w  w  w .  j a  v a2  s.co  m
        selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("vsd_uri"));
        if (selectedvalueset != null && selectedvalueset.indexOf("|") != -1) {
            Vector u = DataUtils.parseData(selectedvalueset);
            selectedvalueset = (String) u.elementAt(1);
        }
    }
    String uri = selectedvalueset;
    request.getSession().setAttribute("selectedvalueset", uri);

    String xml_str = valueSetDefinition2XMLString(uri);

    try {
        response.setContentType("text/xml");

        String vsd_name = DataUtils.valueSetDefiniionURI2Name(uri);
        vsd_name = vsd_name.replaceAll(" ", "_");
        vsd_name = vsd_name + ".xml";

        response.setHeader("Content-Disposition", "attachment; filename=" + vsd_name);

        response.setContentLength(xml_str.length());

        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(xml_str.getBytes("UTF8"), 0, xml_str.length());
        ouputStream.flush();
        ouputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    FacesContext.getCurrentInstance().responseComplete();

}

From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java

public void export_mapping(HttpServletRequest request, HttpServletResponse response) {
    String mapping_schema = HTTPUtils.cleanXSS((String) request.getParameter("dictionary"));
    String mapping_version = HTTPUtils.cleanXSS((String) request.getParameter("version"));

    ResolvedConceptReferencesIterator iterator = DataUtils.getMappingDataIterator(mapping_schema,
            mapping_version);/*from  ww w  .  j  av a2  s . c  om*/
    int numRemaining = 0;
    if (iterator != null) {
        try {
            numRemaining = iterator.numberRemaining();
            //System.out.println("number of records: " + numRemaining);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    StringBuffer sb = new StringBuffer();
    try {
        sb.append("Source Code,");
        sb.append("Source Name,");
        sb.append("Source Coding Scheme,");
        sb.append("Source Coding Scheme Version,");
        sb.append("Source Coding Scheme Namespace,");

        sb.append("Association Name,");
        sb.append("REL,");
        sb.append("Map Rank,");

        sb.append("Target Code,");
        sb.append("Target Name,");
        sb.append("Target Coding Scheme,");
        sb.append("Target Coding Scheme Version,");
        sb.append("Target Coding Scheme Namespace");
        sb.append("\r\n");

        MappingIteratorBean bean = new MappingIteratorBean(iterator);
        List list = bean.getData(0, numRemaining - 1);
        for (int k = 0; k < list.size(); k++) {
            MappingData mappingData = (MappingData) list.get(k);
            sb.append("\"" + mappingData.getSourceCode() + "\",");
            sb.append("\"" + mappingData.getSourceName() + "\",");
            sb.append("\"" + mappingData.getSourceCodingScheme() + "\",");
            sb.append("\"" + mappingData.getSourceCodingSchemeVersion() + "\",");
            sb.append("\"" + mappingData.getSourceCodeNamespace() + "\",");

            sb.append("\"" + mappingData.getAssociationName() + "\",");
            sb.append("\"" + mappingData.getRel() + "\",");
            sb.append("\"" + mappingData.getScore() + "\",");

            sb.append("\"" + mappingData.getTargetCode() + "\",");
            sb.append("\"" + mappingData.getTargetName() + "\",");
            sb.append("\"" + mappingData.getTargetCodingScheme() + "\",");
            sb.append("\"" + mappingData.getTargetCodingSchemeVersion() + "\",");
            sb.append("\"" + mappingData.getTargetCodeNamespace() + "\"");
            sb.append("\r\n");
        }
    } catch (Exception ex) {
        sb.append("WARNING: Export to CVS action failed.");
        ex.printStackTrace();
    }

    String filename = mapping_schema + "_" + mapping_version;
    filename = filename.replaceAll(" ", "_");
    filename = filename + ".csv";

    response.setContentType("text/csv");
    response.setHeader("Content-Disposition", "attachment; filename=" + filename);

    response.setContentLength(sb.length());

    try {
        ServletOutputStream ouputStream = response.getOutputStream();
        ouputStream.write(sb.toString().getBytes("UTF-8"), 0, sb.length());
        ouputStream.flush();
        ouputStream.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        sb.append("WARNING: Export to CVS action failed.");
    }
    FacesContext.getCurrentInstance().responseComplete();
    return;
}

From source file:com.turborep.turbotracker.banking.service.BankingServiceImpl.java

@Override
public void newCheckDetails(HttpServletResponse theResponse, HttpServletRequest theRequest)
        throws BankingException {
    Session printBeanSession = itsSessionFactory.openSession();
    SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) printBeanSession
            .getSessionFactory();//from w  ww.  j  a va2s . c  o m
    ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
    Map<String, Object> params = new HashMap<String, Object>();
    Connection connection = null;
    try {
        itsLogger.info("Testing:--->" + theRequest.getParameter("moTransactionID"));

        params.put("traxID", Integer.parseInt(theRequest.getParameter("moTransactionID")));
        ServletOutputStream out = theResponse.getOutputStream();
        String fileName = theRequest.getParameter("fileName");
        theResponse.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        theResponse.setContentType("application/pdf");
        connection = connectionProvider.getConnection();
        String path_JRXML = theRequest.getSession().getServletContext()
                .getRealPath("/resources/jasper_reports/newcheck.jrxml");
        JasperReport report = JasperCompileManager.compileReport(path_JRXML);
        JasperPrint print = JasperFillManager.fillReport(report, params, connection);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        JasperExportManager.exportReportToPdfStream(print, baos);
        out.write(baos.toByteArray());
        out.flush();
        out.close();
    } catch (Exception e) {
        itsLogger.error(e.getMessage(), e);
        BankingException aBankingException = new BankingException(e.getMessage(), e);
    } finally {
        try {

            if (connectionProvider != null) {
                connectionProvider.closeConnection(connection);
                connectionProvider = null;
            }

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        printBeanSession.flush();
        printBeanSession.close();
    }
}