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.sakaiproject.assignment.impl.AssignmentServiceImpl.java

private void createTextZipEntry(ZipOutputStream out, final String zipEntryName, final String textEntryString)
        throws IOException {
    final ZipEntry textEntry = new ZipEntry(zipEntryName);
    out.putNextEntry(textEntry);/*from  ww w  . ja  v a2 s  . com*/
    if (textEntryString != null) {
        final byte[] text = textEntryString.getBytes();
        out.write(text);
        textEntry.setSize(text.length);
    }
    out.closeEntry();
}

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

protected void zipGroupSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString,
        int typeOfSubmission, Iterator submissions, OutputStream outputStream, StringBuilder exceptionMessage,
        boolean withStudentSubmissionText, boolean withStudentSubmissionAttachment, boolean withGradeFile,
        boolean withFeedbackText, boolean withFeedbackComment, boolean withFeedbackAttachment,
        String gradeFileFormat, boolean includeNotSubmitted) {
    ZipOutputStream out = null;// ww w  . j  a  v a  2  s  . c o  m
    try {
        out = new ZipOutputStream(outputStream);

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

        SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase());
        SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeTypeString);

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

        // Write the header
        sheet.addHeader("Group", rb.getString("grades.eid"), rb.getString("grades.members"),
                rb.getString("grades.grade"), rb.getString("grades.submissionTime"),
                rb.getString("grades.late"));

        // allow add assignment members
        List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);

        // Create the ZIP file
        String submittersName = "";
        String caughtException = null;
        String caughtStackTrace = null;
        while (submissions.hasNext()) {

            GroupSubmission gs = (GroupSubmission) submissions.next();
            AssignmentSubmission s = gs.getSubmission();

            M_log.debug(this + " ZIPGROUP " + (s == null ? "null" : s.getId()));

            //SAK-29314 added a new value where it's by default submitted but is marked when the user submits
            if ((s.getSubmitted() && s.isUserSubmission()) || includeNotSubmitted) {
                try {
                    submittersName = root;

                    User[] submitters = s.getSubmitters();
                    String submitterString = gs.getGroup().getTitle() + " (" + gs.getGroup().getId() + ")";
                    String submittersString = "";
                    String submitters2String = "";

                    for (int i = 0; i < submitters.length; i++) {
                        if (i > 0) {
                            submittersString = submittersString.concat("; ");
                            submitters2String = submitters2String.concat("; ");
                        }
                        String fullName = submitters[i].getSortName();
                        // in case the user doesn't have first name or last name
                        if (fullName.indexOf(",") == -1) {
                            fullName = fullName.concat(",");
                        }
                        submittersString = submittersString.concat(fullName);
                        submitters2String = submitters2String.concat(submitters[i].getDisplayName());
                        // add the eid to the end of it to guarantee folder name uniqness
                        submittersString = submittersString + "(" + submitters[i].getEid() + ")";
                    }
                    String latenessStatus = whenSubmissionMade(s);

                    //Adding the row
                    sheet.addRow(gs.getGroup().getTitle(), gs.getGroup().getId(), submitters2String,
                            s.getGradeDisplay(), s.getTimeSubmittedString(), latenessStatus);

                    if (StringUtil.trimToNull(submitterString) != null) {
                        submittersName = submittersName.concat(StringUtil.trimToNull(submitterString));
                        submittedText = s.getSubmittedText();

                        submittersName = submittersName.concat("/");

                        // record submission timestamp
                        if (s.getSubmitted() && s.getTimeSubmitted() != null) {
                            ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
                            out.putNextEntry(textEntry);
                            byte[] b = (s.getTimeSubmitted().toString()).getBytes();
                            out.write(b);
                            textEntry.setSize(b.length);
                            out.closeEntry();
                        }

                        // create the folder structure - named after the submitter's name
                        if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION
                                && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
                            // include student submission text
                            if (withStudentSubmissionText) {
                                // create the text file only when a text submission is allowed
                                ZipEntry textEntry = new ZipEntry(submittersName + submitterString
                                        + "_submissionText" + ZIP_SUBMITTED_TEXT_FILE_TYPE);
                                out.putNextEntry(textEntry);
                                byte[] text = submittedText.getBytes();
                                out.write(text);
                                textEntry.setSize(text.length);
                                out.closeEntry();
                            }

                            // include student submission feedback text
                            if (withFeedbackText) {
                                // create a feedbackText file into zip
                                ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
                                out.putNextEntry(fTextEntry);
                                byte[] fText = s.getFeedbackText().getBytes();
                                out.write(fText);
                                fTextEntry.setSize(fText.length);
                                out.closeEntry();
                            }
                        }

                        if (typeOfSubmission != Assignment.TEXT_ONLY_ASSIGNMENT_SUBMISSION
                                && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
                            // include student submission attachment
                            if (withStudentSubmissionAttachment) {
                                // create a attachment folder for the submission attachments
                                String sSubAttachmentFolder = submittersName
                                        + rb.getString("stuviewsubm.submissatt") + "/";
                                ZipEntry sSubAttachmentFolderEntry = new ZipEntry(sSubAttachmentFolder);
                                out.putNextEntry(sSubAttachmentFolderEntry);
                                // add all submission attachment into the submission attachment folder
                                zipAttachments(out, submittersName, sSubAttachmentFolder,
                                        s.getSubmittedAttachments());
                                out.closeEntry();
                            }
                        }

                        if (withFeedbackComment) {
                            // the comments.txt file to show instructor's comments
                            ZipEntry textEntry = new ZipEntry(
                                    submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
                            out.putNextEntry(textEntry);
                            byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
                            out.write(b);
                            textEntry.setSize(b.length);
                            out.closeEntry();
                        }

                        if (withFeedbackAttachment) {
                            // create an attachment folder for the feedback attachments
                            String feedbackSubAttachmentFolder = submittersName
                                    + rb.getString("download.feedback.attachment") + "/";
                            ZipEntry feedbackSubAttachmentFolderEntry = new ZipEntry(
                                    feedbackSubAttachmentFolder);
                            out.putNextEntry(feedbackSubAttachmentFolderEntry);
                            // add all feedback attachment folder
                            zipAttachments(out, submittersName, feedbackSubAttachmentFolder,
                                    s.getFeedbackAttachments());
                            out.closeEntry();
                        }

                        if (submittersString.trim().length() > 0) {
                            // the comments.txt file to show instructor's comments
                            ZipEntry textEntry = new ZipEntry(
                                    submittersName + "members" + ZIP_COMMENT_FILE_TYPE);
                            out.putNextEntry(textEntry);
                            byte[] b = FormattedText.encodeUnicode(submittersString).getBytes();
                            out.write(b);
                            textEntry.setSize(b.length);
                            out.closeEntry();
                        }

                    } // if
                } catch (Exception e) {
                    caughtException = e.toString();
                    if (M_log.isDebugEnabled()) {
                        caughtStackTrace = ExceptionUtils.getStackTrace(e);
                    }
                    break;
                }
            } // if the user is still in site

        } // while -- there is submission

        if (caughtException == null) {
            // continue
            if (withGradeFile) {
                ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension());
                out.putNextEntry(gradesCSVEntry);
                sheet.write(out);
                out.closeEntry();
            }
        } else {
            // log the error
            exceptionMessage.append(" Exception " + caughtException
                    + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
            if (M_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
            }
        }
    }
}

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

protected void zipSubmissions(String assignmentReference, String assignmentTitle, String gradeTypeString,
        int 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) {
    ZipOutputStream out = null;//from  www  . java  2 s . c  om

    try {
        out = new ZipOutputStream(outputStream);

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

        SpreadsheetExporter.Type type = SpreadsheetExporter.Type.valueOf(gradeFileFormat.toUpperCase());
        SpreadsheetExporter sheet = SpreadsheetExporter.getInstance(type, assignmentTitle, gradeTypeString);

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

        sheet.addHeader(rb.getString("grades.id"), rb.getString("grades.eid"), rb.getString("grades.lastname"),
                rb.getString("grades.firstname"), rb.getString("grades.grade"),
                rb.getString("grades.submissionTime"), rb.getString("grades.late"));

        // allow add assignment members
        List allowAddSubmissionUsers = allowAddSubmissionUsers(assignmentReference);

        // Create the ZIP file
        String submittersName = "";
        String caughtException = null;
        String caughtStackTrace = null;
        while (submissions.hasNext()) {
            AssignmentSubmission s = (AssignmentSubmission) submissions.next();
            boolean isAnon = assignmentUsesAnonymousGrading(s);
            //SAK-29314 added a new value where it's by default submitted but is marked when the user submits
            if ((s.getSubmitted() && s.isUserSubmission()) || includeNotSubmitted) {
                // get the submission user id and see if the user is still in site
                String userId = s.getSubmitterId();
                try {
                    User u = UserDirectoryService.getUser(userId);
                    if (allowAddSubmissionUsers.contains(u)) {
                        submittersName = root;

                        User[] submitters = s.getSubmitters();
                        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.indexOf(",") == -1) {
                                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
                            String userEid = submitters[i].getEid();
                            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.
                            String latenessStatus = whenSubmissionMade(s);

                            String fullAnonId = s.getAnonymousSubmissionId();
                            String anonTitle = rb.getString("grading.anonymous.title");

                            // SAK-17606
                            if (!isAnon) {
                                sheet.addRow(submitters[i].getDisplayId(), submitters[i].getEid(),
                                        submitters[i].getLastName(), submitters[i].getFirstName(),
                                        s.getGradeDisplay(), s.getTimeSubmittedString(), latenessStatus);
                            } else {
                                sheet.addRow(fullAnonId, fullAnonId, anonTitle, anonTitle, s.getGradeDisplay(),
                                        s.getTimeSubmittedString(), latenessStatus);
                            }
                        }

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

                            // SAK-17606
                            if (isAnon) {
                                submittersName = root + s.getAnonymousSubmissionId();
                                submittersString = s.getAnonymousSubmissionId();
                            }

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

                            // record submission timestamp
                            if (!withoutFolders) {
                                if (s.getSubmitted() && s.getTimeSubmitted() != null) {
                                    ZipEntry textEntry = new ZipEntry(submittersName + "timestamp.txt");
                                    out.putNextEntry(textEntry);
                                    byte[] b = (s.getTimeSubmitted().toString()).getBytes();
                                    out.write(b);
                                    textEntry.setSize(b.length);
                                    out.closeEntry();
                                }
                            }

                            // create the folder structure - named after the submitter's name
                            if (typeOfSubmission != Assignment.ATTACHMENT_ONLY_ASSIGNMENT_SUBMISSION
                                    && typeOfSubmission != Assignment.NON_ELECTRONIC_ASSIGNMENT_SUBMISSION) {
                                // include student submission text
                                if (withStudentSubmissionText) {
                                    // create the text file only when a text submission is allowed
                                    String submittersNameString = submittersName + submittersString;

                                    //remove folder name if Download All is without user folders
                                    if (withoutFolders) {
                                        submittersNameString = submittersName;
                                    }
                                    ZipEntry textEntry = new ZipEntry(submittersNameString + "_submissionText"
                                            + ZIP_SUBMITTED_TEXT_FILE_TYPE);
                                    out.putNextEntry(textEntry);
                                    byte[] text = submittedText.getBytes();
                                    out.write(text);
                                    textEntry.setSize(text.length);
                                    out.closeEntry();
                                }

                                // include student submission feedback text
                                if (withFeedbackText) {
                                    // create a feedbackText file into zip
                                    ZipEntry fTextEntry = new ZipEntry(submittersName + "feedbackText.html");
                                    out.putNextEntry(fTextEntry);
                                    byte[] fText = s.getFeedbackText().getBytes();
                                    out.write(fText);
                                    fTextEntry.setSize(fText.length);
                                    out.closeEntry();
                                }
                            }

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

                                    } else {
                                        sSubAttachmentFolder = sSubAttachmentFolder + "_";
                                        //submittersName = submittersName.concat("_");
                                    }

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

                            if (withFeedbackComment) {
                                // the comments.txt file to show instructor's comments
                                ZipEntry textEntry = new ZipEntry(
                                        submittersName + "comments" + ZIP_COMMENT_FILE_TYPE);
                                out.putNextEntry(textEntry);
                                byte[] b = FormattedText.encodeUnicode(s.getFeedbackComment()).getBytes();
                                out.write(b);
                                textEntry.setSize(b.length);
                                out.closeEntry();
                            }

                            if (withFeedbackAttachment) {
                                // create an attachment folder for the feedback attachments
                                String feedbackSubAttachmentFolder = submittersName
                                        + rb.getString("download.feedback.attachment");
                                if (!withoutFolders) {
                                    feedbackSubAttachmentFolder = feedbackSubAttachmentFolder + "/";
                                    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
                    }
                } catch (Exception e) {
                    caughtException = e.toString();
                    if (M_log.isDebugEnabled()) {
                        caughtStackTrace = ExceptionUtils.getStackTrace(e);
                    }
                    break;
                }
            } // if the user is still in site

        } // while -- there is submission

        if (caughtException == null) {
            // continue
            if (withGradeFile) {
                ZipEntry gradesCSVEntry = new ZipEntry(root + "grades." + sheet.getFileExtension());
                out.putNextEntry(gradesCSVEntry);
                sheet.write(out);
                out.closeEntry();
            }
        } else {
            // log the error
            exceptionMessage.append(" Exception " + caughtException
                    + " for creating submission zip file for assignment " + "\"" + assignmentTitle + "\"\n");
            if (M_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
            }
        }
    }
}

From source file:org.sakaiproject.lessonbuildertool.ccexport.CCExport.java

public boolean outputAllFiles(ZipPrintStream out) {
    try {/* w  ww .  ja  v a 2s .c o m*/
        for (Map.Entry<String, Resource> entry : fileMap.entrySet()) {

            // normally this is a file ID for contenthosting.
            // But jforum gives us an actual filesystem filename. We stick /// on
            // the front to make that clear. inSakai is contenthosting.
            boolean inSakai = !entry.getKey().startsWith("///");

            ZipEntry zipEntry = new ZipEntry(entry.getValue().location);

            // for contenthosting
            ContentResource resource = null;
            // for raw file
            File infile = null;
            InputStream instream = null;
            if (inSakai) {
                resource = contentHostingService.getResource(entry.getKey());
                // if URL there's no file to output. The link XML file will
                // be done at the end, since some links are discovered while outputting manifest
                if (((Resource) entry.getValue()).islink) {
                    continue;
                } else
                    zipEntry.setSize(resource.getContentLength());
            } else {
                infile = new File(entry.getKey().substring(3));
                instream = new FileInputStream(infile);
            }

            out.putNextEntry(zipEntry);

            InputStream contentStream = null;

            // see if this is HTML. If so, we need to scan it.
            String filename = entry.getKey();
            int lastdot = filename.lastIndexOf(".");
            int lastslash = filename.lastIndexOf("/");
            String extension = "";
            if (lastdot >= 0 && lastdot > lastslash)
                extension = filename.substring(lastdot + 1);
            String mimeType = null;
            if (inSakai)
                mimeType = resource.getContentType();
            boolean isHtml = false;
            if (mimeType != null && (mimeType.startsWith("http") || mimeType.equals("")))
                mimeType = null;
            if (mimeType != null && (mimeType.equals("text/html") || mimeType.equals("application/xhtml+xml"))
                    || mimeType == null && (extension.equals("html") || extension.equals("htm"))) {
                isHtml = true;
            }

            try {
                if (isHtml) {
                    // treat html separately. Need to convert urls to relative
                    String content = null;
                    if (inSakai) {
                        content = new String(resource.getContent());
                    } else {
                        byte[] b = new byte[(int) infile.length()];
                        instream.read(b);
                        content = new String(b);
                    }
                    content = relFixup(content, entry.getValue());
                    out.print(content);
                } else {
                    if (inSakai) {
                        contentStream = resource.streamContent();
                    } else {
                        contentStream = instream;
                    }
                    IOUtils.copy(contentStream, out);
                }
            } catch (Exception e) {
                log.error("Lessons export error outputting file " + e);
            } finally {
                IOUtils.closeQuietly(contentStream);
                IOUtils.closeQuietly(instream);
            }

        }
    } catch (Exception e) {
        log.error("Lessons export error outputting file, outputAllFiles " + e);
        setErrKey("simplepage.exportcc-fileerr", e.getMessage());
        return false;
    }

    return true;

}

From source file:org.signserver.anttasks.PostProcessModulesTask.java

/**
 * Replacer for the postprocess-jar Ant macro.
 * // w  w  w. jav a  2s. co m
 * @param replaceincludes Ant list of all files in the jar to replace in
 * @param src Source jar file
 * @param destfile Destination jar file
 * @param properties Properties to replace from
 * @param self The Task (used for logging)
 * @throws IOException in case of error
 */
protected void replaceInJar(String replaceincludes, String src, String destfile, Map properties, Task self)
        throws IOException {
    try {
        self.log("Replace " + replaceincludes + " in " + src + " to " + destfile, Project.MSG_VERBOSE);

        File srcFile = new File(src);
        if (!srcFile.exists()) {
            throw new FileNotFoundException(srcFile.getAbsolutePath());
        }

        // Expand properties of all files in replaceIncludes
        HashSet<String> replaceFiles = new HashSet<String>();
        String[] rfiles = replaceincludes.split(",");
        for (int i = 0; i < rfiles.length; i++) {
            rfiles[i] = rfiles[i].trim();
        }
        replaceFiles.addAll(Arrays.asList(rfiles));
        self.log("Files to replace: " + replaceFiles, Project.MSG_INFO);

        // Open source zip file
        ZipFile zipSrc = new ZipFile(srcFile);
        ZipOutputStream zipDest = new ZipOutputStream(new FileOutputStream(destfile));

        // For each entry in the source file copy them to dest file and postprocess if necessary
        Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();

            if (entry.isDirectory()) {
                // Just put the directory
                zipDest.putNextEntry(entry);
            } else {
                // If we should postprocess the entry
                if (replaceFiles.contains(name)) {
                    name += (" [REPLACE]");
                    self.log(name, Project.MSG_VERBOSE);

                    // Create a new zip entry for the file
                    ZipEntry newEntry = new ZipEntry(entry.getName());
                    newEntry.setComment(entry.getComment());
                    newEntry.setExtra(entry.getExtra());
                    zipDest.putNextEntry(newEntry);

                    // Read the old document
                    StringBuffer oldDocument = stringBufferFromFile(zipSrc.getInputStream(entry));
                    self.log("Before replace ********\n" + oldDocument.toString() + "\n", Project.MSG_DEBUG);

                    // Do properties substitution
                    StrSubstitutor sub = new StrSubstitutor(properties);
                    StringBuffer newerDocument = commentReplacement(oldDocument, properties);
                    String newDocument = sub.replace(newerDocument);
                    self.log("After replace ********\n" + newDocument.toString() + "\n", Project.MSG_DEBUG);

                    // Write the new document
                    byte[] newBytes = newDocument.getBytes("UTF-8");
                    entry.setSize(newBytes.length);
                    copy(new ByteArrayInputStream(newBytes), zipDest);
                } else {
                    // Just copy the entry to dest zip file
                    name += (" []");
                    self.log(name, Project.MSG_VERBOSE);
                    zipDest.putNextEntry(entry);
                    copy(zipSrc.getInputStream(entry), zipDest);
                }
                zipDest.closeEntry();
            }
        }
        zipSrc.close();
        zipDest.close();
    } catch (IOException ex) {
        throw new BuildException(ex);
    }
}

From source file:org.silverpeas.applicationbuilder.WriteOnlyArchive.java

/**
 * Adds an XML file in the archive by the means of streams.
 *
 * @param xmlDoc the XML document to add in the archive
 * @since 1.0//from   w ww. j a v a2  s . co  m
 * @roseuid 3AAF4D630303
 */
public void add(XmlDocument xmlDoc) throws AppBuilderException {
    try {
        addDirectory(xmlDoc.getLocation());
        ZipEntry entry = getNormalizedEntry(xmlDoc.getArchivePath());
        entry.setSize(xmlDoc.getDocumentSize());
        jarOut.putNextEntry(entry);
        xmlDoc.saveTo(getOutputStream());
        getOutputStream().flush();
        getOutputStream().closeEntry();
    } catch (Exception e) {
        throw new AppBuilderException(
                getName() + " : impossible to add the document \"" + xmlDoc.getArchivePath() + '"', e);
    }
}

From source file:org.silverpeas.applicationbuilder.WriteOnlyArchive.java

/**
 * Adds a new entry from a stream. The entry is placed and named according to the entry. It can be
 * usefull when merging two archives./* w w  w  . j av  a  2  s.  c  om*/
 *
 * @param entry the description of the new entry
 * @param in the stream carrying the contents of the new entry
 * @since 1.0
 */
public void add(ApplicationBuilderItem entry, InputStream contents) throws AppBuilderException {
    try {
        addDirectory(entry.getLocation());
        ZipEntry destEntry = getNormalizedEntry(entry.getArchivePath());
        destEntry.setSize(entry.getSize());
        getOutputStream().putNextEntry(destEntry);
    } catch (Exception e) {
        throw new AppBuilderException(
                getName() + " : impossible to create new entry \"" + entry.getArchivePath() + '"', e);
    }
    try {
        IOUtils.copy(contents, getOutputStream());
        contents.close();
        getOutputStream().flush();
        getOutputStream().closeEntry();
    } catch (Exception e) {
        throw new AppBuilderException(
                getName() + " : impossible to write contents of \"" + entry.getArchivePath() + '"', e);
    } finally {
        IOUtils.closeQuietly(contents);
    }
}

From source file:org.sourcepit.tpmp.SimpleZipper.java

public void zip(final File platformDir, File platformZipFile, final String pathPrefix) {
    new IOOperation<ZipOutputStream>(zipOut(fileOut(platformZipFile, true))) {
        @Override/*from  w  w  w. j  av a2 s  .c  o m*/
        protected void run(final ZipOutputStream zipOut) throws IOException {
            org.sourcepit.common.utils.file.FileUtils.accept(platformDir, new FileVisitor() {
                @Override
                public boolean visit(File file) {
                    if (!file.equals(platformDir)) {
                        try {
                            String path = PathUtils.getRelativePath(file, platformDir, "/");
                            if (pathPrefix != null) {
                                path = pathPrefix + "/" + path;
                            }
                            pack(zipOut, file, path);
                        } catch (IOException e) {
                            throw Exceptions.pipe(e);
                        }
                    }
                    return true;
                }

                private void pack(final ZipOutputStream zipOut, File file, final String path)
                        throws IOException {
                    if (file.isDirectory()) {
                        ZipEntry entry = new ZipEntry(path + "/");
                        zipOut.putNextEntry(entry);
                        zipOut.closeEntry();
                    } else {
                        ZipEntry entry = new ZipEntry(path);
                        entry.setSize(file.length());
                        zipOut.putNextEntry(entry);
                        new IOOperation<InputStream>(buffIn(fileIn(file))) {
                            @Override
                            protected void run(InputStream openFile) throws IOException {
                                IOUtils.copy(openFile, zipOut);
                            }
                        }.run();
                        zipOut.closeEntry();
                    }
                }
            });
        }
    }.run();
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Compresses the given files into a ZIP file.
 * <p>//from  w  w w.  j  ava 2  s .  co  m
 * The ZIP file must not be a directory and its parent directory must exist.
 *
 * @param filesToPack
 *          files that needs to be zipped.
 * @param destZipFile
 *          ZIP file that will be created or overwritten.
 */
public static void packEntries(File[] filesToPack, File destZipFile) {
    log.debug("Compressing '{}' into '{}'.", filesToPack, destZipFile);

    ZipOutputStream out = null;
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(destZipFile);
        out = new ZipOutputStream(new BufferedOutputStream(fos));

        for (int i = 0; i < filesToPack.length; i++) {
            File fileToPack = filesToPack[i];

            ZipEntry zipEntry = new ZipEntry(fileToPack.getName());
            zipEntry.setSize(fileToPack.length());
            zipEntry.setTime(fileToPack.lastModified());
            out.putNextEntry(zipEntry);
            FileUtil.copy(fileToPack, out);
            out.closeEntry();
        }
    } catch (IOException e) {
        throw ZipExceptionUtil.rethrow(e);
    } finally {
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(fos);
    }
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Compresses the given directory and all its sub-directories into a ZIP file.
 *
 * @param dir// w  ww  .j  a  v  a  2  s  . co  m
 *          root directory.
 * @param out
 *          ZIP output stream.
 * @param mapper
 *          call-back for renaming the entries.
 * @param pathPrefix
 *          prefix to be used for the entries.
 * @param mustHaveChildren
 *          if true, but directory to pack doesn't have any files, throw an exception.
 */
private static void pack(File dir, ZipOutputStream out, NameMapper mapper, String pathPrefix,
        boolean mustHaveChildren) throws IOException {
    String[] filenames = dir.list();
    if (filenames == null) {
        if (!dir.exists()) {
            throw new ZipException("Given file '" + dir + "' doesn't exist!");
        }
        throw new IOException("Given file is not a directory '" + dir + "'");
    }

    if (mustHaveChildren && filenames.length == 0) {
        throw new ZipException("Given directory '" + dir + "' doesn't contain any files!");
    }

    for (int i = 0; i < filenames.length; i++) {
        String filename = filenames[i];
        File file = new File(dir, filename);
        boolean isDir = file.isDirectory();
        String path = pathPrefix + file.getName(); // NOSONAR
        if (isDir) {
            path += PATH_SEPARATOR; // NOSONAR
        }

        // Create a ZIP entry
        String name = mapper.map(path);
        if (name != null) {
            ZipEntry zipEntry = new ZipEntry(name);
            if (!isDir) {
                zipEntry.setSize(file.length());
                zipEntry.setTime(file.lastModified());
            }

            out.putNextEntry(zipEntry);

            // Copy the file content
            if (!isDir) {
                FileUtil.copy(file, out);
            }

            out.closeEntry();
        }

        // Traverse the directory
        if (isDir) {
            pack(file, out, mapper, path, false);
        }
    }
}