Example usage for java.util.zip ZipFile getEntry

List of usage examples for java.util.zip ZipFile getEntry

Introduction

In this page you can find the example usage for java.util.zip ZipFile getEntry.

Prototype

public ZipEntry getEntry(String name) 

Source Link

Document

Returns the zip file entry for the specified name, or null if not found.

Usage

From source file:brut.androlib.res.AndrolibResources.java

public void installFramework(File frameFile, String tag) throws AndrolibException {
    InputStream in = null;/*from  w  ww.j  av  a  2 s  .c  o  m*/
    ZipOutputStream out = null;
    try {
        ZipFile zip = new ZipFile(frameFile);
        ZipEntry entry = zip.getEntry("resources.arsc");

        if (entry == null) {
            throw new AndrolibException("Can't find resources.arsc file");
        }

        in = zip.getInputStream(entry);
        byte[] data = IOUtils.toByteArray(in);

        ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true);
        publicizeResources(data, arsc.getFlagsOffsets());

        File outFile = new File(getFrameworkDir(),
                String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk");

        out = new ZipOutputStream(new FileOutputStream(outFile));
        out.setMethod(ZipOutputStream.STORED);
        CRC32 crc = new CRC32();
        crc.update(data);
        entry = new ZipEntry("resources.arsc");
        entry.setSize(data.length);
        entry.setCrc(crc.getValue());
        out.putNextEntry(entry);
        out.write(data);
        zip.close();
        LOGGER.info("Framework installed to: " + outFile);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * Deserializes examplars stored in archives in getArchiveDirectory().
 *
 * @throws RuntimeException if clazz cannot be serialized. This exception
 *                          has an informative message and wraps the
 *                          originally thrown exception as root cause.
 * @see #getArchiveDirectory()/*from w ww  .  j  a v  a  2 s . c  o  m*/
 */
public void deserializeArchivedVersions() throws RuntimeException {
    System.out.println("Deserializing archived instances in " + getArchiveDirectory() + ".");

    File archive = new File(getArchiveDirectory());

    if (!archive.exists() || !archive.isDirectory()) {
        return;
    }

    String[] listing = archive.list();

    for (String archiveName : listing) {
        if (!(archiveName.endsWith(".zip"))) {
            continue;
        }

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            ZipFile zipFile = new ZipFile(file);
            ZipEntry entry = zipFile.getEntry("class_fields.ser");
            InputStream inputStream = zipFile.getInputStream(entry);
            ObjectInputStream objectIn = new ObjectInputStream(inputStream);
            Map<String, List<String>> classFields = (Map<String, List<String>>) objectIn.readObject();
            zipFile.close();

            for (String className : classFields.keySet()) {

                //                    if (classFields.equals("HypotheticalGraph")) continue;

                List<String> fieldNames = classFields.get(className);
                Class<?> clazz = Class.forName(className);
                ObjectStreamClass streamClass = ObjectStreamClass.lookup(clazz);

                if (streamClass == null) {
                    System.out.println();
                }

                for (String fieldName : fieldNames) {
                    assert streamClass != null;
                    ObjectStreamField field = streamClass.getField(fieldName);

                    if (field == null) {
                        throw new RuntimeException("Field '" + fieldName + "' was dropped from class '"
                                + className + "' as a serializable field! Please " + "put it back!!!"
                                + "\nIt used to be in " + className + " in this archive: " + archiveName + ".");
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Could not read class_fields.ser in archive + " + archiveName + " .", e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }

        System.out.println("...Deserializing instances in " + archiveName + "...");
        ZipEntry zipEntry = null;

        try {
            File file = new File(getArchiveDirectory(), archiveName);
            FileInputStream in = new FileInputStream(file);
            ZipInputStream zipinputstream = new ZipInputStream(in);

            while ((zipEntry = zipinputstream.getNextEntry()) != null) {
                if (!zipEntry.getName().endsWith(".ser")) {
                    continue;
                }

                ObjectInputStream objectIn = new ObjectInputStream(zipinputstream);
                objectIn.readObject();
                zipinputstream.closeEntry();
            }

            zipinputstream.close();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(
                    "Could not read object zipped file " + zipEntry.getName() + " in archive " + archiveName
                            + ". " + "Perhaps the class was renamed, moved to another package, or "
                            + "removed. In any case, please put it back where it was.",
                    e);
        } catch (IOException e) {
            throw new RuntimeException("Problem reading archive" + archiveName + "; see cause.", e);
        }
    }

    System.out.println("Finished deserializing archived instances.");
}

From source file:nl.ordina.bag.etl.loader.ExtractLoader.java

protected void processBAGExtractFile(BAGExtractLevering levering, ZipFile zipFile) throws ProcessorException {
    //final Map<String,String> files = getFiles(levering);
    final Map<String, String> files = getFiles(zipFile);
    BAGObjectType[] objectTypes = new BAGObjectType[] { BAGObjectType.WOONPLAATS, BAGObjectType.OPENBARE_RUIMTE,
            BAGObjectType.NUMMERAANDUIDING, BAGObjectType.PAND, BAGObjectType.VERBLIJFSOBJECT,
            BAGObjectType.LIGPLAATS, BAGObjectType.STANDPLAATS };
    for (final BAGObjectType objectType : objectTypes) {
        try {//from  w  ww.j  ava2  s  .c om
            String filename = files.get(objectType.getCode());
            ZipEntry entry = zipFile.getEntry(filename);
            skipObjects = bagDAO.getCount(objectType);
            if (skipObjects > 0)
                logger.info("Skipping " + skipObjects + " object" + (skipObjects > 1 ? "en" : "") + " ("
                        + objectType.toString() + ")");
            ZipStreamReader zipStreamReader = new ZipStreamReader() {
                @Override
                public void handle(String filename, InputStream stream) throws IOException {
                    if (filename.matches("\\d{4}(WPL|OPR|NUM|PND|VBO|LIG|STA)\\d{8}-\\d{6}\\.xml")) {
                        logger.info("Processing file " + filename + " started");
                        processXML(stream);
                        logger.info("Processing file " + filename + " finished");
                    } else
                        logger.info("Skipping file " + filename);
                }
            };
            logger.info("Processing file " + filename + " started");
            zipStreamReader.read(zipFile.getInputStream(entry));
            logger.info("Processing file " + filename + " finished");
        } catch (DAOException e) {
            throw new ProcessingException(e);
        } catch (IOException e) {
            throw new ProcessingException(e);
        }
    }
}

From source file:org.jenkinsci.maven.plugins.hpi.RunMojo.java

private boolean isExtractedWebAppDirStale(File extractedWebAppDir, File webApp) throws IOException {
    if (!extractedWebAppDir.isDirectory()) {
        getLog().info(extractedWebAppDir + " does not yet exist, will receive " + webApp);
        return false;
    }// www . j  a  v  a2  s . c o m
    if (extractedWebAppDir.lastModified() < webApp.lastModified()) {
        getLog().info(extractedWebAppDir + " is older than " + webApp + ", will recreate");
        return true;
    }
    File extractedPath = new File(extractedWebAppDir, VERSION_PATH);
    if (!extractedPath.isFile()) {
        getLog().warn("no such file " + extractedPath);
        return false;
    }
    InputStream is = new FileInputStream(extractedPath);
    String extractedVersion;
    try {
        extractedVersion = loadVersion(is);
    } finally {
        is.close();
    }
    if (extractedVersion == null) {
        getLog().warn("no " + VERSION_PROP + " in " + extractedPath);
        return false;
    }
    ZipFile zip = new ZipFile(webApp);
    String originalVersion;
    try {
        ZipEntry entry = zip.getEntry(VERSION_PATH);
        if (entry == null) {
            getLog().warn("no " + VERSION_PATH + " in " + webApp);
            return false;
        }
        is = zip.getInputStream(entry);
        try {
            originalVersion = loadVersion(is);
        } finally {
            is.close();
        }
    } finally {
        zip.close();
    }
    if (originalVersion == null) {
        getLog().warn("no " + VERSION_PROP + " in jar:" + webApp.toURI() + "!/" + VERSION_PATH);
        return false;
    }
    if (!extractedVersion.equals(originalVersion)) {
        getLog().info("Version " + extractedVersion + " in " + extractedWebAppDir + " does not match "
                + originalVersion + " in " + webApp + ", will recreate");
        return true;
    }
    getLog().info(extractedWebAppDir + " already up to date with respect to " + webApp);
    return false;
}

From source file:com.ichi2.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Timber.e("Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*w w  w . j ava  2  s  .co  m*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    Timber.i("uncompress %s", name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Timber.e(e, "Utils.unzipFiles: Error while unzipping archive.");
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing output stream.");
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing zip input stream.");
        }
    }
    return true;
}

From source file:org.geoserver.kml.KMLReflectorTest.java

@Test
public void testKmzEmbededPointImageSize() throws Exception {

    WMSMapContent mapContent = createMapContext(MockData.POINTS, "big-mark");

    File temp = File.createTempFile("test", "kmz", new File("target"));
    temp.delete();/*from   w ww.  ja v  a  2s. c  om*/
    temp.mkdir();
    temp.deleteOnExit();

    File zip = new File(temp, "kmz.zip");
    zip.deleteOnExit();

    // create hte map producer
    KMZMapOutputFormat mapProducer = new KMZMapOutputFormat(getWMS());
    KMLMap map = mapProducer.produceMap(mapContent);

    FileOutputStream output = new FileOutputStream(zip);
    new KMLMapResponse(new KMLEncoder(), getWMS()).write(map, output, null);

    output.flush();
    output.close();

    assertTrue(zip.exists());

    // unzip and test it
    ZipFile zipFile = new ZipFile(zip);

    ZipEntry kmlEntry = zipFile.getEntry("wms.kml");
    InputStream kmlStream = zipFile.getInputStream(kmlEntry);

    Document kmlResult = XMLUnit.buildTestDocument(new InputSource(kmlStream));

    Double scale = Double.parseDouble(XMLUnit.newXpathEngine()
            .getMatchingNodes("(//kml:Style)[1]/kml:IconStyle/kml:scale", kmlResult).item(0).getTextContent());
    assertEquals(49d / 16d, scale, 0.01);

    zipFile.close();
}

From source file:org.bdval.ConsensusBDVModel.java

/**
 * Loads the juror models used for consensus.
 * @param options specific options to use when loading the model
 * @throws IOException if there is a problem accessing the model
 * @throws ClassNotFoundException if the type of the model is not recognized
 *//*w w  w  .ja v a 2s.c  om*/
private void loadJurorModels(final DAVOptions options) throws IOException, ClassNotFoundException {
    jurorModels.clear();

    final String pathToModel = FilenameUtils.getFullPath(modelFilename);
    final String endpointName = FilenameUtils.getBaseName(FilenameUtils.getPathNoEndSeparator(pathToModel));

    if (properties.getBoolean("bdval.consensus.jurors.embedded", false)) {
        final File tmpdir = File.createTempFile("juror-models", "");
        tmpdir.delete();
        tmpdir.mkdir();

        try {
            // load juror models from the zip file
            final ZipFile zipFile = new ZipFile(zipFilename);
            for (final String jurorPrefix : jurorModelFilenamePrefixes) {
                // zip files should always use "/" as a separator
                final String jurorFilename = "models/" + endpointName + "/" + jurorPrefix + ".zip";
                LOG.debug("Loading juror model " + jurorFilename);
                final InputStream jurorStream = zipFile.getInputStream(zipFile.getEntry(jurorFilename));

                final File jurorFile = new File(FilenameUtils.concat(tmpdir.getPath(), jurorFilename));

                // put the juror model to disk so it can be loaded with existing code
                IOUtils.copy(jurorStream, FileUtils.openOutputStream(jurorFile));

                final BDVModel jurorModel = new BDVModel(jurorFile.getPath());
                jurorModel.load(options);
                jurorModels.add(jurorModel);
            }
        } finally {
            FileUtils.forceDeleteOnExit(tmpdir);
        }
    } else {
        // load juror models from disk
        final File finalModelPath = new File(pathToModel);
        final File finalModelParentPath = new File(finalModelPath.getParent());
        // assume the model is under a directory "models" at the same level as a models
        // directory which contains the model components.
        for (final String jurorPrefix : jurorModelFilenamePrefixes) {
            final String modelComponentFilename = finalModelParentPath.getParent() + SystemUtils.FILE_SEPARATOR
                    + "models" + SystemUtils.FILE_SEPARATOR + endpointName + SystemUtils.FILE_SEPARATOR
                    + jurorPrefix;
            LOG.debug("Loading model component " + modelComponentFilename);
            final BDVModel jurorModel = new BDVModel(modelComponentFilename);
            jurorModel.load(options);
            jurorModels.add(jurorModel);
        }
    }

    if (jurorModels.size() < 1) {
        throw new IllegalStateException("No juror models could be found");
    }

    jurorModelsAreLoaded = true;
}

From source file:com.facebook.buck.android.AndroidBinaryIntegrationTest.java

@Test
public void testLibraryMetadataChecksum() throws IOException {
    String target = "//apps/sample:app_cxx_lib_asset";
    workspace.runBuckCommand("build", target).assertSuccess();
    Path pathToZip = workspace/*from   w w w .  j  ava 2 s  .  co  m*/
            .getPath(BuildTargets.getGenPath(filesystem, BuildTargetFactory.newInstance(target), "%s.apk"));
    ZipFile file = new ZipFile(pathToZip.toFile());
    ZipEntry metadata = file.getEntry("assets/lib/metadata.txt");
    assertNotNull(metadata);

    BufferedReader contents = new BufferedReader(new InputStreamReader(file.getInputStream(metadata)));
    String line = contents.readLine();
    byte[] buffer = new byte[512];
    while (line != null) {
        // Each line is of the form <filename> <filesize> <SHA256 checksum>
        String[] tokens = line.split(" ");
        assertSame(tokens.length, 3);
        String filename = tokens[0];
        int filesize = Integer.parseInt(tokens[1]);
        String checksum = tokens[2];

        ZipEntry lib = file.getEntry("assets/lib/" + filename);
        assertNotNull(lib);
        InputStream is = file.getInputStream(lib);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        while (filesize > 0) {
            int read = is.read(buffer, 0, Math.min(buffer.length, filesize));
            assertTrue(read >= 0);
            out.write(buffer, 0, read);
            filesize -= read;
        }
        String actualChecksum = Hashing.sha256().hashBytes(out.toByteArray()).toString();
        assertEquals(checksum, actualChecksum);
        is.close();
        out.close();
        line = contents.readLine();
    }
    file.close();
    contents.close();
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Load data. Meant for testing. Most users should use #promptForFile().
 * /*  w ww.j a  v a 2  s. c o  m*/
 * @param file where to read the data in from and where to save data to
 * @throws IOException
 */
public void load(final File file) throws IOException {
    _file = file;

    ZipFile zipfile = null;
    try {
        zipfile = new ZipFile(file);

        final ZipEntry challengeEntry = zipfile.getEntry(DownloadSubjectiveData.CHALLENGE_ENTRY_NAME);
        if (null == challengeEntry) {
            throw new FLLRuntimeException(
                    "Unable to find challenge descriptor in file, you probably choose the wrong file or it is corrupted");
        }
        final InputStream challengeStream = zipfile.getInputStream(challengeEntry);
        _challengeDocument = ChallengeParser
                .parse(new InputStreamReader(challengeStream, Utilities.DEFAULT_CHARSET));
        challengeStream.close();

        _challengeDescription = new ChallengeDescription(_challengeDocument.getDocumentElement());

        final ZipEntry scoreEntry = zipfile.getEntry(DownloadSubjectiveData.SCORE_ENTRY_NAME);
        if (null == scoreEntry) {
            throw new FLLRuntimeException(
                    "Unable to find score data in file, you probably choose the wrong file or it is corrupted");
        }
        final InputStream scoreStream = zipfile.getInputStream(scoreEntry);
        _scoreDocument = XMLUtils.parseXMLDocument(scoreStream);
        scoreStream.close();

        final ZipEntry scheduleEntry = zipfile.getEntry(DownloadSubjectiveData.SCHEDULE_ENTRY_NAME);
        if (null != scheduleEntry) {
            ObjectInputStream scheduleStream = null;
            try {
                scheduleStream = new ObjectInputStream(zipfile.getInputStream(scheduleEntry));
                _schedule = (TournamentSchedule) scheduleStream.readObject();
            } finally {
                IOUtils.closeQuietly(scheduleStream);
            }
        } else {
            _schedule = null;
        }

        final ZipEntry mappingEntry = zipfile.getEntry(DownloadSubjectiveData.MAPPING_ENTRY_NAME);
        if (null != mappingEntry) {
            ObjectInputStream mappingStream = null;
            try {
                mappingStream = new ObjectInputStream(zipfile.getInputStream(mappingEntry));
                // ObjectStream isn't type safe
                @SuppressWarnings("unchecked")
                final Collection<CategoryColumnMapping> mappings = (Collection<CategoryColumnMapping>) mappingStream
                        .readObject();
                _scheduleColumnMappings = mappings;
            } finally {
                IOUtils.closeQuietly(mappingStream);
            }
        } else {
            _scheduleColumnMappings = null;
        }

    } catch (final ClassNotFoundException e) {
        throw new FLLInternalException("Internal error loading schedule from data file", e);
    } catch (final SAXParseException spe) {
        final String errorMessage = String.format(
                "Error parsing file line: %d column: %d%n Message: %s%n This may be caused by using the wrong version of the software attempting to parse a file that is not subjective data.",
                spe.getLineNumber(), spe.getColumnNumber(), spe.getMessage());
        throw new FLLRuntimeException(errorMessage, spe);
    } catch (final SAXException se) {
        final String errorMessage = "The subjective scores file was found to be invalid, check that you are parsing a subjective scores file and not something else";
        throw new FLLRuntimeException(errorMessage, se);
    } finally {
        if (null != zipfile) {
            try {
                zipfile.close();
            } catch (final IOException e) {
                LOGGER.debug("Error closing zipfile", e);
            }
        }
    }

    for (final ScoreCategory subjectiveCategory : getChallengeDescription().getSubjectiveCategories()) {
        createSubjectiveTable(tabbedPane, subjectiveCategory);
    }

    // get the name and location of the tournament
    final Element top = _scoreDocument.getDocumentElement();
    final String tournamentName = top.getAttribute("tournamentName");
    if (top.hasAttribute("tournamentLocation")) {
        final String tournamentLocation = top.getAttribute("tournamentName");
        setTitle(String.format("Subjective Score Entry - %s @ %s", tournamentName, tournamentLocation));
    } else {
        setTitle(String.format("Subjective Score Entry - %s", tournamentName));
    }

    pack();
}

From source file:org.esa.s1tbx.sentinel1.gpf.EAPPhaseCorrectionOp.java

private void readAuxCalFile() throws Exception {

    try {/*ww w . j  a  v a2 s.c  o  m*/
        final DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        final DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();

        final Document doc;
        if (auxCalFile.getName().toLowerCase().endsWith(".zip")) {
            final ZipFile productZip = new ZipFile(auxCalFile, ZipFile.OPEN_READ);
            final Enumeration<? extends ZipEntry> entries = productZip.entries();
            final ZipEntry folderEntry = entries.nextElement();
            final ZipEntry zipEntry = productZip.getEntry(folderEntry.getName() + "data/s1a-aux-cal.xml");

            InputStream is = productZip.getInputStream(zipEntry);
            doc = documentBuilder.parse(is);
        } else {
            doc = documentBuilder.parse(auxCalFile);
        }

        if (doc == null) {
            System.out.println("EAPPhaseCorrection: failed to create Document for AUX_CAL file");
            return;
        }

        doc.getDocumentElement().normalize();

        final org.w3c.dom.Node calibrationParamsListNode = doc.getElementsByTagName("auxiliaryCalibration")
                .item(0).getChildNodes().item(1);

        org.w3c.dom.Node childNode = calibrationParamsListNode.getFirstChild();
        while (childNode != null) {
            if (childNode.getNodeName().equals("calibrationParams")) {
                final String swath = getNodeTextContent(childNode, "swath");
                if (swath != null && swath.contains(acquisitionMode)) {
                    final String pol = getNodeTextContent(childNode, "polarisation");
                    readOneEAPVector(childNode, swath, pol.toUpperCase());
                }
            }
            childNode = childNode.getNextSibling();
        }

    } catch (IOException e) {
        System.out.println("EAPPhaseCorrection: IOException " + e.getMessage());
    } catch (ParserConfigurationException e) {
        System.out.println("EAPPhaseCorrection: ParserConfigurationException " + e.getMessage());
    } catch (SAXException e) {
        System.out.println("EAPPhaseCorrection: SAXException " + e.getMessage());
    } catch (Exception e) {
        System.out.println("EAPPhaseCorrection: Exception " + e.getMessage());
    }
}