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

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

Introduction

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

Prototype

public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:org.cloudfoundry.util.FileUtils.java

private static void write(Path root, Path path, ZipArchiveOutputStream out) {
    try {// www. j a  v a 2s . c  o  m
        if (Files.isSameFile(root, path)) {
            return;
        }

        ZipArchiveEntry entry = new ZipArchiveEntry(getRelativePathName(root, path));
        entry.setUnixMode(getUnixMode(path));
        entry.setLastModifiedTime(Files.getLastModifiedTime(path));
        out.putArchiveEntry(entry);

        if (Files.isRegularFile(path)) {
            Files.copy(path, out);
        }

        out.closeArchiveEntry();
    } catch (IOException e) {
        throw Exceptions.propagate(e);
    }
}

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

private BasicPackageFileSystemObject<F2<UnixFsObject, ZipArchiveOutputStream, IoEffect>> directory(
        Directory directory) {// w  w  w.  j av a  2  s.  c o m
    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());
                        }/*from w ww. j a  v a 2  s . co  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

/**
  * Adds a new entry to the archive, takes care of duplicates as well.
  *  @param in                 the stream to read data for the entry from.
  * @param zOut               the stream to write to.
  * @param vPath              the name this entry shall have in the archive.
  * @param lastModified       last modification time for the entry.
  * @param fromArchive        the original archive we are copying this
  * @param symlinkDestination//  ww w.ja  va 2  s.  c  o  m
  */
@SuppressWarnings({ "JavaDoc" })
protected void zipFile(InputStreamSupplier in, ConcurrentJarCreator zOut, String vPath, long lastModified,
        File fromArchive, int mode, String symlinkDestination) throws IOException, ArchiverException {
    getLogger().debug("adding entry " + vPath);

    entries.put(vPath, vPath);

    if (!skipWriting) {
        ZipArchiveEntry ze = new ZipArchiveEntry(vPath);
        setTime(ze, lastModified);

        ze.setMethod(doCompress ? ZipArchiveEntry.DEFLATED : ZipArchiveEntry.STORED);
        ze.setUnixMode(UnixStat.FILE_FLAG | mode);

        InputStream payload;
        if (ze.isUnixSymlink()) {
            ZipEncoding enc = ZipEncodingHelper.getZipEncoding(getEncoding());
            final byte[] bytes = enc.encode(symlinkDestination).array();
            payload = new ByteArrayInputStream(bytes);
            zOut.addArchiveEntry(ze, createInputStreamSupplier(payload));
        } else {
            zOut.addArchiveEntry(ze, wrappedRecompressor(ze, in));
        }
    }
}

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  w w  w  .j  a  v  a  2s. com
    }

    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.AnnotationDrivenPackageStateSerializerTest.java

@Test
public void testDeserializeZipArchiveSimple() throws Exception {
    // produce a zip archive containing a single serialized stream for this test.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipArchiveOutputStream zipOut = new ZipArchiveOutputStream(baos);
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(StreamId.APPLICATION_VERSION.name());
    zipOut.putArchiveEntry(zipEntry);/*from   w w  w.  j a  v  a  2 s.  c  o m*/
    IOUtils.copy(APPLICATION_VERSION_1.getInputStream(), zipOut);
    zipOut.closeArchiveEntry();
    zipOut.close();

    state = new PackageState();
    when(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller().unmarshal(any(Source.class)))
            .thenReturn(applicationVersion);
    ByteArrayInputStream zipIn = new ByteArrayInputStream(baos.toByteArray());
    underTest.deserialize(state, StreamId.APPLICATION_VERSION, zipIn);

    assertNotNull(state.getCreationToolVersion());
    assertEquals(applicationVersion, state.getCreationToolVersion());
    verify(mockedMarshallerMap.get(StreamId.APPLICATION_VERSION).getUnmarshaller())
            .unmarshal(any(Source.class));
}

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);//  w ww .j av  a 2 s  .  c om
    zipArxEntry.setUnixMode(unixPermissions);
    zipArxEntry.setLastModifiedTime(lastModified);
    zipArxEntry.setCreationTime(created);
    zipArxEntry.setCrc(crc);
    return zipArxEntry;
}

From source file:org.dbflute.helper.io.compress.DfZipArchiver.java

protected void addDir(ArchiveOutputStream archive, File topDir, File targetDir) throws IOException {
    final String name = buildEntryName(topDir, targetDir, true);
    archive.putArchiveEntry(new ZipArchiveEntry(name));
    archive.closeArchiveEntry();/*w  ww. jav  a  2  s .  co  m*/
}

From source file:org.dbflute.helper.io.compress.DfZipArchiver.java

protected void addFile(ArchiveOutputStream archive, File topDir, File targetFile) throws IOException {
    final String name = buildEntryName(topDir, targetFile, false);
    archive.putArchiveEntry(new ZipArchiveEntry(name));
    FileInputStream ins = null;/*w  ww . j  a va  2 s  .  c o m*/
    try {
        ins = new FileInputStream(targetFile);
        IOUtils.copy(ins, archive);
    } finally {
        if (ins != null) {
            try {
                ins.close();
            } catch (IOException ignored) {
            }
        }
    }
    archive.closeArchiveEntry();
}

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

/**
 * Make a Zipped up METS package for the given DSpace Object
 *
 * @param context DSpace Context//w  w  w . j  av a  2s  .  c o  m
 * @param dso The DSpace Object
 * @param params Parameters to the Packager script
 * @param pkg Package output stream
 * @throws PackageValidationException
 * @throws AuthorizeException
 * @throws SQLException
 * @throws IOException
 */
protected void writeZipPackage(Context context, DSpaceObject dso, PackageParameters params, OutputStream pkg)
        throws PackageValidationException, CrosswalkException, MetsException, AuthorizeException, SQLException,
        IOException {
    long lmTime = 0;
    if (dso.getType() == Constants.ITEM) {
        lmTime = ((Item) dso).getLastModified().getTime();
    }

    // map of extra streams to put in Zip (these are located during makeManifest())
    MdStreamCache extraStreams = new MdStreamCache();
    ZipArchiveOutputStream zip = new ZipArchiveOutputStream(pkg);
    zip.setComment("METS archive created by DSpace " + Util.getSourceVersion());
    Mets manifest = makeManifest(context, dso, params, extraStreams);

    // copy extra (metadata, license, etc) bitstreams into zip, update manifest
    if (extraStreams != null) {
        for (Map.Entry<MdRef, InputStream> ment : extraStreams.getMap().entrySet()) {
            MdRef ref = ment.getKey();

            // Both Deposit Licenses & CC Licenses which are referenced as "extra streams" may already be
            // included in our Package (if their bundles are already included in the <filSec> section of manifest).
            // So, do a special check to see if we need to link up extra License <mdRef> entries to the bitstream in the <fileSec>.
            // (this ensures that we don't accidentally add the same License file to our package twice)
            linkLicenseRefsToBitstreams(context, params, dso, ref);

            //If this 'mdRef' is NOT already linked up to a file in the package,
            // then its file must be missing.  So, we are going to add a new
            // file to the Zip package.
            if (ref.getXlinkHref() == null || ref.getXlinkHref().isEmpty()) {
                InputStream is = ment.getValue();

                // create a hopefully unique filename within the Zip
                String fname = gensym("metadata");
                // link up this 'mdRef' to point to that file
                ref.setXlinkHref(fname);
                if (log.isDebugEnabled()) {
                    log.debug("Writing EXTRA stream to Zip: " + fname);
                }
                //actually add the file to the Zip package
                ZipArchiveEntry ze = new ZipArchiveEntry(fname);
                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);
                }
                zip.putArchiveEntry(ze);
                Utils.copy(is, zip);
                zip.closeArchiveEntry();

                is.close();
            }
        }
    }

    // write manifest after metadata.
    ZipArchiveEntry me = new ZipArchiveEntry(METSManifest.MANIFEST_FILE);
    if (lmTime != 0) {
        me.setTime(lmTime);
    } else //Set a default modified date so that checksum of Zip doesn't change if Zip contents are unchanged
    {
        me.setTime(DEFAULT_MODIFIED_DATE);
    }

    zip.putArchiveEntry(me);

    // can only validate now after fixing up extraStreams
    // note: only validate METS if specified (default = true)
    if (params.getBooleanProperty("validate", true)) {
        manifest.validate(new MetsValidator());
    }
    manifest.write(new MetsWriter(zip));
    zip.closeArchiveEntry();

    //write any bitstreams associated with DSpace object to zip package
    addBitstreamsToZip(context, dso, params, zip);

    zip.close();

}