Example usage for java.util.zip ZipEntry getMethod

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

Introduction

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

Prototype

public int getMethod() 

Source Link

Document

Returns the compression method of the entry.

Usage

From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java

@Test
public void mimeTypePosition() throws Exception {
    UCFPackage container = new UCFPackage();
    container.setPackageMediaType(UCFPackage.MIME_EPUB);
    assertEquals(UCFPackage.MIME_EPUB, container.getPackageMediaType());
    container.save(tmpFile);//from ww w . j a  v  a2  s.co m
    assertTrue(tmpFile.exists());
    ZipFile zipFile = new ZipFile(tmpFile);
    // Must be first entry
    ZipEntry mimeEntry = zipFile.entries().nextElement();
    assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName());
    assertEquals("mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(),
            mimeEntry.getSize());
    assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod());
    assertEquals("Wrong mimetype", UCFPackage.MIME_EPUB,
            IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII"));

    // Check position 30++ according to
    // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568
    byte[] expected = ("mimetype" + UCFPackage.MIME_EPUB + "PK").getBytes("ASCII");
    FileInputStream in = new FileInputStream(tmpFile);
    byte[] actual = new byte[expected.length];
    try {
        assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET));
        assertEquals(expected.length, in.read(actual));
    } finally {
        in.close();
    }
    assertArrayEquals(expected, actual);
}

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

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

    try {// w  w w  . ja  va2 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.jahia.ajax.gwt.helper.ZipHelper.java

private boolean doUnzipContent(final NoCloseZipInputStream zis, final String dest,
        JCRSessionWrapper currentUserSession) throws RepositoryException {
    List<String> errorFiles = new ArrayList<String>();
    boolean result = false;
    try {//from w w w  .  j  a  v  a2s. c o  m
        ZipEntry zipentry;

        while ((zipentry = zis.getNextEntry()) != null) {
            String filename = null;
            try {
                filename = zipentry.getName().replace('\\', '/');
                if (logger.isDebugEnabled()) {
                    logger.debug("Unzip file (" + zipentry.getMethod() + ")" + filename);
                }
                if (filename.endsWith("/")) {
                    filename = filename.substring(0, filename.length() - 1);
                }
                int endIndex = filename.lastIndexOf('/');
                String parentName = dest;
                if (endIndex > -1) {
                    parentName += "/" + filename.substring(0, endIndex);
                    filename = filename.substring(endIndex + 1);
                }
                JCRNodeWrapper target = ensureDir(parentName, currentUserSession);

                if (zipentry.isDirectory()) {
                    String folderName = JCRContentUtils.escapeLocalNodeName(filename);
                    if (!target.hasNode(folderName)) {
                        try {
                            target.createCollection(folderName);
                        } catch (ItemExistsException e) {
                            // ignore - it is already there
                        }
                    }
                } else {
                    target.uploadFile(filename, zis, JCRContentUtils.getMimeType(filename));
                }
                result = true;
            } catch (InternalError err) {
                logger.error("Error when unzipping file", err);
                if (filename != null) {
                    errorFiles.add(filename);
                }
            }
        }
    } catch (IOException e) {
        logger.error("Error when unzipping file", e);
        result = false;
    } catch (InternalError err) {
        logger.error("Error when unzipping file, " + err.getMessage(), err);
        result = false;
    }

    return result;
}

From source file:reconcile.hbase.mapreduce.ZipInputFormat.java

private List<ZipEntrySplit> getZipFileEntries(JobContext context, FileSystem fs, Path[] zipFiles,
        Integer maxEntryFiles, Integer ignoreFilesLargerThanMB, List<String> processMimeTypes)
        throws IOException {
    ArrayList<ZipEntrySplit> splits = new ArrayList<ZipEntrySplit>();
    ZipInputStream zis = null;/* w w w.  j a  va2  s.  c o m*/
    ZipEntry zipEntry = null;

    for (int i = 0; i < zipFiles.length; i++) {
        Path file = zipFiles[i];
        LOG.debug("Opening zip file: " + file.toString());
        try {
            zis = new ZipInputStream(fs.open(file));
            while ((zipEntry = zis.getNextEntry()) != null) {
                if (maxEntryFiles != null && splits.size() == maxEntryFiles.intValue()) {
                    LOG.debug("Exceeded maximum number of splits.  End getSplits()");
                    return splits;
                }

                boolean processFile = true;

                if (processMimeTypes.size() > 0) {
                    // Ensure that if process mime types were specified, that entry
                    // mime type meets that criteria
                    String mimeType = fileNameMap.getContentTypeFor(zipEntry.getName());
                    if (mimeType == null || (!processMimeTypes.contains(mimeType.toLowerCase()))) {
                        processFile = false;
                        LOG.debug("Ignoring entry file (" + zipEntry.getName() + " mimeType(" + mimeType
                                + ") not in process list");
                    }
                }

                long byteCount = zipEntry.getSize();
                /*
                if (byteCount <= 0) {
                   // Read entry and figure out size for ourselves
                   byteCount = 0;
                   while (zis.available()==1) {
                      zis.read();
                      ++byteCount;
                   }
                }
                */
                if (ignoreFilesLargerThanMB != null && byteCount > ignoreFilesLargerThanMB.intValue()) {
                    processFile = false;
                    LOG.debug("Ignoring entry file (" + zipEntry.getName() + ") which exceeds size limit");
                }

                if (processFile) {
                    LOG.debug("Creating split for zip entry: " + zipEntry.getName() + " Size: " + byteCount
                            + " Method: " + (ZipEntry.DEFLATED == zipEntry.getMethod() ? "DEFLATED" : "STORED")
                            + " Compressed Size: " + zipEntry.getCompressedSize());

                    ZipEntrySplit zipSplit = new ZipEntrySplit(file, zipEntry.getName(), zipEntry.getSize(),
                            context);
                    splits.add(zipSplit);
                }
                zis.closeEntry();
            }
        } finally {
            IOUtils.closeQuietly(zis);
        }

    }
    return splits;
}

From source file:VASSAL.tools.io.ZipArchive.java

private void writeToDisk() throws IOException {
    // write all files to a temporary zip archive
    final File tmpFile = File.createTempFile("tmp", ".zip", archiveFile.getParentFile());

    ZipOutputStream out = null;/*from  ww w  .  j a  v  a 2 s.c  om*/
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(tmpFile)));
        out.setLevel(9);

        final byte[] buf = new byte[8192];

        if (zipFile != null) {
            zipFile.close();
            zipFile = null;

            // copy unmodified file into the temp archive
            ZipInputStream in = null;
            try {
                in = new ZipInputStream(new BufferedInputStream(new FileInputStream(archiveFile)));

                ZipEntry ze = null;
                while ((ze = in.getNextEntry()) != null) {
                    // skip modified or removed entries
                    final Entry e = entries.get(ze.getName());
                    if (e == null || e.file != null)
                        continue;

                    // We can't reuse entries for compressed files because there's
                    // no way to reset all fields to acceptable values.
                    if (ze.getMethod() == ZipEntry.DEFLATED) {
                        ze = new ZipEntry(ze.getName());
                        ze.setTime(ze.getTime());
                    }

                    out.putNextEntry(ze);
                    IOUtils.copy(in, out, buf);

                    entries.remove(ze.getName());
                }

                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        for (String name : entries.keySet()) {
            final Entry e = entries.get(name);

            // write new or modified file into the temp archive
            FileInputStream in = null;
            try {
                in = new FileInputStream(e.file);
                out.putNextEntry(e.ze);
                IOUtils.copy(in, out, buf);
                in.close();
            } finally {
                IOUtils.closeQuietly(in);
            }
        }

        out.close();
    } finally {
        IOUtils.closeQuietly(out);
    }

    // Replace old archive with temp archive.
    if (!tmpFile.renameTo(archiveFile)) {
        try {
            FileUtils.forceDelete(archiveFile);
            FileUtils.moveFile(tmpFile, archiveFile);
        } catch (IOException e) {
            String err = "Unable to overwrite " + archiveFile.getAbsolutePath() + ": ";

            if (!archiveFile.exists()) {
                err += " file does not exist.";
            } else if (!archiveFile.canWrite()) {
                err += " file is not writable.";
            } else if (!archiveFile.isFile()) {
                err += " not a normal file.";
            }

            err += " Data written to " + tmpFile.getAbsolutePath() + " instead.";
            throw (IOException) new IOException(err).initCause(e);
        }
    }

    closed = true;
    modified = false;
    entries.clear();
}