Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry getSize

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getSize

Introduction

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

Prototype

public long getSize() 

Source Link

Document

Returns the uncompressed size of the entry data.

Usage

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

/**
 * Entry point. /*w  w  w  . j  a  va  2 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:com.haulmont.cuba.core.sys.logging.LogArchiver.java

private static ArchiveEntry newTailArchive(String name, byte[] tail) {
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(name);
    zipEntry.setSize(tail.length);//from w ww.j av a  2s .c o m
    zipEntry.setCompressedSize(zipEntry.getSize());
    CRC32 crc32 = new CRC32();
    crc32.update(tail);
    zipEntry.setCrc(crc32.getValue());
    return zipEntry;
}

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

private static ArchiveEntry newArchive(File file) throws IOException {
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(file.getName());
    zipEntry.setSize(file.length());/*w  ww .  ja v  a2  s.  c  o m*/
    zipEntry.setCompressedSize(zipEntry.getSize());
    zipEntry.setCrc(FileUtils.checksumCRC32(file));
    return zipEntry;
}

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

/**
 * Compute the checksum of a ZIP file./*from www .  ja va 2s . c  om*/
 * @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.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  a v  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   w w w. j  ava2s .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:com.liferay.blade.cli.command.InstallExtensionCommandTest.java

private static void _testJarsDiff(File warFile1, File warFile2) throws IOException {
    DifferenceCalculator differenceCalculator = new DifferenceCalculator(warFile1, warFile2);

    differenceCalculator.setFilenameRegexToIgnore(Collections.singleton(".*META-INF.*"));
    differenceCalculator.setIgnoreTimestamps(true);

    Differences differences = differenceCalculator.getDifferences();

    if (!differences.hasDifferences()) {
        return;/*from   w w w . j av a  2  s.co  m*/
    }

    StringBuilder message = new StringBuilder();

    message.append("WAR ");
    message.append(warFile1);
    message.append(" and ");
    message.append(warFile2);
    message.append(" do not match:");
    message.append(System.lineSeparator());

    boolean realChange;

    Map<String, ZipArchiveEntry> added = differences.getAdded();
    Map<String, ZipArchiveEntry[]> changed = differences.getChanged();
    Map<String, ZipArchiveEntry> removed = differences.getRemoved();

    if (added.isEmpty() && !changed.isEmpty() && removed.isEmpty()) {
        realChange = false;

        ZipFile zipFile1 = null;
        ZipFile zipFile2 = null;

        try {
            zipFile1 = new ZipFile(warFile1);
            zipFile2 = new ZipFile(warFile2);

            for (Map.Entry<String, ZipArchiveEntry[]> entry : changed.entrySet()) {
                ZipArchiveEntry[] zipArchiveEntries = entry.getValue();

                ZipArchiveEntry zipArchiveEntry1 = zipArchiveEntries[0];
                ZipArchiveEntry zipArchiveEntry2 = zipArchiveEntries[0];

                if (zipArchiveEntry1.isDirectory() && zipArchiveEntry2.isDirectory()
                        && (zipArchiveEntry1.getSize() == zipArchiveEntry2.getSize())
                        && (zipArchiveEntry1.getCompressedSize() <= 2)
                        && (zipArchiveEntry2.getCompressedSize() <= 2)) {

                    // Skip zipdiff bug

                    continue;
                }

                try (InputStream inputStream1 = zipFile1
                        .getInputStream(zipFile1.getEntry(zipArchiveEntry1.getName()));
                        InputStream inputStream2 = zipFile2
                                .getInputStream(zipFile2.getEntry(zipArchiveEntry2.getName()))) {

                    List<String> lines1 = StringTestUtil.readLines(inputStream1);
                    List<String> lines2 = StringTestUtil.readLines(inputStream2);

                    message.append(System.lineSeparator());

                    message.append("--- ");
                    message.append(zipArchiveEntry1.getName());
                    message.append(System.lineSeparator());

                    message.append("+++ ");
                    message.append(zipArchiveEntry2.getName());
                    message.append(System.lineSeparator());

                    Patch<String> diff = DiffUtils.diff(lines1, lines2);

                    for (Delta<String> delta : diff.getDeltas()) {
                        message.append('\t');
                        message.append(delta.getOriginal());
                        message.append(System.lineSeparator());

                        message.append('\t');
                        message.append(delta.getRevised());
                        message.append(System.lineSeparator());
                    }
                }

                realChange = true;

                break;
            }
        } finally {
            ZipFile.closeQuietly(zipFile1);
            ZipFile.closeQuietly(zipFile2);
        }
    } else {
        realChange = true;
    }

    Assert.assertFalse(message.toString(), realChange);
}

From source file:at.treedb.jslib.JsLib.java

/**
 * Loads an external JavaScript library.
 * //from w w  w. j a  v a  2 s .  co  m
 * @param dao
 *            {@code DAOiface} (data access object)
 * @param name
 *            library name
 * @param version
 *            optional library version. If this parameter is null the
 *            library with the highest version number will be loaded
 * @return {@code JsLib} object
 * @throws Exception
 */
@SuppressWarnings("resource")
public static synchronized JsLib load(DAOiface dao, String name, String version) throws Exception {
    initJsLib(dao);
    if (jsLibs == null) {
        return null;
    }
    JsLib lib = null;
    synchronized (lockObj) {
        HashMap<Version, JsLib> v = jsLibs.get(name);
        if (v == null) {
            return null;
        }

        if (version != null) {
            lib = v.get(new Version(version));
        } else {
            Version[] array = v.keySet().toArray(new Version[v.size()]);
            Arrays.sort(array);
            // return the library with the highest version number
            lib = v.get(array[array.length - 1]);
        }
    }
    if (lib != null) {
        if (!lib.isExtracted) {
            // load binary archive data
            lib.callbackAfterLoad(dao);
            // detect zip of 7z archive
            MimeType mtype = ContentInfo.getContentInfo(lib.data);
            int totalSize = 0;
            HashMap<String, byte[]> dataMap = null;
            String libName = "jsLib" + lib.getHistId();
            String classPath = lib.getName() + "/java/classes/";
            if (mtype != null) {
                // ZIP archive
                if (mtype.equals(MimeType.ZIP)) {
                    dataMap = new HashMap<String, byte[]>();
                    lib.zipInput = new ZipArchiveInputStream(new ByteArrayInputStream(lib.data));
                    do {
                        ZipArchiveEntry entry = lib.zipInput.getNextZipEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.zipInput.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }
                    } while (true);
                    lib.zipInput.close();
                    lib.isExtracted = true;
                    // 7-zip archive
                } else if (mtype.equals(MimeType._7Z)) {
                    dataMap = new HashMap<String, byte[]>();
                    File tempFile = FileStorage.getInstance().createTempFile(libName, ".7z");
                    tempFile.deleteOnExit();
                    Stream.writeByteStream(tempFile, lib.data);
                    lib.sevenZFile = new SevenZFile(tempFile);
                    do {
                        SevenZArchiveEntry entry = lib.sevenZFile.getNextEntry();
                        if (entry == null) {
                            break;
                        }
                        if (entry.isDirectory()) {
                            continue;
                        }
                        int size = (int) entry.getSize();
                        totalSize += size;
                        byte[] data = new byte[size];
                        lib.sevenZFile.read(data, 0, size);
                        dataMap.put(entry.getName(), data);
                        if (entry.getName().contains(classPath)) {
                            lib.javaFiles.add(entry.getName());
                        }

                    } while (true);
                    lib.sevenZFile.close();
                    lib.isExtracted = true;
                }
            }
            if (!lib.isExtracted) {
                throw new Exception("JsLib.load(): No JavaScript archive extracted!");
            }
            // create a buffer for the archive
            byte[] buf = new byte[totalSize];
            int offset = 0;
            // enumerate the archive entries
            for (String n : dataMap.keySet()) {
                byte[] d = dataMap.get(n);
                System.arraycopy(d, 0, buf, offset, d.length);
                lib.archiveMap.put(n, new ArchiveEntry(offset, d.length));
                offset += d.length;
            }
            // create a temporary file containing the extracted archive
            File tempFile = FileStorage.getInstance().createTempFile(libName, ".dump");
            lib.dumpFile = tempFile;
            tempFile.deleteOnExit();
            Stream.writeByteStream(tempFile, buf);
            FileInputStream inFile = new FileInputStream(tempFile);
            // closed by the GC
            lib.inChannel = inFile.getChannel();
            // discard the archive data - free the memory
            lib.data = null;
            dataMap = null;
        }
    }
    return lib;
}

From source file:com.android.repository.util.InstallerUtil.java

private static boolean readZipEntry(ZipFile zipFile, ZipArchiveEntry entry, OutputStream dest,
        long expectedSize, @NonNull ProgressIndicator progress) throws IOException {
    int size;//from   w w w.  ja va  2  s  .  c  o m
    byte[] buf = new byte[8192];
    double fraction = progress.getFraction();
    try (BufferedOutputStream bufferedDest = new BufferedOutputStream(dest);
            InputStream s = new BufferedInputStream(zipFile.getInputStream(entry))) {
        while ((size = s.read(buf)) > -1) {
            bufferedDest.write(buf, 0, size);
            fraction += ((double) entry.getCompressedSize() / expectedSize) * ((double) size / entry.getSize());
            progress.setFraction(fraction);
            if (progress.isCanceled()) {
                return true;
            }
        }
    }
    return false;
}

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

/**
 * Entry to new name./*w  ww  .ja  v a  2 s .co m*/
 *
 * @param source the source
 * @param name the name
 * @return the zip archive entry
 * @throws ZipException the zip exception
 */
public static ZipArchiveEntry entryToNewName(ZipArchiveEntry source, String name) throws ZipException {
    if (source.getName().equals(name))
        return new ZipArchiveEntry(source);
    ZipArchiveEntry ret = new ZipArchiveEntry(name);
    byte[] extra = source.getExtra();
    if (extra != null) {
        ret.setExtraFields(ExtraFieldUtils.parse(extra, true, ExtraFieldUtils.UnparseableExtraField.READ));
    } else {
        ret.setExtra(ExtraFieldUtils.mergeLocalFileDataData(source.getExtraFields(true)));
    }
    ret.setInternalAttributes(source.getInternalAttributes());
    ret.setExternalAttributes(source.getExternalAttributes());
    ret.setExtraFields(source.getExtraFields(true));
    ret.setCrc(source.getCrc());
    ret.setMethod(source.getMethod());
    ret.setSize(source.getSize());
    return ret;
}