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:edu.ur.ir.ir_export.service.DefaultCollectionExportService.java

/**
 * Export all collections in the repository.
 * /* w ww  .j  a va 2  s. com*/
 * @param repository - repository to export
 * @throws IOException 
 */
public void export(Repository repository, 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);
    }

    File collectionXmlFile = temporaryFileCreator.createTemporaryFile(extension);
    Set<FileInfo> allPictures = createXmlFile(collectionXmlFile, repository.getInstitutionalCollections(),
            true);

    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.digitalpebble.behemoth.util.ContentExtractor.java

private void addToArchive(String fileName, byte[] content, Path dirPath) throws IOException, ArchiveException {
    numEntriesInCurrentArchive++;/*from   w ww. j ava2  s.  c o  m*/
    currentArchive.putArchiveEntry(new ZipArchiveEntry(fileName));
    currentArchive.write(content);
    currentArchive.closeArchiveEntry();
    index.flush();
    if (numEntriesInCurrentArchive == maxNumEntriesInArchive) {
        currentArchive.finish();
        currentArchive.close();
        createArchive(dirPath);
    }
}

From source file:jetbrains.exodus.util.CompressBackupUtil.java

/**
 * Adds the file to the tar archive represented by output stream. It's caller's responsibility to close output stream
 * properly.//from  ww w .  j  a v  a  2  s  .c o m
 *
 * @param out           target archive.
 * @param pathInArchive relative path in archive. It will lead the name of the file in the archive.
 * @param source        file to be added.
 * @param fileSize      size of the file (which is known in most cases).
 * @throws IOException in case of any issues with underlying store.
 */
public static void archiveFile(@NotNull final ArchiveOutputStream out, @NotNull final String pathInArchive,
        @NotNull final File source, final long fileSize) throws IOException {
    if (!source.isFile()) {
        throw new IllegalArgumentException("Provided source is not a file: " + source.getAbsolutePath());
    }
    //noinspection ChainOfInstanceofChecks
    if (out instanceof TarArchiveOutputStream) {
        final TarArchiveEntry entry = new TarArchiveEntry(pathInArchive + source.getName());
        entry.setSize(fileSize);
        entry.setModTime(source.lastModified());
        out.putArchiveEntry(entry);
    } else if (out instanceof ZipArchiveOutputStream) {
        final ZipArchiveEntry entry = new ZipArchiveEntry(pathInArchive + source.getName());
        entry.setSize(fileSize);
        entry.setTime(source.lastModified());
        out.putArchiveEntry(entry);
    } else {
        throw new IOException("Unknown archive output stream");
    }
    try (InputStream input = new FileInputStream(source)) {
        IOUtil.copyStreams(input, fileSize, out, IOUtil.BUFFER_ALLOCATOR);
    }
    out.closeArchiveEntry();
}

From source file:com.mulesoft.jockey.maven.GenerateMojo.java

private void copyArchiveFile(File file, ArchiveOutputStream os, boolean zipFile) throws IOException {
    if (file.isDirectory()) {
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                copyArchiveFile(child, os, zipFile);
            }/* www.j a va2  s  .  c  o  m*/
        }
    } else {
        String relativePath = file.getAbsolutePath();
        relativePath = relativePath.substring(new File(buildDirectory).getAbsolutePath().length() + 1);
        relativePath = relativePath.replaceAll("\\\\", "/");

        if (zipFile) {
            ZipArchiveEntry entry = new ZipArchiveEntry(relativePath);

            os.putArchiveEntry(entry);
            if (isScript(file)) {
                entry.setUnixMode(EXECUTABLE_MODE);
            }
        } else {
            TarArchiveEntry entry = new TarArchiveEntry(relativePath);
            if (isScript(file)) {
                entry.setMode(EXECUTABLE_MODE);
            }
            entry.setSize(file.length());
            os.putArchiveEntry(entry);
        }

        IOUtils.copy(new FileInputStream(file), os);
        os.closeArchiveEntry();
    }
}

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

@Test
public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, 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) MostFiles.S_IFLNK);
        String target = "target.txt";
        entry.setSize(target.getBytes(Charsets.UTF_8).length);
        entry.setMethod(ZipEntry.STORED);

        // Mark the file as being executable.
        Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE);

        long externalAttributes = entry.getExternalAttributes()
                + (MorePosixFilePermissions.toMode(filePermissions) << 16);
        entry.setExternalAttributes(externalAttributes);

        zip.putArchiveEntry(entry);/* w w  w  .j  a  va  2s.  c om*/
        zip.write(target.getBytes(Charsets.UTF_8));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();

    ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(),
            zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), 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:es.ucm.fdi.util.archive.ZipFormat.java

/**
 * Simulates creation of a zip file, but returns only the size of the zip
 * that results from the given input stream
 *//*from w  ww.j  a  v  a2  s .  co  m*/
public int compressedSize(InputStream is) throws IOException {
    try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ZipArchiveOutputStream zout = new ZipArchiveOutputStream(bos);) {
        zout.setMethod(ZipArchiveOutputStream.DEFLATED);
        ZipArchiveEntry entry = new ZipArchiveEntry("z");
        zout.putArchiveEntry(entry);
        int n;
        byte[] bytes = new byte[1024];
        while ((n = is.read(bytes)) > -1) {
            zout.write(bytes, 0, n);
        }
        is.close();
        zout.closeArchiveEntry();
        zout.finish();
        return bos.size();
    }
}

From source file:de.fischer.thotti.core.distbuilder.DistributionBuilder.java

public File buildDistribution() throws Exception, ArchiveException {
    String mahoutVersion = org.apache.mahout.Version.version();
    // @todo Throw an exception if the distfile cannot created
    File output = targetFile;/*from w w  w  .  j a v a  2  s  . c  o m*/

    Set<String> addedFiles = new HashSet<String>();

    List<FetchResult> fetchedArtifacts = depFetcher.fetchDependencies();

    final OutputStream out = new FileOutputStream(output);
    ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

    String subDirectory;

    for (FetchResult fetch : fetchedArtifacts) {
        String coord = fetch.getArtifactCoordinates();

        // @todo This is not safe! It is a hack!
        if (coord.split(":")[0].equals(MAHOUT_GROUP_ID)) {
            subDirectory = MAHOUT_LIB_DIRECTORY;
        } else {
            subDirectory = EXTERNAL_LIB_DIRECTORY;
        }

        for (File file : fetch.getFiles()) {
            String targetCP = subDirectory + "/" + file.getName();
            String targetArchive = BASE_DIRECTORY + "/" + targetCP;

            if (!addedFiles.contains(targetCP)) {
                cpBuilder.addPath(targetCP);

                if (getListener() != null) {
                    StringBuilder sb = new StringBuilder();

                    sb.append("Add: ").append(file.toURI()).append(" as ").append(targetCP);

                    getListener().onAddingMavenArtifact(sb.toString());
                }

                os.putArchiveEntry(new ZipArchiveEntry(targetArchive));
                IOUtils.copy(new FileInputStream(file), os);
                os.closeArchiveEntry();

                addedFiles.add(targetCP);
            }
        }
    }

    cpBuilder.addPath(DATA_DIRECTORY);

    for (File file : dataFiles) {
        String targetCP = DATA_DIRECTORY + "/" + file.getName();
        String targetArchive = BASE_DIRECTORY + "/" + targetCP;

        if (getListener() != null) {
            StringBuilder sb = new StringBuilder();

            sb.append("Add: ").append(file.toURI()).append(" as ").append(targetCP);

            getListener().onAddingTestData(sb.toString());
        }

        os.putArchiveEntry(new ZipArchiveEntry(targetArchive));
        IOUtils.copy(new FileInputStream(file), os);
        os.closeArchiveEntry();
    }

    String testCaseTargetCP = TEST_CASE_LIB_DIRECTORY + "/" + testArtifact.getName();
    String testCaseTargetArchive = BASE_DIRECTORY + "/" + testCaseTargetCP;

    if (getListener() != null) {
        StringBuilder sb = new StringBuilder();

        sb.append("Add: ").append(testArtifact.toURI()).append(" as ").append(testCaseTargetCP);

        listener.onAddingTestCases(sb.toString());
    }

    os.putArchiveEntry(new ZipArchiveEntry(testCaseTargetArchive));
    IOUtils.copy(new FileInputStream(testArtifact), os);
    os.closeArchiveEntry();

    cpBuilder.addPath(testCaseTargetCP);

    generateRunSkript(os);

    out.flush();
    os.close();

    return output;
}

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

/**
 * Apply delta.//from  ww w .j av a2s .  co m
 *
 * @param patch the patch
 * @param source the source
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list,
        String prefix) throws IOException {
    String fileName = null;
    try {
        for (fileName = (next == null ? list.readLine()
                : next); fileName != null; fileName = (next == null ? list.readLine() : next)) {
            if (next != null)
                next = null;
            if (!fileName.startsWith(prefix)) {
                next = fileName;
                return;
            }
            int crcDelim = fileName.lastIndexOf(':');
            int crcStart = fileName.lastIndexOf('|');
            long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16);
            long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16);
            fileName = fileName.substring(prefix.length(), crcStart);
            if ("META-INF/file.list".equalsIgnoreCase(fileName))
                continue;
            if (fileName.contains("!")) {
                String[] embeds = fileName.split("\\!");
                ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc);
                File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip");
                File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip");
                Exception thrown = null;
                try (FileOutputStream out = new FileOutputStream(originalFile);
                        InputStream in = source.getInputStream(original)) {
                    int read = 0;
                    while (-1 < (read = in.read(buffer))) {
                        out.write(buffer, 0, read);
                    }
                    out.flush();
                    applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list,
                            prefix + embeds[0] + "!");
                } catch (Exception e) {
                    thrown = e;
                    throw e;
                } finally {
                    originalFile.delete();
                    try (FileInputStream in = new FileInputStream(outputFile)) {
                        if (thrown == null) {
                            ZipArchiveEntry outEntry = copyEntry(original);
                            output.putArchiveEntry(outEntry);
                            int read = 0;
                            while (-1 < (read = in.read(buffer))) {
                                output.write(buffer, 0, read);
                            }
                            output.flush();
                            output.closeArchiveEntry();
                        }
                    } finally {
                        outputFile.delete();
                    }
                }
            } else {
                try {
                    ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc);
                    if (patchEntry != null) { // new Entry
                        ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName);
                        output.putArchiveEntry(outputEntry);
                        if (!patchEntry.isDirectory()) {
                            try (InputStream in = patch.getInputStream(patchEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                        }
                        closeEntry(output, outputEntry, crc);
                    } else {
                        ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc);
                        if (sourceEntry == null) {
                            throw new FileNotFoundException(
                                    fileName + " not found in " + sourceName + " or " + patchName);
                        }
                        if (sourceEntry.isDirectory()) {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            closeEntry(output, outputEntry, crc);
                            continue;
                        }
                        patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc);
                        if (patchEntry != null) { // changed Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            outputEntry.setTime(patchEntry.getTime());
                            output.putArchiveEntry(outputEntry);
                            byte[] sourceBytes = new byte[(int) sourceEntry.getSize()];
                            try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                for (int erg = sourceStream
                                        .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                .read(sourceBytes, erg, sourceBytes.length - erg))
                                    ;
                            }
                            InputStream patchStream = patch.getInputStream(patchEntry);
                            GDiffPatcher diffPatcher = new GDiffPatcher();
                            diffPatcher.patch(sourceBytes, patchStream, output);
                            patchStream.close();
                            outputEntry.setCrc(crc);
                            closeEntry(output, outputEntry, crc);
                        } else { // unchanged Entry
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry);
                            output.putArchiveEntry(outputEntry);
                            try (InputStream in = source.getInputStream(sourceEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    output.write(buffer, 0, read);
                                }
                            }
                            output.flush();
                            closeEntry(output, outputEntry, crc);
                        }
                    }
                } catch (PatchException pe) {
                    IOException ioe = new IOException();
                    ioe.initCause(pe);
                    throw ioe;
                }
            }
        }
    } catch (Exception e) {
        System.err.println(prefix + fileName);
        throw e;
    } finally {
        source.close();
        output.close();
    }
}

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

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

    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        zip.putArchiveEntry(new ZipArchiveEntry("foo/bar/baz"));
        zip.write(DUMMY_FILE_CONTENTS, 0, DUMMY_FILE_CONTENTS.length);
        zip.closeArchiveEntry();//from  w  w w.  j av  a2s  . com
        zip.putArchiveEntry(new ZipArchiveEntry("foo/"));
        zip.closeArchiveEntry();
        zip.putArchiveEntry(new ZipArchiveEntry("qux/"));
        zip.closeArchiveEntry();
    }

    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo")));
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("foo/bar/baz")));

    assertEquals(ImmutableList.of(extractFolder.resolve("foo/bar/baz")), result);
}

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

/**
 * Compute delta./*from  ww  w . j av a2s . c o  m*/
 *
 * @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();
    }
}