Example usage for java.util.zip ZipEntry getCrc

List of usage examples for java.util.zip ZipEntry getCrc

Introduction

In this page you can find the example usage for java.util.zip ZipEntry getCrc.

Prototype

public long getCrc() 

Source Link

Document

Returns the CRC-32 checksum of the uncompressed entry data.

Usage

From source file:io.gromit.geolite2.geonames.SubdivisionFinder.java

/**
 * Read level two./* ww  w .jav a  2 s . co m*/
 *
 * @param subdivisionTwoLocationUrl the subdivision two location url
 * @return the subdivision finder
 */
public SubdivisionFinder readLevelTwo(String subdivisionTwoLocationUrl) {
    ZipInputStream zipis = null;
    try {
        zipis = new ZipInputStream(new URL(subdivisionTwoLocationUrl).openStream(), Charset.forName("UTF-8"));
        ZipEntry zipEntry = zipis.getNextEntry();
        logger.info("reading " + zipEntry.getName());
        if (crc2 == zipEntry.getCrc()) {
            logger.info("skipp, same CRC");
            return this;
        }
        CsvParserSettings settings = new CsvParserSettings();
        settings.setSkipEmptyLines(true);
        settings.trimValues(true);
        CsvFormat format = new CsvFormat();
        format.setDelimiter('\t');
        format.setLineSeparator("\n");
        format.setCharToEscapeQuoteEscaping('\0');
        format.setQuote('\0');
        settings.setFormat(format);
        CsvParser parser = new CsvParser(settings);

        List<String[]> lines = parser.parseAll(new InputStreamReader(zipis, "UTF-8"));

        for (String[] entry : lines) {
            Subdivision subdivision = new Subdivision();
            subdivision.setId(entry[0]);
            subdivision.setName(entry[1]);
            subdivision.setGeonameId(NumberUtils.toInt(entry[2]));
            idTowMap.put(subdivision.getId(), subdivision);
            geonameIdMap.put(subdivision.getGeonameId(), subdivision);
        }
        logger.info("loaded " + lines.size() + " subdivisions level 2");
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.close();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:io.gromit.geolite2.geonames.TimeZoneFinder.java

/**
 * Read time zones./*from   w  w  w  .  ja  v  a  2s . c  o  m*/
 *
 * @param timeZonesLocationUrl the time zones location url
 * @return the time zone finder
 */
private TimeZoneFinder readTimeZones(String timeZonesLocationUrl) {
    ClosableZipInputStream zipis = null;
    try {
        zipis = new ClosableZipInputStream(new URL(timeZonesLocationUrl).openStream(),
                Charset.forName("UTF-8"));
        ZipEntry zipEntry = null;
        while ((zipEntry = zipis.getNextEntry()) != null) {
            logger.info("reading " + zipEntry.getName());
            if (zipEntry.getName().equalsIgnoreCase(TIMEZONE_FILE_NAME)) {
                if (crcTimezones == zipEntry.getCrc()) {
                    logger.info("skipp, same CRC");
                    return this;
                } else {
                    loadOffsets(zipis);
                    zipis.closeEntry();
                }
            } else if (zipEntry.getName().equalsIgnoreCase(ZONE_FILE_NAME)) {
                if (crcZone == zipEntry.getCrc()) {
                    logger.info("skipp, same CRC");
                    return this;
                } else {
                    loadZones(zipis);
                    zipis.closeEntry();
                }
            } else {
                logger.info("skip entry: " + zipEntry.getName());
            }
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        try {
            zipis.manualClose();
        } catch (Exception e) {
        }
        ;
    }
    return this;
}

From source file:com.taobao.android.builder.tasks.app.bundle.ProcessAwbAndroidResources.java

@Override
protected void doFullTaskAction() throws IOException {
    // we have to clean the source folder output in case the package name changed.
    File srcOut = getSourceOutputDir();
    if (srcOut != null) {
        //            FileUtils.emptyFolder(srcOut);
        srcOut.delete();/*from   w w  w.j a v  a2  s. c o m*/
        srcOut.mkdirs();
    }

    getTextSymbolOutputDir().mkdirs();
    getPackageOutputFile().getParentFile().mkdirs();

    @Nullable
    File resOutBaseNameFile = getPackageOutputFile();

    // If are in instant run mode and we have an instant run enabled manifest
    File instantRunManifest = getInstantRunManifestFile();
    File manifestFileToPackage = instantRunBuildContext.isInInstantRunMode() && instantRunManifest != null
            && instantRunManifest.exists() ? instantRunManifest : getManifestFile();

    //awb????
    addAaptOptions();
    AaptPackageProcessBuilder aaptPackageCommandBuilder = new AaptPackageProcessBuilder(manifestFileToPackage,
            getAaptOptions()).setAssetsFolder(getAssetsDir()).setResFolder(getResDir())
                    .setLibraries(getLibraries()).setPackageForR(getPackageForR())
                    .setSourceOutputDir(absolutePath(srcOut))
                    .setSymbolOutputDir(absolutePath(getTextSymbolOutputDir()))
                    .setResPackageOutput(absolutePath(resOutBaseNameFile))
                    .setProguardOutput(absolutePath(getProguardOutputFile())).setType(getType())
                    .setDebuggable(getDebuggable()).setPseudoLocalesEnabled(getPseudoLocalesEnabled())
                    .setResourceConfigs(getResourceConfigs()).setSplits(getSplits())
                    .setPreferredDensity(getPreferredDensity());

    @NonNull
    AtlasBuilder builder = (AtlasBuilder) getBuilder();

    //        MergingLog mergingLog = new MergingLog(getMergeBlameLogFolder());
    //
    //        ProcessOutputHandler processOutputHandler = new ParsingProcessOutputHandler(
    //                new ToolOutputParser(new AaptOutputParser(), getILogger()),
    //                 builder.getErrorReporter());

    ProcessOutputHandler processOutputHandler = new LoggedProcessOutputHandler(getILogger());
    try {
        builder.processAwbResources(aaptPackageCommandBuilder, getEnforceUniquePackageName(),
                processOutputHandler, getMainSymbolFile());
        if (resOutBaseNameFile != null) {
            if (instantRunBuildContext.isInInstantRunMode()) {

                instantRunBuildContext.addChangedFile(FileType.RESOURCES, resOutBaseNameFile);

                // get the new manifest file CRC
                JarFile jarFile = new JarFile(resOutBaseNameFile);
                String currentIterationCRC = null;
                try {
                    ZipEntry entry = jarFile.getEntry(SdkConstants.ANDROID_MANIFEST_XML);
                    if (entry != null) {
                        currentIterationCRC = String.valueOf(entry.getCrc());
                    }
                } finally {
                    jarFile.close();
                }

                // check the manifest file binary format.
                File crcFile = new File(instantRunSupportDir, "manifest.crc");
                if (crcFile.exists() && currentIterationCRC != null) {
                    // compare its content with the new binary file crc.
                    String previousIterationCRC = Files.readFirstLine(crcFile, Charsets.UTF_8);
                    if (!currentIterationCRC.equals(previousIterationCRC)) {
                        instantRunBuildContext.close();
                        //instantRunBuildContext.setVerifierResult(InstantRunVerifierStatus
                        // .BINARY_MANIFEST_FILE_CHANGE);
                    }
                }

                // write the new manifest file CRC.
                Files.createParentDirs(crcFile);
                Files.write(currentIterationCRC, crcFile, Charsets.UTF_8);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new GradleException("process res exception", e);
    }
}

From source file:org.atombeat.xquery.functions.util.GetZipEntries.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from w  w w .j  a  v a 2 s .  c  o  m
        String path = args[0].getStringValue();
        ZipFile zf = new ZipFile(path);
        log.debug(zf.getName());
        log.debug(zf.size());
        log.debug(zf.hashCode());
        ZipEntry e;
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ValueSequence s = new ValueSequence();
        for (int i = 0; entries.hasMoreElements(); i++) {
            log.debug(i);
            e = entries.nextElement();
            log.debug(e.getName());
            log.debug(e.getComment());
            log.debug(e.isDirectory());
            log.debug(e.getCompressedSize());
            log.debug(e.getCrc());
            log.debug(e.getMethod());
            log.debug(e.getSize());
            log.debug(e.getTime());
            if (!e.isDirectory())
                s.add(new StringValue(e.getName()));
        }
        return s;
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

From source file:org.atombeat.xquery.functions.util.GetZipEntryCrc.java

public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {/*  w  w  w.  j a v  a2 s.  c  o m*/
        ZipFile zf = new ZipFile(args[0].getStringValue());
        ZipEntry ze = zf.getEntry(args[1].getStringValue());
        return new IntegerValue(ze.getCrc());
    } catch (Exception e) {
        throw new XPathException("error processing zip file: " + e.getLocalizedMessage(), e);
    }

}

From source file:org.esa.snap.engine_utilities.util.ZipUtils.java

public static boolean isValid(final File file) {
    try (ZipFile zipfile = new ZipFile(file)) {
        try (ZipInputStream zis = new ZipInputStream(new FileInputStream(file))) {
            ZipEntry ze = zis.getNextEntry();
            if (ze == null) {
                return false;
            }//from w  ww  .j a  v a  2s  .c  o m
            while (ze != null) {
                // if it throws an exception fetching any of the following then we know the file is corrupted.
                try (InputStream in = zipfile.getInputStream(ze)) {
                    ze.getCrc();
                    ze.getCompressedSize();
                    ze = zis.getNextEntry();
                } catch (IOException e) {
                    return false;
                }
            }
            return true;
        } catch (IOException e) {
            return false;
        }
    } catch (IOException e) {
        return false;
    }
}

From source file:org.gradle.api.plugins.buildcomparison.outcome.internal.archive.entry.FileToArchiveEntrySetTransformer.java

private ImmutableSet<ArchiveEntry> walk(InputStream archiveInputStream,
        ImmutableSet.Builder<ArchiveEntry> allEntries, ImmutableList<String> parentPaths) {
    ImmutableSet.Builder<ArchiveEntry> entries = ImmutableSet.builder();
    ZipInputStream zipStream = new ZipInputStream(archiveInputStream);

    try {//from ww  w  .  j a  v  a 2 s .  c o  m
        ZipEntry entry = zipStream.getNextEntry();
        while (entry != null) {
            ArchiveEntry.Builder builder = new ArchiveEntry.Builder();
            builder.setParentPaths(parentPaths);
            builder.setPath(entry.getName());
            builder.setCrc(entry.getCrc());
            builder.setDirectory(entry.isDirectory());
            builder.setSize(entry.getSize());
            if (!builder.isDirectory() && (zipStream.available() == 1)) {
                boolean zipEntry;
                final BufferedInputStream bis = new BufferedInputStream(zipStream) {
                    @Override
                    public void close() throws IOException {
                    }
                };
                bis.mark(Integer.MAX_VALUE);
                zipEntry = new ZipInputStream(bis).getNextEntry() != null;
                bis.reset();
                if (zipEntry) {
                    ImmutableList<String> nextParentPaths = ImmutableList.<String>builder().addAll(parentPaths)
                            .add(entry.getName()).build();
                    ImmutableSet<ArchiveEntry> subEntries = walk(bis, allEntries, nextParentPaths);
                    builder.setSubEntries(subEntries);
                }
            }

            ArchiveEntry archiveEntry = builder.build();
            entries.add(archiveEntry);
            allEntries.add(archiveEntry);
            zipStream.closeEntry();
            entry = zipStream.getNextEntry();
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(zipStream);
    }

    return entries.build();
}

From source file:org.zeroturnaround.zip.ZipUtil.java

/**
 * Compares meta-data of two ZIP entries.
 * <p>/*from   ww w  .j a v  a2 s.  c o m*/
 * Two entries are considered the same if
 * <ol>
 * <li>both entries exist,</li>
 * <li>both entries are either directories or files,</li>
 * <li>both entries have the same size,</li>
 * <li>both entries have the same CRC.</li>
 * </ol>
 *
 * @param path
 *          name of the entries.
 * @param e1
 *          first entry (required).
 * @param e2
 *          second entry (may be <code>null</code>).
 * @return <code>true</code> if no difference was found.
 */
private static boolean metaDataEquals(String path, ZipEntry e1, ZipEntry e2) throws IOException {
    // Check if the same entry exists in the second archive
    if (e2 == null) {
        log.debug("Entry '{}' removed.", path);
        return false;
    }

    // Check the directory flag
    if (e1.isDirectory()) {
        if (e2.isDirectory()) {
            return true; // Let's skip the directory as there is nothing to compare
        } else {
            log.debug("Entry '{}' not a directory any more.", path);
            return false;
        }
    } else if (e2.isDirectory()) {
        log.debug("Entry '{}' now a directory.", path);
        return false;
    }

    // Check the size
    long size1 = e1.getSize();
    long size2 = e2.getSize();
    if (size1 != -1 && size2 != -1 && size1 != size2) {
        log.debug("Entry '" + path + "' size changed (" + size1 + " vs " + size2 + ").");
        return false;
    }

    // Check the CRC
    long crc1 = e1.getCrc();
    long crc2 = e2.getCrc();
    if (crc1 != -1 && crc2 != -1 && crc1 != crc2) {
        log.debug("Entry '" + path + "' CRC changed (" + crc1 + " vs " + crc2 + ").");
        return false;
    }

    // Check the time (ignored, logging only)
    if (log.isTraceEnabled()) {
        long time1 = e1.getTime();
        long time2 = e2.getTime();
        if (time1 != -1 && time2 != -1 && time1 != time2) {
            log.trace(
                    "Entry '" + path + "' time changed (" + new Date(time1) + " vs " + new Date(time2) + ").");
        }
    }

    return true;
}