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:org.codehaus.mojo.webstart.JnlpMojo.java

protected void removeSignatures(File currentJar, String shortName) throws IOException {
    // We should remove any previous signature information.  This
    // can screw up the packing code, and if it is signed with 2 signatures
    // it can not be verified.
    ZipFile currentJarZipFile = new ZipFile(currentJar);
    Enumeration entries = currentJarZipFile.entries();

    // There might be more valid extensions but this is what we've seen so far 
    // the ?i makes it case insensitive       
    Pattern signatureChecker = Pattern.compile("(?i)^meta-inf/.*((\\.sf)|(\\.rsa))$");

    getLog().debug("checking for old signature : " + shortName);
    Vector signatureFiles = new Vector();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        Matcher matcher = signatureChecker.matcher(entry.getName());
        if (matcher.find()) {
            // we found a old signature in the file
            signatureFiles.add(entry.getName());
            getLog().warn("found signature: " + entry.getName());
        }/*from   w w w  .  j av  a 2 s  .  com*/
    }

    if (signatureFiles.size() == 0) {
        // no old files were found
        currentJarZipFile.close();
        return;
    }

    // We found some old signature files, write out the file again without
    // them    
    File outFile = new File(currentJar.getParent(), currentJar.getName() + ".unsigned");
    ZipOutputStream zipOutStream = new ZipOutputStream(new FileOutputStream(outFile));

    entries = currentJarZipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        if (signatureFiles.contains(entry.getName())) {
            continue;
        }
        InputStream entryInStream = currentJarZipFile.getInputStream(entry);
        ZipEntry newEntry = new ZipEntry(entry);
        zipOutStream.putNextEntry(newEntry);
        IOUtil.copy(entryInStream, zipOutStream);
        entryInStream.close();
    }

    zipOutStream.close();
    currentJarZipFile.close();

    FileUtils.rename(outFile, currentJar);

    getLog().info("removed signature");
}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

private File[] exportReport(ReportTemplateRequestDef templateRequestDef, Map<String, String> varValues,
        String directoryName, ExportFormat format, ServerIfProvider serverIfProvider, ExportInfo exportInfo,
        int customerIdOfTemplate, String customerNameOfTemplate, String templateId) throws PariException {
    // transformation resources
    File topLevelFolder = null;/* w  ww. j  a v  a 2s  . c  om*/
    try {
        topLevelFolder = getTopLevelFolder(new File(zipFileName));
    } catch (IOException e1) {
        logger.error("Unable to get top level folder of zip file " + zipFileName);
    }

    // unzip the template
    String outDirName = directoryName + "/" + topLevelFolder.getName();
    UnzipDir.unzip(zipFileName, directoryName);

    File outDir = new File(outDirName);

    /*
     * if ((valueMap != null) && (valueMap.size() > 0)) { varValues.putAll(valueMap); }
     */
    ReportTemplateMetaInfo templateMetaInfo = null;
    try {
        templateMetaInfo = ReportTemplateDefManagerImpl.getInstance().getTemplateMetaInfo(templateId,
                customerIdOfTemplate);
        if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) {
            // device count considered as 1 as report template wont be executed per device.
            ICManager.getInstance().validateLicense(customerIdOfTemplate, templateMetaInfo.getIdentifier(), 1);
        }
    } catch (Exception e) {
        if (templateMetaInfo != null) {
            logger.warn("No sufficient license to run " + templateMetaInfo.getTitle() + " - " + e.getMessage());
        } else {
            logger.warn("No sufficient license to run.Failed to get ReportTemplateMetaInfo for " + templateId
                    + " - " + e.getMessage());
        }
        throw new PariException(e.getMessage());
    }

    FileOutputStream fos = null;
    try {
        // ReportExportFactory.createDirectories(outDir.getAbsolutePath());TODO
        fos = new FileOutputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml"));
        ReportTemplateExecutor executor = new ReportTemplateExecutor(templateIndexDef, templateRequestDef);
        executor.setUserDetails(getUserDetails());
        executor.setDevices(new HashSet<Integer>(getSelectedDevices()));
        executor.execute(selectedDevices, parameters, varValues, fos, serverIfProvider, customerIdOfTemplate,
                customerNameOfTemplate);
    } catch (Exception e) {
        logger.error("Error while exporting the report", e);
        throw new PariException(ShadowWrapper.getString("Error_While_Report_Export"));
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                logger.warn("Error while closing the output stream");
            }
        }
    }

    FileInputStream xml = null;
    FileOutputStream os = null;
    InputStream xsl = null;
    ZipFile zipFile = null;
    try {
        zipFile = new ZipFile(new File(zipFileName));

        // transformation file
        String xslFileName = templateIndexDef.getTransformationFileMap().get(format);
        xsl = getInputStream(zipFile, xslFileName);

        // intermediate xml with data
        xml = new FileInputStream(new File(outDir, templateIndexDef.getIdentifier() + ".xml"));

        File outputFile = null;

        outputFile = new File(outDir.getAbsolutePath(),
                templateIndexDef.getIdentifier() + "." + format.getDefaultExtension());
        os = new FileOutputStream(outputFile);
        if (format == ExportFormat.WEB_PAGE_COMPLETE) {

            ReportExporter.exportToHtml(xml, xsl, os, outDir);
        } else if (format == ExportFormat.MSWORD_DOCUMENT) {

            ReportExporter.exportToHtml(xml, xsl, os, outDir);
        } else if (format == ExportFormat.ADOBE_PDF) {

            ReportExporter.exportToPDF(xml, xsl, os, outDir);
        }

        // cleanup
        if (xml != null) {
            try {
                xml.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the InputStream" + xml, ioe);
            }
        }

        if (xsl != null) {
            try {
                xsl.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the InputStream" + xsl, ioe);
            }
        }

        if (os != null) {
            try {
                os.close();
            } catch (IOException ioe) {
                logger.warn("Could not close the OutputStream" + os, ioe);
            }
        }

        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (Exception e) {
                logger.warn("Unable to close zip file.");
            }

            File file = new File(zipFileName);
            if (!file.delete()) {
                logger.warn("Unable to delete zip file.");
            }
        }

        // Cleanup the additional xml and png files created.
        File tempXmlFile = new File(outDir, templateIndexDef.getIdentifier() + ".xml");

        // Delete temp file // TODO:- Not deleting. Required to write XSL.

        try {
            if (tempXmlFile.exists()) {
                if (!tempXmlFile.delete()) {
                    logger.error("Could not delete the temporary xml file after" + " exporting the report: "
                            + tempXmlFile.getAbsolutePath());
                }
            }
        } catch (SecurityException se) {
            logger.error("Exception while deleting temporary xml file." + se);
        }

        String fileName = directoryName + "/" + topLevelFolder.getName() + "_" + exportInfo.getTaskID()
                + ".zip";
        ZIPProcessor.zipDirectory(outDirName, fileName);
        updateExportInfo(new File(fileName), exportInfo);

        if (templateMetaInfo != null && templateMetaInfo.getSourceType() == IC_SOURCE_TYPE.ICF) {
            ICStatisticsManager.getInstance().populateICUsageStatisticsInfo(templateMetaInfo, 1);
        }

        return new File[] { outDir, outputFile };
    } catch (Exception ex) {
        logger.warn(ex.getMessage());
        throw new PariException(ShadowWrapper.getString("Error_While_Report_Export") + "\n" + ex.getMessage());
    } finally {
        try {
            if (xml != null) {
                xml.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        try {
            if (os != null) {
                os.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:org.springsource.ide.eclipse.boot.maven.analyzer.JarTypeDiscovery.java

public void getTypes(Requestor<ExternalTypeEntry> requestor) {
    if (jarFile == null) {
        //can happen for unresolved or unresolveable artifacts.
        // In that case there's nothing to find. Move along!
        return;//from   ww  w  .ja v  a  2  s  .c  om
    }
    ZipFile unzipper = null;
    try {
        unzipper = new ZipFile(jarFile);
        Enumeration<? extends ZipEntry> entries = unzipper.entries();
        boolean continu = true;
        while (entries.hasMoreElements() && continu) {
            ZipEntry e = entries.nextElement();
            String path = e.getName();
            //We are interested in class files that aren't inner or anonymous classes or classes in
            // the default package
            if (path.endsWith(".class") && !path.contains("$") && path.lastIndexOf('/') > 1) {
                InputStream classFile = unzipper.getInputStream(e);
                try {
                    if (AsmUtils.isPublic(classFile)) {
                        //TODO: can optimize a little to do less string copying here.
                        int beg = path.charAt(0) == '/' ? 1 : 0;
                        String fqName = path.substring(beg, path.length() - 6/*".class".length()*/);
                        fqName = fqName.replace('/', '.');
                        continu = requestor.receive(new ExternalTypeEntry(fqName, getTypeSource()));
                    } else {
                        if (DEBUG) {
                            System.out.println("Filtered type (not public): " + e.getName());
                        }
                    }
                } catch (Exception e2) {
                    String msg = ExceptionUtil.getMessage(e2);
                    System.err.println("Error in jar file: " + jarFile + "\n" + "   entry: " + path + "\n"
                            + "   msg  : " + msg);
                    continu = false; //zip file corrupt? bail out here now.
                } finally {
                    try {
                        classFile.close();
                    } catch (IOException ignore) {
                        //ignore
                    }
                }
            }
        }
    } catch (ZipException e) {
        String msg = ExceptionUtil.getMessage(e);
        System.err.println("Error in jar file: " + jarFile + "\n" + "   msg  : " + msg);
    } catch (Exception e) {
        Logger.log(e);
    } finally {
        if (unzipper != null) {
            try {
                unzipper.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
}

From source file:com.seajas.search.contender.service.modifier.ArchiveModifierService.java

/**
 * Store the not-already-cached files from the given URL and return their locations.
 * //  w  w w.j a v  a2s . c  o m
 * @param archive
 * @return Map<File, String>
 */
private Map<File, String> storeAndDecompressFiles(final Archive archive) {
    Map<File, String> result = new HashMap<File, String>();

    // Create the FTP client

    FTPClient ftpClient = retrieveFtpClient(archive.getUri());

    try {
        // Retrieve the directory listing

        List<ArchiveFile> files = retrieveFiles(archive.getUri().getPath(), ftpClient,
                archive.getExclusionExpression());

        Integer archiveNumber = -1, archiveTotal = files.size();

        logger.info("Archive with name '" + archive.getName() + "' produced " + archiveTotal + " files");

        // An empty archive typically indicates failure

        if (archiveTotal == 0)
            logger.warn("The given archive produced no entries - something probably went wrong");

        // Handle all archive files

        for (ArchiveFile archiveFile : files) {
            archiveNumber++;

            // Check whether the file already exists within the cache

            String baseUrl = (StringUtils.hasText(archive.getUri().getScheme())
                    ? archive.getUri().getScheme() + "://"
                    : "") + archive.getUri().getHost()
                    + (archive.getUri().getPort() != -1 ? ":" + archive.getUri().getPort() : "");

            if (!cacheService.isArchived(baseUrl + archiveFile.getFullPath())) {
                logger.info("Started decompressing archive " + archiveNumber + "/" + archiveTotal
                        + " with name " + archiveFile.getFullPath());

                // Write out the archive to disk so we can determine the MIME type

                File archiveFileFolder = new File(archiveFile
                        .getTranslatedPath(packagesLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!archiveFileFolder.exists())
                    archiveFileFolder.mkdirs();

                File archiveFileLocation = new File(archiveFileFolder, archiveFile.getFile().getName());

                InputStream archiveInputStream = ftpClient.retrieveFileStream(archiveFile.getFullPath());
                OutputStream archiveOutputStream = new FileOutputStream(archiveFileLocation);

                IOUtils.copy(archiveInputStream, archiveOutputStream);

                archiveInputStream.close();
                ftpClient.completePendingCommand();

                archiveOutputStream.flush();
                archiveOutputStream.close();

                // Now unpack the archive and transform each file

                InputStream compressedArchiveInputStream = new FileInputStream(archiveFileLocation);

                // Now determine the content type and create a reader in case of structured content

                MediaType archiveMediaType = autoDetectParser.getDetector()
                        .detect(new BufferedInputStream(compressedArchiveInputStream), new Metadata());

                if (!(archiveMediaType.getType().equals("application")
                        && archiveMediaType.getSubtype().equals("zip"))) {
                    logger.warn("Archive file " + archiveFile.getFullPath() + " contains " + archiveMediaType
                            + " data, which is not yet supported");

                    compressedArchiveInputStream.close();

                    continue;
                } else
                    compressedArchiveInputStream.close();

                // Create a new ZIP file from the given archive and decompress it

                ZipFile zipFile = new ZipFile(archiveFileLocation);

                File resultsLocationFolder = new File(archiveFile
                        .getTranslatedPath(resultsLocation.replace("%1", String.valueOf(archive.getId()))));

                if (!resultsLocationFolder.exists())
                    resultsLocationFolder.mkdirs();

                File resultsLocation = new File(resultsLocationFolder,
                        stripExtension(archiveFile.getFile().getName()));

                if (!resultsLocation.exists())
                    resultsLocation.mkdirs();

                logger.info("Started processing archive with name " + archiveFile.getFullPath());

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

                while (zipEnumerator.hasMoreElements()) {
                    ZipEntry entry = zipEnumerator.nextElement();

                    // Store it locally first

                    File entryLocation = new File(resultsLocation, entry.getName());

                    try {
                        InputStream entryInputStream = zipFile.getInputStream(entry);
                        OutputStream entryOutputStream = new FileOutputStream(entryLocation);

                        IOUtils.copy(entryInputStream, entryOutputStream);

                        entryInputStream.close();
                        entryOutputStream.close();
                    } catch (IOException e) {
                        logger.error("Could not store the compressed archive entry on disk", e);

                        continue;
                    }
                }

                zipFile.close();

                // Add it to the results

                result.put(resultsLocation, baseUrl + archiveFile.getFullPath());

                logger.info("Finished processing archive with name " + archiveFile.getFullPath());
            } else if (logger.isDebugEnabled())
                logger.debug("Skipping previously processed archive with name " + archiveFile.getFullPath());
        }
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    } finally {
        try {
            if (ftpClient.isConnected())
                ftpClient.disconnect();
        } catch (IOException e) {
            logger.error("Could not disconnect the FTP client", e);
        }
    }

    return result;
}

From source file:com.pari.nm.utils.backup.BackupRestore.java

public boolean unzip(File zipFile) {
    ZipFile zf = null;
    FileOutputStream fout = null;
    // File zipFile = new File(localDir, zipFileName);

    try {/*from   ww w .ja v a2 s.c  o m*/
        zf = new ZipFile(zipFile);

        Enumeration en = zf.entries();

        while (en.hasMoreElements()) {
            ZipEntry ze = (ZipEntry) en.nextElement();
            String currentEntry = ze.getName();
            File destFile = new File(zipFile.getParent(), currentEntry);
            File destinationParent = destFile.getParentFile();
            if (!destinationParent.exists()) {
                destinationParent.mkdirs();
                destinationParent.setWritable(true, false);
            }
            System.err.println("ZIP ENTRY NAME:" + currentEntry);
            if (!ze.isDirectory()) {
                InputStream in = zf.getInputStream(ze);
                byte[] data = new byte[4096];
                int read = 0;

                File extractFile = new File(zipFile.getParent(), ze.getName());
                fout = new FileOutputStream(extractFile);

                while ((read = in.read(data)) != -1) {
                    fout.write(data, 0, read);
                }

                fout.close();
            }
        }
        return true;
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {
            if (zf != null) {
                zf.close();
            }
        } catch (Exception ex) {
        }

        try {
            if (fout != null) {
                fout.close();
            }
        } catch (Exception ex) {
        }
    }

    return false;
}

From source file:nl.edia.sakai.tool.skinmanager.impl.SkinFileSystemServiceImpl.java

protected void validateSkinZip(File file) throws SkinException {
    ZipFile myZipFile = null;
    try {/*from  ww  w  .  ja v  a  2 s.  co  m*/
        boolean isToolFound = false;
        boolean isPortalFound = false;
        boolean isImagesFound = false;
        myZipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> myEntries = myZipFile.entries();
        while (myEntries.hasMoreElements()) {
            ZipEntry myZipEntry = (ZipEntry) myEntries.nextElement();
            String myName = myZipEntry.getName();
            if (myName.contains("..") || myName.startsWith("/")) {
                throw new SkinException("Illegal file name found in zip file '" + myName + "'");
            }
            if (!myZipEntry.isDirectory()) {
                if (myName.equals("tool.css")) {
                    isToolFound = true;
                } else if (myName.equals("portal.css")) {
                    isPortalFound = true;
                } else if (PATTERN_IMAGES_DIR_CONTENT.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            } else {
                if (PATTERN_IMAGES_DIR_EMPTY.matcher(myName).matches()) {
                    isImagesFound = true;
                }
            }
        }

        if (!isPortalFound) {
            throw getMissingResourceException("portal.css", false);
        }
        if (!isToolFound) {
            throw getMissingResourceException("tool.css", false);
        }
        if (!isImagesFound) {
            throw getMissingResourceException("images", true);
        }
    } catch (ZipException z) {
        throw new SkinException("Error reading zip file", z);
    } catch (IOException e) {
        throw new SkinException("IO Error reading zip file", e);
    } finally {
        if (myZipFile != null) {
            try {
                myZipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }

    }

}

From source file:com.meltmedia.cadmium.core.util.WarUtils.java

/**
 * <p>This method updates a template war with the following settings.</p>
 * @param templateWar The name of the template war to pull from the classpath.
 * @param war The path of an external war to update (optional).
 * @param newWarNames The name to give the new war. (note: only the first element of this list is used.)
 * @param repoUri The uri to a github repo to pull content from.
 * @param branch The branch of the github repo to pull content from.
 * @param configRepoUri The uri to a github repo to pull config from.
 * @param configBranch The branch of the github repo to pull config from.
 * @param domain The domain to bind a vHost to.
 * @param context The context root that this war will deploy to.
 * @param secure A flag to set if this war needs to have its contents password protected.
 * @throws Exception//  ww w.  java  2s  .c om
 */
public static void updateWar(String templateWar, String war, List<String> newWarNames, String repoUri,
        String branch, String configRepoUri, String configBranch, String domain, String context, boolean secure,
        Logger log) throws Exception {
    ZipFile inZip = null;
    ZipOutputStream outZip = null;
    InputStream in = null;
    OutputStream out = null;
    try {
        if (war != null) {
            if (war.equals(newWarNames.get(0))) {
                File tmpZip = File.createTempFile(war, null);
                tmpZip.delete();
                tmpZip.deleteOnExit();
                new File(war).renameTo(tmpZip);
                war = tmpZip.getAbsolutePath();
            }
            inZip = new ZipFile(war);
        } else {
            File tmpZip = File.createTempFile("cadmium-war", "war");
            tmpZip.delete();
            tmpZip.deleteOnExit();
            in = WarUtils.class.getClassLoader().getResourceAsStream(templateWar);
            out = new FileOutputStream(tmpZip);
            FileSystemManager.streamCopy(in, out);
            inZip = new ZipFile(tmpZip);
        }
        outZip = new ZipOutputStream(new FileOutputStream(newWarNames.get(0)));

        ZipEntry cadmiumPropertiesEntry = null;
        cadmiumPropertiesEntry = inZip.getEntry("WEB-INF/cadmium.properties");

        Properties cadmiumProps = updateProperties(inZip, cadmiumPropertiesEntry, repoUri, branch,
                configRepoUri, configBranch);

        ZipEntry jbossWeb = null;
        jbossWeb = inZip.getEntry("WEB-INF/jboss-web.xml");

        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry e = entries.nextElement();
            if (e.getName().equals(cadmiumPropertiesEntry.getName())) {
                storeProperties(outZip, cadmiumPropertiesEntry, cadmiumProps, newWarNames);
            } else if (((domain != null && domain.length() > 0) || (context != null && context.length() > 0))
                    && e.getName().equals(jbossWeb.getName())) {
                updateDomain(inZip, outZip, jbossWeb, domain, context);
            } else if (secure && e.getName().equals("WEB-INF/web.xml")) {
                addSecurity(inZip, outZip, e);
            } else {
                outZip.putNextEntry(e);
                if (!e.isDirectory()) {
                    FileSystemManager.streamCopy(inZip.getInputStream(e), outZip, true);
                }
                outZip.closeEntry();
            }
        }
    } finally {
        if (FileSystemManager.exists("tmp_cadmium-war.war")) {
            new File("tmp_cadmium-war.war").delete();
        }
        try {
            if (inZip != null) {
                inZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + war);
            }
        }
        try {
            if (outZip != null) {
                outZip.close();
            }
        } catch (Exception e) {
            if (log != null) {
                log.error("Failed to close " + newWarNames.get(0));
            }
        }
        try {
            if (out != null) {
                out.close();
            }
        } catch (Exception e) {
        }
        try {
            if (in != null) {
                in.close();
            }
        } catch (Exception e) {
        }
    }

}

From source file:org.panbox.desktop.linux.dbus.PanboxInterfaceImpl.java

@Override
public byte restoreIdentity(String backupFile, boolean backupOldOne) {
    logger.debug("[DBUS] restoreIdentity(" + backupFile + ", " + backupOldOne + ")");

    byte ret = StatusCode.DBUS_OK;

    File bakFile = new File(backupFile);
    FileOutputStream fos = null;/*from w w  w  .ja v  a2 s .  co m*/
    InputStream eis = null;
    ZipFile zip = null;
    ZipEntry entry = null;

    if (bakFile.exists()) {

        if (backupOldOne) {
            backupIdentity();
        }

        try {
            zip = new ZipFile(bakFile);

            Enumeration<?> zipentries = zip.entries();

            while (zipentries.hasMoreElements()) {
                entry = (ZipEntry) zipentries.nextElement();
                eis = zip.getInputStream(entry);
                byte[] buffer = new byte[1024];
                int bytesRead = 0;

                File f = new File(entry.getName());

                if (f.exists()) {
                    f.delete();
                } else {
                    if (!f.getParentFile().exists()) {
                        f.getParentFile().mkdirs();
                    }
                }

                f.createNewFile();
                fos = new FileOutputStream(f);

                while ((bytesRead = eis.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                eis.close();
                fos.flush();
                fos.close();

            }

        } catch (Exception e) {
            ret = StatusCode.getAndLog(logger, e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    ret = StatusCode.getAndLog(logger, e);
                }
            }
            if (zip != null) {
                try {
                    zip.close();
                } catch (IOException e) {
                    ret = StatusCode.getAndLog(logger, e);
                }
            }
        }
    }
    return ret;
}

From source file:org.fuin.utils4j.Utils4J.java

/**
 * Unzips a file into a given directory. WARNING: Only relative path entries
 * are allowed inside the archive!/*ww w .  j a  v a2 s . c o  m*/
 * 
 * @param zipFile
 *            Source ZIP file - Cannot be <code>null</code> and must be a
 *            valid ZIP file.
 * @param destDir
 *            Destination directory - Cannot be <code>null</code> and must
 *            exist.
 * @param wrapper
 *            Callback interface to give the caller the chance to wrap the
 *            ZIP input stream into another one. This is useful for example
 *            to display a progress bar - Can be <code>null</code> if no
 *            wrapping is required.
 * @param cancelable
 *            Signals if the unzip should be canceled - Can be
 *            <code>null</code> if no cancel option is required.
 * 
 * @throws IOException
 *             Error unzipping the file.
 */
public static void unzip(final File zipFile, final File destDir, final UnzipInputStreamWrapper wrapper,
        final Cancelable cancelable) throws IOException {

    checkNotNull("zipFile", zipFile);
    checkValidFile(zipFile);
    checkNotNull("destDir", destDir);
    checkValidDir(destDir);

    final ZipFile zip = new ZipFile(zipFile);
    try {
        final Enumeration enu = zip.entries();
        while (enu.hasMoreElements() && ((cancelable == null) || !cancelable.isCanceled())) {
            final ZipEntry entry = (ZipEntry) enu.nextElement();
            final File file = new File(entry.getName());
            if (file.isAbsolute()) {
                throw new IllegalArgumentException(
                        "Only relative path entries are allowed! [" + entry.getName() + "]");
            }
            if (entry.isDirectory()) {
                final File dir = new File(destDir, entry.getName());
                createIfNecessary(dir);
            } else {
                final File outFile = new File(destDir, entry.getName());
                createIfNecessary(outFile.getParentFile());
                final InputStream in;
                if (wrapper == null) {
                    in = new BufferedInputStream(zip.getInputStream(entry));
                } else {
                    in = new BufferedInputStream(
                            wrapper.wrapInputStream(zip.getInputStream(entry), entry, outFile));
                }
                try {
                    final OutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
                    try {
                        final byte[] buf = new byte[4096];
                        int len;
                        while ((len = in.read(buf)) > 0) {
                            out.write(buf, 0, len);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        zip.close();
    }
}

From source file:de.uni_potsdam.hpi.bpt.promnicat.importer.bpmai.BpmaiImporter.java

/**
 * Scans the given root directory for sgx-archives and extracts them into the dummy folder.
 * The extracted models can be parsed like any other process models from the BPM AI.
 * @param rootDir container of archives to extract
 * @param dummyFolder folder to extract the models to
 * @throws ZipException if archive extraction went wrong
 * @throws IOException if one of the given paths can not be read or written
 *//* w w w. ja v  a2  s. co m*/
private void extractAvailableSgxArchives(File rootDir, File dummyFolder) throws ZipException, IOException {
    for (File file : rootDir.listFiles()) {
        if ((!file.isDirectory()) && (file.getName().endsWith(".sgx"))) {
            ZipFile zipFile = new ZipFile(file);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            //iterate through files of an zip archive
            while (entries.hasMoreElements()) {
                ZipEntry entry = (ZipEntry) entries.nextElement();
                String entryName = entry.getName();
                if (entryName.contains("/")) {
                    //ignore meta data files
                    if (entryName.endsWith("_meta.json")) {
                        continue;
                    }
                    //remove directory folder to fit into expected structure
                    String[] pathParts = entryName.split("/");
                    if (entryName.contains("directory_")) {
                        entryName = "";
                        for (int i = 0; i < pathParts.length; i++) {
                            if (!(pathParts[i].startsWith("directory_"))) {
                                entryName = entryName.concat(pathParts[i] + "/");
                            }
                        }
                        entryName = entryName.substring(0, entryName.length() - 1);
                    }
                    //rename process model files
                    String oldModelName = pathParts[pathParts.length - 1];
                    String[] nameParts = oldModelName.split("_");
                    if (nameParts.length > 2) {
                        String modelName = pathParts[pathParts.length - 2].split("_")[1] + "_rev" + nameParts[1]
                                + nameParts[2];
                        entryName = entryName.replace(oldModelName, modelName);
                    }
                    //create directories
                    (new File(dummyFolder.getPath() + File.separatorChar
                            + entryName.substring(0, entryName.lastIndexOf("/")))).mkdirs();
                }
                //extract process model
                copyInputStream(zipFile.getInputStream(entry),
                        dummyFolder.getPath() + File.separatorChar + entryName);
            }
            zipFile.close();
        }
    }
}