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

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

Introduction

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

Prototype

public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException 

Source Link

Usage

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

/**
 * Entry point. /*  w  w  w. ja v a  2s .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:com.daphne.es.maintain.editor.web.controller.utils.CompressUtils.java

private static void addFilesToCompression(ZipArchiveOutputStream zaos, File file, String dir)
        throws IOException {

    ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, dir + file.getName());
    zaos.putArchiveEntry(zipArchiveEntry);

    if (file.isFile()) {
        BufferedInputStream bis = null;
        try {/*  w  w  w. jav  a  2  s. c  om*/
            bis = new BufferedInputStream(new FileInputStream(file));
            IOUtils.copy(bis, zaos);
            zaos.closeArchiveEntry();
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(bis);
        }
    } else if (file.isDirectory()) {
        zaos.closeArchiveEntry();

        for (File childFile : file.listFiles()) {
            addFilesToCompression(zaos, childFile, dir + file.getName() + File.separator);
        }
    }
}

From source file:aiai.apps.commons.utils.ZipUtils.java

/**
 * Creates a zip entry for the path specified with a name built from the base passed in and the file/directory
 * name. If the path is a directory, a recursive call is made such that the full directory is added to the zip.
 *
 * @param zOut The zip file's output stream
 * @param f The filesystem path of the file/directory being added
 * @param base The base prefix to for the name of the zip file entry
 *
 * @throws IOException If anything goes wrong
 *///  ww  w .  j  av a 2 s  . c o  m
private static void addFileToZip(ZipArchiveOutputStream zOut, File f, String base) throws IOException {
    String entryName = base + f.getName();
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

    zOut.putArchiveEntry(zipEntry);

    if (f.isFile()) {
        try (FileInputStream fInputStream = new FileInputStream(f)) {
            IOUtils.copy(fInputStream, zOut);
            zOut.closeArchiveEntry();
        }
    } else {
        zOut.closeArchiveEntry();
        File[] children = f.listFiles();

        if (children != null) {
            for (File child : children) {
                addFileToZip(zOut, child.getAbsoluteFile(), entryName + "/");
            }
        }
    }
}

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

/**
 * Creates a zip entry for the path specified with a name built from the base passed in and the file/directory
 * name. If the path is a directory, a recursive call is made such that the full directory is added to the zip.
 *
 * @param zOut The zip file's output stream
 * @param path The filesystem path of the file/directory being added
 * @param base The base prefix to for the name of the zip file entry
 *
 * @throws IOException If anything goes wrong
 *///from   ww  w.ja v  a 2s  .  co  m
private static void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException {
    File f = new File(path);
    String entryName = base + f.getName();
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

    zOut.putArchiveEntry(zipEntry);

    if (f.isFile()) {
        FileInputStream fInputStream = null;
        try {
            fInputStream = new FileInputStream(f);
            IOUtils.copy(fInputStream, zOut);
            zOut.closeArchiveEntry();
        } finally {
            IOUtils.closeQuietly(fInputStream);
        }

    } else {
        zOut.closeArchiveEntry();
        File[] children = f.listFiles();

        if (children != null) {
            for (File child : children) {
                addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
            }
        }
    }
}

From source file:com.haulmont.cuba.core.sys.logging.LogArchiver.java

public static void writeArchivedLogToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }/*w ww . jav  a 2s  .  c o m*/

    File tempFile = File.createTempFile(FilenameUtils.getBaseName(logFile.getName()) + "_log_", ".zip");

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(tempFile);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    ArchiveEntry archiveEntry = newArchive(logFile);
    zipOutputStream.putArchiveEntry(archiveEntry);

    FileInputStream logFileInput = new FileInputStream(logFile);
    IOUtils.copyLarge(logFileInput, zipOutputStream);

    logFileInput.close();

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();

    FileInputStream tempFileInput = new FileInputStream(tempFile);
    IOUtils.copyLarge(tempFileInput, outputStream);

    tempFileInput.close();

    FileUtils.deleteQuietly(tempFile);
}

From source file:com.haulmont.cuba.core.sys.logging.LogArchiver.java

public static void writeArchivedLogTailToStream(File logFile, OutputStream outputStream) throws IOException {
    if (!logFile.exists()) {
        throw new FileNotFoundException();
    }//from w  w  w . j  av a 2  s.  c  o m

    ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream);
    zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED);
    zipOutputStream.setEncoding(ZIP_ENCODING);

    byte[] content = getTailBytes(logFile);

    ArchiveEntry archiveEntry = newTailArchive(logFile.getName(), content);
    zipOutputStream.putArchiveEntry(archiveEntry);
    zipOutputStream.write(content);

    zipOutputStream.closeArchiveEntry();
    zipOutputStream.close();
}

From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java

private static void zipFile(ZipArchiveOutputStream out, File file, String parentInZip) {
    ZipArchiveEntry entry = null;//from w  w w.ja va 2s  . c  om
    try {
        if (file.isFile()) {
            // out
            String name = FileUtil.removeFirstIfIsSparator(parentInZip + File.separator + file.getName());
            entry = new ZipArchiveEntry(name);
            logger.info("zip file : " + name);
            out.putArchiveEntry(entry);
            FileUtil.copyFile(file, out);
            out.closeArchiveEntry();
        } else {// ??out

            // ?
            File[] children = file.listFiles();
            if (children != null) {
                for (int i = 0; i < children.length; i++) {
                    zipFile(out, children[i], parentInZip + File.separator + file.getName());
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}

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

/**
 * Mthode permettant la cration et l'organisation d'un fichier zip en lui passant directement un
 * flux d'entre//  w  ww .j ava 2  s .c  om
 *
 * @param inputStream - flux de donnes  enregistrer dans le zip
 * @param filePathNameToCreate - chemin et nom du fichier port par les donnes du flux dans le
 * zip
 * @param outfilename - chemin et nom du fichier zip  creer ou complter
 * @throws IOException
 */
public static void compressStreamToZip(InputStream inputStream, String filePathNameToCreate, String outfilename)
        throws IOException {
    ZipArchiveOutputStream zos = null;
    try {
        zos = new ZipArchiveOutputStream(new FileOutputStream(outfilename));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding("UTF-8");
        zos.putArchiveEntry(new ZipArchiveEntry(filePathNameToCreate));
        IOUtils.copy(inputStream, zos);
        zos.closeArchiveEntry();
    } finally {
        if (zos != null) {
            IOUtils.closeQuietly(zos);
        }
    }
}

From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java

/**
 * Creates a zip entry for the path specified with a name built from the base
 * passed in and the file/directory name. If the path is a directory, a 
 * recursive call is made such that the full directory is added to the zip.
 *
 * @param zOut The zip file's output stream
 * @param path The filesystem path of the file/directory being added
 * @param base The base prefix to for the name of the zip file entry
 *
 * @throws IOException If anything goes wrong
 *//*from   ww  w. ja  v  a  2s.c o m*/
private static void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException {
    File f = new File(path);
    String entryName = base + f.getName();
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

    zOut.putArchiveEntry(zipEntry);

    if (f.isFile()) {
        FileInputStream fInputStream = null;
        try {
            fInputStream = new FileInputStream(f);
            IOUtils.copy(fInputStream, zOut, 65535);
            zOut.closeArchiveEntry();
        } finally {
            fInputStream.close();
        }
    } else {
        zOut.closeArchiveEntry();
        File[] children = f.listFiles();

        if (children != null) {
            for (File child : children) {
                logger.debug("ZIP Adding " + child.getName());
                addFileToZip(zOut, child.getAbsolutePath(), entryName + "/");
            }
        }
    }
}

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

/**
 * Recursively create ZIP archive from directory helper utility 
 *///from   w  w  w .  jav  a2 s  . c  om
private static void createZipHelper(File fs, ZipArchiveOutputStream zaos, String zePath) throws IOException {
    log.debug("createZipHelper({}, {}, {})", new Object[] { fs, zaos, zePath });
    File[] files = fs.listFiles();

    for (int i = 0; i < files.length; i++) {
        if (files[i].isDirectory()) {
            log.debug("DIRECTORY {}", files[i]);
            ZipArchiveEntry zae = new ZipArchiveEntry(zePath + "/" + files[i].getName() + "/");
            zaos.putArchiveEntry(zae);
            zaos.closeArchiveEntry();

            createZipHelper(files[i], zaos, zePath + "/" + files[i].getName());
        } else {
            log.debug("FILE {}", files[i]);
            ZipArchiveEntry zae = new ZipArchiveEntry(zePath + "/" + files[i].getName());
            zaos.putArchiveEntry(zae);
            FileInputStream fis = new FileInputStream(files[i]);
            IOUtils.copy(fis, zaos);
            fis.close();
            zaos.closeArchiveEntry();
        }
    }

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