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

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

Introduction

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

Prototype

public ZipFile(String name) throws IOException 

Source Link

Document

Opens the given file for reading, assuming "UTF8".

Usage

From source file:org.apache.james.mailbox.backup.ZipperTest.java

@Test
void archiveShouldWriteMailboxHierarchyWhenMissingParent() throws Exception {
    testee.archive(ImmutableList.of(MAILBOX_1_SUB_1, MAILBOX_2), Stream.of(), output);

    try (ZipFile zipFile = new ZipFile(toSeekableByteChannel(output))) {
        assertThatZip(zipFile).containsOnlyEntriesMatching(
                hasName(MAILBOX_1_SUB_1.getName() + "/").isDirectory(),
                hasName(MAILBOX_2.getName() + "/").isDirectory());
    }/*w w w  . ja v a  2 s . c om*/
}

From source file:org.apache.james.mailbox.backup.ZipperTest.java

@Test
void archiveShouldWriteMailboxMetadataWhenPresent() throws Exception {
    testee.archive(ImmutableList.of(MAILBOX_1), Stream.of(), output);

    try (ZipFile zipFile = new ZipFile(toSeekableByteChannel(output))) {
        assertThatZip(zipFile).containsOnlyEntriesMatching(hasName(MAILBOX_1.getName() + "/")
                .containsExtraFields(new MailboxIdExtraField(MAILBOX_1.getMailboxId()),
                        new UidValidityExtraField(MAILBOX_1.getUidValidity())));
    }//from   w w  w .j  a va  2 s .  c om
}

From source file:org.apache.tika.parser.pkg.ZipContainerDetector.java

private static MediaType detectZipFormat(TikaInputStream tis) {
    try {/*from  w ww.j  ava 2  s  .c om*/

        //try opc first because opening a package
        //will not necessarily throw an exception for
        //truncated files.
        MediaType type = detectOPCBased(tis);
        if (type != null) {
            return type;
        }

        ZipFile zip = new ZipFile(tis.getFile()); // TODO: hasFile()?
        try {
            type = detectOpenDocument(zip);

            if (type == null) {
                type = detectIWork13(zip);
            }
            if (type == null) {
                type = detectIWork(zip);
            }
            if (type == null) {
                type = detectJar(zip);
            }
            if (type == null) {
                type = detectKmz(zip);
            }
            if (type == null) {
                type = detectIpa(zip);
            }
            if (type != null) {
                return type;
            }
        } finally {
            // TODO: shouldn't we record the open
            // container so it can be later
            // reused...?
            // tis.setOpenContainer(zip);
            try {
                zip.close();
            } catch (IOException e) {
                // ignore
            }
        }
    } catch (IOException e) {
        // ignore
    }
    // Fallback: it's still a zip file, we just don't know what kind of one
    return MediaType.APPLICATION_ZIP;
}

From source file:org.apache.tika.server.CXFTestBase.java

protected Map<String, String> readZipArchive(InputStream inputStream) throws IOException {
    Map<String, String> data = new HashMap<String, String>();
    Path tempFile = writeTemporaryArchiveFile(inputStream, "zip");
    ZipFile zip = new ZipFile(tempFile.toFile());
    Enumeration<ZipArchiveEntry> entries = zip.getEntries();
    while (entries.hasMoreElements()) {
        ZipArchiveEntry entry = entries.nextElement();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOUtils.copy(zip.getInputStream(entry), bos);
        data.put(entry.getName(), DigestUtils.md5Hex(bos.toByteArray()));
    }/* w  w w . j a v a2 s  .c om*/
    zip.close();
    Files.delete(tempFile);
    return data;
}

From source file:org.apache.tika.server.CXFTestBase.java

protected String readArchiveText(InputStream inputStream) throws IOException {
    Path tempFile = writeTemporaryArchiveFile(inputStream, "zip");
    ZipFile zip = new ZipFile(tempFile.toFile());
    zip.getEntry(UnpackerResource.TEXT_FILENAME);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    IOUtils.copy(zip.getInputStream(zip.getEntry(UnpackerResource.TEXT_FILENAME)), bos);

    zip.close();/*  w w  w  . j  a  va  2s.  c o m*/
    Files.delete(tempFile);
    return bos.toString(UTF_8.name());
}

From source file:org.apache.wookie.w3c.W3CWidgetFactory.java

/**
 * Process a widget package for the given zip file
 * @param zipFile/*from   w w w .  ja  v  a2 s.co m*/
 * @return a W3CWidget representing the widget
 * @throws BadWidgetZipFileException
 * @throws BadManifestException
 */
private W3CWidget processWidgetPackage(File zipFile) throws BadWidgetZipFileException, BadManifestException {
    ZipFile zip;
    try {
        zip = new ZipFile(zipFile);
    } catch (IOException e) {
        throw new BadWidgetZipFileException();
    }
    if (WidgetPackageUtils.hasManifest(zip)) {
        try {
            // build the model
            WidgetManifestModel widgetModel = new WidgetManifestModel(WidgetPackageUtils.extractManifest(zip),
                    locales, features, encodings, zip);

            // get the widget identifier
            String manifestIdentifier = widgetModel.getIdentifier();
            // create the folder structure to unzip the zip into
            unzippedWidgetDirectory = WidgetPackageUtils.createUnpackedWidgetFolder(outputDirectory,
                    manifestIdentifier);
            // now unzip it into that folder
            WidgetPackageUtils.unpackZip(zip, unzippedWidgetDirectory);

            // Iterate over all start files and update paths
            for (IContentEntity content : widgetModel.getContentList()) {
                // now update the js links in the start page
                File startFile = new File(
                        unzippedWidgetDirectory.getCanonicalPath() + File.separator + content.getSrc());
                String relativestartUrl = (WidgetPackageUtils.getURLForWidget(localPath, manifestIdentifier,
                        content.getSrc()));
                content.setSrc(relativestartUrl);
                if (startFile.exists() && startPageProcessor != null) {
                    startPageProcessor.processStartFile(startFile, widgetModel);
                }
            }
            if (widgetModel.getContentList().isEmpty()) {
                throw new InvalidStartFileException("Widget has no start page");
            }

            // get the path to the root of the unzipped folder
            String thelocalPath = WidgetPackageUtils.getURLForWidget(localPath, manifestIdentifier, "");
            // now pass this to the model which will prepend the path to local resources (not web icons)
            widgetModel.updateIconPaths(thelocalPath);

            // check to see if this widget already exists in the DB - using the ID (guid) key from the manifest
            return widgetModel;
        } catch (InvalidStartFileException e) {
            throw e;
        } catch (BadManifestException e) {
            throw e;
        } catch (Exception e) {
            throw new BadManifestException(e);
        }
    } else {
        // no manifest file found in zip archive
        throw new BadWidgetZipFileException(); //$NON-NLS-1$ 
    }
}

From source file:org.artificer.atom.archive.ArchiveUtils.java

/**
 * Unpacks the given archive file into the output directory.
 * @param archiveFile an archive file/* w w w  . ja  v  a 2 s  . c  o  m*/
 * @param toDir where to unpack the archive to
 * @throws IOException
 */
public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException {
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(archiveFile);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntriesInPhysicalOrder();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            String entryName = entry.getName();
            File outFile = new File(toDir, entryName);
            if (!outFile.getParentFile().exists()) {
                if (!outFile.getParentFile().mkdirs()) {
                    throw new IOException(Messages.i18n.format("FAILED_TO_CREATE_PARENT_DIR",
                            outFile.getParentFile().getCanonicalPath()));
                }
            }

            if (entry.isDirectory()) {
                if (outFile.isDirectory()) {
                    // Do nothing - already created.
                } else if (outFile.isFile()) {
                    throw new IOException(
                            Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath()));
                } else if (!outFile.mkdir()) {
                    throw new IOException(
                            Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath()));
                }
            } else {
                InputStream zipStream = null;
                OutputStream outFileStream = null;

                zipStream = zipFile.getInputStream(entry);
                outFileStream = new FileOutputStream(outFile);
                try {
                    IOUtils.copy(zipStream, outFileStream);
                } finally {
                    IOUtils.closeQuietly(zipStream);
                    IOUtils.closeQuietly(outFileStream);
                }
            }
        }
    } finally {
        ZipFile.closeQuietly(zipFile);
    }
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;/*from w  w  w. ja v  a  2 s.c o  m*/
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        @SuppressWarnings("unchecked")
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOUtils.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}

From source file:org.beangle.commons.archiver.ZipUtils.java

public static boolean isZipFile(File zipFile) {
    try {//from  w  w w.  j  a v a2s .  c om
        ZipFile zf = new ZipFile(zipFile);
        boolean isZip = zf.getEntries().hasMoreElements();
        zf.close();
        return isZip;
    } catch (IOException e) {
        return false;
    }
}

From source file:org.beangle.ems.util.ZipUtils.java

/**
 * <p>/* ww w .j av a2s.com*/
 * unzip.
 * </p>
 * 
 * @param zipFile a {@link java.io.File} object.
 * @param destination a {@link java.lang.String} object.
 * @param encoding a {@link java.lang.String} object.
 * @return a {@link java.util.List} object.
 */
public static List<String> unzip(final File zipFile, final String destination, String encoding) {
    List<String> fileNames = CollectUtils.newArrayList();
    String dest = destination;
    if (!destination.endsWith(File.separator)) {
        dest = destination + File.separator;
    }
    ZipFile file;
    try {
        file = null;
        if (null == encoding)
            file = new ZipFile(zipFile);
        else
            file = new ZipFile(zipFile, encoding);
        Enumeration<ZipArchiveEntry> en = file.getEntries();
        ZipArchiveEntry ze = null;
        while (en.hasMoreElements()) {
            ze = en.nextElement();
            File f = new File(dest, ze.getName());
            if (ze.isDirectory()) {
                f.mkdirs();
                continue;
            } else {
                f.getParentFile().mkdirs();
                InputStream is = file.getInputStream(ze);
                OutputStream os = new FileOutputStream(f);
                IOs.copy(is, os);
                is.close();
                os.close();
                fileNames.add(f.getAbsolutePath());
            }
        }
        file.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return fileNames;
}