Example usage for java.util.zip ZipEntry setSize

List of usage examples for java.util.zip ZipEntry setSize

Introduction

In this page you can find the example usage for java.util.zip ZipEntry setSize.

Prototype

public void setSize(long size) 

Source Link

Document

Sets the uncompressed size of the entry data.

Usage

From source file:org.jumpmind.metl.core.runtime.component.Zip.java

@Override
public void handle(Message inputMessage, ISendMessageCallback messageTarget,
        boolean unitOfWorkBoundaryReached) {

    String targetPath = resolveParamsAndHeaders(targetRelativePath, inputMessage);
    if (inputMessage instanceof TextMessage) {
        List<String> files = ((TextMessage) inputMessage).getPayload();
        fileNames.addAll(files);/*  ww  w.j  av a2 s.  c o m*/
        getComponentStatistics().incrementNumberEntitiesProcessed(files.size());
    }

    if (inputMessage instanceof ControlMessage) {
        IDirectory sourceDir = null;
        IDirectory targetDir = null;
        ZipOutputStream zos = null;

        sourceDir = sourceResource.reference();
        targetDir = targetResource.reference();

        try {
            targetDir.delete(targetPath);
            zos = new ZipOutputStream(targetDir.getOutputStream(targetPath, false), Charset.forName(encoding));

            for (String fileName : fileNames) {
                FileInfo sourceZipFile = sourceDir.listFile(fileName);
                log(LogLevel.INFO, "Received file name to add to zip: %s", sourceZipFile);
                if (mustExist && sourceZipFile == null) {
                    throw new IoException(String.format("Could not find file to zip: %s", sourceZipFile));
                }

                if (sourceZipFile != null) {
                    try {
                        if (!sourceZipFile.isDirectory()) {
                            ZipEntry entry = new ZipEntry(sourceZipFile.getName());
                            entry.setSize(sourceZipFile.getSize());
                            entry.setTime(sourceZipFile.getLastUpdated());
                            zos.putNextEntry(entry);
                            log(LogLevel.INFO, "Adding %s", sourceZipFile.getName());
                            InputStream fis = sourceDir.getInputStream(sourceZipFile.getRelativePath(),
                                    unitOfWorkBoundaryReached);
                            if (fis != null) {
                                try {
                                    IOUtils.copy(fis, zos);
                                } finally {
                                    IOUtils.closeQuietly(fis);
                                }
                            }
                        }
                        zos.closeEntry();
                    } catch (IOException e) {
                        throw new IoException(e);
                    }
                }
            }

            log(LogLevel.INFO, "Generated %s", targetPath);

        } finally {
            IOUtils.closeQuietly(zos);
        }

        if (deleteOnComplete) {
            for (String fileName : fileNames) {
                sourceDir.delete(fileName);
            }
        }

        fileNames.clear();
    }
}

From source file:org.jumpmind.symmetric.file.FileSyncZipDataWriter.java

public void end(Batch batch, boolean inError) {

    try {/*from   w w w  . j  a v  a 2 s. com*/
        if (!inError) {
            if (zos == null) {
                zos = new ZipOutputStream(stagedResource.getOutputStream());
            }

            Map<String, LastEventType> entries = new HashMap<String, LastEventType>();
            StringBuilder script = new StringBuilder("fileList = new HashMap();\n");
            for (FileSnapshot snapshot : snapshotEvents) {
                FileTriggerRouter triggerRouter = fileSyncService.getFileTriggerRouter(snapshot.getTriggerId(),
                        snapshot.getRouterId());
                if (triggerRouter != null) {
                    StringBuilder command = new StringBuilder("\n");
                    LastEventType eventType = snapshot.getLastEventType();

                    FileTrigger fileTrigger = triggerRouter.getFileTrigger();

                    String targetBaseDir = ((triggerRouter.getTargetBaseDir() == null) ? null
                            : triggerRouter.getTargetBaseDir().replace('\\', '/'));
                    if (StringUtils.isBlank(targetBaseDir)) {
                        targetBaseDir = ((fileTrigger.getBaseDir() == null) ? null
                                : fileTrigger.getBaseDir().replace('\\', '/'));
                    }
                    targetBaseDir = StringEscapeUtils.escapeJava(targetBaseDir);

                    command.append("targetBaseDir = \"").append(targetBaseDir).append("\";\n");
                    command.append("processFile = true;\n");
                    command.append("sourceFileName = \"").append(snapshot.getFileName()).append("\";\n");
                    command.append("targetRelativeDir = \"");
                    if (!snapshot.getRelativeDir().equals(".")) {
                        command.append(StringEscapeUtils.escapeJava(snapshot.getRelativeDir()));
                        command.append("\";\n");
                    } else {
                        command.append("\";\n");
                    }
                    command.append("targetFileName = sourceFileName;\n");
                    command.append("sourceFilePath = \"");
                    command.append(StringEscapeUtils.escapeJava(snapshot.getRelativeDir())).append("\";\n");

                    StringBuilder entryName = new StringBuilder(Long.toString(batch.getBatchId()));
                    entryName.append("/");
                    if (!snapshot.getRelativeDir().equals(".")) {
                        entryName.append(snapshot.getRelativeDir()).append("/");
                    }
                    entryName.append(snapshot.getFileName());

                    File file = fileTrigger.createSourceFile(snapshot);
                    if (file.isDirectory()) {
                        entryName.append("/");
                    }

                    if (StringUtils.isNotBlank(fileTrigger.getBeforeCopyScript())) {
                        command.append(fileTrigger.getBeforeCopyScript()).append("\n");
                    }

                    command.append("if (processFile) {\n");
                    String targetFile = "targetBaseDir + \"/\" + targetRelativeDir + \"/\" + targetFileName";

                    switch (eventType) {
                    case CREATE:
                    case MODIFY:
                        if (file.exists()) {
                            command.append("  File targetBaseDirFile = new File(targetBaseDir);\n");
                            command.append("  if (!targetBaseDirFile.exists()) {\n");
                            command.append("    targetBaseDirFile.mkdirs();\n");
                            command.append("  }\n");
                            command.append("  java.io.File sourceFile = new java.io.File(batchDir + \"/\"");
                            if (!snapshot.getRelativeDir().equals(".")) {
                                command.append(" + sourceFilePath + \"/\"");
                            }
                            command.append(" + sourceFileName");
                            command.append(");\n");

                            command.append("  java.io.File targetFile = new java.io.File(");
                            command.append(targetFile);
                            command.append(");\n");

                            // no need to copy directory if it already exists
                            command.append("  if (targetFile.exists() && targetFile.isDirectory()) {\n");
                            command.append("      processFile = false;\n");
                            command.append("  }\n");

                            // conflict resolution
                            FileConflictStrategy conflictStrategy = triggerRouter.getConflictStrategy();
                            if (conflictStrategy == FileConflictStrategy.TARGET_WINS
                                    || conflictStrategy == FileConflictStrategy.MANUAL) {
                                command.append("  if (targetFile.exists() && !targetFile.isDirectory()) {\n");
                                command.append(
                                        "    long targetChecksum = org.apache.commons.io.FileUtils.checksumCRC32(targetFile);\n");
                                command.append("    if (targetChecksum != " + snapshot.getOldCrc32Checksum()
                                        + "L) {\n");
                                if (conflictStrategy == FileConflictStrategy.MANUAL) {
                                    command.append(
                                            "      throw new org.jumpmind.symmetric.file.FileConflictException(targetFileName + \" was in conflict \");\n");
                                } else {
                                    command.append("      processFile = false;\n");
                                }
                                command.append("    }\n");
                                command.append("  }\n");
                            }

                            command.append("  if (processFile) {\n");
                            command.append("    if (sourceFile.isDirectory()) {\n");
                            command.append(
                                    "      org.apache.commons.io.FileUtils.copyDirectory(sourceFile, targetFile, true);\n");
                            command.append("    } else {\n");
                            command.append(
                                    "      org.apache.commons.io.FileUtils.copyFile(sourceFile, targetFile, true);\n");
                            command.append("    }\n");
                            command.append("  }\n");
                            command.append("  fileList.put(").append(targetFile).append(",\"");
                            command.append(eventType.getCode());
                            command.append("\");\n");
                        }
                        break;
                    case DELETE:
                        command.append("  org.apache.commons.io.FileUtils.deleteQuietly(new java.io.File(");
                        command.append(targetFile);
                        command.append("));\n");
                        command.append("  fileList.put(").append(targetFile).append(",\"");
                        command.append(eventType.getCode());
                        command.append("\");\n");
                        break;
                    default:
                        break;
                    }

                    if (StringUtils.isNotBlank(fileTrigger.getAfterCopyScript())) {
                        command.append(fileTrigger.getAfterCopyScript()).append("\n");
                    }

                    LastEventType previousEventForEntry = entries.get(entryName.toString());
                    boolean process = true;
                    if (previousEventForEntry != null) {
                        if ((previousEventForEntry == eventType)
                                || (previousEventForEntry == LastEventType.CREATE
                                        && eventType == LastEventType.MODIFY)) {
                            process = false;
                        }
                    }

                    if (process) {
                        if (eventType != LastEventType.DELETE) {
                            if (file.exists()) {
                                byteCount += file.length();
                                ZipEntry entry = new ZipEntry(entryName.toString());
                                entry.setSize(file.length());
                                entry.setTime(file.lastModified());
                                zos.putNextEntry(entry);
                                if (file.isFile()) {
                                    FileInputStream fis = new FileInputStream(file);
                                    try {
                                        IOUtils.copy(fis, zos);
                                    } finally {
                                        IOUtils.closeQuietly(fis);
                                    }
                                }
                                zos.closeEntry();
                                entries.put(entryName.toString(), eventType);
                            } else {
                                log.warn(
                                        "Could not find the {} file to package for synchronization.  Skipping it.",
                                        file.getAbsolutePath());
                            }
                        }

                        command.append("}\n\n");
                        script.append(command.toString());

                    }

                } else {
                    log.error(
                            "Could not locate the file trigger ({}) router ({}) to process a snapshot event.  The event will be ignored",
                            snapshot.getTriggerId(), snapshot.getRouterId());
                }
            }

            script.append("return fileList;\n");
            ZipEntry entry = new ZipEntry(batch.getBatchId() + "/sync.bsh");
            zos.putNextEntry(entry);
            IOUtils.write(script.toString(), zos);
            zos.closeEntry();

            entry = new ZipEntry(batch.getBatchId() + "/batch-info.txt");
            zos.putNextEntry(entry);
            IOUtils.write(batch.getChannelId(), zos);
            zos.closeEntry();

        }
    } catch (IOException e) {
        throw new IoException(e);
    }

}

From source file:org.junitee.testngee.servlet.TestNGEEServlet.java

private void zipOutputDir(File outdir, ServletOutputStream outputStream) throws IOException {
    ZipOutputStream out = new ZipOutputStream(outputStream);
    File[] files = outdir.listFiles();

    out.setMethod(ZipOutputStream.DEFLATED);

    for (int i = 0; i < files.length; i++) {
        File file = files[i];//from w  ww.  j a  v  a 2 s. c o  m

        if (!file.isDirectory()) {
            ZipEntry zipEntry = new ZipEntry(file.getName());
            zipEntry.setSize(file.length());
            zipEntry.setTime(file.lastModified());

            out.putNextEntry(zipEntry);

            FileInputStream in = new FileInputStream(file);
            byte[] buffer = new byte[4096];
            int r;

            while ((r = in.read(buffer)) > 0) {
                out.write(buffer, 0, r);
            }
            in.close();
            out.closeEntry();
        }
    }
    out.close();
}

From source file:org.kuali.kfs.module.ar.document.service.impl.DunningLetterServiceImpl.java

/**
 * This method generates the actual pdf files to print.
 *
 * @param mapping// w w w.  ja v  a  2  s  .c o  m
 * @param form
 * @param list
 * @return
 */
@Override
public boolean createZipOfPDFs(byte[] report, ByteArrayOutputStream baos) throws IOException {

    ZipOutputStream zos = new ZipOutputStream(baos);
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();

    if (ObjectUtils.isNotNull(report)) {
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(report));
        crc.reset();
        while ((bytesRead = bis.read(buffer)) != -1) {
            crc.update(buffer, 0, bytesRead);
        }
        bis.close();
        // Reset to beginning of input stream
        bis = new BufferedInputStream(new ByteArrayInputStream(report));
        ZipEntry entry = new ZipEntry("DunningLetters&Invoices-"
                + getDateTimeService().toDateStringForFilename(getDateTimeService().getCurrentDate()) + ".pdf");
        entry.setMethod(ZipEntry.STORED);
        entry.setCompressedSize(report.length);
        entry.setSize(report.length);
        entry.setCrc(crc.getValue());
        zos.putNextEntry(entry);
        while ((bytesRead = bis.read(buffer)) != -1) {
            zos.write(buffer, 0, bytesRead);
        }
        bis.close();
    }

    zos.close();
    return true;
}

From source file:org.kuali.kfs.module.ar.report.service.impl.TransmitContractsAndGrantsInvoicesServiceImpl.java

/**
 *
 * @param report//  w  ww.j  a  va2s.c  o m
 * @param invoiceFileWritten
 * @param zos
 * @param buffer
 * @param crc
 * @return
 * @throws IOException
 */
private boolean writeFile(byte[] arrayToWrite, ZipOutputStream zos, String fileName) throws IOException {
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();

    if (ObjectUtils.isNotNull(arrayToWrite) && arrayToWrite.length > 0) {
        BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite));
        try {
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer, 0, bytesRead);
            }
            bis.close();
            // Reset to beginning of input stream
            bis = new BufferedInputStream(new ByteArrayInputStream(arrayToWrite));
            ZipEntry entry = new ZipEntry(fileName);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(arrayToWrite.length);
            entry.setSize(arrayToWrite.length);
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
        } finally {
            bis.close();
        }
        return true;
    }
    return false;
}

From source file:org.nuxeo.template.odt.OOoArchiveModifier.java

protected void writeOOoEntry(ZipOutputStream zipOutputStream, String entryName, File fileEntry, int zipMethod)
        throws IOException {

    if (fileEntry.isDirectory()) {
        entryName = entryName + "/";
        ZipEntry zentry = new ZipEntry(entryName);
        zipOutputStream.putNextEntry(zentry);
        zipOutputStream.closeEntry();//from  ww  w.  j av  a 2  s  . c o m
        for (File child : fileEntry.listFiles()) {
            writeOOoEntry(zipOutputStream, entryName + child.getName(), child, zipMethod);
        }
        return;
    }

    ZipEntry zipEntry = new ZipEntry(entryName);
    try (InputStream entryInputStream = new FileInputStream(fileEntry)) {
        zipEntry.setMethod(zipMethod);
        if (zipMethod == ZipEntry.STORED) {
            byte[] inputBytes = IOUtils.toByteArray(entryInputStream);
            CRC32 crc = new CRC32();
            crc.update(inputBytes);
            zipEntry.setCrc(crc.getValue());
            zipEntry.setSize(inputBytes.length);
            zipEntry.setCompressedSize(inputBytes.length);
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.write(inputBytes, zipOutputStream);
        } else {
            zipOutputStream.putNextEntry(zipEntry);
            IOUtils.copy(entryInputStream, zipOutputStream);
        }
    }
    zipOutputStream.closeEntry();
}

From source file:org.openecomp.sdc.common.util.ZipUtil.java

public static byte[] zipBytes(byte[] input) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    ZipEntry entry = new ZipEntry("zip");
    entry.setSize(input.length);
    zos.putNextEntry(entry);/*from   ww w  .  j  a  v  a 2  s. com*/
    zos.write(input);
    zos.closeEntry();
    zos.close();
    return baos.toByteArray();
}

From source file:org.openremote.modeler.cache.LocalFileCache.java

/**
 * Compresses a set of files into a target zip archive. The file instances should be relative
 * paths used to structure the archive into directories. The relative paths will be resolved
 * to actual file paths in the current account's file cache.
 *
 * @param target    Target file path where the zip archive will be stored.
 * @param files     Set of <b>relative</b> file paths to include in the zip archive. The file
 *                  paths should be set to match the expected directory structure in the final
 *                  archive (therefore should not reflect the absolute file paths expected to
 *                  be included in the archive).
 *
 * @throws CacheOperationException/* www .ja v a 2  s  .c om*/
 *            if any of the zip file operations fail
 *
 * @throws ConfigurationException
 *            if there are any security restrictions about reading the set of included files
 *            or writing the target zip archive file
 */
private void compress(File target, Set<File> files) throws CacheOperationException, ConfigurationException {
    ZipOutputStream zipOutput = null;

    try {
        zipOutput = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));

        for (File file : files) {
            BufferedInputStream fileInput = null;

            // translate the relative zip archive directory path to existing user cache absolute path...

            File cachePathName = new File(cacheFolder, file.getPath());

            try {
                if (!cachePathName.exists()) {
                    throw new CacheOperationException(
                            "Expected to add file ''{0}'' to export archive ''{1}'' (Account : {2}) but it "
                                    + "has gone missing (cause unknown). This can indicate implementation or deployment "
                                    + "error. Aborting export operation as a safety precaution.",
                            cachePathName.getPath(), target.getAbsolutePath(),
                            currentUserAccount.getAccount().getOid());
                }

                fileInput = new BufferedInputStream(new FileInputStream(cachePathName));

                ZipEntry entry = new ZipEntry(file.getPath());

                entry.setSize(cachePathName.length());
                entry.setTime(cachePathName.lastModified());

                zipOutput.putNextEntry(entry);

                cacheLog.debug("Added new export zip entry ''{0}''.", file.getPath());

                int count, total = 0;
                final int BUFFER_SIZE = 2048;
                byte[] data = new byte[BUFFER_SIZE];

                while ((count = fileInput.read(data, 0, BUFFER_SIZE)) != -1) {
                    zipOutput.write(data, 0, count);

                    total += count;
                }

                zipOutput.flush();

                // Sanity check...

                if (total != cachePathName.length()) {
                    throw new CacheOperationException(
                            "Only wrote {0} out of {1} bytes when archiving file ''{2}'' (Account : {3}). "
                                    + "This could have occured either due implementation error or file I/O error. "
                                    + "Aborting archive operation to prevent a potentially corrupt export archive to "
                                    + "be created.",
                            total, cachePathName.length(), cachePathName.getPath(),
                            currentUserAccount.getAccount().getOid());
                }

                else {
                    cacheLog.debug("Wrote {0} out of {1} bytes to zip entry ''{2}''", total,
                            cachePathName.length(), file.getPath());
                }
            }

            catch (SecurityException e) {
                // we've messed up deployment... quite likely unrecoverable...

                throw new ConfigurationException(
                        "Security manager has denied r/w access when attempting to read file ''{0}'' and "
                                + "write it to archive ''{1}'' (Account : {2}) : {3}",
                        e, cachePathName.getPath(), target, currentUserAccount.getAccount().getOid(),
                        e.getMessage());
            }

            catch (IllegalArgumentException e) {
                // This may occur if we overrun some fixed size limits in ZIP format...

                throw new CacheOperationException("Error creating ZIP archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (FileNotFoundException e) {
                throw new CacheOperationException(
                        "Attempted to include file ''{0}'' in export archive but it has gone missing "
                                + "(Account : {1}). Possible implementation error in local file cache. Aborting  "
                                + "export operation as a precaution ({2})",
                        e, cachePathName.getPath(), currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (ZipException e) {
                throw new CacheOperationException("Error writing export archive for account ID = {0} : {1}", e,
                        currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            catch (IOException e) {
                throw new CacheOperationException(
                        "I/O error while creating export archive for account ID = {0}. "
                                + "Operation aborted ({1})",
                        e, currentUserAccount.getAccount().getOid(), e.getMessage());
            }

            finally {
                if (zipOutput != null) {
                    try {
                        zipOutput.closeEntry();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Unable to close zip entry for file ''{0}'' in export archive ''{1}'' "
                                        + "(Account : {2}) : {3}.",
                                t, file.getPath(), target.getAbsolutePath(),
                                currentUserAccount.getAccount().getOid(), t.getMessage());
                    }
                }

                if (fileInput != null) {
                    try {
                        fileInput.close();
                    }

                    catch (Throwable t) {
                        cacheLog.warn(
                                "Failed to close input stream from file ''{0}'' being added "
                                        + "to export archive (Account : {1}) : {2}",
                                t, cachePathName.getPath(), currentUserAccount.getAccount().getOid(),
                                t.getMessage());
                    }
                }
            }
        }
    }

    catch (FileNotFoundException e) {
        throw new CacheOperationException(
                "Unable to create target export archive ''{0}'' for account {1) : {2}", e, target,
                currentUserAccount.getAccount().getOid(), e.getMessage());
    }

    finally {
        try {
            if (zipOutput != null) {
                zipOutput.close();
            }
        }

        catch (Throwable t) {
            cacheLog.warn("Failed to close the stream to export archive ''{0}'' : {1}.", t, target,
                    t.getMessage());
        }
    }
}

From source file:org.openremote.modeler.utils.ZipUtils.java

/**
 * Compress./*from  w  w  w.j  a v a2  s.  com*/
 * 
 * @param outputFilePath the output file path
 * @param files the files
 * 
 * @return the file
 */
public static File compress(String outputFilePath, List<File> files) {
    final int buffer = 2048;
    BufferedInputStream bufferedInputStream;
    File outputFile = new File(outputFilePath);
    try {
        FileUtils.touch(outputFile);
    } catch (IOException e) {
        LOGGER.error("create zip file fail.", e);
        throw new FileOperationException("create zip file fail.", e);
    }
    FileOutputStream fileOutputStream = null;
    ZipOutputStream zipOutputStream = null;
    FileInputStream fileInputStream;
    try {
        fileOutputStream = new FileOutputStream(outputFilePath);
        zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
        byte[] data = new byte[buffer];
        for (File file : files) {
            if (!file.exists()) {
                continue;
            }
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream, buffer);
            ZipEntry entry = new ZipEntry(file.getName());
            entry.setSize(file.length());
            entry.setTime(file.lastModified());
            zipOutputStream.putNextEntry(entry);

            int count;
            while ((count = bufferedInputStream.read(data, 0, buffer)) != -1) {
                zipOutputStream.write(data, 0, count);
            }
            zipOutputStream.closeEntry();
            if (fileInputStream != null) {
                fileInputStream.close();
            }
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }
        }
    } catch (FileNotFoundException e) {
        LOGGER.error("Can't find the output file.", e);
        throw new FileOperationException("Can't find the output file.", e);
    } catch (IOException e) {
        LOGGER.error("Can't compress file to zip archive, occured IOException", e);
        throw new FileOperationException("Can't compress file to zip archive, occured IOException", e);
    } finally {
        try {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            LOGGER.error("Close zipOutputStream and fileOutputStream occur IOException", e);
        }
    }
    return outputFile;
}

From source file:org.sakaiproject.assignment.impl.AssignmentServiceImpl.java

private void zipSubmissions(String assignmentReference, String assignmentTitle, Assignment.GradeType gradeType,
        Assignment.SubmissionType typeOfSubmission, Iterator submissions, OutputStream outputStream,
        StringBuilder exceptionMessage, boolean withStudentSubmissionText,
        boolean withStudentSubmissionAttachment, boolean withGradeFile, boolean withFeedbackText,
        boolean withFeedbackComment, boolean withFeedbackAttachment, boolean withoutFolders,
        String gradeFileFormat, boolean includeNotSubmitted, String siteId) {
    ZipOutputStream out = null;/* www .j a  v  a2s.  c  o m*/

    boolean isAdditionalNotesEnabled = false;
    Site st = null;
    try {
        st = siteService.getSite(siteId);
        isAdditionalNotesEnabled = candidateDetailProvider != null
                && candidateDetailProvider.isAdditionalNotesEnabled(st);
    } catch (IdUnusedException e) {
        log.warn("Could not find site {} - isAdditionalNotesEnabled set to false", siteId);
    }

    try {
        out = new ZipOutputStream(outputStream);

        // create the folder structure - named after the assignment's title
        final String root = escapeInvalidCharsEntry(Validator.escapeZipEntry(assignmentTitle))
                + Entity.SEPARATOR;

        final SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase());
        final SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle,
                gradeType.toString(), getCsvSeparator());

        String submittedText = "";
        if (!submissions.hasNext()) {
            exceptionMessage.append("There is no submission yet. ");
        }

        if (isAdditionalNotesEnabled) {
            sheet.addHeader(resourceLoader.getString("grades.id"), resourceLoader.getString("grades.eid"),
                    resourceLoader.getString("grades.lastname"), resourceLoader.getString("grades.firstname"),
                    resourceLoader.getString("grades.grade"), resourceLoader.getString("grades.submissionTime"),
                    resourceLoader.getString("grades.late"), resourceLoader.getString("gen.notes"));
        } else {
            sheet.addHeader(resourceLoader.getString("grades.id"), resourceLoader.getString("grades.eid"),
                    resourceLoader.getString("grades.lastname"), resourceLoader.getString("grades.firstname"),
                    resourceLoader.getString("grades.grade"), resourceLoader.getString("grades.submissionTime"),
                    resourceLoader.getString("grades.late"));
        }

        // allow add assignment members
        final List<User> allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);

        // Create the ZIP file
        String caughtException = null;
        String caughtStackTrace = null;
        final StringBuilder submittersAdditionalNotesHtml = new StringBuilder();

        while (submissions.hasNext()) {
            final AssignmentSubmission s = (AssignmentSubmission) submissions.next();
            boolean isAnon = assignmentUsesAnonymousGrading(s.getAssignment());
            //SAK-29314 added a new value where it's by default submitted but is marked when the user submits
            if ((s.getSubmitted() && s.getUserSubmission()) || includeNotSubmitted) {
                // get the submitter who submitted the submission see if the user is still in site
                final Optional<AssignmentSubmissionSubmitter> assignmentSubmitter = s.getSubmitters().stream()
                        .findAny();
                try {
                    User u = null;
                    if (assignmentSubmitter.isPresent()) {
                        u = userDirectoryService.getUser(assignmentSubmitter.get().getSubmitter());
                    }
                    if (allowAddSubmissionUsers.contains(u)) {
                        String submittersName = root;

                        final User[] submitters = s.getSubmitters().stream().map(p -> {
                            try {
                                return userDirectoryService.getUser(p.getSubmitter());
                            } catch (UserNotDefinedException e) {
                                log.warn("User not found {}, {}", p.getSubmitter(), e.getMessage());
                            }
                            return null;
                        }).filter(Objects::nonNull).toArray(User[]::new);

                        String submittersString = "";
                        for (int i = 0; i < submitters.length; i++) {
                            if (i > 0) {
                                submittersString = submittersString.concat("; ");
                            }
                            String fullName = submitters[i].getSortName();
                            // in case the user doesn't have first name or last name
                            if (!fullName.contains(",")) {
                                fullName = fullName.concat(",");
                            }
                            submittersString = submittersString.concat(fullName);
                            // add the eid to the end of it to guarantee folder name uniqness
                            // if user Eid contains non ascii characters, the user internal id will be used
                            final String userEid = submitters[i].getEid();
                            final String candidateEid = escapeInvalidCharsEntry(userEid);
                            if (candidateEid.equals(userEid)) {
                                submittersString = submittersString + "(" + candidateEid + ")";
                            } else {
                                submittersString = submittersString + "(" + submitters[i].getId() + ")";
                            }
                            submittersString = escapeInvalidCharsEntry(submittersString);
                            // Work out if submission is late.
                            final String latenessStatus = whenSubmissionMade(s);
                            log.debug("latenessStatus: " + latenessStatus);

                            final String anonTitle = resourceLoader.getString("grading.anonymous.title");
                            final String fullAnonId = s.getId() + " " + anonTitle;

                            String[] params = new String[7];
                            if (isAdditionalNotesEnabled && candidateDetailProvider != null) {
                                final List<String> notes = candidateDetailProvider
                                        .getAdditionalNotes(submitters[i], st).orElse(new ArrayList<String>());

                                if (!notes.isEmpty()) {
                                    params = new String[notes.size() + 7];
                                    System.arraycopy(notes.toArray(new String[notes.size()]), 0, params, 7,
                                            notes.size());
                                }
                            }

                            // SAK-17606
                            if (!isAnon) {
                                log.debug("Zip user: " + submitters[i].toString());
                                params[0] = submitters[i].getDisplayId();
                                params[1] = submitters[i].getEid();
                                params[2] = submitters[i].getLastName();
                                params[3] = submitters[i].getFirstName();
                                params[4] = this.getGradeForSubmitter(s, submitters[i].getId());
                                if (s.getDateSubmitted() != null) {
                                    params[5] = s.getDateSubmitted().toString(); // TODO may need to be formatted
                                } else {
                                    params[5] = "";
                                }
                                params[6] = latenessStatus;
                            } else {
                                params[0] = fullAnonId;
                                params[1] = fullAnonId;
                                params[2] = anonTitle;
                                params[3] = anonTitle;
                                params[4] = this.getGradeForSubmitter(s, submitters[i].getId());
                                if (s.getDateSubmitted() != null) {
                                    params[5] = s.getDateSubmitted().toString(); // TODO may need to be formatted
                                } else {
                                    params[5] = "";
                                }
                                params[6] = latenessStatus;
                            }
                            sheet.addRow(params);
                        }

                        if (StringUtils.trimToNull(submittersString) != null) {
                            submittersName = submittersName.concat(StringUtils.trimToNull(submittersString));
                            submittedText = s.getSubmittedText();

                            // SAK-17606
                            if (isAnon) {
                                submittersString = s.getId() + " "
                                        + resourceLoader.getString("grading.anonymous.title");
                                submittersName = root + submittersString;
                            }

                            if (!withoutFolders) {
                                submittersName = submittersName.concat("/");
                            } else {
                                submittersName = submittersName.concat("_");
                            }

                            // record submission timestamp
                            if (!withoutFolders && s.getSubmitted() && s.getDateSubmitted() != null) {
                                final String zipEntryName = submittersName + "timestamp.txt";
                                final String textEntryString = s.getDateSubmitted().toString();
                                createTextZipEntry(out, zipEntryName, textEntryString);
                            }

                            // create the folder structure - named after the submitter's name
                            if (typeOfSubmission != Assignment.SubmissionType.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION
                                    && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
                                // include student submission text
                                if (withStudentSubmissionText) {
                                    // create the text file only when a text submission is allowed
                                    final StringBuilder submittersNameString = new StringBuilder(
                                            submittersName);
                                    //remove folder name if Download All is without user folders
                                    if (!withoutFolders) {
                                        submittersNameString.append(submittersString);
                                    }

                                    final String zipEntryName = submittersNameString
                                            .append("_submissionText"
                                                    + AssignmentConstants.ZIP_SUBMITTED_TEXT_FILE_TYPE)
                                            .toString();
                                    createTextZipEntry(out, zipEntryName, submittedText);
                                }

                                // include student submission feedback text
                                if (withFeedbackText) {
                                    // create a feedbackText file into zip
                                    final String zipEntryName = submittersName + "feedbackText.html";
                                    final String textEntryString = s.getFeedbackText();
                                    createTextZipEntry(out, zipEntryName, textEntryString);
                                }
                            }

                            if (typeOfSubmission != Assignment.SubmissionType.TEXT_ONLY_ASSIGNMENT_SUBMISSION
                                    && typeOfSubmission != Assignment.SubmissionType.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION
                                    && withStudentSubmissionAttachment) {
                                // include student submission attachment
                                //remove "/" that creates a folder if Download All is without user folders
                                String sSubAttachmentFolder = submittersName
                                        + resourceLoader.getString("stuviewsubm.submissatt");//jh + "/";
                                if (!withoutFolders) {
                                    // create a attachment folder for the submission attachments
                                    sSubAttachmentFolder = submittersName
                                            + resourceLoader.getString("stuviewsubm.submissatt") + "/";
                                    sSubAttachmentFolder = escapeInvalidCharsEntry(sSubAttachmentFolder);
                                    final ZipEntry sSubAttachmentFolderEntry = new ZipEntry(
                                            sSubAttachmentFolder);
                                    out.putNextEntry(sSubAttachmentFolderEntry);
                                } else {
                                    sSubAttachmentFolder += "_";
                                    //submittersName = submittersName.concat("_");
                                }

                                // add all submission attachment into the submission attachment folder
                                zipAttachments(out, submittersName, sSubAttachmentFolder, s.getAttachments());
                                out.closeEntry();
                            }

                            if (withFeedbackComment) {
                                // the comments.txt file to show instructor's comments
                                final String zipEntryName = submittersName + "comments"
                                        + AssignmentConstants.ZIP_COMMENT_FILE_TYPE;
                                final String textEntryString = formattedText
                                        .encodeUnicode(s.getFeedbackComment());
                                createTextZipEntry(out, zipEntryName, textEntryString);
                            }

                            if (withFeedbackAttachment) {
                                // create an attachment folder for the feedback attachments
                                String feedbackSubAttachmentFolder = submittersName
                                        + resourceLoader.getString("download.feedback.attachment");
                                if (!withoutFolders) {
                                    feedbackSubAttachmentFolder += "/";
                                    final ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(
                                            feedbackSubAttachmentFolder);
                                    out.putNextEntry(feedbackSubAttachmentFolderEntry);
                                } else {
                                    submittersName = submittersName.concat("_");
                                }

                                // add all feedback attachment folder
                                zipAttachments(out, submittersName, feedbackSubAttachmentFolder,
                                        s.getFeedbackAttachments());
                                out.closeEntry();
                            }
                        } // if

                        if (isAdditionalNotesEnabled && candidateDetailProvider != null) {
                            final List<String> notes = candidateDetailProvider.getAdditionalNotes(u, st)
                                    .orElse(new ArrayList<String>());
                            if (!notes.isEmpty()) {
                                final StringBuilder noteList = new StringBuilder("<ul>");
                                for (String note : notes) {
                                    noteList.append("<li>" + StringEscapeUtils.escapeHtml4(note) + "</li>");
                                }
                                noteList.append("</ul>");
                                submittersAdditionalNotesHtml
                                        .append("<tr><td style='padding-right:10px;padding-left:10px'>"
                                                + submittersString + "</td><td style='padding-right:10px'>"
                                                + noteList + "</td></tr>");
                            }
                        }
                    } else {
                        log.warn(
                                "Can't add submission: {} to zip, missing the submittee or they are no longer allowed to submit in the site",
                                s.getId());
                    }
                } catch (Exception e) {
                    caughtException = e.toString();
                    if (log.isDebugEnabled()) {
                        caughtStackTrace = ExceptionUtils.getStackTrace(e);
                    }
                    break;
                }
            } // if the user is still in site

        } // while -- there is submission

        if (caughtException == null) {
            // continue
            if (withGradeFile) {
                final ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension());
                out.putNextEntry(gradesCSVEntry);
                sheet.write(out);
                out.closeEntry();
            }

            if (isAdditionalNotesEnabled) {
                final ZipEntry additionalEntry = new ZipEntry(
                        root + resourceLoader.getString("assignment.additional.notes.file.title") + ".html");
                out.putNextEntry(additionalEntry);

                String htmlString = emailUtil.htmlPreamble("additionalnotes");
                htmlString += "<h1>" + resourceLoader.getString("assignment.additional.notes.export.title")
                        + "</h1>";
                htmlString += "<div>" + resourceLoader.getString("assignment.additional.notes.export.header")
                        + "</div><br/>";
                htmlString += "<table border=\"1\"  style=\"border-collapse:collapse;\"><tr><th>"
                        + resourceLoader.getString("gen.student") + "</th><th>"
                        + resourceLoader.getString("gen.notes") + "</th>" + submittersAdditionalNotesHtml
                        + "</table>";
                htmlString += "<br/><div>"
                        + resourceLoader.getString("assignment.additional.notes.export.footer") + "</div>";
                htmlString += emailUtil.htmlEnd();
                log.debug("Additional information html: " + htmlString);

                final byte[] wes = htmlString.getBytes();
                out.write(wes);
                additionalEntry.setSize(wes.length);
                out.closeEntry();
            }
        } else {
            // log the error
            exceptionMessage.append(" Exception " + caughtException
                    + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
            if (log.isDebugEnabled()) {
                exceptionMessage.append(caughtStackTrace);
            }
        }
    } catch (IOException e) {
        exceptionMessage.append("IOException for creating submission zip file for assignment " + "\""
                + assignmentTitle + "\" exception: " + e + "\n");
    } finally {
        // Complete the ZIP file
        if (out != null) {
            try {
                out.finish();
                out.flush();
            } catch (IOException e) {
                // tried
            }
            try {
                out.close();
            } catch (IOException e) {
                // tried
            }
        }
    }
}