Example usage for java.util.zip ZipFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java

protected FileInfo doImportXmlDocument(String docId, String filePath, Pair collectivite, Pair budget,
        String overwriteRule, Element document, File volume, String archiveName) throws IOException {
    File source = null;//from   w  w w.j av  a2 s.  c o  m
    try {
        ZipFile zipArchive = new ZipFile(volume);
        source = extractFileFromZip(zipArchive, filePath);
        zipArchive.close();
    } catch (Exception ex) {
        // on a pas russi  extraire le fichier, on l'indique dans le manifeste
        document.addAttribute(new Attribute("imported", NON_DISPONIBLE));

    }
    DocumentModel dm = documentsModel.getDocumentById(docId);
    try {
        Class clazz = Class.forName(dm.getImportClass());
        Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
        Object obj = cc.newInstance(getUser(), applicationProperties);
        if (!(obj instanceof EtatImporteur)) {
            throw new DataConfigurationException(
                    "Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a t livr est certainement invalide.\nVeuillez contacter votre fournisseur.");
        }
        EtatImporteur ei = (EtatImporteur) obj;
        // WARNING : if one name per archive (and not one per volume), change this
        ei.setArchiveName(archiveName);
        ei.setImpSvcProvider(importServiceProvider);
        ei.setOverwriteRule(overwriteRule);
        ei.setApplicationConfiguration(applicationProperties);

        ei.setDocument(dm);
        File[] fichiers = new File[] { source };
        ei.setFilesToImport(fichiers);

        importServiceProvider.setEtatImporter(ei);
        importServiceProvider.setCollectivite(collectivite);
        importServiceProvider.setBudget(budget);

        ei.setManifeste(DOMConverter.convert(archiveManifeste,
                FactoryProvider.getDocumentBuilderFactory().newDocumentBuilder().getDOMImplementation()));
        ei.run();
        if (ei.getInProcessException() != null) {
            // il s'est pass un truc pourri, on regarde si il faut tout interrompre
            document.addAttribute(new Attribute("imported", "Non"));
            if (ei.getInProcessException() instanceof RuntimeException) {
                // l c'est certain, il faut interrompre
                throw ei.getInProcessException();
            }
        }
        FileInfo fInfo = ei.getFileInfo();
        fInfo.setLastModify(volume.lastModified());
        fInfo.setWarningCount(ei.getWarningCount());
        document.addAttribute(new Attribute("imported", "Oui"));
        return fInfo;
    } catch (Exception ex) {
        logger.error("importer", ex);
        return new FileInfo(ex);
    } finally {
        if (source.exists()) {
            source.delete();
        }
    }
}

From source file:de.tarent.maven.plugins.pkg.packager.IzPackPackager.java

/**
 * Puts the embedded izpack jar from the (resource) classpath into the work
 * directory and unpacks it there.//w ww  .j a va2 s.c  o m
 * 
 * @param l
 * @param izPackEmbeddedFile
 * @param izPackEmbeddedHomeDir
 * @throws MojoExecutionException
 */
private void unpackIzPack(Log l, File izPackEmbeddedFile, File izPackEmbeddedHomeDir)
        throws MojoExecutionException {
    l.info("storing embedded IzPack installation in " + izPackEmbeddedFile);
    Utils.storeInputStream(IzPackPackager.class.getResourceAsStream(IZPACK_EMBEDDED_JAR), izPackEmbeddedFile,
            "IOException while unpacking embedded IzPack installation.");

    l.info("unzipping embedded IzPack installation to" + izPackEmbeddedHomeDir);
    int count = 0;
    ZipFile zip = null;
    try {
        zip = new ZipFile(izPackEmbeddedFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        while (e.hasMoreElements()) {
            count++;
            ZipEntry entry = (ZipEntry) e.nextElement();
            File unpacked = new File(izPackEmbeddedHomeDir, entry.getName());
            if (entry.isDirectory()) {
                unpacked.mkdirs(); // TODO: Check success.
            } else {
                Utils.createFile(unpacked, "Unable to create ZIP file entry ");
                Utils.storeInputStream(zip.getInputStream(entry), unpacked,
                        "IOException while unpacking ZIP file entry.");
            }
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException("IOException while unpacking embedded IzPack installation.", ioe);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                l.info(String.format("Error at closing zipfile %s caused by %s", izPackEmbeddedFile.getName(),
                        e.getMessage()));
            }
        }
    }
    l.info("unpacked " + count + " entries");
}

From source file:com.flexive.tests.disttools.DistPackageTest.java

/**
 * Extracts the flexive-dist.zip package and returns the (temporary) directory handle. All extracted
 * files will be registered for deletion on the JVM exit.
 *
 * @return  the (temporary) directory handle.
 * @throws IOException  if the package could not be extracted
 *///from   ww w .ja va2  s  .c  o  m
private File extractDistPackage() throws IOException {
    final ZipFile file = getDistFile();
    final File tempDir = createTempDir();
    try {
        final Enumeration<? extends ZipEntry> entries = file.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry zipEntry = entries.nextElement();
            final String path = getTempPath(tempDir, zipEntry);
            if (zipEntry.isDirectory()) {
                final File dir = new File(path);
                dir.mkdirs();
                dir.deleteOnExit();
            } else {
                final InputStream in = file.getInputStream(zipEntry);
                final OutputStream out = new BufferedOutputStream(new FileOutputStream(path));
                // copy streams
                final byte[] buffer = new byte[32768];
                int len;
                while ((len = in.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                new File(path).deleteOnExit();
            }
        }
    } finally {
        file.close();
    }
    return new File(tempDir + File.separator + "flexive-dist");
}

From source file:org.opencastproject.util.ZipUtilTest.java

/**
 * Test unzipping//from  w ww .j a  va2  s .co  m
 */
@Test
public void testUnzip() throws Exception {

    ZipUtil.unzip(sampleZip, destDir);

    ZipFile test = new ZipFile(sampleZip);

    Enumeration<? extends ZipEntry> entries = test.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Assert.assertTrue(new File(destDir, entry.getName()).exists());
        }
    } catch (AssertionError ae) {
        test.close();
        throw ae;
    }

    test.close();

}

From source file:net.sf.zekr.engine.translation.TranslationData.java

private void loadAndVerify() throws TranslationException {
    ZipFile zf = null;
    try {/*  ww w . j  a  va 2  s .c o m*/
        logger.info("Loading translation pack " + this + "...");
        zf = new ZipFile(archiveFile);
        ZipEntry ze = zf.getEntry(file);
        if (ze == null) {
            logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\".");
            return;
        }

        byte[] textBuf = new byte[(int) ze.getSize()];
        if (!verify(zf.getInputStream(ze), textBuf))
            logger.warn("Unauthorized translation data pack: " + this);
        // throw new TranslationException("INVALID_TRANSLATION_SIGNATURE", new String[] { name });

        refineText(new String(textBuf, encoding));

        logger.log("Translation pack " + this + " loaded successfully.");
    } catch (IOException e) {
        logger.error("Problem while loading translation pack " + this + ".");
        logger.log(e);
        throw new TranslationException(e);
    } finally {
        try {
            zf.close();
        } catch (Exception e) {
            // do nothing
        }
    }
}

From source file:com.aimfire.main.MainActivity.java

private void displayVersion() {
    try {//w ww . j av a  2  s.c  om
        ApplicationInfo ai = getPackageManager().getApplicationInfo(getPackageName(), 0);
        ZipFile zf = new ZipFile(ai.sourceDir);
        ZipEntry ze = zf.getEntry("classes.dex");
        long time = ze.getTime();
        String s = SimpleDateFormat.getInstance().format(new java.util.Date(time));
        zf.close();

        if (BuildConfig.DEBUG)
            printDebugMsg("App creation time: " + s + "\n");

    } catch (Exception e) {
    }
}

From source file:org.digidoc4j.impl.BDocContainer.java

private String getBdocMimeTypeFromZip(String path) {
    logger.debug("Get mime type from zip for " + path);
    String mimeType;//from   w  w w  .ja v a 2 s .com
    try {
        ZipFile zipFile = new ZipFile(path);
        ZipEntry entry = zipFile.getEntry("mimetype");
        if (entry == null) {
            logger.error("Unsupported format, mimetype missing");
            throw new UnsupportedFormatException("Not an asic-e document. Mimetype is missing.");
        }
        InputStream stream = zipFile.getInputStream(entry);
        mimeType = IOUtils.toString(stream);
        stream.close();
        zipFile.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new DigiDoc4JException(e);
    }

    logger.debug("Mime type " + mimeType);
    return mimeType;
}

From source file:net.minecraftforge.gradle.util.ZipFileTree.java

public void visit(FileVisitor visitor) {
    if (!zipFile.exists()) {
        DeprecationLogger.nagUserOfDeprecatedBehaviour(String.format(
                "The specified zip file %s does not exist and will be silently ignored", getDisplayName()));
        return;/*from ww  w.j a va 2  s. c  om*/
    }
    if (!zipFile.isFile()) {
        throw new InvalidUserDataException(
                String.format("Cannot expand %s as it is not a file.", getDisplayName()));
    }

    AtomicBoolean stopFlag = new AtomicBoolean();

    try {
        ZipFile zip = new ZipFile(zipFile);
        try {
            // The iteration order of zip.getEntries() is based on the hash of the zip entry. This isn't much use
            // to us. So, collect the entries in a map and iterate over them in alphabetical order.
            Map<String, ZipEntry> entriesByName = new TreeMap<String, ZipEntry>();
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                entriesByName.put(entry.getName(), entry);
            }
            Iterator<ZipEntry> sortedEntries = entriesByName.values().iterator();
            while (!stopFlag.get() && sortedEntries.hasNext()) {
                ZipEntry entry = sortedEntries.next();
                if (entry.isDirectory()) {
                    visitor.visitDir(new DetailsImpl(entry, zip, stopFlag));
                } else {
                    visitor.visitFile(new DetailsImpl(entry, zip, stopFlag));
                }
            }
        } finally {
            zip.close();
        }
    } catch (Exception e) {
        throw new GradleException(String.format("Could not expand %s.", getDisplayName()), e);
    }
}

From source file:org.opencastproject.util.ZipUtilTest.java

@Test
public void zipNoRecStrFile() throws Exception {

    File destFile = new File(destDir, "noRecStrFile.zip");

    Vector<String> names = new Vector<String>();
    names.add(srcFileName);/*from w w w . ja v  a 2s.c  om*/
    names.add(nestedSrcFileName);

    File test = ZipUtil.zip(new String[] { srcFile.getCanonicalPath(), nestedSrcFile.getCanonicalPath(),
            nestedSrcDir.getCanonicalPath() }, destFile, false, ZipUtil.NO_COMPRESSION);
    Assert.assertTrue(test.exists());
    ZipFile zip = new ZipFile(test);
    Assert.assertEquals(2, zip.size());
    Enumeration<? extends ZipEntry> entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Assert.assertTrue(names.contains(entry.getName()));
        }
    } catch (AssertionError ae) {
        zip.close();
        throw ae;
    }

    zip.close();
}

From source file:org.opencastproject.util.ZipUtilTest.java

@Test
public void zipNoRecFileStr() throws Exception {

    File destFile = new File(destDir, "noRecFileStr.zip");

    Vector<String> names = new Vector<String>();
    names.add(srcFileName);//w w  w  .  j  a va  2 s.c  om
    names.add(nestedSrcFileName);

    File test = ZipUtil.zip(new File[] { srcFile, nestedSrcFile, nestedSrcDir }, destFile.getCanonicalPath(),
            false, ZipUtil.NO_COMPRESSION);
    Assert.assertTrue(test.exists());
    ZipFile zip = new ZipFile(test);
    Assert.assertEquals(2, zip.size());
    Enumeration<? extends ZipEntry> entries = zip.entries();

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            Assert.assertTrue(names.contains(entry.getName()));
        }
    } catch (AssertionError ae) {
        zip.close();
        throw ae;
    }

    zip.close();
}