Example usage for org.apache.commons.compress.archivers.zip ZipFile close

List of usage examples for org.apache.commons.compress.archivers.zip ZipFile close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the archive.

Usage

From source file:org.bml.util.io.IOUtils.java

public static void closeQuietly(ZipFile zipFile) {
    if (zipFile == null) {
        return;/*from w w w. ja va2 s  .  c om*/
    }
    try {
        zipFile.close();
    } catch (IOException ex) {
        Logger.getLogger(IOUtils.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.codehaus.mojo.unix.maven.zip.ZipPackageTest.java

@SuppressWarnings("OctalInteger")
public void testBasic() throws Exception {
    File zip1 = testUtil.getTestFile("src/test/resources/zip/zip-1");
    File zip = testUtil.getTestFile("target/zip/zip-1/test.zip");
    if (!zip.getParentFile().isDirectory()) {
        assertTrue(zip.getParentFile().mkdirs());
    }//from w  w  w .  j av a  2 s  .  c  o  m

    LocalFs basedir = new LocalFs(zip1);

    ZipUnixPackage zipPackage = new ZipUnixPackage(new SystemStreamLog());

    zipPackage.beforeAssembly(EMPTY.mode(UnixFileMode._0755), timestamp);

    assertTrue(basedir.isDirectory());

    // Git set the timestamp of file objects
    assertTrue(new File(zip1, "dirs").setLastModified(dirsTimestamp.toDateTime().getMillis()));
    assertTrue(new File(zip1, "dirs/bar.txt").setLastModified(dirsBarTxtTimestamp.toDateTime().getMillis()));
    assertTrue(new File(zip1, "file").setLastModified(fileTimestamp.toDateTime().getMillis()));
    assertTrue(new File(zip1, "file/foo.txt").setLastModified(fileFooTxtTimestamp.toDateTime().getMillis()));

    Replacer replacer = new Replacer("@bar@", "awesome");

    new CreateDirectoriesOperation(timestamp, new String[] { "/opt/hudson" }, EMPTY).perform(zipPackage);

    new CopyDirectoryOperation(basedir, relativePath(""), List.<String>nil(), List.<String>nil(),
            Option.<P2<String, String>>none(), EMPTY, EMPTY).perform(zipPackage);

    new CopyFileOperation(EMPTY, basedir.resolve("file/foo.txt"), relativePath("/file/foo.txt"))
            .perform(zipPackage);

    new SymlinkOperation(relativePath("/var/log/hudson"), "/var/opt/hudson/log", Option.<String>none(),
            Option.<String>none()).perform(zipPackage);

    new FilterFilesOperation(single("dirs/**"), List.<String>nil(), single(replacer), LineEnding.unix)
            .perform(zipPackage);

    UnixFileMode fileMode = UnixFileMode.fromInt(0600);
    UnixFileMode dirMode = _0777;

    FileAttributes fileAttributes = new FileAttributes("root", "root", fileMode);
    FileAttributes directoryAttributes = new FileAttributes("root", "root", dirMode);
    new SetAttributesOperation(BASE, single("**/*"), List.<String>nil(), some(fileAttributes),
            some(directoryAttributes)).perform(zipPackage);

    zipPackage.prepare(SINGLE).packageToFile(zip);

    ZipFile file = new ZipFile(zip);
    Enumeration<ZipArchiveEntry> enumeration = file.getEntriesInPhysicalOrder();
    assertDirectory(enumeration.nextElement(), "./dirs/", dirsTimestamp);
    // Is it really correct that filtered files should retain the old timestamp?
    assertFile(file, enumeration.nextElement(), "./dirs/bar.txt", 8, dirsBarTxtTimestamp, "awesome\n",
            fileMode);
    assertDirectory(enumeration.nextElement(), "./file/", fileTimestamp);
    assertFile(file, enumeration.nextElement(), "./file/foo.txt", 6, fileFooTxtTimestamp, "@foo@\n", fileMode);
    assertDirectory(enumeration.nextElement(), "./opt/", timestamp);
    assertDirectory(enumeration.nextElement(), "./opt/hudson/", timestamp);
    assertFalse(enumeration.hasMoreElements());
    file.close();
}

From source file:org.codehaus.plexus.archiver.jar.JarArchiver.java

/**
 * Grab lists of all root-level files and all directories
 * contained in the given archive.//from  www  . jav a  2 s .c om
 *
 * @param file  .
 * @param files .
 * @param dirs  .
 * @throws java.io.IOException .
 */
protected static void grabFilesAndDirs(String file, List<String> dirs, List<String> files) throws IOException {
    File zipFile = new File(file);
    if (!zipFile.exists()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.error("JarArchive skipping non-existing file: " + zipFile.getAbsolutePath());
    } else if (zipFile.isDirectory()) {
        Logger logger = new ConsoleLogger(Logger.LEVEL_INFO, "console");
        logger.info("JarArchiver skipping indexJar " + zipFile + " because it is not a jar");
    } else {
        org.apache.commons.compress.archivers.zip.ZipFile zf = null;
        try {
            zf = new org.apache.commons.compress.archivers.zip.ZipFile(file, "utf-8");
            Enumeration<ZipArchiveEntry> entries = zf.getEntries();
            HashSet<String> dirSet = new HashSet<String>();
            while (entries.hasMoreElements()) {
                ZipArchiveEntry ze = entries.nextElement();
                String name = ze.getName();
                // avoid index for manifest-only jars.
                if (!name.equals(META_INF_NAME) && !name.equals(META_INF_NAME + '/') && !name.equals(INDEX_NAME)
                        && !name.equals(MANIFEST_NAME)) {
                    if (ze.isDirectory()) {
                        dirSet.add(name);
                    } else if (!name.contains("/")) {
                        files.add(name);
                    } else {
                        // a file, not in the root
                        // since the jar may be one without directory
                        // entries, add the parent dir of this file as
                        // well.
                        dirSet.add(name.substring(0, name.lastIndexOf("/") + 1));
                    }
                }
            }
            dirs.addAll(dirSet);
        } finally {
            if (zf != null) {
                zf.close();
            }
        }
    }
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.java

public void testCreateResourceCollection() throws Exception {
    final File srcDir = new File("src");
    final File zipFile = new File("target/output/src.zip");
    ZipArchiver zipArchiver = getZipArchiver(zipFile);
    zipArchiver.addDirectory(srcDir, null, FileUtils.getDefaultExcludes());
    zipArchiver.setEncoding("UTF-8");
    FileUtils.removePath(zipFile.getPath());
    zipArchiver.createArchive();// ww w  . ja  v a 2  s . com

    final File zipFile2 = new File("target/output/src2.zip");
    ZipArchiver zipArchiver2 = getZipArchiver(zipFile2);
    zipArchiver2.addArchivedFileSet(zipFile, "prfx/");
    zipArchiver2.setEncoding("UTF-8");
    FileUtils.removePath(zipFile2.getPath());
    zipArchiver2.createArchive();

    final ZipFile cmp1 = new ZipFile(zipFile);
    final ZipFile cmp2 = new ZipFile(zipFile2);
    ArchiveFileComparator.assertEquals(cmp1, cmp2, "prfx/");
    cmp1.close();
    cmp2.close();
}

From source file:org.codehaus.plexus.archiver.zip.ZipArchiverTest.java

public void testForcedFileModes() throws IOException {
    File step1file = new File("target/output/forced-file-mode.zip");
    {/*  w w w  .j a  v  a 2 s.c  o  m*/
        final ZipArchiver zipArchiver = getZipArchiver(step1file);
        zipArchiver.setFileMode(0077);
        zipArchiver.setDirectoryMode(0007);
        PlexusIoResourceAttributes attrs = new SimpleResourceAttributes(123, "fred", 22, "filntstones", 0111);
        PlexusIoResource resource = ResourceFactory
                .createResource(new File("src/test/resources/folders/File.txt"), "Test.txt", null, attrs);
        zipArchiver.addResource(resource, "Test2.txt", 0707);
        PlexusIoFileResourceCollection files = new PlexusIoFileResourceCollection();
        files.setBaseDir(new File("src/test/resources/folders"));
        files.setPrefix("sixsixsix/");
        zipArchiver.addResources(files);

        zipArchiver.createArchive();

        ZipFile zf = new ZipFile(step1file);
        fileModeAssert(040007, zf.getEntry("sixsixsix/a/").getUnixMode());
        fileModeAssert(0100077, zf.getEntry("sixsixsix/b/FileInB.txt").getUnixMode());
        fileModeAssert(0100707, zf.getEntry("Test2.txt").getUnixMode());
        zf.close();
    }

    File Step2file = new File("target/output/forced-file-mode-from-zip.zip");
    {
        final ZipArchiver za2 = getZipArchiver(Step2file);
        za2.setFileMode(0666);
        za2.setDirectoryMode(0676);

        PlexusIoZipFileResourceCollection zipSrc = new PlexusIoZipFileResourceCollection();
        zipSrc.setFile(step1file);
        zipSrc.setPrefix("zz/");
        za2.addResources(zipSrc);
        za2.createArchive();
        ZipFile zf = new ZipFile(Step2file);
        fileModeAssert(040676, zf.getEntry("zz/sixsixsix/a/").getUnixMode());
        fileModeAssert(0100666, zf.getEntry("zz/Test2.txt").getUnixMode());
        zf.close();
    }

    File step3file = new File("target/output/forced-file-mode-from-zip2.zip");
    {
        final ZipArchiver za2 = getZipArchiver(step3file);
        za2.setFileMode(0666);
        za2.setDirectoryMode(0676);

        PlexusArchiverZipFileResourceCollection zipSrc = new PlexusArchiverZipFileResourceCollection();
        zipSrc.setFile(step1file);
        zipSrc.setPrefix("zz/");
        za2.addResources(zipSrc);
        za2.createArchive();
        ZipFile zf = new ZipFile(Step2file);
        fileModeAssert(040676, zf.getEntry("zz/sixsixsix/a/").getUnixMode());
        fileModeAssert(0100666, zf.getEntry("zz/Test2.txt").getUnixMode());
        zf.close();
    }
}

From source file:org.cytobank.acs.core.ACS.java

/**
 * Writes out a file contained within this <code>ACS</code> instance to the
 * specified <code>OutputStream</code>.
 * //  w w w .ja  va 2s . c o  m
 * @param filePath
 *            the <code>String</code> path representing a file within this
 *            <code>ACS</code> instance.
 * @param outputStream
 *            to write the requested file to
 * @throws IOException
 *             If an input or output exception occurred
 */
public void extractFile(String filePath, OutputStream outputStream) throws IOException {
    ZipFile zipFile = new ZipFile(acsFile);

    if (filePath.startsWith("/"))
        filePath = filePath.substring(1);

    InputStream inputStream = null;
    ZipArchiveEntry entry = zipFile.getEntry(filePath);
    try {
        if (entry == null)
            throw new IOException("Could not find zip file entry " + filePath);

        inputStream = zipFile.getInputStream(entry);
        IOUtils.copy(inputStream, outputStream);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException ignore) {
        }

        try {
            zipFile.close();
        } catch (IOException ignore) {
        }
    }

}

From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace.ArchiveUtil.java

private static boolean isZipFile(String fileName) {
    ZipFile specifiedZipSourceFile = getSpecifiedZipSourceFile(fileName);
    if (specifiedZipSourceFile != null) {
        try {//  ww w .j  a  v  a2 s. com
            specifiedZipSourceFile.close();
            return true;
        } catch (IOException e) {
            // ignore
        }
    }

    return false;
}

From source file:org.eclipse.tracecompass.internal.tmf.ui.project.wizards.importtrace.ArchiveUtil.java

static boolean closeZipFile(ZipFile file) {
    try {//from w ww.  j  av  a 2  s.  c  om
        file.close();
    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:org.everit.osgi.dev.maven.util.FileManager.java

public final void unpackZipFile(final File file, final File destinationDirectory) throws IOException {
    destinationDirectory.mkdirs();//w  w  w  .ja  v  a  2  s .c o  m
    ZipFile zipFile = new ZipFile(file);

    try {
        Enumeration<? extends ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            String name = entry.getName();
            File destFile = new File(destinationDirectory, name);
            if (entry.isDirectory()) {
                destFile.mkdirs();
            } else {
                File parentFolder = destFile.getParentFile();
                parentFolder.mkdirs();
                InputStream inputStream = zipFile.getInputStream(entry);
                overCopyFile(inputStream, destFile);
                FileManager.setPermissionsOnFile(destFile, entry);
            }

        }
    } finally {
        zipFile.close();
    }
}

From source file:org.interreg.docexplore.util.ZipUtils.java

public static void unzip(File zipfile, File directory, float[] progress, float progressOffset,
        float progressAmount, boolean overwrite) throws IOException {
    org.apache.commons.compress.archivers.zip.ZipFile zfile = new org.apache.commons.compress.archivers.zip.ZipFile(
            zipfile);//from   w ww. j a  v  a 2 s  . co  m

    int nEntries = 0;
    Enumeration<ZipArchiveEntry> entries = zfile.getEntries();
    while (entries.hasMoreElements())
        if (!entries.nextElement().isDirectory())
            nEntries++;

    int cnt = 0;
    entries = zfile.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        File file = new File(directory, entry.getName());
        if (entry.isDirectory())
            file.mkdirs();
        else {
            if (!file.exists() || overwrite) {
                file.getParentFile().mkdirs();
                InputStream in = zfile.getInputStream(entry);
                try {
                    copy(in, file);
                } finally {
                    in.close();
                }
            }

            cnt++;
            if (progress != null)
                progress[0] = progressOffset + cnt * progressAmount / nEntries;
        }
    }
    zfile.close();
}