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.orange.mmp.midlet.MidletManager.java

/**
 * Get Midlet for download./*w  w w .  j  av  a2  s  . c  o  m*/
 * @param appId            The midlet main application ID
 * @param mobile          The mobile to use
 * @param isMidletSigned   Boolean indicating if the midlet is signed (true), unsigned (false), to sign (null)
 * @throws IOException
 */
@SuppressWarnings("unchecked")
public ByteArrayOutputStream getJar(String appId, Mobile mobile, Boolean isMidletSigned) throws MMPException {
    if (appId == null)
        appId = ServiceManager.getInstance().getDefaultService().getId();

    //Search in Cache first
    String jarKey = appId + isMidletSigned + mobile.getKey();

    if (this.midletCache.isKeyInCache(jarKey)) {
        return (ByteArrayOutputStream) this.midletCache.get(jarKey).getValue();
    }

    Object extraCSSJadAttr = null;

    //Not found, build the JAR
    ByteArrayOutputStream output = null;
    ZipOutputStream zipOut = null;
    ZipInputStream zipIn = null;
    InputStream resourceStream = null;
    try {
        Midlet midlet = new Midlet();
        midlet.setType(mobile.getMidletType());
        Midlet[] midlets = (Midlet[]) DaoManagerFactory.getInstance().getDaoManager().getDao("midlet")
                .find(midlet);
        if (midlets.length == 0)
            throw new MMPException("Midlet type not found : " + mobile.getMidletType());
        else
            midlet = midlets[0];

        //Get navigation widget
        Widget appWidget = WidgetManager.getInstance().getWidget(appId, mobile.getBranchId());
        if (appWidget == null) {
            // Use Default if not found
            appWidget = WidgetManager.getInstance().getWidget(appId);
        }
        List<URL> embeddedResources = WidgetManager.getInstance().findWidgetResources("/m4m/", "*", appId,
                mobile.getBranchId(), false);
        output = new ByteArrayOutputStream();
        zipOut = new ZipOutputStream(output);
        zipIn = new ZipInputStream(new FileInputStream(new File(new URI(midlet.getJarLocation()))));

        ZipEntry entry;
        while ((entry = zipIn.getNextEntry()) != null) {
            zipOut.putNextEntry(entry);

            // Manifest found, modify it before delivery
            if (entry.getName().equals(Constants.JAR_MANIFEST_ENTRY) && appWidget != null) {
                Manifest midletManifest = new Manifest(zipIn);

                // TODO ? Remove optional permissions if midlet is not signed
                if (isMidletSigned != null && !isMidletSigned)
                    midletManifest.getMainAttributes().remove(Constants.JAD_PARAMETER_OPT_PERMISSIONS);

                midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_APPNAME,
                        appWidget.getName());
                String launcherLine = midletManifest.getMainAttributes()
                        .getValue(Constants.JAD_PARAMETER_LAUNCHER);
                Matcher launcherLineMatcher = launcherPattern.matcher(launcherLine);
                if (launcherLineMatcher.matches()) {
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName().concat(", ").concat(launcherLineMatcher.group(2)).concat(", ")
                                    .concat(launcherLineMatcher.group(3)));
                } else
                    midletManifest.getMainAttributes().putValue(Constants.JAD_PARAMETER_LAUNCHER,
                            appWidget.getName());

                // Add/Modify/Delete MANIFEST parameters according to mobile rules
                JadAttributeAction[] jadActions = mobile.getJadAttributeActions();
                for (JadAttributeAction jadAction : jadActions) {
                    if (jadAction.getInManifest().equals(ApplyCase.ALWAYS)
                            || (isMidletSigned != null && isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.SIGNED))
                            || (isMidletSigned != null && !isMidletSigned
                                    && jadAction.getInManifest().equals(ApplyCase.UNSIGNED))) {
                        Attributes.Name attrName = new Attributes.Name(jadAction.getAttribute());
                        boolean exists = midletManifest.getMainAttributes().get(attrName) != null;
                        if (jadAction.isAddAction() || jadAction.isModifyAction()) {
                            if (exists || !jadAction.isStrict())
                                midletManifest.getMainAttributes().putValue(jadAction.getAttribute(),
                                        jadAction.getValue());
                        } else if (jadAction.isDeleteAction() && exists)
                            midletManifest.getMainAttributes().remove(attrName);
                    }
                }

                //Retrieve MeMo CSS extra attribute
                extraCSSJadAttr = midletManifest.getMainAttributes()
                        .get(new Attributes.Name(Constants.JAD_PARAMETER_MEMO_EXTRA_CSS));

                midletManifest.write(zipOut);
            }
            //Other files of Midlet
            else {
                IOUtils.copy(zipIn, zipOut);
            }
            zipIn.closeEntry();
            zipOut.closeEntry();
        }

        if (embeddedResources != null) {
            for (URL resourceUrl : embeddedResources) {
                resourceStream = resourceUrl.openConnection().getInputStream();
                String resourcePath = resourceUrl.getPath();
                entry = new ZipEntry(resourcePath.substring(resourcePath.lastIndexOf("/") + 1));
                entry.setTime(MIDLET_LAST_MODIFICATION_DATE);
                zipOut.putNextEntry(entry);
                IOUtils.copy(resourceStream, zipOut);
                zipOut.closeEntry();
                resourceStream.close();
            }
        }

        //Put JAR in cache for next uses
        this.midletCache.set(new Element(jarKey, output));

        //If necessary, add special CSS file if specified in JAD attributes
        if (extraCSSJadAttr != null) {
            String extraCSSSheetName = (String) extraCSSJadAttr;
            //Get resource stream
            resourceStream = WidgetManager.getInstance().getWidgetResource(
                    extraCSSSheetName + "/" + this.cssSheetsBundleName, mobile.getBranchId());

            if (resourceStream == null)
                throw new DataAccessResourceFailureException("no CSS sheet named " + extraCSSSheetName + " in "
                        + this.cssSheetsBundleName + " special bundle");

            //Append CSS sheet file into JAR
            entry = new ZipEntry(new File(extraCSSSheetName).getName());
            entry.setTime(MidletManager.MIDLET_LAST_MODIFICATION_DATE);
            zipOut.putNextEntry(entry);
            IOUtils.copy(resourceStream, zipOut);
            zipOut.closeEntry();
            resourceStream.close();
        }

        return output;

    } catch (IOException ioe) {
        throw new MMPException(ioe);
    } catch (URISyntaxException use) {
        throw new MMPException(use);
    } catch (DataAccessException dae) {
        throw new MMPException(dae);
    } finally {
        try {
            if (output != null)
                output.close();
            if (zipIn != null)
                zipIn.close();
            if (zipOut != null)
                zipOut.close();
            if (resourceStream != null)
                resourceStream.close();
        } catch (IOException ioe) {
            //NOP
        }
    }
}

From source file:edu.harvard.iq.dvn.core.web.servlet.FileDownloadServlet.java

private void zipMultipleFiles(HttpServletRequest req, HttpServletResponse res, VDCUser user, VDC vdc,
        UserGroup ipUserGroup) {//from w  w  w  .jav a  2s  . c o  m
    // a request for a zip-packaged multiple file archive.

    String fileId = req.getParameter("fileId");
    String studyId = req.getParameter("studyId");
    String versionNumber = req.getParameter("versionNumber");
    System.out.print("zip multiple files version number" + versionNumber);
    Study study = null;
    Collection files = new ArrayList();
    boolean createDirectoriesForCategories = false;

    String fileManifest = "";

    String sessionId = null;
    javax.servlet.http.Cookie cookies[] = req.getCookies();

    for (int i = 0; i < cookies.length; i++) {
        if ("JSESSIONID".equals(cookies[i].getName())) {
            sessionId = cookies[i].getValue();
        }
    }

    if (sessionId == null || "".equals(sessionId)) {
        // if there's no JSESSIONID, we'll use the vdcSession id, for 
        // logging the download counts: 
        String[] stringArray = vdcSession.toString().toString().split("@");
        sessionId = stringArray[1];
    }

    if (fileId != null) {
        String[] idTokens = fileId.split(",");

        for (String tok : idTokens) {
            StudyFile sf;
            try {
                sf = studyFileService.getStudyFile(new Long(tok));
                files.add(sf);
            } catch (Exception ex) {
                fileManifest = fileManifest + tok + " DOES NOT APPEAR TO BE A VALID FILE ID;\r\n";
            }
        }
    } else if (studyId != null) {
        try {
            study = studyService.getStudy(new Long(studyId));
            files = study.getStudyFiles();
            createDirectoriesForCategories = true;
        } catch (Exception ex) {
            if (ex.getCause() instanceof IllegalArgumentException) {
                createErrorResponse404(res);
                return;
            }
        }
    } else {
        createErrorResponse404(res);
        return;
    }

    // check for restricted files
    Iterator iter = files.iterator();
    while (iter.hasNext()) {
        StudyFile file = (StudyFile) iter.next();
        if (file.isFileRestrictedForUser(user, ipUserGroup)) {
            fileManifest = fileManifest + file.getFileName() + " IS RESTRICTED AND CANNOT BE DOWNLOADED\r\n";
            iter.remove();
        }
    }

    if (files.size() == 0) {
        createErrorResponse403(res);
        return;
    }

    Long sizeLimit = Long.valueOf(104857600);
    // that's the default of 100 MB.

    Long sizeTotal = Long.valueOf(0);

    // this is the total limit of the size of all the files we
    // are packaging. if exceeded, we stop packaging files and add
    // a note to the manifest explaining what happened.
    // the value above is the default. a different value can
    // be set with a JVM option.

    String sizeLimitOption = System.getProperty("dvn.batchdownload.limit");

    if (sizeLimitOption != null) {
        Long sizeOptionValue = new Long(sizeLimitOption);
        if (sizeOptionValue > 0) {
            sizeLimit = sizeOptionValue;
        }
    }

    FileDownloadObject remoteDownload = null;

    // now create zip stream
    try {
        // set content type:
        res.setContentType("application/zip");

        // create zipped output stream:

        OutputStream out = res.getOutputStream();
        ZipOutputStream zout = new ZipOutputStream(out);

        List nameList = new ArrayList(); // used to check for duplicates
        List successList = new ArrayList();

        iter = files.iterator();

        while (iter.hasNext()) {
            int fileSize = 0;
            StudyFile file = (StudyFile) iter.next();

            if (sizeTotal < sizeLimit) {
                InputStream in = null;

                String varHeaderLine = null;
                String dbContentType = file.getFileType();

                if (dbContentType != null && dbContentType.equals("text/tab-separated-values")
                        && file.isSubsettable()) {
                    List datavariables = ((TabularDataFile) file).getDataTable().getDataVariables();
                    varHeaderLine = generateVariableHeader(datavariables);
                }

                if (dbContentType == null) {
                    dbContentType = "unknown filetype;";
                }

                Boolean Success = true;

                if (file.isRemote()) {

                    // do the http magic;
                    // remote files may be subject to complex authentication and
                    // authorization.
                    // And for that we have a special method...

                    remoteDownload = initiateRemoteDownload(file, req);

                    if (remoteDownload.getStatus() != 200) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        if (remoteDownload.getInputStream() != null) {
                            remoteDownload.getInputStream().close();
                        }

                        remoteDownload.releaseConnection();

                        Success = false;
                    } else {
                        in = remoteDownload.getInputStream();
                    }
                } else {
                    in = getLocalFileAsStream(file);
                    if (in == null) {
                        fileManifest = fileManifest + file.getFileName() + " (" + dbContentType
                                + ") COULD NOT be downloaded because an I/O error has occured. \r\n";

                        Success = false;
                    }
                }

                if (Success) {
                    // String zipEntryName = file.getFileName();

                    // get file name and category according to study version number chosen by user 

                    Long versionNum = null;
                    if (versionNumber != null)
                        versionNum = Long.valueOf(versionNumber).longValue();
                    String zipEntryName = file.getFileName(versionNum);

                    zipEntryName = checkZipEntryName(zipEntryName, nameList);

                    // ZipEntry e = new ZipEntry(zipEntryName);

                    String zipEntryDirectoryName = file.getCategory(versionNum);
                    ZipEntry e = new ZipEntry(zipEntryDirectoryName + "/" + zipEntryName);

                    zout.putNextEntry(e);

                    if (varHeaderLine != null) {
                        byte[] headerBuffer = varHeaderLine.getBytes();
                        zout.write(headerBuffer);
                        fileSize += (headerBuffer.length);
                    }

                    byte[] dataBuffer = new byte[8192];

                    int i = 0;
                    while ((i = in.read(dataBuffer)) > 0) {
                        zout.write(dataBuffer, 0, i);
                        fileSize += i;
                        out.flush();
                    }
                    in.close();
                    zout.closeEntry();

                    if (dbContentType == null) {
                        dbContentType = "unknown filetype;";
                    }

                    fileManifest = fileManifest + file.getFileName() + " (" + dbContentType + ") " + fileSize
                            + " bytes.\r\n";

                    if (fileSize > 0) {
                        successList.add(file.getId());
                        sizeTotal += Long.valueOf(fileSize);
                    }

                    // if this was a remote stream, let's close
                    // the connection properly:

                    if (remoteDownload != null) {
                        remoteDownload.releaseConnection();
                    }
                }
            } else {
                fileManifest = fileManifest + file.getFileName()
                        + " skipped because the total size of the download bundle exceeded the limit of "
                        + sizeLimit + " bytes.\r\n";
            }
        }

        // finally, let's create the manifest entry:

        ZipEntry e = new ZipEntry("MANIFEST.TXT");

        zout.putNextEntry(e);
        zout.write(fileManifest.getBytes());
        zout.closeEntry();

        zout.close();

        // and finally finally, we can now increment the download
        // counts on all the files successfully zipped:

        Iterator it = successList.iterator();
        while (it.hasNext()) {
            Long fid = (Long) it.next();
            StudyFile file = studyFileService.getStudyFile(new Long(fid));
            Long versionNum = null;
            if (versionNumber != null)
                versionNum = Long.valueOf(versionNumber).longValue();
            System.out.print("versionNumber " + versionNumber);
            StudyVersion sv = file.getStudy().getStudyVersionByNumber(versionNum);
            GuestBookResponse guestbookResponse = (GuestBookResponse) vdcSession.getGuestbookResponseMap()
                    .get("guestBookResponse_" + file.getStudy().getId());
            if (guestbookResponse == null) {
                //need to set up dummy network response
                guestbookResponse = guestBookResponseServiceBean.initNetworkGuestBookResponse(file.getStudy(),
                        file, vdcSession.getLoginBean());
            }
            guestbookResponse.setStudyVersion(sv);
            guestbookResponse.setSessionId(sessionId);

            String friendlyFormatType = FileUtil.getUserFriendlyTypeForMime(file.getFileType());

            guestbookResponse.setDownloadtype("File Download (as Zip archive) - " + friendlyFormatType);

            if (vdc != null) {
                studyService.incrementNumberOfDownloads(fid, vdc.getId(),
                        (GuestBookResponse) guestbookResponse);
            } else {
                studyService.incrementNumberOfDownloads(fid, (Long) null,
                        (GuestBookResponse) guestbookResponse);
            }
        }

    } catch (IOException ex) {
        // if we caught an exception *here*, it means something
        // catastrophic has happened while packaging the zip archive
        // itself (I/O errors on individual files would be caught
        // above); so there's not much we can do except print a
        // generic error message:

        String errorMessage = "An unknown I/O error has occured while generating a Zip archive of multiple data files. Unfortunately, no further diagnostic information on the nature of the problem is avaiable to the Application at this point. It is possible that the problem was caused by a temporary network error. Please try again later and if the problem persists, report it to your DVN technical support contact.";
        createErrorResponse403(res);

        if (remoteDownload != null) {
            remoteDownload.releaseConnection();
        }
    }
}

From source file:fr.cirad.mgdb.exporting.individualoriented.DARwinExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, Collection<File> individualExportFiles,
        boolean fDeleteSampleExportFilesOnExit, ProgressIndicator progress, DBCursor markerCursor,
        Map<Comparable, Comparable> markerSynonyms, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    GenotypingProject aProject = mongoTemplate.findOne(
            new Query(Criteria.where(GenotypingProject.FIELDNAME_PLOIDY_LEVEL).exists(true)),
            GenotypingProject.class);
    if (aProject == null)
        LOG.warn("Unable to find a project containing ploidy level information! Assuming ploidy level is 2.");

    int ploidy = aProject == null ? 2 : aProject.getPloidyLevel();

    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    int markerCount = markerCursor.count();

    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }/*from   ww  w  .  ja va 2s . c  om*/
        }

    String exportName = sModule + "_" + markerCount + "variants_" + individualExportFiles.size()
            + "individuals";

    StringBuffer donFileContents = new StringBuffer(
            "@DARwin 5.0 - DON -" + LINE_SEPARATOR + individualExportFiles.size() + "\t" + 1 + LINE_SEPARATOR
                    + "N" + "\t" + "individual" + LINE_SEPARATOR);

    int count = 0;
    String missingGenotype = "";
    for (int j = 0; j < ploidy; j++)
        missingGenotype += "\tN";

    zos.putNextEntry(new ZipEntry(exportName + ".var"));
    zos.write(("@DARwin 5.0 - ALLELIC - " + ploidy + LINE_SEPARATOR + individualExportFiles.size() + "\t"
            + markerCount * ploidy + LINE_SEPARATOR + "N").getBytes());

    DBCursor markerCursorCopy = markerCursor.copy(); // dunno how expensive this is, but seems safer than keeping all IDs in memory at any time

    short nProgress = 0, nPreviousProgress = 0;
    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;
    markerCursorCopy.batchSize(nChunkSize);

    int nMarkerIndex = 0;
    while (markerCursorCopy.hasNext()) {
        DBObject exportVariant = markerCursorCopy.next();
        Comparable markerId = (Comparable) exportVariant.get("_id");

        if (markerSynonyms != null) {
            Comparable syn = markerSynonyms.get(markerId);
            if (syn != null)
                markerId = syn;
        }
        for (int j = 0; j < ploidy; j++)
            zos.write(("\t" + markerId).getBytes());
    }

    TreeMap<Integer, Comparable> problematicMarkerIndexToNameMap = new TreeMap<Integer, Comparable>();
    ArrayList<String> distinctAlleles = new ArrayList<String>(); // the index of each allele will be used as its code
    int i = 0;
    for (File f : individualExportFiles) {
        BufferedReader in = new BufferedReader(new FileReader(f));
        try {
            String individualId, line = in.readLine(); // read sample id

            if (line != null)
                individualId = line;
            else
                throw new Exception("Unable to read first line of temp export file " + f.getName());

            donFileContents.append(++count + "\t" + individualId + LINE_SEPARATOR);

            zos.write((LINE_SEPARATOR + count).getBytes());
            nMarkerIndex = 0;

            while ((line = in.readLine()) != null) {
                List<String> genotypes = MgdbDao.split(line, "|");
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                int highestGenotypeCount = 0;
                String mostFrequentGenotype = null;
                for (String genotype : genotypes) {
                    if (genotype.length() == 0)
                        continue; /* skip missing genotypes */

                    int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                    if (gtCount > highestGenotypeCount) {
                        highestGenotypeCount = gtCount;
                        mostFrequentGenotype = genotype;
                    }
                    genotypeCounts.put(genotype, gtCount);
                }

                if (genotypeCounts.size() > 1) {
                    warningFileWriter.write("- Dissimilar genotypes found for variant __" + nMarkerIndex
                            + "__, individual " + individualId + ". Exporting most frequent: "
                            + mostFrequentGenotype + "\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String codedGenotype = "";
                if (mostFrequentGenotype != null)
                    for (String allele : mostFrequentGenotype.split(" ")) {
                        if (!distinctAlleles.contains(allele))
                            distinctAlleles.add(allele);
                        codedGenotype += "\t" + distinctAlleles.indexOf(allele);
                    }
                else
                    codedGenotype = missingGenotype.replaceAll("N", "-1"); // missing data is coded as -1
                zos.write(codedGenotype.getBytes());

                nMarkerIndex++;
            }
        } catch (Exception e) {
            LOG.error("Error exporting data", e);
            progress.setError("Error exporting data: " + e.getClass().getSimpleName()
                    + (e.getMessage() != null ? " - " + e.getMessage() : ""));
            return;
        } finally {
            in.close();
        }

        if (progress.hasAborted())
            return;

        nProgress = (short) (++i * 100 / individualExportFiles.size());
        if (nProgress > nPreviousProgress) {
            //            LOG.debug("============= doDARwinExport (" + i + "): " + nProgress + "% =============");
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }

        if (!f.delete()) {
            f.deleteOnExit();
            LOG.info("Unable to delete tmp export file " + f.getAbsolutePath());
        }
    }

    zos.putNextEntry(new ZipEntry(exportName + ".don"));
    zos.write(donFileContents.toString().getBytes());

    // now read variant names for those that induced warnings
    nMarkerIndex = 0;
    markerCursor.batchSize(nChunkSize);
    while (markerCursor.hasNext()) {
        DBObject exportVariant = markerCursor.next();
        if (problematicMarkerIndexToNameMap.containsKey(nMarkerIndex)) {
            Comparable markerId = (Comparable) exportVariant.get("_id");

            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(markerId);
                if (syn != null)
                    markerId = syn;
            }
            for (int j = 0; j < ploidy; j++)
                zos.write(("\t" + markerId).getBytes());

            problematicMarkerIndexToNameMap.put(nMarkerIndex, markerId);
        }
    }

    warningFileWriter.close();
    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            for (Integer aMarkerIndex : problematicMarkerIndexToNameMap.keySet())
                sLine = sLine.replaceAll("__" + aMarkerIndex + "__",
                        problematicMarkerIndexToNameMap.get(aMarkerIndex).toString());
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:fr.cirad.mgdb.exporting.individualoriented.PLinkExportHandler.java

@Override
public void exportData(OutputStream outputStream, String sModule, Collection<File> individualExportFiles,
        boolean fDeleteSampleExportFilesOnExit, ProgressIndicator progress, DBCursor markerCursor,
        Map<Comparable, Comparable> markerSynonyms, Map<String, InputStream> readyToExportFiles)
        throws Exception {
    File warningFile = File.createTempFile("export_warnings_", "");
    FileWriter warningFileWriter = new FileWriter(warningFile);

    ZipOutputStream zos = new ZipOutputStream(outputStream);

    if (readyToExportFiles != null)
        for (String readyToExportFile : readyToExportFiles.keySet()) {
            zos.putNextEntry(new ZipEntry(readyToExportFile));
            InputStream inputStream = readyToExportFiles.get(readyToExportFile);
            byte[] dataBlock = new byte[1024];
            int count = inputStream.read(dataBlock, 0, 1024);
            while (count != -1) {
                zos.write(dataBlock, 0, count);
                count = inputStream.read(dataBlock, 0, 1024);
            }//w  ww  . j  a v a 2s .c om
        }

    MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule);
    int markerCount = markerCursor.count();

    String exportName = sModule + "_" + markerCount + "variants_" + individualExportFiles.size()
            + "individuals";
    zos.putNextEntry(new ZipEntry(exportName + ".ped"));

    TreeMap<Integer, Comparable> problematicMarkerIndexToNameMap = new TreeMap<Integer, Comparable>();
    short nProgress = 0, nPreviousProgress = 0;
    int i = 0;
    for (File f : individualExportFiles) {
        BufferedReader in = new BufferedReader(new FileReader(f));
        try {
            String individualId, line = in.readLine(); // read sample id
            if (line != null) {
                individualId = line;
                String population = getIndividualPopulation(sModule, line);
                String individualInfo = (population == null ? "." : population) + " " + individualId;
                zos.write((individualInfo + " 0 0 0 " + getIndividualGenderCode(sModule, individualId))
                        .getBytes());
            } else
                throw new Exception("Unable to read first line of temp export file " + f.getName());

            int nMarkerIndex = 0;
            while ((line = in.readLine()) != null) {
                List<String> genotypes = MgdbDao.split(line, "|");
                HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes
                int highestGenotypeCount = 0;
                String mostFrequentGenotype = null;
                for (String genotype : genotypes) {
                    if (genotype.length() == 0)
                        continue; /* skip missing genotypes */

                    int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype);
                    if (gtCount > highestGenotypeCount) {
                        highestGenotypeCount = gtCount;
                        mostFrequentGenotype = genotype;
                    }
                    genotypeCounts.put(genotype, gtCount);
                }

                if (genotypeCounts.size() > 1) {
                    warningFileWriter.write("- Dissimilar genotypes found for variant " + nMarkerIndex
                            + ", individual " + individualId + ". Exporting most frequent: "
                            + mostFrequentGenotype + "\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String[] alleles = mostFrequentGenotype == null ? new String[0]
                        : mostFrequentGenotype.split(" ");
                if (alleles.length > 2) {
                    warningFileWriter.write("- More than 2 alleles found for variant " + nMarkerIndex
                            + ", individual " + individualId + ". Exporting only the first 2 alleles.\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                }

                String all1 = alleles.length == 0 ? "0" : alleles[0];
                String all2 = alleles.length == 0 ? "0" : alleles[alleles.length == 1 ? 0 : 1];
                if (all1.length() != 1 || all2.length() != 1) {
                    warningFileWriter
                            .write("- SNP expected, but alleles are not coded on a single char for variant "
                                    + nMarkerIndex + ", individual " + individualId
                                    + ". Ignoring this genotype.\n");
                    problematicMarkerIndexToNameMap.put(nMarkerIndex, "");
                } else
                    zos.write((" " + all1 + " " + all2).getBytes());

                nMarkerIndex++;
            }
        } catch (Exception e) {
            LOG.error("Error exporting data", e);
            progress.setError("Error exporting data: " + e.getClass().getSimpleName()
                    + (e.getMessage() != null ? " - " + e.getMessage() : ""));
            return;
        } finally {
            in.close();
        }

        if (progress.hasAborted())
            return;

        nProgress = (short) (++i * 100 / individualExportFiles.size());
        if (nProgress > nPreviousProgress) {
            progress.setCurrentStepProgress(nProgress);
            nPreviousProgress = nProgress;
        }
        zos.write('\n');

        if (!f.delete()) {
            f.deleteOnExit();
            LOG.info("Unable to delete tmp export file " + f.getAbsolutePath());
        }
    }
    warningFileWriter.close();

    zos.putNextEntry(new ZipEntry(exportName + ".map"));

    int avgObjSize = (Integer) mongoTemplate
            .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize");
    int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize;

    markerCursor.batchSize(nChunkSize);
    int nMarkerIndex = 0;
    while (markerCursor.hasNext()) {
        DBObject exportVariant = markerCursor.next();
        DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION);
        Comparable markerId = (Comparable) exportVariant.get("_id");
        String chrom = (String) refPos.get(ReferencePosition.FIELDNAME_SEQUENCE);
        Long pos = ((Number) refPos.get(ReferencePosition.FIELDNAME_START_SITE)).longValue();

        if (chrom == null)
            LOG.warn("Chromosomal position not found for marker " + markerId);
        Comparable exportedId = markerSynonyms == null ? markerId : markerSynonyms.get(markerId);
        zos.write(((chrom == null ? "0" : chrom) + " " + exportedId + " " + 0 + " " + (pos == null ? 0 : pos)
                + LINE_SEPARATOR).getBytes());

        if (problematicMarkerIndexToNameMap.containsKey(nMarkerIndex)) { // we are going to need this marker's name for the warning file
            Comparable variantName = markerId;
            if (markerSynonyms != null) {
                Comparable syn = markerSynonyms.get(markerId);
                if (syn != null)
                    variantName = syn;
            }
            problematicMarkerIndexToNameMap.put(nMarkerIndex, variantName);
        }
        nMarkerIndex++;
    }

    if (warningFile.length() > 0) {
        zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt"));
        int nWarningCount = 0;
        BufferedReader in = new BufferedReader(new FileReader(warningFile));
        String sLine;
        while ((sLine = in.readLine()) != null) {
            for (Integer aMarkerIndex : problematicMarkerIndexToNameMap.keySet())
                sLine = sLine.replaceAll("__" + aMarkerIndex + "__",
                        problematicMarkerIndexToNameMap.get(aMarkerIndex).toString());
            zos.write((sLine + "\n").getBytes());
            in.readLine();
            nWarningCount++;
        }
        LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount);
        in.close();
    }
    warningFile.delete();

    zos.close();
    progress.setCurrentStepProgress((short) 100);
}

From source file:edu.harvard.iq.dvn.core.web.subsetting.AnalysisPage.java

public void zipFiles(OutputStream out, List<File> fllst) {
    ZipOutputStream zout = null;
    //BufferedInputStream infile = null;
    FileInputStream infile = null;

    zout = new ZipOutputStream(out);

    for (int i = 0; i < fllst.size(); i++) {
        try {//from ww  w.  j a  va 2  s  .  c  o  m
            infile = new FileInputStream(fllst.get(i));//new BufferedInputStream()

        } catch (FileNotFoundException e) {
            err.println("input file is not found");
            e.printStackTrace();
            try {
                zout.close();
            } catch (ZipException ze) {
                err.println("zip file invalid");
                ze.printStackTrace();
            } catch (IOException ex) {
                err.println("closing output file");
                ex.printStackTrace();
            }
        }

        ZipEntry ze = new ZipEntry(fllst.get(i).getName());
        try {
            zout.putNextEntry(ze);
            /*
                int len;
                while ((len = infile.read())> 0) {
            zout.write(len);
                }
            */

            byte[] dataBuffer = new byte[8192];

            int k = 0;
            while ((k = infile.read(dataBuffer)) > 0) {
                zout.write(dataBuffer, 0, k);
                //fileSize += i; 
                out.flush();
            }

        } catch (ZipException zpe) {
            zpe.printStackTrace();
            err.println("zip file is invalid");
        } catch (IOException ie) {
            ie.printStackTrace();
            err.println("output file io-error");
        }

        try {
            infile.close();
        } catch (IOException ie) {
            err.println("error: closing input file");
        }
    }

    try {
        zout.close();
    } catch (ZipException zpe) {
        err.println("zip file invalid");
        zpe.printStackTrace();
    } catch (IOException ioe) {
        err.println("error closing zip file");
        ioe.printStackTrace();
    }

}

From source file:it.govpay.web.rs.dars.reportistica.pagamenti.PagamentiHandler.java

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

            if (sb.length() > 0) {
                sb.append(", ");
            }/*from  w w w . j a  v a 2s  .  com*/

            sb.append(long1);
        }
    }
    Printer printer = null;
    String methodName = "esporta " + this.titoloServizio + "[" + sb.toString() + "]";
    int numeroZipEntries = 0;

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

    String fileName = "Pagamenti.zip";

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        Operatore operatore = this.darsService.getOperatoreByPrincipal(bd);
        ProfiloOperatore profilo = operatore.getProfilo();
        boolean isAdmin = profilo.equals(ProfiloOperatore.ADMIN);

        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = estrattiContoBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = idsToExport;

        if (!isAdmin) {

            AclBD aclBD = new AclBD(bd);
            List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId());

            boolean vediTuttiDomini = false;
            List<Long> idDomini = new ArrayList<Long>();
            for (Acl acl : aclOperatore) {
                if (Tipo.DOMINIO.equals(acl.getTipo())) {
                    if (acl.getIdDominio() == null) {
                        vediTuttiDomini = true;
                        break;
                    } else {
                        idDomini.add(acl.getIdDominio());
                    }
                }
            }
            if (!vediTuttiDomini) {
                if (idDomini.isEmpty()) {
                    eseguiRicerca = false;
                } else {
                    filter.setIdDomini(toListCodDomini(idDomini, bd));
                }
            }

            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
            if (eseguiRicerca) {
                filter.setIdSingoloVersamento(ids);
                eseguiRicerca = eseguiRicerca && estrattiContoBD.count(filter) > 0;
            }
        }

        if (eseguiRicerca) {
            Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
            Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(filter)
                    : new ArrayList<EstrattoConto>();

            if (findAll != null && findAll.size() > 0) {
                numeroZipEntries++;
                //ordinamento record
                Collections.sort(findAll, new EstrattoContoComparator());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv");
                    zout.putNextEntry(pagamentoCsv);
                    printer = new Printer(this.getFormat(), baos);
                    printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                    for (EstrattoConto pagamento : findAll) {
                        printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                    }
                } finally {
                    try {
                        if (printer != null) {
                            printer.close();
                        }
                    } catch (Exception e) {
                        throw new Exception("Errore durante la chiusura dello stream ", e);
                    }
                }
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }

            for (Long idSingoloVersamento : idsToExport) {
                SingoloVersamento singoloVersamento = singoliVersamentiBD
                        .getSingoloVersamento(idSingoloVersamento);
                Versamento versamento = singoloVersamento.getVersamento(bd);

                // Prelevo il dominio
                UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
                Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());

                // Aggrego i versamenti per dominio per generare gli estratti conto
                List<Long> idSingoliVersamentiDominio = null;
                if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                    idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
                } else {
                    idSingoliVersamentiDominio = new ArrayList<Long>();
                    mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio);
                    mappaInputDomini.put(dominio.getCodDominio(), dominio);
                }
                idSingoliVersamentiDominio.add(idSingoloVersamento);
            }

            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            for (String codDominio : mappaInputEstrattoConto.keySet()) {
                it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                        .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio),
                                mappaInputEstrattoConto.get(codDominio));
                listInputEstrattoConto.add(input);
            }

            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(
                    bd);
            List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                    .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi);

            for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
                Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
                for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                    numeroZipEntries++;
                    ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                    ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                    zout.putNextEntry(estrattoContoEntry);
                    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 sui pagamenti 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);
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public InputStream dumpContentStore(WGDatabase dbSource, String filterExpression, boolean autoCorrect,
        Logger log, boolean includeACL, boolean includeSystemAreas, boolean includeArchived)
        throws WGAPIException, IOException {

    log.info("Creating dump database");

    // Create working folder for dump database
    File dir = File.createTempFile("csd", ".tmp", WGFactory.getTempDir());
    dir.delete();//w w w  . j  a  v a  2s.c om
    dir.mkdir();

    // Create dump database
    Map<String, String> options = new HashMap<String, String>();
    options.put(WGDatabase.COPTION_MONITORLASTCHANGE, "false");
    options.put(WGDatabaseImpl.COPTION_DISTINCTFILECONTENTS, "false");
    WGDatabase dbTarget = WGFactory.getInstance().openDatabase(null,
            de.innovationgate.webgate.api.hsql.WGDatabaseImpl.class.getName(), dir.getAbsolutePath() + "/wgacs",
            "sa", null, options);
    dbTarget.setDbReference("Temporary WGACS dump target");

    // Replicate
    log.info("Synchronizing data to dump database");
    dbSource.lock();
    try {
        ContentStoreDumpManager importer = new ContentStoreDumpManager(dbSource, dbTarget, log);
        importer.exportDump(includeACL, includeSystemAreas, includeArchived);
    } finally {
        dbSource.unlock();
    }

    // Close database and zip up its contents
    log.info("Creating dump file");
    dbTarget.close();
    File zipFile = File.createTempFile("csz", ".tmp", WGFactory.getTempDir());
    ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipFile)));
    out.setLevel(9);
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
        File file = files[i];
        out.putNextEntry(new ZipEntry(file.getName()));
        InputStream in = new BufferedInputStream(new FileInputStream(file));
        WGUtils.inToOut(in, out, 2048);
        in.close();
        out.closeEntry();
    }
    out.close();

    // Delete temp dir
    WGUtils.delTree(dir);

    // Return input stream for zip file
    return new TempFileInputStream(zipFile);

}

From source file:lu.fisch.unimozer.Diagram.java

/**
 * http://snippets.dzone.com/posts/show/3468
 * modified to create the zip file if it does not exist
 * /*from w  w  w . j  a  v a2  s  .c  o m*/
 * @param zipFile
 * @param files
 * @throws IOException
 */
public void addFilesToExistingZip(File zipFile, String baseDir, File directory) throws IOException {
    ZipOutputStream out;
    File tempFile = null;

    byte[] buf = new byte[1024];
    boolean delete = false;

    if (zipFile.exists()) {
        delete = true;
        // get a temp file
        tempFile = File.createTempFile(zipFile.getName(), null);
        // delete it, otherwise you cannot rename your existing zip to it.
        tempFile.delete();

        boolean renameOk = zipFile.renameTo(tempFile);
        if (!renameOk) {
            throw new RuntimeException("could not rename the file " + zipFile.getAbsolutePath() + " to "
                    + tempFile.getAbsolutePath());
        }

        ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
        out = new ZipOutputStream(new FileOutputStream(zipFile));

        ZipEntry entry = zin.getNextEntry();
        while (entry != null) {
            String name = entry.getName();
            boolean notInFiles = true;
            /*
            for (File f : files)
            {
            if (f.getName().equals(name))
            {
                notInFiles = false;
                break;
            }
            }*/
            if (notInFiles) {
                // Add ZIP entry to output stream.
                out.putNextEntry(new ZipEntry(name));
                // Transfer bytes from the ZIP file to the output file
                int len;
                while ((len = zin.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            }
            entry = zin.getNextEntry();
        }
        // Close the streams
        zin.close();
    } else {
        out = new ZipOutputStream(new FileOutputStream(zipFile));
    }
    /*
    // Compress the files
    for (int i = 0; i < files.length; i++)
    {
    InputStream in = new FileInputStream(files[i]);
    // Add ZIP entry to output stream.
    out.putNextEntry(new ZipEntry(files[i].getName()));
    // Transfer bytes from the file to the ZIP file
    int len;
    while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
    }
    // Complete the entry
    out.closeEntry();
    in.close();
    }
    */

    addToZip(out, baseDir, directory);

    // Complete the ZIP file
    out.close();

    if (delete == true)
        tempFile.delete();
}

From source file:it.govpay.web.rs.dars.monitoraggio.versamenti.VersamentiHandler.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(", ");
            }//from  w  w  w.j a v  a2 s. c  o m

            sb.append(long1);
        }
    }

    Printer printer = null;
    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);
        VersamentiBD versamentiBD = new VersamentiBD(bd);
        it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(bd);

        Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
        Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();

        VersamentoFilter filter = versamentiBD.newFilter(simpleSearch);

        // se ho ricevuto anche gli id li utilizzo per fare il check della count
        if (idsToExport != null && idsToExport.size() > 0)
            filter.setIdVersamento(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 = versamentiBD.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.Versamento.model().DATA_ORA_ULTIMO_AGGIORNAMENTO);
        fsw.setSortOrder(SortOrder.DESC);
        filter.getFilterSortList().add(fsw);

        List<Versamento> findAll = versamentiBD.findAll(filter);

        for (Versamento versamento : findAll) {

            // Prelevo il dominio
            UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
            Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());
            // Aggrego i versamenti per dominio per generare gli estratti conto
            List<Long> idVersamentiDominio = null;
            if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                idVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
            } else {
                idVersamentiDominio = new ArrayList<Long>();
                mappaInputEstrattoConto.put(dominio.getCodDominio(), idVersamentiDominio);
                mappaInputDomini.put(dominio.getCodDominio(), dominio);
            }
            idVersamentiDominio.add(versamento.getId());
        }

        List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
        for (String codDominio : mappaInputEstrattoConto.keySet()) {
            it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                    .creaEstrattoContoVersamentiPDF(mappaInputDomini.get(codDominio),
                            mappaInputEstrattoConto.get(codDominio));
            listInputEstrattoConto.add(input);
        }

        List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                .getEstrattoContoVersamenti(listInputEstrattoConto, pathLoghi);

        for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
            Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
            for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                numeroZipEntries++;
                ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                ZipEntry estrattoContoEntry = new ZipEntry(
                        estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                zout.putNextEntry(estrattoContoEntry);
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }

        }

        // Estratto Conto in formato CSV
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter ecFilter = estrattiContoBD.newFilter();
        ecFilter.setIdVersamento(idsToExport);
        List<EstrattoConto> findAllEstrattoConto = estrattiContoBD.estrattoContoFromIdVersamenti(ecFilter);

        if (findAllEstrattoConto != null && findAllEstrattoConto.size() > 0) {
            //ordinamento record
            Collections.sort(findAllEstrattoConto, new EstrattoContoComparator());
            numeroZipEntries++;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                ZipEntry pagamentoCsv = new ZipEntry("estrattoConto.csv");
                zout.putNextEntry(pagamentoCsv);
                printer = new Printer(this.getFormat(), baos);
                printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                for (EstrattoConto pagamento : findAllEstrattoConto) {
                    printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                }
            } finally {
                try {
                    if (printer != null) {
                        printer.close();
                    }
                } catch (Exception e) {
                    throw new Exception("Errore durante la chiusura dello stream ", e);
                }
            }
            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 sui versamenti selezionati.".getBytes());
            zout.closeEntry();
        }

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

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

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

From source file:it.govpay.web.rs.dars.monitoraggio.pagamenti.ReportisticaPagamentiHandler.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 . j a  v a 2 s . c  om

            sb.append(long1);
        }
    }
    Printer printer = null;
    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);
    }

    int numeroZipEntries = 0;

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

    String fileName = "Pagamenti.zip";

    try {
        this.log.info("Esecuzione " + methodName + " in corso...");
        //         Operatore operatore = this.darsService.getOperatoreByPrincipal(bd); 

        SingoliVersamentiBD singoliVersamentiBD = new SingoliVersamentiBD(bd);
        EstrattiContoBD estrattiContoBD = new EstrattiContoBD(bd);
        EstrattoContoFilter filter = estrattiContoBD.newFilter();
        boolean eseguiRicerca = true;
        List<Long> ids = idsToExport;

        //         if(!isAdmin){
        //
        //            AclBD aclBD = new AclBD(bd);
        //            List<Acl> aclOperatore = aclBD.getAclOperatore(operatore.getId());
        //
        //            boolean vediTuttiDomini = false;
        //            List<Long> idDomini = new ArrayList<Long>();
        //            for(Acl acl: aclOperatore) {
        //               if(Tipo.DOMINIO.equals(acl.getTipo())) {
        //                  if(acl.getIdDominio() == null) {
        //                     vediTuttiDomini = true;
        //                     break;
        //                  } else {
        //                     idDomini.add(acl.getIdDominio());
        //                  }
        //               }
        //            }
        //            if(!vediTuttiDomini) {
        //               if(idDomini.isEmpty()) {
        //                  eseguiRicerca = false;
        //               } else {
        //                  filter.setIdDomini(toListCodDomini(idDomini, bd));
        //               }
        //            }
        //
        //            // l'operatore puo' vedere i domini associati, controllo se c'e' un versamento con Id nei domini concessi.
        //            if(eseguiRicerca){
        //               filter.setIdSingoloVersamento(ids);
        //               eseguiRicerca = eseguiRicerca && estrattiContoBD.count(filter) > 0;
        //            }
        //         }

        if (eseguiRicerca) {
            Map<String, List<Long>> mappaInputEstrattoConto = new HashMap<String, List<Long>>();
            Map<String, Dominio> mappaInputDomini = new HashMap<String, Dominio>();
            // recupero oggetto
            filter.setIdSingoloVersamento(ids);
            List<EstrattoConto> findAll = eseguiRicerca
                    ? estrattiContoBD.estrattoContoFromIdSingoliVersamenti(filter)
                    : new ArrayList<EstrattoConto>();

            if (findAll != null && findAll.size() > 0) {
                numeroZipEntries++;
                //ordinamento record
                Collections.sort(findAll, new EstrattoContoComparator());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try {
                    ZipEntry pagamentoCsv = new ZipEntry("pagamenti.csv");
                    zout.putNextEntry(pagamentoCsv);
                    printer = new Printer(this.getFormat(), baos);
                    printer.printRecord(CSVUtils.getEstrattoContoCsvHeader());
                    for (EstrattoConto pagamento : findAll) {
                        printer.printRecord(CSVUtils.getEstrattoContoAsCsvRow(pagamento, this.sdf));
                    }
                } finally {
                    try {
                        if (printer != null) {
                            printer.close();
                        }
                    } catch (Exception e) {
                        throw new Exception("Errore durante la chiusura dello stream ", e);
                    }
                }
                zout.write(baos.toByteArray());
                zout.closeEntry();
            }

            for (Long idSingoloVersamento : idsToExport) {
                SingoloVersamento singoloVersamento = singoliVersamentiBD
                        .getSingoloVersamento(idSingoloVersamento);
                Versamento versamento = singoloVersamento.getVersamento(bd);

                // Prelevo il dominio
                UnitaOperativa uo = AnagraficaManager.getUnitaOperativa(bd, versamento.getIdUo());
                Dominio dominio = AnagraficaManager.getDominio(bd, uo.getIdDominio());

                // Aggrego i versamenti per dominio per generare gli estratti conto
                List<Long> idSingoliVersamentiDominio = null;
                if (mappaInputEstrattoConto.containsKey(dominio.getCodDominio())) {
                    idSingoliVersamentiDominio = mappaInputEstrattoConto.get(dominio.getCodDominio());
                } else {
                    idSingoliVersamentiDominio = new ArrayList<Long>();
                    mappaInputEstrattoConto.put(dominio.getCodDominio(), idSingoliVersamentiDominio);
                    mappaInputDomini.put(dominio.getCodDominio(), dominio);
                }
                idSingoliVersamentiDominio.add(idSingoloVersamento);
            }

            List<it.govpay.core.business.model.EstrattoConto> listInputEstrattoConto = new ArrayList<it.govpay.core.business.model.EstrattoConto>();
            for (String codDominio : mappaInputEstrattoConto.keySet()) {
                it.govpay.core.business.model.EstrattoConto input = it.govpay.core.business.model.EstrattoConto
                        .creaEstrattoContoPagamentiPDF(mappaInputDomini.get(codDominio),
                                mappaInputEstrattoConto.get(codDominio));
                listInputEstrattoConto.add(input);
            }

            String pathLoghi = ConsoleProperties.getInstance().getPathEstrattoContoPdfLoghi();
            it.govpay.core.business.EstrattoConto estrattoContoBD = new it.govpay.core.business.EstrattoConto(
                    bd);
            List<it.govpay.core.business.model.EstrattoConto> listOutputEstattoConto = estrattoContoBD
                    .getEstrattoContoPagamenti(listInputEstrattoConto, pathLoghi);

            for (it.govpay.core.business.model.EstrattoConto estrattoContoOutput : listOutputEstattoConto) {
                Map<String, ByteArrayOutputStream> estrattoContoVersamenti = estrattoContoOutput.getOutput();
                for (String nomeEntry : estrattoContoVersamenti.keySet()) {
                    numeroZipEntries++;
                    ByteArrayOutputStream baos = estrattoContoVersamenti.get(nomeEntry);
                    ZipEntry estrattoContoEntry = new ZipEntry(nomeEntry);
                    //                  ZipEntry estrattoContoEntry = new ZipEntry(estrattoContoOutput.getDominio().getCodDominio() + "/" + nomeEntry);
                    zout.putNextEntry(estrattoContoEntry);
                    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 sui pagamenti 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);
    }
}