Example usage for java.util.zip ZipOutputStream close

List of usage examples for java.util.zip ZipOutputStream close

Introduction

In this page you can find the example usage for java.util.zip ZipOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP output stream as well as the stream being filtered.

Usage

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

@RequestMapping(value = "/createSearchablePDF", method = RequestMethod.POST)
@ResponseBody// w  ww  .  j a va  2s .  c om
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/*from   w  w w.  j a  v  a  2  s  . co 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:cn.edu.zju.acm.onlinejudge.judgeservice.JudgeClientJudgeThread.java

private void zipProblemData(File outputFile, Problem problem)
        throws PersistenceException, JudgeServerErrorException, ProblemDataErrorException {

    try {/*  www. j  a v a 2s.co m*/
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(outputFile));
        try {
            List<Reference> inputFiles = this.referenceDAO.getProblemReferences(problem.getId(),
                    ReferenceType.INPUT);
            List<Reference> outputFiles = this.referenceDAO.getProblemReferences(problem.getId(),
                    ReferenceType.OUTPUT);
            if (inputFiles.size() != outputFiles.size() && inputFiles.size() > 0 && outputFiles.size() > 0) {
                throw new ProblemDataErrorException(
                        "Unequal number of inputs and outputs for problem " + problem.getId());
            }
            for (Reference input : inputFiles) {
                if (input.getContent() == null) {
                    throw new ProblemDataErrorException(
                            "Can not find content for input with reference id " + input.getId());
                }
            }
            for (Reference output : outputFiles) {
                if (output.getContent() == null) {
                    throw new ProblemDataErrorException(
                            "Can not find content for output with reference id " + output.getId());
                }
            }
            Reference specialJudge = null;
            if (problem.isChecker()) {
                List<Reference> specialJudges = this.referenceDAO.getProblemReferences(problem.getId(),
                        ReferenceType.CHECKER_SOURCE);
                if (specialJudges.size() == 0) {
                    throw new ProblemDataErrorException(
                            "Can not find special judge for problem " + problem.getId());
                }
                if (specialJudges.size() > 1) {
                    throw new ProblemDataErrorException(
                            "Find more than one special judge for problem " + problem.getId());
                }
                specialJudge = specialJudges.get(0);
                String contentType = specialJudge.getContentType();
                if (contentType == null) {
                    throw new ProblemDataErrorException(
                            "Can not find source content type for special judge with reference id "
                                    + specialJudge.getId());
                }
                byte[] content = specialJudge.getContent();
                if (content == null) {
                    throw new ProblemDataErrorException(
                            "Can not find source content for special judge with reference id "
                                    + specialJudge.getId());
                }
                if (content.length == 0) {
                    throw new ProblemDataErrorException(
                            "Empty source for special judge with reference id " + specialJudge.getId());
                }
            }
            for (int i = 0; i < inputFiles.size(); i++) {
                zipOut.putNextEntry(new ZipEntry(String.format("%d.in", i + 1)));
                CopyUtils.copy(inputFiles.get(i).getContent(), zipOut);
            }
            for (int i = 0; i < outputFiles.size(); i++) {
                zipOut.putNextEntry(new ZipEntry(String.format("%d.out", i + 1)));
                CopyUtils.copy(outputFiles.get(i).getContent(), zipOut);
            }

            if (specialJudge != null) {
                zipOut.putNextEntry(new ZipEntry(String.format("judge.%s", specialJudge.getContentType())));
                CopyUtils.copy(specialJudge.getContent(), zipOut);
            }
        } finally {
            zipOut.close();
        }
    } catch (IOException e) {
        throw new JudgeServerErrorException("Fail to zip problem data", e);
    }
}

From source file:it.govpay.web.rs.dars.anagrafica.domini.DominiHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }/*w  ww . ja  va  2  s .  c  om*/

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    if (idsToExport == null || idsToExport.size() == 0) {
        List<String> msg = new ArrayList<String>();
        msg.add(Utils.getInstance(this.getLanguage())
                .getMessageFromResourceBundle(this.nomeServizio + ".esporta.erroreSelezioneVuota"));
        throw new ExportException(msg, EsitoOperazione.ERRORE);
    }

    if (idsToExport.size() == 1) {
        return this.esporta(idsToExport.get(0), rawValues, uriInfo, bd, zout);
    }

    String fileName = "Domini.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);

        DominiBD dominiBD = new DominiBD(bd);

        for (Long idDominio : idsToExport) {
            Dominio dominio = dominiBD.getDominio(idDominio);
            String folderName = dominio.getCodDominio();

            IbanAccreditoBD ibanAccreditoDB = new IbanAccreditoBD(bd);
            IbanAccreditoFilter filter = ibanAccreditoDB.newFilter();
            filter.setIdDominio(idDominio);
            List<IbanAccredito> ibans = ibanAccreditoDB.findAll(filter);
            final byte[] contiAccredito = DominioUtils.buildInformativaContoAccredito(dominio, ibans);

            ZipEntry contiAccreditoXml = new ZipEntry(folderName + "/contiAccredito.xml");
            zout.putNextEntry(contiAccreditoXml);
            zout.write(contiAccredito);
            zout.closeEntry();

            final byte[] informativa = DominioUtils.buildInformativaControparte(dominio, true);

            ZipEntry informativaXml = new ZipEntry(folderName + "/informativa.xml");
            zout.putNextEntry(informativaXml);
            zout.write(informativa);
            zout.closeEntry();

        }
        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}

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

@RequestMapping(value = "/extractFixedForm", method = RequestMethod.POST)
@ResponseBody//from   w w  w  .j  a v  a2 s  . c  om
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:de.unikassel.puma.openaccess.sword.SwordService.java

/**
 * collects all informations to send Documents with metadata to repository 
 * @throws SwordException /*from   w  ww  .  j  ava2 s . c om*/
 */
public void submitDocument(PumaData<?> pumaData, User user) throws SwordException {
    log.info("starting sword");
    DepositResponse depositResponse = new DepositResponse(999);
    File swordZipFile = null;

    Post<?> post = pumaData.getPost();

    // -------------------------------------------------------------------------------
    /*
     * retrieve ZIP-FILE
     */
    if (post.getResource() instanceof BibTex) {

        // fileprefix
        String fileID = HashUtils.getMD5Hash(user.getName().getBytes()) + "_"
                + post.getResource().getIntraHash();

        // Destination directory 
        File destinationDirectory = new File(repositoryConfig.getDirTemp() + "/" + fileID);

        // zip-filename
        swordZipFile = new File(destinationDirectory.getAbsoluteFile() + "/" + fileID + ".zip");

        byte[] buffer = new byte[18024];

        log.info("getIntraHash = " + post.getResource().getIntraHash());

        /*
         * get documents
         */

        // At the moment, there are no Documents delivered by method parameter post.
        // retrieve list of documents from database - workaround

        // get documents for post and insert documents into post 
        ((BibTex) post.getResource())
                .setDocuments(retrieveDocumentsFromDatabase(user, post.getResource().getIntraHash()));

        if (((BibTex) post.getResource()).getDocuments().isEmpty()) {
            // Wenn kein PDF da, dann Fehlermeldung ausgeben!!
            log.info("throw SwordException: noPDFattached");
            throw new SwordException("error.sword.noPDFattached");
        }

        try {
            // create directory
            boolean mkdir_success = (new File(destinationDirectory.getAbsolutePath())).mkdir();
            if (mkdir_success) {
                log.info("Directory: " + destinationDirectory.getAbsolutePath() + " created");
            }

            // open zip archive to add files to
            log.info("zipFilename: " + swordZipFile);
            ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(swordZipFile));

            ArrayList<String> fileList = new ArrayList<String>();

            for (final Document document : ((BibTex) post.getResource()).getDocuments()) {

                //getpostdetails
                // get file and store it in hard coded folder "/tmp/"
                //final Document document2 = logic.getDocument(user.getName(), post.getResource().getIntraHash(), document.getFileName());

                // move file to user folder with username_resource-hash as folder name

                // File (or directory) to be copied 
                //File fileToZip = new File(document.getFileHash());

                fileList.add(document.getFileName());

                // Move file to new directory 
                //boolean rename_success = fileToCopy.renameTo(new File(destinationDirectory, fileToMove.getName()));
                /*
                if (!rename_success) { 
                   // File was not successfully moved } 
                   log.info("File was not successfully moved: "+fileToMove.getName());
                }
                */
                ZipEntry zipEntry = new ZipEntry(document.getFileName());

                // Set the compression ratio
                zipOutputStream.setLevel(Deflater.DEFAULT_COMPRESSION);

                String inputFilePath = projectDocumentPath + document.getFileHash().substring(0, 2) + "/"
                        + document.getFileHash();
                FileInputStream in = new FileInputStream(inputFilePath);

                // Add ZIP entry to output stream.
                zipOutputStream.putNextEntry(zipEntry);

                // Transfer bytes from the current file to the ZIP file
                //out.write(buffer, 0, in.read(buffer));

                int len;
                while ((len = in.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }

                zipOutputStream.closeEntry();

                // Close the current file input stream
                in.close();
            }

            // write meta data into zip archive
            ZipEntry zipEntry = new ZipEntry("mets.xml");
            zipOutputStream.putNextEntry(zipEntry);

            // create XML-Document
            // PrintWriter from a Servlet

            MetsBibTexMLGenerator metsBibTexMLGenerator = new MetsBibTexMLGenerator(urlRenderer);
            metsBibTexMLGenerator.setUser(user);
            metsBibTexMLGenerator.setFilenameList(fileList);
            //metsGenerator.setMetadata(metadataMap);
            metsBibTexMLGenerator.setMetadata((PumaData<BibTex>) pumaData);

            //            PumaPost additionalMetadata = new PumaPost();
            //            additionalMetadata.setExaminstitution(null);
            //            additionalMetadata.setAdditionaltitle(null);
            //            additionalMetadata.setExamreferee(null);
            //            additionalMetadata.setPhdoralexam(null);
            //            additionalMetadata.setSponsors(null);
            //            additionalMetadata.setAdditionaltitle(null);   

            //            metsBibTexMLGenerator.setMetadata((Post<BibTex>) post);

            //StreamResult streamResult = new StreamResult(zipOutputStream);

            zipOutputStream.write(metsBibTexMLGenerator.generateMets().getBytes("UTF-8"));

            zipOutputStream.closeEntry();

            // close zip archive  
            zipOutputStream.close();

            log.debug("saved to " + swordZipFile.getPath());

        } catch (MalformedURLException e) {
            // e.printStackTrace();
            log.info("MalformedURLException! " + e.getMessage());
        } catch (IOException e) {
            //e.printStackTrace();
            log.info("IOException! " + e.getMessage());

        } catch (ResourceNotFoundException e) {
            // e.printStackTrace();
            log.warn("ResourceNotFoundException! SwordService-retrievePost");
        }
    }
    /*
     * end of retrieve ZIP-FILE
     */
    //---------------------------------------------------

    /*
     * do the SWORD stuff
     */

    if (null != swordZipFile) {

        // get an instance of SWORD-Client
        Client swordClient = new Client();

        PostMessage swordMessage = new PostMessage();

        // create sword post message

        // message file
        // create directory in temp-folder
        // store post documents there
        // store meta data there in format http://purl.org/net/sword-types/METSDSpaceSIP
        // delete post document files and meta data file

        // add files to zip archive
        // -- send zip archive
        // -- delete zip archive

        swordClient.setServer(repositoryConfig.getHttpServer(), repositoryConfig.getHttpPort());
        swordClient.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordClient.setCredentials(repositoryConfig.getAuthUsername(), repositoryConfig.getAuthPassword());

        // message meta
        swordMessage.setNoOp(false);
        swordMessage.setUserAgent(repositoryConfig.getHttpUserAgent());
        swordMessage.setFilepath(swordZipFile.getAbsolutePath());
        swordMessage.setFiletype("application/zip");
        swordMessage.setFormatNamespace("http://purl.org/net/sword-types/METSDSpaceSIP"); // sets packaging!
        swordMessage.setVerbose(false);

        try {
            // check depositurl against service document
            if (checkServicedokument(retrieveServicedocument(), repositoryConfig.getHttpServicedocumentUrl(),
                    SWORDFILETYPE, SWORDFORMAT)) {
                // transmit sword message (zip file with document metadata and document files
                swordMessage.setDestination(repositoryConfig.getHttpDepositUrl());

                depositResponse = swordClient.postFile(swordMessage);

                /*
                 * 200 OK Used in response to successful GET operations and
                 * to Media Resource Creation operations where X-No-Op is
                 * set to true and the server supports this header.
                 * 
                 * 201 Created
                 * 
                 * 202 Accepted - One of these MUST be used to indicate that
                 * a deposit was successful. 202 Accepted is used when
                 * processing of the data is not yet complete.
                 * 
                 * 
                 * 400 Bad Request - used to indicate that there is some
                 * problem with the request where there is no more
                 * appropriate 4xx code.
                 * 
                 * 401 Unauthorized - In addition to the usage described in
                 * HTTP, servers that support mediated deposit SHOULD use
                 * this status code when the server does not understand the
                 * value given in the X-Behalf-Of header. In this case a
                 * human-readable explanation MUST be provided.
                 * 
                 * 403 Forbidden - indicates that there was a problem making
                 * the deposit, it may be that the depositor is not
                 * authorised to deposit on behalf of the target owner, or
                 * the target owner does not have permission to deposit into
                 * the specified collection.
                 * 
                 * 412 Precondition failed - MUST be returned by server
                 * implementations if a calculated checksum does not match a
                 * value provided by the client in the Content-MD5 header.
                 * 
                 * 415 Unsupported Media Type - MUST be used to indicate
                 * that the format supplied in either a Content-Type header
                 * or in an X-Packaging header or the combination of the two
                 * is not accepted by the server.
                 */

                log.info("throw SwordException: errcode" + depositResponse.getHttpResponse());
                throw new SwordException("error.sword.errcode" + depositResponse.getHttpResponse());

            }

        } catch (SWORDClientException e) {
            log.warn("SWORDClientException: " + e.getMessage() + "\n" + e.getCause() + " / "
                    + swordMessage.getDestination());
            throw new SwordException("error.sword.urlnotaccessable");
        }

    }

}

From source file:it.cnr.icar.eric.server.query.CompressContentQueryFilterPlugin.java

/**
 * This method processes the AdhocQueryRequest in the RequestContext
 *
 * @param context/*from w  w w . j av  a 2 s. c o  m*/
 * A it.cnr.icar.eric.common.spi.RequestContext
 */
public void processRequest(RequestContext context) throws RegistryException {
    try {
        ServerRequestContext serverContext = ServerRequestContext.convert(context);
        Map<?, ?> queryParamsMap = serverContext.getQueryParamsMap();
        int depth = 0;
        String depthString = (String) queryParamsMap.get(CanonicalConstants.CANONICAL_SEARCH_DEPTH_PARAMETER);
        if (depthString != null && depthString.length() > 0) {
            try {
                depth = Integer.parseInt(depthString);
            } catch (Throwable t) {
                log.error(t);
            }
        }
        Iterator<?> resultsItr = serverContext.getQueryResults().iterator();
        Collection<Object> idCollection = new ArrayList<Object>();
        @SuppressWarnings("unused")
        Iterator<Object> idIter = idCollection.iterator();
        File zipFile = null;
        ZipOutputStream zos = null;
        Collection<String> exportedIds = new ArrayList<String>();
        try {
            while (resultsItr.hasNext()) {
                RegistryObjectType ro = (RegistryObjectType) resultsItr.next();
                String id = ro.getId();
                ExtrinsicObjectType eot = null;
                RegistryObjectType rot = null;
                try {
                    rot = QueryManagerFactory.getInstance().getQueryManager().getRegistryObject(serverContext,
                            id, "ExtrinsicObject");
                } catch (ObjectNotFoundException oex) {
                    String msg = ServerResourceBundle.getInstance().getString("message.registryObjectNotFound",
                            new Object[] { id });
                    log.error(msg, oex);
                } catch (Throwable t) {
                    log.error(t);
                }
                if (rot != null) {
                    if (!(rot instanceof ExtrinsicObjectType)) {
                        String msg = ServerResourceBundle.getInstance()
                                .getString("message.expectedExtrinsicObjectNotFound", new Object[] { rot });
                        log.debug(msg);
                    } else {
                        eot = (ExtrinsicObjectType) rot;
                        RepositoryItem ri = (RepositoryItem) context.getRepositoryItemsMap().get(id);
                        if (ri == null) {
                            // Get each artifact from the Repository
                            try {
                                ri = RepositoryManagerFactory.getInstance().getRepositoryManager()
                                        .getRepositoryItem(id);
                            } catch (RepositoryItemNotFoundException rex) {
                                String msg = ServerResourceBundle.getInstance().getString(
                                        "message.RepositoryItemDoesNotExist", new Object[] { rot.getId() });
                                log.warn(msg);
                            } catch (Throwable t) {
                                log.warn(t);
                            }
                        }
                        if (ri == null) {
                            // Check if EO is an element contained in a different EO
                            eot = getContainedExtrinsicObject(eot, serverContext);
                            if (eot != null) {
                                try {
                                    ri = RepositoryManagerFactory.getInstance().getRepositoryManager()
                                            .getRepositoryItem(eot.getId());
                                } catch (RepositoryItemNotFoundException rex) {
                                    String msg = ServerResourceBundle.getInstance().getString(
                                            "message.RepositoryItemDoesNotExist", new Object[] { rot.getId() });
                                    log.warn(msg);
                                } catch (Throwable t) {
                                    log.warn(t);
                                }
                            }
                        }
                        if (ri != null) {
                            if (zipFile == null) {
                                zipFile = getZipFile(serverContext);
                                zos = getZipOutputStream(zipFile);
                            }
                            // Store each RI in the compressed content zip file
                            addRepositoryItemToZipFile(ri, zos, serverContext, eot, exportedIds, depth);
                        }
                    }
                }
            }
        } finally {
            if (zos != null) {
                try {
                    zos.close();
                } catch (Throwable t) {
                    zos = null;
                }
            }
        }
        ArrayList<ExtrinsicObjectType> results = new ArrayList<ExtrinsicObjectType>();
        if (zipFile != null) {

            // Create an initialze the compressed content zip file EO
            ExtrinsicObjectType ebExtrinsicObjectType = BindingUtility.getInstance().rimFac
                    .createExtrinsicObjectType();
            String lid = "urn:uuid:" + UUIDFactory.getInstance().newUUID().toString();
            String zipFileName = zipFile.getName();
            ebExtrinsicObjectType.setId(lid);
            ebExtrinsicObjectType.setLid(lid);
            ebExtrinsicObjectType.setName(bu.createInternationalStringType(zipFileName));
            SlotType1 slot = bu.rimFac.createSlotType1();
            slot.setName(BindingUtility.FREEBXML_REGISTRY_FILTER_QUERY_COMPRESSCONTENT_FILENAME);
            ValueListType vlt = bu.rimFac.createValueListType();
            //                Value value = bu.rimFac.createValue(zipFileName);
            vlt.getValue().add(zipFileName);
            slot.setValueList(vlt);
            ebExtrinsicObjectType.getSlot().add(slot);
            ebExtrinsicObjectType.setMimeType("application/zip");
            ebExtrinsicObjectType.setObjectType(CanonicalConstants.CANONICAL_OBJECT_TYPE_ID_ExtrinsicObject);
            ebExtrinsicObjectType.setContentVersionInfo(bu.rimFac.createVersionInfoType());

            results.add(ebExtrinsicObjectType);
        }
        serverContext.setSpecialQueryResults(results);
    } catch (RegistryException re) {
        throw re;
    } catch (Throwable t) {
        throw new RegistryException(t);
    }
}

From source file:cross.io.misc.WorkflowZipper.java

/**
 * Saves the currently assigned workflow elements, matching currently
 * assigned FileFilter to File. Marks all files for deletion on exit.
 *
 * @param f the file to save to/*from  w  w w . jav a2  s .  c  o m*/
 * @return true if the workflow was zipped, false otherwise
 * @throws RuntimeException if IOExceptions are encountered
 */
public boolean save(final File f) {
    if (this.zipWorkflow) {
        HashSet<String> zipEntries = new HashSet<>();
        final int bufsize = 1024;
        final File zipFile = f;
        ZipOutputStream zos;
        try {
            final FileOutputStream fos = new FileOutputStream(zipFile);
            zos = new ZipOutputStream(new BufferedOutputStream(fos));
            log.info("Created zip output stream");
            final byte[] input_buffer = new byte[bufsize];
            File basedir = FileTools.prependDefaultDirsWithPrefix("", null, this.iw.getStartupDate());
            if (this.deleteOnExit) {
                log.info("marked basedir for deletion on exit: {}", basedir);
                basedir.deleteOnExit();
            }
            if (flatten) {
                log.info("setting basedir to parent file: {}", basedir.getParentFile());
                basedir = basedir.getParentFile();
                final Iterator<IWorkflowResult> iter = this.iw.getResults();
                while (iter.hasNext()) {
                    final IWorkflowResult iwr = iter.next();
                    if (iwr instanceof IWorkflowFileResult) {
                        final IWorkflowFileResult iwfr = (IWorkflowFileResult) iwr;
                        final File file = iwfr.getFile();
                        log.info("Retrieving file result {}", file);
                        // mark file for deletion
                        final File parent = file.getParentFile();
                        log.info("Retrieving parent of file result {}", parent);
                        // Also delete the parent directory in which file was
                        // contained,
                        // unless it is the base directory + possibly additional
                        // defaultDirs
                        if (parent.getAbsolutePath().startsWith(basedir.getAbsolutePath())
                                && !parent.getAbsolutePath().equals(basedir.getAbsolutePath())) {
                            log.info("Marking file and parent for deletion");
                            if (this.deleteOnExit) {
                                parent.deleteOnExit();
                                file.deleteOnExit();
                            }
                        }
                        if (file.getAbsolutePath().startsWith(basedir.getAbsolutePath())) {
                            log.info("Marking file for deletion");
                            if (this.deleteOnExit) {
                                file.deleteOnExit();
                            }
                        }
                        if ((this.ff != null) && !this.ff.accept(file)) {
                            // Skip file if file filter does not accept it
                            continue;
                        } else {
                            log.info("Adding zip entry!");
                            addZipEntry(bufsize, zos, input_buffer, file, zipEntries);
                        }
                    }

                }
            } else {
                LinkedList<File> files = new LinkedList<>(Arrays.asList(basedir.listFiles(ff)));
                File archiveBase = basedir.getParentFile();
                while (!files.isEmpty()) {
                    File currentFile = files.removeFirst();
                    if (currentFile.isDirectory()) {
                        files.addAll(Arrays.asList(currentFile.listFiles(ff)));
                    } else {
                        try {
                            String relativePath = FileTools.getRelativeFile(archiveBase, currentFile).getPath()
                                    .replaceAll("\\\\", "/");
                            log.info("Adding zip entry for {} below {}", relativePath, archiveBase);
                            addRelativeZipEntry(bufsize, zos, input_buffer, relativePath, currentFile,
                                    zipEntries);
                        } catch (Exception ex) {
                            log.warn("Caught exception while retrieving relative path:", ex);
                        }
                    }
                    if (this.deleteOnExit) {
                        log.info("Marking file for deletion");
                        currentFile.deleteOnExit();
                    }
                }
            }

            try {
                zos.flush();
                zos.close();
            } catch (final IOException e) {
                throw new RuntimeException(e);
            }
        } catch (final IOException e) {
            throw new RuntimeException(e);
        }
        return true;
    } else {
        log.debug("Configured to not zip Workflow results!");
        return false;
    }
}

From source file:com.joliciel.csvLearner.CSVEventListWriter.java

public void writeFile(GenericEvents events) {
    try {//from  w ww. j  a  v  a 2  s  .c o m
        LOG.debug("writeFile: " + file.getName());
        file.delete();
        file.createNewFile();
        if (file.getName().endsWith(".zip"))
            isZip = true;
        Writer writer = null;
        ZipOutputStream zos = null;
        try {
            if (isZip) {
                zos = new ZipOutputStream(new FileOutputStream(file, false));
                writer = new BufferedWriter(new OutputStreamWriter(zos));
            } else {
                writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF8"));
            }
            Set<String> features = new TreeSet<String>();
            if (!filePerEvent) {
                if (isZip) {
                    zos.putNextEntry(new ZipEntry(
                            file.getName().substring(0, file.getName().lastIndexOf('.')) + ".csv"));
                }

                for (GenericEvent event : events) {
                    if (LOG.isTraceEnabled())
                        LOG.trace("Writing event: " + event.getIdentifier());
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }
                }

                writer.append("ID,");

                if (includeOutcomes)
                    writer.append("outcome,");
                for (String feature : features) {
                    writer.append(CSVFormatter.format(feature) + ",");
                }

                writer.append("\n");
                writer.flush();
            }

            for (GenericEvent event : events) {
                if (filePerEvent) {
                    features = new TreeSet<String>();
                    for (String feature : event.getFeatures()) {
                        int classIndex = feature.indexOf(CSVLearner.NOMINAL_MARKER);
                        if (classIndex < 0 || denominalise)
                            features.add(feature);
                        else
                            features.add(feature.substring(0, classIndex));
                    }

                    if (isZip)
                        zos.putNextEntry(new ZipEntry(event.getIdentifier() + ".csv"));
                    writer.append("ID,");
                    if (includeOutcomes)
                        writer.append("outcome,");

                    for (String feature : features) {
                        writer.append(CSVFormatter.format(feature) + ",");
                    }

                    writer.append("\n");
                    writer.flush();
                }
                writer.append(CSVFormatter.format(identifierPrefix + event.getIdentifier()) + ",");
                if (includeOutcomes)
                    writer.append(CSVFormatter.format(event.getOutcome()) + ",");

                for (String feature : features) {
                    Integer featureIndexObj = event.getFeatureIndex(feature);
                    int featureIndex = featureIndexObj == null ? -1 : featureIndexObj.intValue();

                    if (featureIndex < 0) {
                        writer.append(missingValueString + ",");
                    } else {
                        String eventFeature = event.getFeatures().get(featureIndex);
                        if (!eventFeature.equals(feature)) {
                            int classIndex = eventFeature.indexOf(CSVLearner.NOMINAL_MARKER);
                            String clazz = eventFeature
                                    .substring(classIndex + CSVLearner.NOMINAL_MARKER.length());
                            writer.append(CSVFormatter.format(clazz) + ",");
                        } else {
                            double value = event.getWeights().get(featureIndex);
                            writer.append(CSVFormatter.format(value) + ",");
                        }
                    }
                }
                writer.append("\n");
                writer.flush();
                if (filePerEvent && isZip)
                    zos.closeEntry();
            }
            if (!filePerEvent && isZip)
                zos.closeEntry();
        } finally {
            if (zos != null) {
                zos.flush();
                zos.close();
            }
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:it.govpay.web.rs.dars.monitoraggio.incassi.IncassiHandler.java

@Override
public String esporta(List<Long> idsToExport, List<RawParamValue> rawValues, UriInfo uriInfo, BasicBD bd,
        ZipOutputStream zout) throws WebApplicationException, ConsoleException, ExportException {
    StringBuffer sb = new StringBuffer();
    if (idsToExport != null && idsToExport.size() > 0) {
        for (Long long1 : idsToExport) {

            if (sb.length() > 0) {
                sb.append(", ");
            }//ww w.ja va 2 s  .co  m

            sb.append(long1);
        }
    }

    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";

    int numeroZipEntries = 0;
    String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();

    //      if(idsToExport.size() == 1) {
    //         return this.esporta(idsToExport.get(0), uriInfo, bd, zout);
    //      } 

    String fileName = "Export.zip";
    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        // Operazione consentita solo ai ruoli con diritto di lettura
        this.darsService.checkDirittiServizioLettura(bd, this.funzionalita);
        int limit = ConsoleProperties.getInstance().getNumeroMassimoElementiExport();
        boolean simpleSearch = Utils.containsParameter(rawValues, DarsService.SIMPLE_SEARCH_PARAMETER_ID);
        IncassiBD incassiBD = new IncassiBD(bd);
        IncassoFilter filter = incassiBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdIncasso(idsToExport);

        boolean eseguiRicerca = this.popolaFiltroRicerca(rawValues, bd, simpleSearch, filter);

        if (!eseguiRicerca) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.operazioneNonPermessa"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        long count = incassiBD.count(filter);

        if (count < 1) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage())
                    .getMessageFromResourceBundle(this.nomeServizio + ".esporta.nessunElementoDaEsportare"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        if (count > ConsoleProperties.getInstance().getNumeroMassimoElementiExport()) {
            List<String> msg = new ArrayList<String>();
            msg.add(Utils.getInstance(this.getLanguage()).getMessageFromResourceBundle(
                    this.nomeServizio + ".esporta.numeroElementiDaEsportareSopraSogliaMassima"));
            throw new ExportException(msg, EsitoOperazione.ERRORE);
        }

        filter.setOffset(0);
        filter.setLimit(limit);
        FilterSortWrapper fsw = new FilterSortWrapper();
        fsw.setField(it.govpay.orm.Incasso.model().DATA_ORA_INCASSO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Incasso> findAll = incassiBD.findAll(filter);

        for (Incasso incasso : findAll) {
            Applicazione applicazione = incasso.getApplicazione(incassiBD);
            List<Pagamento> pagamenti = incasso.getPagamenti(incassiBD);
            List<it.govpay.model.Pagamento> pagamentiList = new ArrayList<it.govpay.model.Pagamento>();
            pagamentiList.addAll(pagamenti);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IncassoPdf.getPdfIncasso(pathLoghi, incasso, pagamentiList, applicazione, baos, this.log);
            String incassoPdfEntryName = incasso.getTrn() + ".pdf";
            numeroZipEntries++;
            ZipEntry rtPdf = new ZipEntry(incassoPdfEntryName);
            zout.putNextEntry(rtPdf);
            zout.write(baos.toByteArray());
            zout.closeEntry();
        }

        // se non ho inserito nessuna entry
        if (numeroZipEntries == 0) {
            String noEntriesTxt = "/README";
            ZipEntry entryTxt = new ZipEntry(noEntriesTxt);
            zout.putNextEntry(entryTxt);
            zout.write("Non sono state trovate informazioni sugli incassi selezionati.".getBytes());
            zout.closeEntry();
        }

        zout.flush();
        zout.close();

        this.log.info("Esecuzione " + methodName + " completata.");

        return fileName;
    } catch (WebApplicationException e) {
        throw e;
    } catch (Exception e) {
        throw new ConsoleException(e);
    }
}