Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry setComment

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry setComment

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry setComment.

Prototype

public void setComment(String comment) 

Source Link

Document

Sets the optional comment string for the entry.

Usage

From source file:com.gitblit.utils.CompressionUtils.java

/**
 * Zips the contents of the tree at the (optionally) specified revision and
 * the (optionally) specified basepath to the supplied outputstream.
 * /*from www  .  j  a  v a  2 s .c  o m*/
 * @param repository
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
public static boolean zip(Repository repository, String basePath, String objectId, OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
        zos.setComment("Generated by Gitblit");
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        ObjectReader reader = tw.getObjectReader();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString());
            entry.setSize(reader.getObjectSize(id, Constants.OBJ_BLOB));
            entry.setComment(commit.getName());
            entry.setUnixMode(mode.getBits());
            entry.setTime(modified);
            zos.putArchiveEntry(entry);

            ObjectLoader ldr = repository.open(id);
            ldr.copyTo(zos);
            zos.closeArchiveEntry();
        }
        zos.finish();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to zip files from commit {1}", commit.getName());
    } finally {
        tw.release();
        rw.dispose();
    }
    return success;
}

From source file:ee.sk.digidoc.SignedDoc.java

/**
 * Writes the SignedDoc to an output file
 * and automatically calculates DataFile sizes
 * and digests//from w w w. j  av a  2s . co m
 * @param outputFile output file name
 * @param fTempSdoc temporrary file, copy of original for copying items
 * @throws DigiDocException for all errors
 */
public void writeToStream(OutputStream os/*, File fTempSdoc*/) throws DigiDocException {
    DigiDocException ex1 = validateFormatAndVersion();
    if (ex1 != null)
        throw ex1;
    try {
        DigiDocXmlGenFactory genFac = new DigiDocXmlGenFactory(this);
        if (m_format.equals(SignedDoc.FORMAT_BDOC)) {
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("UTF-8");
            if (m_logger.isDebugEnabled())
                m_logger.debug("OS: " + ((os != null) ? "OK" : "NULL"));
            // write mimetype
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MIMET_FILE_NAME);
            ZipArchiveEntry ze = new ZipArchiveEntry(MIMET_FILE_NAME);
            if (m_comment == null)
                m_comment = DigiDocGenFactory.getUserInfo(m_format, m_version);
            ze.setComment(m_comment);
            ze.setMethod(ZipArchiveEntry.STORED);
            java.util.zip.CRC32 crc = new java.util.zip.CRC32();
            if (m_version.equals(BDOC_VERSION_1_0)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_10.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_11.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                ze.setSize(SignedDoc.MIMET_FILE_CONTENT_20.getBytes().length);
                crc.update(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            ze.setCrc(crc.getValue());
            zos.putArchiveEntry(ze);
            if (m_version.equals(BDOC_VERSION_1_0)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_10.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_1_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_11.getBytes());
            }
            if (m_version.equals(BDOC_VERSION_2_1)) {
                zos.write(SignedDoc.MIMET_FILE_CONTENT_20.getBytes());
            }
            zos.closeArchiveEntry();
            // write manifest.xml
            if (m_logger.isDebugEnabled())
                m_logger.debug("Writing: " + MANIF_FILE_NAME);
            ze = new ZipArchiveEntry(MANIF_DIR_META_INF);
            ze = new ZipArchiveEntry(MANIF_FILE_NAME);
            ze.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
            zos.putArchiveEntry(ze);
            //if(m_logger.isDebugEnabled())
            //   m_logger.debug("Writing manif:\n" + m_manifest.toString());
            zos.write(m_manifest.toXML());
            zos.closeArchiveEntry();
            // write data files
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing DF: " + df.getFileName() + " content: " + df.getContentType()
                            + " df-cache: "
                            + ((df.getDfCacheFile() != null) ? df.getDfCacheFile().getAbsolutePath() : "NONE"));
                InputStream is = null;
                if (df.hasAccessToDataFile())
                    is = df.getBodyAsStream();
                else
                    is = findDataFileAsStream(df.getFileName());
                if (is != null) {
                    File dfFile = new File(df.getFileName());
                    String fileName = dfFile.getName();
                    ze = new ZipArchiveEntry(fileName);
                    if (df.getComment() == null)
                        df.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                    ze.setComment(df.getComment());
                    ze.setSize(dfFile.length());
                    ze.setTime(
                            (df.getLastModDt() != null) ? df.getLastModDt().getTime() : dfFile.lastModified());
                    zos.putArchiveEntry(ze);
                    byte[] data = new byte[2048];
                    int nRead = 0, nTotal = 0;
                    crc = new java.util.zip.CRC32();
                    while ((nRead = is.read(data)) > 0) {
                        zos.write(data, 0, nRead);
                        nTotal += nRead;
                        crc.update(data, 0, nRead);
                    }
                    ze.setSize(nTotal);
                    ze.setCrc(crc.getValue());
                    zos.closeArchiveEntry();
                    is.close();
                }
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                String sFileName = sig.getPath();
                if (sFileName == null) {
                    if (m_version.equals(BDOC_VERSION_2_1))
                        sFileName = SIG_FILE_NAME_20 + (i + 1) + ".xml";
                    else
                        sFileName = SIG_FILE_NAME + (i + 1) + ".xml";
                }
                if (!sFileName.startsWith("META-INF"))
                    sFileName = "META-INF/" + sFileName;
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " orig: "
                            + ((sig.getOrigContent() != null) ? "OK" : "NULL"));
                ze = new ZipArchiveEntry(sFileName);
                if (sig.getComment() == null)
                    sig.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version));
                ze.setComment(sig.getComment());
                String sSig = null;
                if (sig.getOrigContent() != null)
                    sSig = new String(sig.getOrigContent(), "UTF-8");
                else
                    sSig = sig.toString();
                if (sSig != null && !sSig.startsWith("<?xml"))
                    sSig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sSig;
                byte[] sdata = sSig.getBytes("UTF-8");
                if (m_logger.isDebugEnabled())
                    m_logger.debug("Writing SIG: " + sFileName + " xml:\n---\n "
                            + ((sSig != null) ? sSig : "NULL") + "\n---\n ");
                ze.setSize(sdata.length);
                crc = new java.util.zip.CRC32();
                crc.update(sdata);
                ze.setCrc(crc.getValue());
                zos.putArchiveEntry(ze);
                zos.write(sdata);
                zos.closeArchiveEntry();
            }
            zos.close();
        } else if (m_format.equals(SignedDoc.FORMAT_DIGIDOC_XML)) { // ddoc format
            os.write(xmlHeader().getBytes());
            for (int i = 0; i < countDataFiles(); i++) {
                DataFile df = getDataFile(i);
                df.writeToFile(os);
                os.write("\n".getBytes());
            }
            for (int i = 0; i < countSignatures(); i++) {
                Signature sig = getSignature(i);
                if (sig.getOrigContent() != null)
                    os.write(sig.getOrigContent());
                else
                    os.write(genFac.signatureToXML(sig));
                os.write("\n".getBytes());
            }
            os.write(xmlTrailer().getBytes());
        }
    } catch (DigiDocException ex) {
        throw ex; // allready handled
    } catch (Exception ex) {
        DigiDocException.handleException(ex, DigiDocException.ERR_WRITE_FILE);
    }
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta.//from  w w  w  .j a v a2s . com
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:org.itstechupnorth.walrus.base.ArticleBuffer.java

public void saveTo(ZipArchiveOutputStream out) throws IOException {
    saving = true;/*from  w w  w. j  a  v  a  2  s .co  m*/
    final int originalPosition = buffer.position();
    // System.out.println(moniker() + "saving@" + buffer.position());
    try {
        buffer.flip();
        encoder.reset();
        final String name = NAME_PREFIX + getTitleHash() + NAME_SUFFIX;
        final ZipArchiveEntry entry = new ZipArchiveEntry(name);
        entry.setComment(getTitle());
        out.putArchiveEntry(entry);

        outBuffer.clear();
        boolean more = true;
        while (more) {
            final CoderResult result = encoder.encode(buffer, outBuffer, true);
            out.write(outBuffer.array(), 0, outBuffer.position());
            outBuffer.clear();
            more = CoderResult.OVERFLOW.equals(result);
        }

        out.closeArchiveEntry();
    } finally {
        buffer.clear();
        buffer.position(originalPosition);
        // System.out.println(moniker() + "saved@" + buffer.position());
        saving = false;
    }
}

From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedZipEntrySource.java

public void setInputStream(InputStream is) throws IOException {
    this.tmpFile = TempFile.createTempFile("hadoopoffice-protected", ".zip");

    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
    ZipArchiveEntry ze;/*from www  . j a va2s  .  c  om*/
    while ((ze = (ZipArchiveEntry) zis.getNextEntry()) != null) {
        // rewrite zip entries to match the size of the encrypted data (with padding)
        ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
        zeNew.setComment(ze.getComment());
        zeNew.setExtra(ze.getExtra());
        zeNew.setTime(ze.getTime());
        zos.putArchiveEntry(zeNew);
        FilterOutputStream fos2 = new FilterOutputStream(zos) {
            // do not close underlyzing ZipOutputStream
            @Override
            public void close() {
            }
        };
        OutputStream nos;
        if (this.ciEncoder != null) { // encrypt if needed
            nos = new CipherOutputStream(fos2, this.ciEncoder);
        } else { // do not encrypt
            nos = fos2;
        }
        IOUtils.copy(zis, nos);
        nos.close();
        if (fos2 != null) {
            fos2.close();
        }
        zos.closeArchiveEntry();

    }
    zos.close();
    fos.close();
    zis.close();
    IOUtils.closeQuietly(is);
    this.zipFile = new ZipFile(this.tmpFile);

}