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

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

Introduction

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

Prototype

public ZipArchiveEntry getNextZipEntry() throws IOException 

Source Link

Usage

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

/**
 * Entry point. //from ww w .  j  a  va2  s  .c o  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: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  w w  w.j av a  2 s  .co m*/
    }
    zin.close();
}

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

public static void unzip(InputStream warInputStream, File destination) {
    try {//from   w ww  .  j  a v a 2 s . c  o 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.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/*from   w  ww . j av a 2s . 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:com.igormaznitsa.zxpoly.utils.ROMLoader.java

public static RomData getROMFrom(final String url) throws IOException {
    final URI uri;
    try {/*from  ww  w  .j  av  a  2 s  .c o m*/
        uri = new URI(url);
    } catch (URISyntaxException ex) {
        throw new IOException("Error in URL '" + url + "\'", ex);
    }
    final String scheme = uri.getScheme();
    final String userInfo = uri.getUserInfo();
    final String name;
    final String password;
    if (userInfo != null) {
        final String[] splitted = userInfo.split("\\:");
        name = splitted[0];
        password = splitted[1];
    } else {
        name = null;
        password = null;
    }

    final byte[] loaded;
    if (scheme.startsWith("http")) {
        loaded = loadHTTPArchive(url);
    } else if (scheme.startsWith("ftp")) {
        loaded = loadFTPArchive(uri.getHost(), uri.getPath(), name, password);
    } else {
        throw new IllegalArgumentException("Unsupported scheme [" + scheme + ']');
    }

    final ZipArchiveInputStream in = new ZipArchiveInputStream(new ByteArrayInputStream(loaded));

    byte[] rom48 = null;
    byte[] rom128 = null;
    byte[] romTrDos = null;

    while (true) {
        final ZipArchiveEntry entry = in.getNextZipEntry();
        if (entry == null) {
            break;
        }

        if (entry.isDirectory()) {
            continue;
        }

        if (ROM_48.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 48 has too big size");
            }
            rom48 = new byte[16384];
            IOUtils.readFully(in, rom48, 0, size);
        } else if (ROM_128TR.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM 128TR has too big size");
            }
            rom128 = new byte[16384];
            IOUtils.readFully(in, rom128, 0, size);
        } else if (ROM_TRDOS.equalsIgnoreCase(entry.getName())) {
            final int size = (int) entry.getSize();
            if (size > 16384) {
                throw new IOException("ROM TRDOS has too big size");
            }
            romTrDos = new byte[16384];
            IOUtils.readFully(in, romTrDos, 0, size);
        }
    }

    if (rom48 == null) {
        throw new IOException(ROM_48 + " not found");
    }
    if (rom128 == null) {
        throw new IOException(ROM_128TR + " not found");
    }
    if (romTrDos == null) {
        throw new IOException(ROM_TRDOS + " not found");
    }

    return new RomData(rom48, rom128, romTrDos);
}

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

/**
 * Compute the checksum of a ZIP file.//from www  .j av  a  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.dex2jar.reader.CCZipExtractor.java

@Override
public byte[] extract(byte[] data, String name) throws IOException {
    ZipArchiveInputStream zis = null;
    try {//  w w w  . j  a v a2 s . c om
        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: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 {// w ww .  j a v a 2s . c o 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:io.github.runassudo.gtfs.ZipStreamGTFSFile.java

public void iterateThroughContents(IterateThroughContentsCallback callback) throws IOException {
    ZipArchiveInputStream gtfsStream = new ZipArchiveInputStream(parentFile.getInputStream(zipEntry));
    ZipArchiveEntry contentEntry;/*  w  w w .j a  v  a2  s .com*/
    while ((contentEntry = gtfsStream.getNextZipEntry()) != null) {
        callback.call(new ZipStreamGTFSCSV(gtfsStream, contentEntry));
    }
}

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  w  w w  .j av  a 2s  .co m
        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);
}