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:com.google.jenkins.plugins.persistentmaster.volume.zip.ZipCreator.java

private void copyRegularFile(Path file, String filenameInZip) throws IOException {
    logger.finer("Adding file: " + file + " with filename: " + filenameInZip);
    ZipArchiveEntry entry = new ZipArchiveEntry(filenameInZip);
    zipStream.putArchiveEntry(entry);//from   ww w .ja  v  a2 s. co  m
    Files.copy(file, zipStream);
    zipStream.closeArchiveEntry();
}

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

/**
 * Computes the binary differences of two zip files. For all files contained in source and target which
 * are not equal, the binary difference is caluclated by using
 * {@link com.nothome.delta.Delta#compute(byte[], InputStream, DiffWriter)}.
 * If the files are equal, nothing is written to the output for them.
 * Files contained only in target and files to small for {@link com.nothome.delta.Delta} are copied to output.
 * Files contained only in source are ignored.
 * At last a list of all files contained in target is written to <code>META-INF/file.list</code> in output.
 *
 * @param sourceName the original zip file
 * @param targetName a modification of the original zip file
 * @param source the original zip file//w w  w  .  j  av  a2s.  c o m
 * @param target a modification of the original zip file
 * @param output the zip file where the patches have to be written to
 * @throws IOException if an error occurs reading or writing any entry in a zip file
 */
public void computeDelta(String sourceName, String targetName, ZipFile source, ZipFile target,
        ZipArchiveOutputStream output) throws IOException {
    ByteArrayOutputStream listBytes = new ByteArrayOutputStream();
    PrintWriter list = new PrintWriter(new OutputStreamWriter(listBytes));
    list.println(sourceName);
    list.println(targetName);
    computeDelta(source, target, output, list, "");
    list.close();
    ZipArchiveEntry listEntry = new ZipArchiveEntry("META-INF/file.list");
    output.putArchiveEntry(listEntry);
    output.write(listBytes.toByteArray());
    output.closeArchiveEntry();
    output.finish();
    output.flush();
}

From source file:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export the specified institutional collection.
 * /* ww w .j a v a2s .  co m*/
 * @param collection - collection to export
 * @param includeChildren - if true children should be exported
 * @param zipFileDestination - zip file destination to store the collection information
 * @throws IOException 
 */
public void export(InstitutionalCollection collection, boolean includeChildren, File zipFileDestination)
        throws IOException {

    // create the path if it doesn't exist
    String path = FilenameUtils.getPath(zipFileDestination.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(zipFileDestination.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    List<InstitutionalCollection> collections = new LinkedList<InstitutionalCollection>();
    collections.add(collection);
    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, collections, includeChildren);

    FileOutputStream out = new FileOutputStream(zipFileDestination);
    ArchiveOutputStream os = null;
    try {
        os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
        os.putArchiveEntry(new ZipArchiveEntry("collection.xml"));

        FileInputStream fis = null;
        try {
            log.debug("adding xml file");
            fis = new FileInputStream(collectionXmlFile);
            IOUtils.copy(fis, os);
        } finally {
            if (fis != null) {
                fis.close();
                fis = null;
            }
        }

        log.debug("adding pictures size " + allPictures.size());
        for (FileInfo fileInfo : allPictures) {
            File f = new File(fileInfo.getFullPath());
            String name = FilenameUtils.getName(fileInfo.getFullPath());
            name = name + '.' + fileInfo.getExtension();
            log.debug(" adding name " + name);
            os.putArchiveEntry(new ZipArchiveEntry(name));
            try {
                log.debug("adding input stream");
                fis = new FileInputStream(f);
                IOUtils.copy(fis, os);
            } finally {
                if (fis != null) {
                    fis.close();
                    fis = null;
                }
            }
        }

        os.closeArchiveEntry();
        out.flush();
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (os != null) {
            os.close();
            os = null;
        }
    }

    FileUtils.deleteQuietly(collectionXmlFile);

}

From source file:com.silverpeas.util.ZipManager.java

/**
 * Mthode compressant un dossier de faon rcursive au format zip.
 *
 * @param folderToZip - dossier  compresser
 * @param zipFile - fichier zip  creer/* w  w w.  ja v  a2s.c o m*/
 * @return la taille du fichier zip gnr en octets
 * @throws FileNotFoundException
 * @throws IOException
 */
public static long compressPathToZip(File folderToZip, File zipFile) throws IOException {
    ZipArchiveOutputStream zos = null;
    try {
        // cration du flux zip
        zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(CharEncoding.UTF_8);
        Collection<File> folderContent = FileUtils.listFiles(folderToZip, null, true);
        for (File file : folderContent) {
            String entryName = file.getPath().substring(folderToZip.getParent().length() + 1);
            entryName = FilenameUtils.separatorsToUnix(entryName);
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            InputStream in = new FileInputStream(file);
            IOUtils.copy(in, zos);
            zos.closeArchiveEntry();
            IOUtils.closeQuietly(in);
        }
    } finally {
        if (zos != null) {
            IOUtils.closeQuietly(zos);
        }
    }
    return zipFile.length();
}

From source file:javaaxp.core.service.impl.fileaccess.XPSZipFileAccess.java

protected ZipArchiveEntry getEntry(String entryName) throws XPSError {
    ZipArchiveEntry entry = getRawEntry(entryName);
    if (entry != null)
        return entry;
    entry = getPiece(entryName, 0);//w w w  . j a  va2  s.  c  o  m
    if (entry == null)
        return null;

    List<ZipArchiveEntry> allPieces = getAllPieces(entryName);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    try {
        for (ZipArchiveEntry e : allPieces) {
            outputStream.write(getEntryData(e));
        }
        outputStream.close();
        entry = new ZipArchiveEntry(entryName);
        fZipEntries.put(entryName, entry);
        fDataCache.put(entryName, outputStream.toByteArray());
    } catch (IOException e1) {
        throw new XPSError(e1);
    }
    for (ZipArchiveEntry e : allPieces) {
        fZipEntries.remove(e.getName());
        fDataCache.remove(e.getName());
    }
    return entry;
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime()
        throws InterruptedException, IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);/*from www. jav a2 s  .c o  m*/
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Creates a zip file with random content.
 *
 * @author S3460//  w ww  .jav  a  2 s  .com
 * @param source the source
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeSourceZipFile(File source) throws Exception {
    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(source));
    int size = randomSize(entryMaxSize);
    for (int i = 0; i < size; i++) {
        out.putArchiveEntry(new ZipArchiveEntry("zipentry" + i));
        int anz = randomSize(10);
        for (int j = 0; j < anz; j++) {
            byte[] bytes = getRandomBytes();
            out.write(bytes, 0, bytes.length);
        }
        out.flush();
        out.closeArchiveEntry();
    }
    //add leeres Entry
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + size));
    out.flush();
    out.closeArchiveEntry();
    out.flush();
    out.finish();
    out.close();
    return new ZipFile(source);
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * This method creates an ArchiveEntry w/o the need of a File required by
 * ArchiveOutputStream.createArchiveEntry(File inputFile, String entryName).
 * /* w ww . j  a  v a 2s.  c om*/
 * @param aos archive output stream.
 * @param name name of entry.
 * @param size size in bytes of the entry.
 * @return an archive entry that matches the archive stream.
 */
public ArchiveEntry createArchiveEntry(ArchiveOutputStream aos, String name, long size) {
    if (aos instanceof TarArchiveOutputStream) {
        final TarArchiveEntry te = new TarArchiveEntry(name);
        te.setSize(size);
        return te;
    } else if (aos instanceof ZipArchiveOutputStream) {
        final ZipArchiveEntry ze = new ZipArchiveEntry(name);
        ze.setSize(size);
        return ze;
    }
    throw new UnsupportedOperationException("unsupported archive " + aos.getClass());
}

From source file:com.facebook.buck.zip.UnzipTest.java

@Test
public void testExtractSymlink() throws IOException {
    assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS)));

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("link.txt");
        entry.setUnixMode((int) MoreFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);
        zip.putArchiveEntry(entry);/*  w  ww . j a v  a 2  s . c  o m*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.ExistingFileMode.OVERWRITE);
    Path link = extractFolder.toAbsolutePath().resolve("link.txt");
    assertTrue(Files.isSymbolicLink(link));
    assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt"));
}

From source file:com.mediaworx.ziputils.Zipper.java

/**
 * Adds the given plaintextContent as a file to the zip archive using the given relative path using the given
 * encoding.//from w w w.j av  a 2 s  .c  o  m
 * @param zipRelativePath   the path of the file relative to the zip root
 * @param plaintextContent  text content to be added as a file
 * @param encoding          the encoding to be used
 * @throws IOException Exceptions from the underlying package framework are bubbled up
 */
public void addStringAsFile(String zipRelativePath, String plaintextContent, String encoding)
        throws IOException {
    zip.putArchiveEntry(new ZipArchiveEntry(zipRelativePath));
    IOUtils.copy(new ByteArrayInputStream(plaintextContent.getBytes(encoding)), zip);
    zip.closeArchiveEntry();
}