Example usage for org.apache.commons.compress.archivers.zip ZipArchiveInputStream close

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

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

/**
 * Entry point. /*  w ww . j a  v  a2 s.com*/
 * 
 * @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.zimbra.cs.util.ZipUtil.java

/**
 *
 * @param inputStream archive input stream
 * @param locale - best guess as to locale for the filenames in the archive
 * @param seqNo - the order of the item to return (excluding directory entries)
 * @return//  www  .j  a  v  a2s  .c o  m
 * @throws IOException
 */
public static ZipNameAndSize getZipEntryNameAndSize(InputStream inputStream, Locale locale, int seqNo)
        throws IOException {
    ZipArchiveInputStream zis = new ZipArchiveInputStream(inputStream, cp437charset.name(),
            false /* useUnicodeExtraFields - we do our own handling of this */);
    ZipArchiveEntry ze;
    int idx = 0;
    while ((ze = zis.getNextZipEntry()) != null) {
        if (ze.isDirectory()) {
            continue;
        }
        if (idx++ == seqNo) {
            String entryName = bestGuessAtEntryName(ze, locale);
            return new ZipNameAndSize(entryName, ze.getSize(), zis);
        }
    }
    zis.close();
    throw new IOException("file " + seqNo + " not in archive");
}

From source file:eml.studio.server.file.FileUploadServlet.java

public static void unZipFiles(InputStream instream, String ID) throws IOException {
    ZipArchiveInputStream zin = new ZipArchiveInputStream(instream);
    java.util.zip.ZipEntry entry = null;
    while ((entry = zin.getNextZipEntry()) != null) {
        String zipEntryName = entry.getName();
        String outPath = zipEntryName.replaceAll("\\*", "/");
        String path = "lib";
        path += zipEntryName.substring(zipEntryName.indexOf('/'), zipEntryName.length());
        System.out.println("[path ]:" + path);
        if (!outPath.endsWith("/")) {
            InputStream in = zin;
            HDFSIO.uploadModel("/" + ID + "/" + path, in);
        }//from  www. j ava  2  s . c o  m
    }
    zin.close();
}

From source file:fr.ens.biologie.genomique.eoulsan.modules.mapping.hadoop.ReadsMapperHadoopModule.java

/**
 * Compute the checksum of a ZIP file.// w  w  w .  j  a va  2  s  . co m
 * @param in input stream
 * @return the checksum as a string
 * @throws IOException if an error occurs while creating the checksum
 */
private static String computeZipCheckSum(final InputStream in) throws IOException {

    ZipArchiveInputStream zais = new ZipArchiveInputStream(in);

    // Create Hash function
    final Hasher hs = Hashing.md5().newHasher();

    // Store entries in a map
    final Map<String, long[]> map = new HashMap<>();

    ZipArchiveEntry e;

    while ((e = zais.getNextZipEntry()) != null) {
        map.put(e.getName(), new long[] { e.getSize(), e.getCrc() });
    }

    zais.close();

    // Add values to hash function in an ordered manner
    for (String filename : new TreeSet<>(map.keySet())) {

        hs.putString(filename, StandardCharsets.UTF_8);
        for (long l : map.get(filename)) {
            hs.putLong(l);
        }
    }

    return hs.hash().toString();
}

From source file:com.googlecode.t7mp.util.ZipUtil.java

public static void unzip(InputStream warInputStream, File destination) {
    try {/*  w ww.j a  v  a2 s .  co  m*/
        ZipArchiveInputStream in = null;
        try {
            in = new ZipArchiveInputStream(warInputStream);

            ZipArchiveEntry entry = null;
            while ((entry = in.getNextZipEntry()) != null) {
                File outfile = new File(destination.getCanonicalPath() + "/" + entry.getName());
                outfile.getParentFile().mkdirs();
                if (entry.isDirectory()) {
                    outfile.mkdir();
                    continue;
                }
                OutputStream o = new FileOutputStream(outfile);
                try {
                    IOUtils.copy(in, o);
                } finally {
                    o.close();
                }
            }
        } finally {
            if (in != null) {
                in.close();
            }
        }
        warInputStream.close();
    } catch (FileNotFoundException e) {
        throw new TomcatSetupException(e.getMessage(), e);
    } catch (IOException e) {
        throw new TomcatSetupException(e.getMessage(), e);
    }
}

From source file:com.googlecode.dex2jar.reader.CCZipExtractor.java

@Override
public byte[] extract(byte[] data, String name) throws IOException {
    ZipArchiveInputStream zis = null;
    try {/*w w w  .  j ava 2  s  .  c o m*/
        zis = new ZipArchiveInputStream(new ByteArrayInputStream(data));
        for (ZipArchiveEntry e = zis.getNextZipEntry(); e != null; e = zis.getNextZipEntry()) {
            e.getGeneralPurposeBit().useEncryption(false);
            if (e.getName().equals(name)) {
                data = IOUtils.toByteArray(zis);
                zis.close();
                return data;
            }
        }
    } finally {
        IOUtils.closeQuietly(zis);
    }
    throw new IOException("can't find classes.dex in the zip");
}

From source file:io.github.runassudo.gtfs.ZipStreamGTFSFile.java

public FlatGTFSFile toFlatFile() throws IOException {
    File destBase = new File(
            new File(GTFSCollection.cacheDir,
                    Hashing.sha256().hashString(parentFile.getName(), StandardCharsets.UTF_8).toString()),
            Hashing.sha256().hashString(zipEntry.getName(), StandardCharsets.UTF_8).toString());

    if (!destBase.exists()) {
        ZipArchiveInputStream gtfsStream = new ZipArchiveInputStream(parentFile.getInputStream(zipEntry));
        ZipArchiveEntry contentEntry;/*from  www . j  a  v a 2s  .  c  om*/
        while ((contentEntry = gtfsStream.getNextZipEntry()) != null) {
            // Copy this file to cache
            File dest = new File(destBase, contentEntry.getName());
            dest.getParentFile().mkdirs();
            FileOutputStream os = new FileOutputStream(dest);
            byte[] buf = new byte[4096];
            int len;
            while ((len = gtfsStream.read(buf)) > 0) {
                os.write(buf, 0, len);
            }
            os.close();
        }
        gtfsStream.close();
    }

    return new FlatGTFSFile(destBase);
}

From source file:de.flapdoodle.embedmongo.extract.ZipExtractor.java

@Override
public void extract(RuntimeConfig runtime, File source, File destination, Pattern file) throws IOException {
    IProgressListener progressListener = runtime.getProgressListener();
    String progressLabel = "Extract " + source;
    progressListener.start(progressLabel);

    FileInputStream fin = new FileInputStream(source);
    BufferedInputStream in = new BufferedInputStream(fin);

    ZipArchiveInputStream zipIn = new ZipArchiveInputStream(in);
    try {/* ww w.j ava  2 s. co  m*/
        ZipArchiveEntry entry;
        while ((entry = zipIn.getNextZipEntry()) != null) {
            if (file.matcher(entry.getName()).matches()) {
                //               System.out.println("File: " + entry.getName());
                if (zipIn.canReadEntryData(entry)) {
                    //                  System.out.println("Can Read: " + entry.getName());
                    long size = entry.getSize();
                    Files.write(zipIn, size, destination);
                    destination.setExecutable(true);
                    //                  System.out.println("DONE");
                    progressListener.done(progressLabel);
                }
                break;

            } else {
                //               System.out.println("SKIP File: " + entry.getName());
            }
        }

    } finally {
        zipIn.close();
    }

}

From source file:fr.gael.ccsds.sip.archive.ZipArchiveManager.java

/**
 * Produces Zip compressed archive.//from   w ww .  j  ava  2 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:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid.//from w  w w. java  2  s . c  om
 *
 * @param is The stream
 * @return
 * @throws java.io.IOException
 */
public TriangleMesh[] loadMeshes(InputStream is) throws IOException {
    ZipArchiveInputStream zis = null;
    TriangleMesh[] ret_val = null;

    try {
        zis = new ZipArchiveInputStream(is);

        ArchiveEntry entry = null;
        int cnt = 0;

        while ((entry = zis.getNextEntry()) != null) {
            // TODO: not sure we can depend on this being first
            if (entry.getName().equals("manifest.xml")) {
                mf = parseManifest(zis);

                ret_val = new TriangleMesh[mf.getParts().size()];
            } else {
                MeshReader reader = new MeshReader(zis, "", FilenameUtils.getExtension(entry.getName()));
                IndexedTriangleSetBuilder its = new IndexedTriangleSetBuilder();
                reader.getTriangles(its);

                // TODO: in this case we could return a less heavy triangle mesh struct?
                WingedEdgeTriangleMesh mesh = new WingedEdgeTriangleMesh(its.getVertices(), its.getFaces());
                ret_val[cnt++] = mesh;
            }
        }
    } finally {
        zis.close();
    }

    return ret_val;
}