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

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

Introduction

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

Prototype

public void setSize(long size) 

Source Link

Document

Sets the uncompressed size of the entry data.

Usage

From source file:org.apache.ant.compress.taskdefs.Zip.java

public Zip() {
    setFactory(new ZipStreamFactory() {
        public ArchiveOutputStream getArchiveStream(OutputStream stream, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveStream(stream, encoding);
            configure(o);/*from   ww w  .j ava2s  .  c o  m*/
            return o;
        }

        public ArchiveOutputStream getArchiveOutputStream(File f, String encoding) throws IOException {
            ZipArchiveOutputStream o = (ZipArchiveOutputStream) super.getArchiveOutputStream(f, encoding);
            configure(o);
            return o;
        }
    });
    setEntryBuilder(new ArchiveBase.EntryBuilder() {
        public ArchiveEntry buildEntry(ArchiveBase.ResourceWithFlags r) {
            boolean isDir = r.getResource().isDirectory();
            ZipArchiveEntry ent = new ZipArchiveEntry(r.getName());
            ent.setTime(round(r.getResource().getLastModified(), 2000));
            ent.setSize(isDir ? 0 : r.getResource().getSize());

            if (!isDir && r.getCollectionFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getMode());
            } else if (isDir && r.getCollectionFlags().hasDirModeBeenSet()) {
                ent.setUnixMode(r.getCollectionFlags().getDirMode());
            } else if (r.getResourceFlags().hasModeBeenSet()) {
                ent.setUnixMode(r.getResourceFlags().getMode());
            } else {
                ent.setUnixMode(isDir ? ArchiveFileSet.DEFAULT_DIR_MODE : ArchiveFileSet.DEFAULT_FILE_MODE);
            }

            if (r.getResourceFlags().getZipExtraFields() != null) {
                ent.setExtraFields(r.getResourceFlags().getZipExtraFields());
            }

            if (keepCompression && r.getResourceFlags().hasCompressionMethod()) {
                ent.setMethod(r.getResourceFlags().getCompressionMethod());
            }

            return ent;
        }
    });
    setFileSetBuilder(new ArchiveBase.FileSetBuilder() {
        public ArchiveFileSet buildFileSet(Resource dest) {
            ArchiveFileSet afs = new ZipFileSet();
            afs.setSrcResource(dest);
            return afs;
        }
    });
}

From source file:org.apache.camel.processor.aggregate.ZipAggregationStrategy.java

@Override
public void onCompletion(Exchange exchange) {
    List<Exchange> list = exchange.getProperty(Exchange.GROUPED_EXCHANGE, List.class);
    try {//w  w  w  .j  a v  a 2s  .  c  o  m
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ZipArchiveOutputStream zout = new ZipArchiveOutputStream(bout);
        for (Exchange item : list) {
            String name = item.getProperty(ZIP_ENTRY_NAME,
                    item.getProperty(Exchange.FILE_NAME, item.getExchangeId(), String.class), String.class);
            byte[] body = item.getIn().getBody(byte[].class);
            ZipArchiveEntry entry = new ZipArchiveEntry(name);
            entry.setSize(body.length);
            zout.putArchiveEntry(entry);
            zout.write(body);
            zout.closeArchiveEntry();
        }
        zout.close();
        exchange.getIn().setBody(bout.toByteArray());
        exchange.removeProperty(Exchange.GROUPED_EXCHANGE);
    } catch (Exception e) {
        throw new RuntimeException("Unable to zip exchanges!", e);
    }
}

From source file:org.apache.karaf.tooling.ArchiveMojo.java

private void addFileToZip(ZipArchiveOutputStream tOut, Path f, String base) throws IOException {
    if (Files.isDirectory(f)) {
        String entryName = base + f.getFileName().toString() + "/";
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        tOut.putArchiveEntry(zipEntry);/* w w  w .  jav  a 2 s.co m*/
        tOut.closeArchiveEntry();
        try (DirectoryStream<Path> children = Files.newDirectoryStream(f)) {
            for (Path child : children) {
                addFileToZip(tOut, child, entryName);
            }
        }
    } else if (useSymLinks && Files.isSymbolicLink(f)) {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setUnixMode(UnixStat.LINK_FLAG | UnixStat.DEFAULT_FILE_PERM);
        tOut.putArchiveEntry(zipEntry);
        tOut.write(Files.readSymbolicLink(f).toString().getBytes());
        tOut.closeArchiveEntry();
    } else {
        String entryName = base + f.getFileName().toString();
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(entryName);
        zipEntry.setSize(Files.size(f));
        if (entryName.contains("/bin/") || (!usePathPrefix && entryName.startsWith("bin"))) {
            if (!entryName.endsWith(".bat")) {
                zipEntry.setUnixMode(0755);
            } else {
                zipEntry.setUnixMode(0644);
            }
        }
        tOut.putArchiveEntry(zipEntry);
        Files.copy(f, tOut);
        tOut.closeArchiveEntry();
    }
}

From source file:org.artifactory.util.ArchiveUtils.java

/**
 * Use for writing streams - must specify file size in advance as well
 *///from  w  w w.  ja  v a  2 s. com
public static ArchiveEntry createArchiveEntry(String relativePath, ArchiveType archiveType, long size) {
    switch (archiveType) {
    case ZIP:
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(relativePath);
        zipEntry.setSize(size);
        return zipEntry;
    case TAR:
    case TARGZ:
    case TGZ:
        TarArchiveEntry tarEntry = new TarArchiveEntry(relativePath);
        tarEntry.setSize(size);
        return tarEntry;
    }
    throw new IllegalArgumentException("Unsupported archive type: '" + archiveType + "'");
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java

private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> directory(
        Directory directory) {/*ww  w .ja v  a  2  s  .c  om*/
    F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() {
        public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) {
            return new IoEffect() {
                public void run() throws IOException {
                    String path = file.path.isBase() ? "." : file.path.asAbsolutePath("./") + "/";

                    ZipArchiveEntry entry = new ZipArchiveEntry(path);
                    entry.setSize(file.size);
                    entry.setTime(file.lastModified.toDateTime().getMillis());
                    if (file.attributes.mode.isSome()) {
                        entry.setUnixMode(file.attributes.mode.some().toInt());
                    }
                    zos.putArchiveEntry(entry);
                    zos.closeArchiveEntry();
                }
            };
        }
    };

    return basicPackageFSO(directory, f);
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipUnixPackage.java

private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> file(
        final Fs<?> fromFile, UnixFsObject file) {
    F2<UnixFsObject, ZipArchiveOutputStream, IoEffect> f = new F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>() {
        public IoEffect f(final UnixFsObject file, final ZipArchiveOutputStream zos) {
            return new IoEffect() {
                public void run() throws IOException {
                    InputStream inputStream = null;
                    BufferedReader reader = null;
                    try {
                        P2<InputStream, Option<Long>> p = filtersAndLineEndingHandingInputStream(file,
                                fromFile.inputStream());

                        inputStream = p._1();

                        long size = p._2().orSome(file.size);

                        ZipArchiveEntry entry = new ZipArchiveEntry(file.path.asAbsolutePath("./"));
                        entry.setSize(size);
                        entry.setTime(file.lastModified.toDateTime().getMillis());
                        if (file.attributes.mode.isSome()) {
                            entry.setUnixMode(file.attributes.mode.some().toInt());
                        }/*  w  ww  .  j a  va 2  s. c  o m*/

                        zos.putArchiveEntry(entry);
                        copy(inputStream, zos, 1024 * 128);
                        zos.closeArchiveEntry();
                    } finally {
                        IOUtil.close(inputStream);
                        IOUtil.close(reader);
                    }
                }
            };
        }
    };

    return basicPackageFSO(file, f);
}

From source file:org.codehaus.plexus.archiver.zip.AbstractZipArchiver.java

protected void zipDir(PlexusIoResource dir, ConcurrentJarCreator zOut, String vPath, int mode,
        String encodingToUse) throws IOException {
    if (addedDirs.update(vPath)) {
        return;/*from   www.j a  va  2 s  .  co  m*/
    }

    getLogger().debug("adding directory " + vPath);

    if (!skipWriting) {
        final boolean isSymlink = dir instanceof SymlinkDestinationSupplier;

        if (isSymlink && vPath.endsWith(File.separator)) {
            vPath = vPath.substring(0, vPath.length() - 1);
        }

        ZipArchiveEntry ze = new ZipArchiveEntry(vPath);

        /*
         * ZipOutputStream.putNextEntry expects the ZipEntry to
         * know its size and the CRC sum before you start writing
         * the data when using STORED mode - unless it is seekable.
         *
         * This forces us to process the data twice.
         */

        if (isSymlink) {
            mode = UnixStat.LINK_FLAG | mode;
        }

        if (dir != null && dir.isExisting()) {
            setTime(ze, dir.getLastModified());
        } else {
            // ZIPs store time with a granularity of 2 seconds, round up
            setTime(ze, System.currentTimeMillis());
        }
        if (!isSymlink) {
            ze.setSize(0);
            ze.setMethod(ZipArchiveEntry.STORED);
            // This is faintly ridiculous:
            ze.setCrc(EMPTY_CRC);
        }
        ze.setUnixMode(mode);

        if (!isSymlink) {
            zOut.addArchiveEntry(ze, createInputStreamSupplier(new ByteArrayInputStream("".getBytes())));
        } else {
            String symlinkDestination = ((SymlinkDestinationSupplier) dir).getSymlinkDestination();
            ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encodingToUse);
            final byte[] bytes = enc.encode(symlinkDestination).array();
            ze.setMethod(ZipArchiveEntry.DEFLATED);
            zOut.addArchiveEntry(ze, createInputStreamSupplier(new ByteArrayInputStream(bytes)));
        }
    }
}

From source file:org.dataconservancy.packaging.tool.impl.ZipArchiveStreamFactory.java

public ZipArchiveEntry newArchiveEntry(String name, long sizeBytes, FileTime created, FileTime lastModified,
        int unixPermissions, long crc) {
    ZipArchiveEntry zipArxEntry = new ZipArchiveEntry(name);
    zipArxEntry.setSize(sizeBytes);
    zipArxEntry.setUnixMode(unixPermissions);
    zipArxEntry.setLastModifiedTime(lastModified);
    zipArxEntry.setCreationTime(created);
    zipArxEntry.setCrc(crc);/*from   w  ww  .  jav a2  s .c o  m*/
    return zipArxEntry;
}

From source file:org.dspace.content.packager.AbstractMETSDisseminator.java

/**
 * Add Bitstreams associated with a given DSpace Object into an
 * existing ZipArchiveOutputStream//ww w  .  j a v  a2  s  .  co  m
 * @param context DSpace Context
 * @param dso The DSpace Object
 * @param params Parameters to the Packager script
 * @param zip Zip output
 */
protected void addBitstreamsToZip(Context context, DSpaceObject dso, PackageParameters params,
        ZipArchiveOutputStream zip)
        throws PackageValidationException, AuthorizeException, SQLException, IOException {
    // how to handle unauthorized bundle/bitstream:
    String unauth = (params == null) ? null : params.getProperty("unauthorized");

    // copy all non-meta bitstreams into zip
    if (dso.getType() == Constants.ITEM) {
        Item item = (Item) dso;

        //get last modified time
        long lmTime = ((Item) dso).getLastModified().getTime();

        Bundle bundles[] = item.getBundles();
        for (int i = 0; i < bundles.length; i++) {
            if (includeBundle(bundles[i])) {
                // unauthorized bundle?
                if (!AuthorizeManager.authorizeActionBoolean(context, bundles[i], Constants.READ)) {
                    if (unauth != null && (unauth.equalsIgnoreCase("skip"))) {
                        log.warn("Skipping Bundle[\"" + bundles[i].getName()
                                + "\"] because you are not authorized to read it.");
                        continue;
                    } else {
                        throw new AuthorizeException(
                                "Not authorized to read Bundle named \"" + bundles[i].getName() + "\"");
                    }
                }
                Bitstream[] bitstreams = bundles[i].getBitstreams();
                for (int k = 0; k < bitstreams.length; k++) {
                    boolean auth = AuthorizeManager.authorizeActionBoolean(context, bitstreams[k],
                            Constants.READ);
                    if (auth || (unauth != null && unauth.equalsIgnoreCase("zero"))) {
                        String zname = makeBitstreamURL(bitstreams[k], params);
                        ZipArchiveEntry ze = new ZipArchiveEntry(zname);
                        if (log.isDebugEnabled()) {
                            log.debug(new StringBuilder().append("Writing CONTENT stream of bitstream(")
                                    .append(bitstreams[k].getID()).append(") to Zip: ").append(zname)
                                    .append(", size=").append(bitstreams[k].getSize()).toString());
                        }
                        if (lmTime != 0) {
                            ze.setTime(lmTime);
                        } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
                        {
                            ze.setTime(DEFAULT_MODIFIED_DATE);
                        }
                        ze.setSize(auth ? bitstreams[k].getSize() : 0);
                        zip.putArchiveEntry(ze);
                        if (auth) {
                            InputStream input = bitstreams[k].retrieve();
                            Utils.copy(input, zip);
                            input.close();
                        } else {
                            log.warn("Adding zero-length file for Bitstream, SID="
                                    + String.valueOf(bitstreams[k].getSequenceID())
                                    + ", not authorized for READ.");
                        }
                        zip.closeArchiveEntry();
                    } else if (unauth != null && unauth.equalsIgnoreCase("skip")) {
                        log.warn("Skipping Bitstream, SID=" + String.valueOf(bitstreams[k].getSequenceID())
                                + ", not authorized for READ.");
                    } else {
                        throw new AuthorizeException("Not authorized to read Bitstream, SID="
                                + String.valueOf(bitstreams[k].getSequenceID()));
                    }
                }
            }
        }
    }

    // Coll, Comm just add logo bitstream to content if there is one
    else if (dso.getType() == Constants.COLLECTION || dso.getType() == Constants.COMMUNITY) {
        Bitstream logoBs = dso.getType() == Constants.COLLECTION ? ((Collection) dso).getLogo()
                : ((Community) dso).getLogo();
        if (logoBs != null) {
            String zname = makeBitstreamURL(logoBs, params);
            ZipArchiveEntry ze = new ZipArchiveEntry(zname);
            if (log.isDebugEnabled()) {
                log.debug("Writing CONTENT stream of bitstream(" + String.valueOf(logoBs.getID()) + ") to Zip: "
                        + zname + ", size=" + String.valueOf(logoBs.getSize()));
            }
            ze.setSize(logoBs.getSize());
            //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
            ze.setTime(DEFAULT_MODIFIED_DATE);
            zip.putArchiveEntry(ze);
            Utils.copy(logoBs.retrieve(), zip);
            zip.closeArchiveEntry();
        }
    }
}

From source file:org.eclipse.jgit.archive.ZipFormat.java

public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader)
        throws IOException {
    // ZipArchiveEntry detects directories by checking
    // for '/' at the end of the filename.
    if (path.endsWith("/") && mode != FileMode.TREE) //$NON-NLS-1$
        throw new IllegalArgumentException(
                MessageFormat.format(ArchiveText.get().pathDoesNotMatchMode, path, mode));
    if (!path.endsWith("/") && mode == FileMode.TREE) //$NON-NLS-1$
        path = path + "/"; //$NON-NLS-1$

    final ZipArchiveEntry entry = new ZipArchiveEntry(path);
    if (mode == FileMode.TREE) {
        out.putArchiveEntry(entry);/*from   w  ww .  j av a  2s  .  c  o m*/
        out.closeArchiveEntry();
        return;
    }

    if (mode == FileMode.REGULAR_FILE) {
        // ok
    } else if (mode == FileMode.EXECUTABLE_FILE || mode == FileMode.SYMLINK) {
        entry.setUnixMode(mode.getBits());
    } else {
        // Unsupported mode (e.g., GITLINK).
        throw new IllegalArgumentException(MessageFormat.format(ArchiveText.get().unsupportedMode, mode));
    }
    entry.setSize(loader.getSize());
    out.putArchiveEntry(entry);
    loader.copyTo(out);
    out.closeArchiveEntry();
}