Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Usage

From source file:cz.muni.fi.xklinec.zipstream.App.java

/**
 * Entry point. //from w w w.  j  a  va2  s  . co  m
 * 
 * @param args
 * @throws FileNotFoundException
 * @throws IOException
 * @throws NoSuchFieldException
 * @throws ClassNotFoundException
 * @throws NoSuchMethodException 
 */
public static void main(String[] args) throws FileNotFoundException, IOException, NoSuchFieldException,
        ClassNotFoundException, NoSuchMethodException, InterruptedException {
    OutputStream fos = null;
    InputStream fis = null;

    if ((args.length != 0 && args.length != 2)) {
        System.err.println(String.format("Usage: app.jar source.apk dest.apk"));
        return;
    } else if (args.length == 2) {
        System.err.println(
                String.format("Will use file [%s] as input file and [%s] as output file", args[0], args[1]));
        fis = new FileInputStream(args[0]);
        fos = new FileOutputStream(args[1]);
    } else if (args.length == 0) {
        System.err.println(String.format("Will use file [STDIN] as input file and [STDOUT] as output file"));
        fis = System.in;
        fos = System.out;
    }

    final Deflater def = new Deflater(9, true);
    ZipArchiveInputStream zip = new ZipArchiveInputStream(fis);

    // List of postponed entries for further "processing".
    List<PostponedEntry> peList = new ArrayList<PostponedEntry>(6);

    // Output stream
    ZipArchiveOutputStream zop = new ZipArchiveOutputStream(fos);
    zop.setLevel(9);

    // Read the archive
    ZipArchiveEntry ze = zip.getNextZipEntry();
    while (ze != null) {

        ZipExtraField[] extra = ze.getExtraFields(true);
        byte[] lextra = ze.getLocalFileDataExtra();
        UnparseableExtraFieldData uextra = ze.getUnparseableExtraFieldData();
        byte[] uextrab = uextra != null ? uextra.getLocalFileDataData() : null;

        // ZipArchiveOutputStream.DEFLATED
        // 

        // Data for entry
        byte[] byteData = Utils.readAll(zip);
        byte[] deflData = new byte[0];
        int infl = byteData.length;
        int defl = 0;

        // If method is deflated, get the raw data (compress again).
        if (ze.getMethod() == ZipArchiveOutputStream.DEFLATED) {
            def.reset();
            def.setInput(byteData);
            def.finish();

            byte[] deflDataTmp = new byte[byteData.length * 2];
            defl = def.deflate(deflDataTmp);

            deflData = new byte[defl];
            System.arraycopy(deflDataTmp, 0, deflData, 0, defl);
        }

        System.err.println(String.format(
                "ZipEntry: meth=%d " + "size=%010d isDir=%5s " + "compressed=%07d extra=%d lextra=%d uextra=%d "
                        + "comment=[%s] " + "dataDesc=%s " + "UTF8=%s " + "infl=%07d defl=%07d " + "name [%s]",
                ze.getMethod(), ze.getSize(), ze.isDirectory(), ze.getCompressedSize(),
                extra != null ? extra.length : -1, lextra != null ? lextra.length : -1,
                uextrab != null ? uextrab.length : -1, ze.getComment(),
                ze.getGeneralPurposeBit().usesDataDescriptor(), ze.getGeneralPurposeBit().usesUTF8ForNames(),
                infl, defl, ze.getName()));

        final String curName = ze.getName();

        // META-INF files should be always on the end of the archive, 
        // thus add postponed files right before them
        if (curName.startsWith("META-INF") && peList.size() > 0) {
            System.err.println(
                    "Now is the time to put things back, but at first, I'll perform some \"facelifting\"...");

            // Simulate som evil being done
            Thread.sleep(5000);

            System.err.println("OK its done, let's do this.");
            for (PostponedEntry pe : peList) {
                System.err.println(
                        "Adding postponed entry at the end of the archive! deflSize=" + pe.deflData.length
                                + "; inflSize=" + pe.byteData.length + "; meth: " + pe.ze.getMethod());

                pe.dump(zop, false);
            }

            peList.clear();
        }

        // Capturing interesting files for us and store for later.
        // If the file is not interesting, send directly to the stream.
        if ("classes.dex".equalsIgnoreCase(curName) || "AndroidManifest.xml".equalsIgnoreCase(curName)) {
            System.err.println("### Interesting file, postpone sending!!!");

            PostponedEntry pe = new PostponedEntry(ze, byteData, deflData);
            peList.add(pe);
        } else {
            // Write ZIP entry to the archive
            zop.putArchiveEntry(ze);
            // Add file data to the stream
            zop.write(byteData, 0, infl);
            zop.closeArchiveEntry();
        }

        ze = zip.getNextZipEntry();
    }

    // Cleaning up stuff
    zip.close();
    fis.close();

    zop.finish();
    zop.close();
    fos.close();

    System.err.println("THE END!");
}

From source file:au.org.ala.biocache.util.AlaFileUtils.java

/**
 * Creates a zip file at the specified path with the contents of the specified directory.
 * NB://from  w ww .j a v a  2 s . co m
 *
 * @param directoryPath The path of the directory where the archive will be created. eg. c:/temp
 * @param zipPath The full path of the archive to create. eg. c:/temp/archive.zip
 * @throws IOException If anything goes wrong
 */
public static void createZip(String directoryPath, String zipPath) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    ZipArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(new File(zipPath));
        bOut = new BufferedOutputStream(fOut);
        tOut = new ZipArchiveOutputStream(bOut);
        addFileToZip(tOut, directoryPath, "");
    } finally {
        tOut.finish();
        tOut.close();
        bOut.close();
        fOut.close();
    }
}

From source file:com.ikon.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory 
 *///from  w  ww .  ja v a  2  s .  co  m
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by openkm");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory
 *///  w ww  .  j  a va 2  s  .com
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Create ZIP archive from file/*w w  w.  j  ava  2  s.  c om*/
 */
public static void createZip(File path, OutputStream os) throws IOException {
    log.debug("createZip({}, {})", new Object[] { path, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        log.debug("FILE {}", path);
        ZipArchiveEntry zae = new ZipArchiveEntry(path.getName());
        zaos.putArchiveEntry(zae);
        FileInputStream fis = new FileInputStream(path);
        IOUtils.copy(fis, zaos);
        fis.close();
        zaos.closeArchiveEntry();

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

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   w w w . ja 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:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java

@Override
public RepeatStatus execute(StepContribution sContribution, ChunkContext sChunkContext) throws Exception {

    // 1. Destination exists
    //    a. Overwrite => default behaviour
    //    b. Update => copy to temporary file, open, read entries, merge with new entries, write merged entries and stream
    // 2. New destination => default behaviour

    Map<String, Object> aSourceParams = new HashMap<String, Object>();
    aSourceParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC,
            ((sChunkContext != null) && (sChunkContext.getStepContext() != null))
                    ? sChunkContext.getStepContext().getStepExecution()
                    : null);/*from w w  w. ja v a 2  s.  co  m*/
    aSourceParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory);
    Resource[] aSourceResources = sourceFactory.getResources(aSourceParams);
    Map<String, Object> aDestinationParams = new HashMap<String, Object>();

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} file(s) to zip", aSourceResources.length);
    }

    if (aSourceResources.length > 0) {

        aDestinationParams.put(ResourceFactoryConstants.PARAM_BASE_DIRECTORY, sourceBaseDirectory);
        aDestinationParams.put(ResourceFactoryConstants.PARAM_STEP_EXEC,
                ((sChunkContext != null) && (sChunkContext.getStepContext() != null))
                        ? sChunkContext.getStepContext().getStepExecution()
                        : null);
        Resource aDestination = destinationFactory.getResource(aDestinationParams);

        ZipArchiveOutputStream aZipArchiveOutputStream = null;
        try {
            aZipArchiveOutputStream = new ZipArchiveOutputStream(aDestination.getFile());

            sourceBaseDirectoryPath = sourceBaseDirectory.getFile().getCanonicalPath();

            for (Resource aSourceResource : aSourceResources) {
                zipResource(aSourceResource, aZipArchiveOutputStream, sContribution, sChunkContext);
            }
        } finally {
            if (aZipArchiveOutputStream != null) {
                aZipArchiveOutputStream.finish();
                aZipArchiveOutputStream.close();
            }
        }
    }

    return RepeatStatus.FINISHED;
}

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 ww . j  a  v a  2s . co 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:fr.gael.ccsds.sip.archive.ZipArchiveManager.java

/**
 * Produces Zip compressed archive./*from  w w w .  jav a2  s .c  o m*/
 */
@Override
public File copy(final File src, final File zip_file, final String dst) throws Exception {
    if (zip_file.exists()) {
        final FileInputStream fis = new FileInputStream(zip_file);
        final ZipArchiveInputStream zis = new ZipArchiveInputStream(fis);

        final File tempFile = File.createTempFile("updateZip", "zip");
        final FileOutputStream fos = new FileOutputStream(tempFile);
        final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);

        // copy the existing entries
        ZipArchiveEntry nextEntry;
        while ((nextEntry = zis.getNextZipEntry()) != null) {
            zos.putArchiveEntry(nextEntry);
            IOUtils.copy(zis, zos);
            zos.closeArchiveEntry();
        }

        // create the new entry
        final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst);
        entry.setSize(src.length());
        zos.putArchiveEntry(entry);
        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, zos);
        sfis.close();
        zos.closeArchiveEntry();

        zos.finish();
        zis.close();
        fis.close();
        zos.close();

        // Rename the new file over the old
        boolean status = zip_file.delete();
        File saved_tempFile = tempFile;
        status = tempFile.renameTo(zip_file);

        // Copy the new file over the old if the renaming failed
        if (!status) {
            final FileInputStream tfis = new FileInputStream(saved_tempFile);
            final FileOutputStream tfos = new FileOutputStream(zip_file);

            final byte[] buf = new byte[1024];
            int i = 0;

            while ((i = tfis.read(buf)) != -1) {
                tfos.write(buf, 0, i);
            }

            tfis.close();
            tfos.close();

            saved_tempFile.delete();
        }

        return zip_file;

    } else {
        final FileOutputStream fos = new FileOutputStream(zip_file);
        final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);

        final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst);
        entry.setSize(src.length());
        zos.putArchiveEntry(entry);

        final FileInputStream sfis = new FileInputStream(src);
        IOUtils.copy(sfis, zos);
        sfis.close();

        zos.closeArchiveEntry();

        zos.finish();
        zos.close();
        fos.close();
    }
    return zip_file;
}

From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java

/**
 * Create a XAR file using commons compress.
 *
 * @param docs The documents to include.
 * @param encodings The charset for each document.
 * @param packageXmlEncoding The encoding of package.xml
 * @return the XAR file as a byte array.
 *///from  www  .j av a2 s  .  c om
protected byte[] createZipFileUsingCommonsCompress(XWikiDocument docs[], String[] encodings,
        String packageXmlEncoding) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(baos);
    ZipArchiveEntry zipp = new ZipArchiveEntry("package.xml");
    zos.putArchiveEntry(zipp);
    zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding));
    for (int i = 0; i < docs.length; i++) {
        String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName();
        if (docs[i].getTranslation() != 0) {
            zipEntryName += "." + docs[i].getLanguage();
        }
        ZipArchiveEntry zipe = new ZipArchiveEntry(zipEntryName);
        zos.putArchiveEntry(zipe);
        String xmlCode = docs[i].toXML(false, false, false, false, getContext());
        zos.write(getEncodedByteArray(xmlCode, encodings[i]));
        zos.closeArchiveEntry();
    }
    zos.finish();
    zos.close();
    return baos.toByteArray();
}