Example usage for java.util.zip ZipFile getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream(ZipEntry entry) throws IOException 

Source Link

Document

Returns an input stream for reading the contents of the specified zip file entry.

Usage

From source file:org.apache.webdav.ant.taskdefs.Put.java

private void uploadZipEntry(HttpURL url, String name, ZipFile zipFile) throws IOException {
    boolean putit = false;
    ZipEntry entry = zipFile.getEntry(name);

    try {//from w  w  w  . j  a v  a 2 s .  c  o  m
        if (this.overwrite) {
            putit = true;
        } else {
            // check last modified date (both GMT)
            long remoteLastMod = Utils.getLastModified(getHttpClient(), url);
            long localLastMod = entry.getTime();
            putit = localLastMod > remoteLastMod;
        }
    } catch (HttpException e) {
        switch (e.getReasonCode()) {
        case HttpStatus.SC_NOT_FOUND:
            putit = true;
            break;
        default:
            throw Utils.makeBuildException("Can't get lastmodified!?", e);
        }
    }

    if (putit) {
        log("Uploading: " + name, ifVerbose());
        String contentType = Mimetypes.getMimeType(name, DEFAULT_CONTENT_TYPE);
        Utils.putFile(getHttpClient(), url, zipFile.getInputStream(entry), contentType, this.locktoken);
        this.countWrittenFiles++;
    } else {
        countOmittedFiles++;
        log("Omitted: " + name + " (uptodate)", ifVerbose());
    }
}

From source file:dalma.container.ClassLoaderImpl.java

/**
 * Returns an inputstream to a given resource in the given file which may
 * either be a directory or a zip file.//w  ww .j ava2  s  .c o  m
 *
 * @param file the file (directory or jar) in which to search for the
 *             resource. Must not be <code>null</code>.
 * @param resourceName The name of the resource for which a stream is
 *                     required. Must not be <code>null</code>.
 *
 * @return a stream to the required resource or <code>null</code> if
 *         the resource cannot be found in the given file.
 */
private InputStream getResourceStream(File file, String resourceName) {
    try {
        if (!file.exists()) {
            return null;
        }

        if (file.isDirectory()) {
            File resource = new File(file, resourceName);

            if (resource.exists()) {
                return new FileInputStream(resource);
            }
        } else {
            // is the zip file in the cache
            ZipFile zipFile = zipFiles.get(file);
            if (zipFile == null) {
                zipFile = new ZipFile(file);
                zipFiles.put(file, zipFile);
            }
            ZipEntry entry = zipFile.getEntry(resourceName);
            if (entry != null) {
                return zipFile.getInputStream(entry);
            }
        }
    } catch (Exception e) {
        logger.fine("Ignoring Exception " + e.getClass().getName() + ": " + e.getMessage()
                + " reading resource " + resourceName + " from " + file);
    }

    return null;
}

From source file:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkZipArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    ZipFile zipFile = null;
    try {/*from   w w w . j  a v a2s .c om*/
        zipFile = new ZipFile(archiveFile);
        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry ze = entries.nextElement();
            if (ze.isDirectory()) {
                assertTrue("Directory in zip should be from us [" + ze.getName() + "]",
                        archiveEntries.dirs.contains(ze.getName()));
                archiveEntries.dirs.remove(ze.getName());
            } else {
                assertTrue("File in zip should be from us [" + ze.getName() + "]",
                        archiveEntries.files.containsKey(ze.getName()));
                final byte[] inflatedMd5 = getMd5Digest(zipFile.getInputStream(ze), true);
                assertArrayEquals("MD5 hash of files should equal [" + ze.getName() + "]",
                        archiveEntries.files.get(ze.getName()), inflatedMd5);
                archiveEntries.files.remove(ze.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the zip", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the zip", archiveEntries.files.isEmpty());
    } finally {
        if (null != zipFile) {
            zipFile.close();
        }
    }
}

From source file:org.adempiere.webui.install.WTranslationDialog.java

private void unZipAndProcess(InputStream istream) throws AdempiereException {
    FileOutputStream ostream = null;
    File file = null;/*from   w  w w  .  j a va 2s. c o m*/
    try {
        file = File.createTempFile("trlImport", ".zip");
        ostream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int read;
        while ((read = istream.read(buffer)) != -1) {
            ostream.write(buffer, 0, read);
        }
    } catch (Throwable e) {
        throw new AdempiereException("Copy zip failed", e);
    } finally {
        if (ostream != null) {
            try {
                ostream.close();
            } catch (Exception e2) {
            }
        }
    }

    // create temp folder
    File tempfolder;
    try {
        tempfolder = File.createTempFile(m_AD_Language.getValue(), ".trl");
        tempfolder.delete();
        tempfolder.mkdir();
    } catch (IOException e1) {
        throw new AdempiereException("Problem creating temp folder", e1);
    }

    String suffix = "_" + m_AD_Language.getValue() + ".xml";
    ZipFile zipFile = null;
    boolean validfile = false;
    try {
        zipFile = new ZipFile(file);

        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();

            if (entry.isDirectory()) {
                // ignore folders
                log.warning("Imported zip must not contain folders, ignored folder" + entry.getName());
                continue;
            }

            if (!entry.getName().endsWith(suffix)) {
                // not valid file
                log.warning("Ignored file " + entry.getName());
                continue;
            }

            if (log.isLoggable(Level.INFO))
                log.info("Extracting file: " + entry.getName());
            copyInputStream(zipFile.getInputStream(entry), new BufferedOutputStream(
                    new FileOutputStream(tempfolder.getPath() + File.separator + entry.getName())));
            validfile = true;
        }
    } catch (Throwable e) {
        throw new AdempiereException("Uncompress zip failed", e);
    } finally {
        if (zipFile != null)
            try {
                zipFile.close();
            } catch (IOException e) {
            }
    }

    if (!validfile) {
        throw new AdempiereException("ZIP file invalid, doesn't contain *" + suffix + " files");
    }

    callImportProcess(tempfolder.getPath());

    file.delete();
    try {
        FileUtils.deleteDirectory(tempfolder);
    } catch (IOException e) {
    }
}

From source file:org.talend.mdm.repository.ui.wizards.imports.ImportServerObjectWizard.java

private byte[] extractBar(File barFile) {
    ZipFile zipFile = null;
    InputStream entryInputStream = null;
    byte[] processBytes = null;
    try {/*from  ww  w  .  ja v  a2s .c  o  m*/
        zipFile = new ZipFile(barFile);

        for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (!entry.isDirectory()) {
                if (entry.getName().endsWith(".proc")) { //$NON-NLS-1$
                    entryInputStream = zipFile.getInputStream(entry);
                    processBytes = IOUtils.toByteArray(entryInputStream);
                }
            }
        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (entryInputStream != null) {
            try {
                entryInputStream.close();
            } catch (IOException e) {
            }
        }
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
            }
        }

    }
    return processBytes;
}

From source file:fr.paris.lutece.plugins.updater.service.UpdateService.java

/**
 * Extract a package/*  ww w .java2 s  . c om*/
 * @param strZipFile The package zip file
 * @param strDirectory The target directory
 * @throws UpdaterDownloadException If an exception occurs during download
 */
private void extractPackage(String strZipFile, String strDirectory) throws UpdaterDownloadException {
    try {
        File file = new File(strZipFile);
        ZipFile zipFile = new ZipFile(file);

        // Each zipped file is indentified by a zip entry :
        Enumeration zipEntries = zipFile.entries();

        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();

            // Clean the name :
            String strEntryName = zipEntry.getName();

            // The unzipped file :
            File destFile = new File(strDirectory, strEntryName);

            // Create the parent directory structure if needed :
            destFile.getParentFile().mkdirs();

            if (!zipEntry.isDirectory()) {
                // InputStream from zipped data
                InputStream inZipStream = null;

                try {
                    AppLogService.debug("unzipping " + strEntryName + " to " + destFile.getName());
                    inZipStream = zipFile.getInputStream(zipEntry);

                    // OutputStream to the destination file
                    OutputStream outDestStream = new FileOutputStream(destFile);

                    // Helper method to copy data
                    copyStream(inZipStream, outDestStream);

                    inZipStream.close();
                    outDestStream.close();
                } catch (IOException e) {
                    AppLogService.error("Error extracting file : " + e.getMessage(), e);
                } finally {
                    try {
                        inZipStream.close();
                    } catch (IOException e) {
                        AppLogService.error("Error extracting file : " + e.getMessage(), e);
                    }
                }
            } else {
                AppLogService.debug("skipping directory " + strEntryName);
            }
        }
    } catch (ZipException e) {
        AppLogService.error("Error extracting file : " + e.getMessage(), e);
        throw new UpdaterDownloadException("Error extracting package ", e);
    } catch (IOException e) {
        AppLogService.error("Error extracting file : " + e.getMessage(), e);
    }
}

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

protected File extractFileFromZip(ZipFile zf, String filePath) throws IOException {
    ZipEntry ze = zf.getEntry(filePath);
    File ret = new File(getTempDir(), filePath);
    File parent = ret.getParentFile();
    parent.mkdirs();//from  www .  j  av a2  s. c  om
    InputStream is = zf.getInputStream(ze);
    OutputStream fos = new FileOutputStream(ret);
    byte[] buffer = new byte[1024];
    int read = is.read(buffer);
    do {
        if (read > 0) {
            fos.write(buffer, 0, read);
        }
        read = is.read(buffer);
    } while (read > 0);
    fos.flush();
    fos.close();
    filesToDrop.add(ret);
    return ret;
}

From source file:org.docx4j.openpackaging.io.LoadFromZipNG.java

public OpcPackage get(File f) throws Docx4JException {
    log.info("Filepath = " + f.getPath());

    ZipFile zf = null;
    try {/*from   w  w w. ja  v a2s . c  o  m*/
        if (!f.exists()) {
            log.info("Couldn't find " + f.getPath());
        }
        zf = new ZipFile(f);
    } catch (IOException ioe) {
        ioe.printStackTrace();
        throw new Docx4JException("Couldn't get ZipFile", ioe);
    }

    HashMap<String, ByteArray> partByteArrays = new HashMap<String, ByteArray>();
    Enumeration entries = zf.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        log.info("\n\n" + entry.getName() + "\n");
        InputStream in = null;
        try {
            byte[] bytes = getBytesFromInputStream(zf.getInputStream(entry));
            partByteArrays.put(entry.getName(), new ByteArray(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // At this point, we've finished with the zip file
    try {
        zf.close();
    } catch (IOException exc) {
        exc.printStackTrace();
    }

    return process(partByteArrays);
}

From source file:org.b3log.symphony.processor.CaptchaProcessor.java

/**
 * Loads captcha./*  ww w  . j a  va2s  .  c  om*/
 */
private synchronized void loadCaptchas() {
    LOGGER.trace("Loading captchas....");

    try {
        captchas = new Image[CAPTCHA_COUNT];

        ZipFile zipFile;

        if (RuntimeEnv.LOCAL == Latkes.getRuntimeEnv()) {
            final InputStream inputStream = SymphonyServletListener.class.getClassLoader()
                    .getResourceAsStream("captcha_static.zip");
            final File file = File.createTempFile("b3log_captcha_static", null);
            final OutputStream outputStream = new FileOutputStream(file);

            IOUtils.copy(inputStream, outputStream);
            zipFile = new ZipFile(file);

            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        } else {
            final URL captchaURL = SymphonyServletListener.class.getClassLoader()
                    .getResource("captcha_static.zip");

            zipFile = new ZipFile(captchaURL.getFile());
        }

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

        int i = 0;

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();

            final BufferedInputStream bufferedInputStream = new BufferedInputStream(
                    zipFile.getInputStream(entry));
            final byte[] captchaCharData = new byte[bufferedInputStream.available()];

            bufferedInputStream.read(captchaCharData);
            bufferedInputStream.close();

            final Image image = IMAGE_SERVICE.makeImage(captchaCharData);

            image.setName(entry.getName().substring(0, entry.getName().lastIndexOf('.')));

            captchas[i] = image;

            i++;
        }

        zipFile.close();
    } catch (final Exception e) {
        LOGGER.error("Can not load captchs!");

        throw new IllegalStateException(e);
    }

    LOGGER.trace("Loaded captch images");
}

From source file:com.idocbox.common.file.ZipExtracter.java

/**
 * extract given zip entry file from zip file
 *  to given destrination directory./*  www .ja  v a2s .  co m*/
 * @param zf         ZipFile object.
 * @param zipEntry   zip entry to extract.
 * @param desDir     destrination directory.
 * @param startDirLevel the level to start create directory.
*                      Its value is 1,2,...
 * @throws IOException throw the exception whil desDir is no directory.
 */
private static void extract(final ZipFile zf, final ZipEntry zipEntry, final String desDir,
        final int... startDirLevel) throws IOException {
    //check destination directory.
    File desf = new File(desDir);
    if (!desf.exists()) {
        desf.mkdirs();
    }
    int start = 1;
    if (null != startDirLevel && startDirLevel.length > 0) {
        start = startDirLevel[0];
        if (start < 1) {
            start = 1;
        }
    }

    String startDir = "";
    String zeName = zipEntry.getName();
    String folder = zeName;
    boolean isDir = zipEntry.isDirectory();
    if (null != folder) {
        String[] folders = folder.split("\\/");
        if (null != folders && folders.length > 0) {
            int len = folders.length;
            if (start == 1) {
                startDir = zeName;
            } else {
                if (start > len) {
                    //nothing to extract.
                } else {
                    for (int i = start - 1; i < len; i++) {
                        startDir += "/" + folders[i];
                    }
                    if (null != startDir) {
                        startDir = startDir.substring(1);
                    }
                }
            }
        }
    }
    startDir = StringUtils.trim(startDir);
    if (StringUtils.isNotEmpty(startDir)) {
        StringBuilder desFileName = new StringBuilder(desDir);
        if (!desDir.endsWith("/") && !startDir.startsWith("/")) {
            desFileName.append("/");
        }
        desFileName.append(startDir);

        File destFile = new File(desFileName.toString());
        if (isDir) {//the entry is a dir.
            if (!destFile.exists()) {
                destFile.mkdirs();
            }
        } else {//the entry is a file.
            File parentDir = new File(destFile.getParentFile().getPath());
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            //get entry input stream.
            InputStream is = zf.getInputStream(zipEntry);
            OutputStream os = new FileOutputStream(destFile);
            IOUtils.copy(is, os);
            if (null != is) {
                is.close();
            }
            if (null != os) {
                os.close();
            }
        }
    }

}