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

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

Introduction

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

Prototype

public void write(byte[] b, int offset, int length) throws IOException 

Source Link

Document

Writes bytes to ZIP entry.

Usage

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

/**
 * Entry point. /*from  ww  w .ja v  a  2s. c  om*/
 * 
 * @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:cz.muni.fi.xklinec.zipstream.PostponedEntry.java

/**
 * Writes whole entry to the ZIPArchiveOutputStream.
 * Optionally recomputes CRC32 checksum.
 * /*from  w  w  w  . j  a  v a2  s  .  com*/
 * @param zop
 * @param recomputeCrc
 * @throws IOException 
 */
public void dump(ZipArchiveOutputStream zop, boolean recomputeCrc) throws IOException {
    ZipArchiveEntry zen = (ZipArchiveEntry) ze.clone();

    // recompute CRC?
    if (recomputeCrc) {
        crc.reset();
        crc.update(byteData);
        ze.setCrc(crc.getValue());
    }

    zop.putArchiveEntry(zen);
    zop.write(byteData, 0, byteData.length);
    zop.closeArchiveEntry();
    zop.flush();
}

From source file:com.glaf.core.util.ZipUtils.java

/**
 * //from  w w  w .  j  a v a2s .co m
 * ?zip?
 * 
 * @param files
 *            ?
 * 
 * @param zipFilePath
 *            ?zip ,"/var/data/aa.zip";
 */
public static void compressFile(File[] files, String zipFilePath) {
    if (files != null && files.length > 0) {
        if (isEndsWithZip(zipFilePath)) {
            ZipArchiveOutputStream zaos = null;
            try {
                File zipFile = new File(zipFilePath);
                zaos = new ZipArchiveOutputStream(zipFile);

                // Use Zip64 extensions for all entries where they are
                // required
                zaos.setUseZip64(Zip64Mode.AsNeeded);

                for (File file : files) {
                    if (file != null) {
                        ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName());
                        zaos.putArchiveEntry(zipArchiveEntry);
                        InputStream is = null;
                        try {
                            is = new BufferedInputStream(new FileInputStream(file));
                            byte[] buffer = new byte[BUFFER];
                            int len = -1;
                            while ((len = is.read(buffer)) != -1) {
                                zaos.write(buffer, 0, len);
                            }

                            // Writes all necessary data for this entry.
                            zaos.closeArchiveEntry();
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        } finally {
                            IOUtils.closeStream(is);
                        }
                    }
                }
                zaos.finish();
            } catch (Exception e) {
                throw new RuntimeException(e);
            } finally {
                IOUtils.closeStream(zaos);
            }
        }
    }
}

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

/**
 * Creates a zip file with random content.
 *
 * @author S3460//from  w w  w .j a  v  a  2s  .  c o  m
 * @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:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java

/**
 * Writes a modified version of zip_Source into target.
 *
 * @author S3460/* w  w  w .j  a v a  2  s . c o  m*/
 * @param zipSource the zip source
 * @param target the target
 * @return the zip file
 * @throws Exception the exception
 */
private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception {
    ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target));
    for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) {
        ZipArchiveEntry sourceEntry = enumer.nextElement();
        out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName()));
        byte[] oldBytes = toBytes(zipSource, sourceEntry);
        byte[] newBytes = getRandomBytes();
        byte[] mixedBytes = mixBytes(oldBytes, newBytes);
        out.write(mixedBytes, 0, mixedBytes.length);
        out.flush();
        out.closeArchiveEntry();
    }
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1));
    byte[] bytes = getRandomBytes();
    out.write(bytes, 0, bytes.length);
    out.flush();
    out.closeArchiveEntry();
    out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2)));
    out.closeArchiveEntry();
    out.flush();
    out.finish();
    out.close();
    return new ZipFile(targetFile);
}

From source file:adams.core.io.ZipUtils.java

/**
 * Creates a zip file from the specified files.
 *
 * @param output   the output file to generate
 * @param files   the files to store in the zip file
 * @param stripRegExp   the regular expression used to strip the file names (only applied to the directory!)
 * @param bufferSize   the buffer size to use
 * @return      null if successful, otherwise error message
 *///from   w  w  w .j a v  a2s. co m
@MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html")
public static String compress(File output, File[] files, String stripRegExp, int bufferSize) {
    String result;
    int i;
    byte[] buf;
    int len;
    ZipArchiveOutputStream out;
    BufferedInputStream in;
    FileInputStream fis;
    FileOutputStream fos;
    String filename;
    String msg;
    ZipArchiveEntry entry;

    in = null;
    fis = null;
    out = null;
    fos = null;
    result = null;
    try {
        // does file already exist?
        if (output.exists())
            System.err.println("WARNING: overwriting '" + output + "'!");

        // create ZIP file
        buf = new byte[bufferSize];
        fos = new FileOutputStream(output.getAbsolutePath());
        out = new ZipArchiveOutputStream(new BufferedOutputStream(fos));
        for (i = 0; i < files.length; i++) {
            fis = new FileInputStream(files[i].getAbsolutePath());
            in = new BufferedInputStream(fis);

            // Add ZIP entry to output stream.
            filename = files[i].getParentFile().getAbsolutePath();
            if (stripRegExp.length() > 0)
                filename = filename.replaceFirst(stripRegExp, "");
            if (filename.length() > 0)
                filename += File.separator;
            filename += files[i].getName();
            entry = new ZipArchiveEntry(filename);
            entry.setSize(files[i].length());
            out.putArchiveEntry(entry);

            // Transfer bytes from the file to the ZIP file
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);

            // Complete the entry
            out.closeArchiveEntry();
            FileUtils.closeQuietly(in);
            FileUtils.closeQuietly(fis);
            in = null;
            fis = null;
        }

        // Complete the ZIP file
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
        out = null;
        fos = null;
    } catch (Exception e) {
        msg = "Failed to generate archive '" + output + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:com.iisigroup.cap.log.TimeFolderSizeRollingFileAppender.java

public void zipFiles(List<String> fileList, String destUrl) throws IOException {

    FileUtils.forceMkdir(new File(FilenameUtils.getFullPathNoEndSeparator(destUrl)));
    BufferedInputStream origin = null;
    FileOutputStream fos = null;/*from   ww  w  .  ja  va 2  s . c o  m*/
    BufferedOutputStream bos = null;
    ZipArchiveOutputStream out = null;
    byte data[] = new byte[BUFFER];
    try {
        fos = new FileOutputStream(destUrl);
        bos = new BufferedOutputStream(fos);
        out = new ZipArchiveOutputStream(bos);

        for (String fName : fileList) {
            File file = new File(fName);
            FileInputStream fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            out.closeArchiveEntry();
            fi.close();
            origin.close();
        }

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        if (origin != null) {
            try {
                origin.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

public void create(ArrayList<File> sources, File destFile, File baseDir) throws IOException {

    // to avoid modifying input argument
    ArrayList<File> toAdd = new ArrayList<>(sources);
    ZipArchiveOutputStream zos = null;

    try {//  w  w  w .  j  a va  2  s  . c o m
        zos = new ZipArchiveOutputStream(new FileOutputStream(destFile));
        zos.setMethod(ZipArchiveOutputStream.DEFLATED);
        byte[] b = new byte[1024];

        //log.debug("Creating zip file: "+ficheroZip.getName());
        for (int i = 0; i < toAdd.size(); i++) {
            // note: cannot use foreach because sources gets modified
            File file = toAdd.get(i);

            // zip standard uses fw slashes instead of backslashes, always
            String baseName = baseDir.getAbsolutePath() + '/';
            String fileName = file.getAbsolutePath().substring(baseName.length());
            if (file.isDirectory()) {
                fileName += '/';
            }
            ZipArchiveEntry entry = new ZipArchiveEntry(fileName);

            // skip directories - after assuring that their children *will* be included.
            if (file.isDirectory()) {
                //log.debug("\tAdding dir "+fileName);
                for (File child : file.listFiles()) {
                    toAdd.add(child);
                }
                zos.putArchiveEntry(entry);
                continue;
            }

            //log.debug("\tAdding file "+fileName);

            // Add the zip entry and associated data.
            zos.putArchiveEntry(entry);

            int n;
            try (FileInputStream fis = new FileInputStream(file)) {
                while ((n = fis.read(b)) > -1) {
                    zos.write(b, 0, n);
                }
                zos.closeArchiveEntry();
            }
        }
    } finally {
        if (zos != null) {
            zos.finish();
            zos.close();
        }
    }
}

From source file:com.atolcd.web.scripts.ZipContents.java

public void addToZip(NodeRef node, ZipArchiveOutputStream out, boolean noaccent, String path)
        throws IOException {
    QName nodeQnameType = this.nodeService.getType(node);

    // Special case : links
    if (this.dictionaryService.isSubClass(nodeQnameType, ApplicationModel.TYPE_FILELINK)) {
        NodeRef linkDestinationNode = (NodeRef) nodeService.getProperty(node,
                ContentModel.PROP_LINK_DESTINATION);
        if (linkDestinationNode == null) {
            return;
        }/* w w  w.j a  v  a2 s .c om*/

        // Duplicate entry: check if link is not in the same space of the link destination
        if (nodeService.getPrimaryParent(node).getParentRef()
                .equals(nodeService.getPrimaryParent(linkDestinationNode).getParentRef())) {
            return;
        }

        nodeQnameType = this.nodeService.getType(linkDestinationNode);
        node = linkDestinationNode;
    }

    String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
    nodeName = noaccent ? unAccent(nodeName) : nodeName;

    if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_CONTENT)) {
        ContentReader reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
        if (reader != null) {
            InputStream is = reader.getContentInputStream();

            String filename = path.isEmpty() ? nodeName : path + '/' + nodeName;

            ZipArchiveEntry entry = new ZipArchiveEntry(filename);
            entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime());

            entry.setSize(reader.getSize());
            out.putArchiveEntry(entry);

            byte buffer[] = new byte[BUFFER_SIZE];
            while (true) {
                int nRead = is.read(buffer, 0, buffer.length);
                if (nRead <= 0) {
                    break;
                }

                out.write(buffer, 0, nRead);
            }
            is.close();
            out.closeArchiveEntry();
        } else {
            logger.warn("Could not read : " + nodeName + "content");
        }
    } else if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_FOLDER)
            && !this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_SYSTEM_FOLDER)) {
        List<ChildAssociationRef> children = nodeService.getChildAssocs(node);
        if (children.isEmpty()) {
            String folderPath = path.isEmpty() ? nodeName + '/' : path + '/' + nodeName + '/';
            out.putArchiveEntry(new ZipArchiveEntry(new ZipEntry(folderPath)));
        } else {
            for (ChildAssociationRef childAssoc : children) {
                NodeRef childNodeRef = childAssoc.getChildRef();

                addToZip(childNodeRef, out, noaccent, path.isEmpty() ? nodeName : path + '/' + nodeName);
            }
        }
    } else {
        logger.info("Unmanaged type: " + nodeQnameType.getPrefixedQName(this.namespaceService) + ", filename: "
                + nodeName);
    }
}

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

/**
 * Compute delta.//from  w  ww  .j  a v  a2s  .co  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();
    }
}