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:moskitt4me.repositoryClient.core.util.RepositoryClientUtil.java

public static void extractZipFile(String folder, String zipName) throws Exception {

    ZipFile zipFile = new ZipFile(new File(folder + "/" + zipName));

    Enumeration entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        Object obj = entries.nextElement();
        if (obj instanceof ZipEntry) {
            ZipEntry entry = (ZipEntry) obj;

            InputStream eis = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            File f = new File(folder + "/" + entry.getName());

            if (entry.isDirectory()) {
                f.mkdirs();/*from  w  w w .j  a v  a 2  s.  c o  m*/
                eis.close();
                continue;
            } else {
                f.getParentFile().mkdirs();
                f.createNewFile();
            }

            FileOutputStream fos = new FileOutputStream(f);

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

            if (eis != null) {
                eis.close();
            }

            if (fos != null) {
                fos.close();
            }
        }
    }

    zipFile.close();
}

From source file:org.openmrs.module.amrsreports.rule.MohEvaluableRuleProvider.java

/**
 * @see org.openmrs.logic.rule.provider.RuleProvider#afterStartup()
 *//*from ww  w . jav a  2 s. co  m*/
@Override
public void afterStartup() {

    if (log.isDebugEnabled())
        log.debug("Registering AMRS reports summary rules ...");

    try {
        ModuleClassLoader moduleClassLoader = ModuleFactory.getModuleClassLoader(AMRS_REPORT_MODULE);
        for (URL url : moduleClassLoader.getURLs()) {
            String filename = url.getFile();
            if (StringUtils.contains(filename, AMRS_REPORT_MODULE_API)) {
                ZipFile zipFile = new ZipFile(filename);
                for (Enumeration list = zipFile.entries(); list.hasMoreElements();) {
                    ZipEntry entry = (ZipEntry) list.nextElement();
                    String zipFileName = FilenameUtils.getBaseName(entry.getName());
                    String zipFileExtension = FilenameUtils.getExtension(entry.getName());
                    if (StringUtils.endsWith(zipFileName, RULE_CLASS_SUFFIX)
                            && StringUtils.equals(zipFileExtension, CLASS_SUFFIX)) {
                        MohEvaluableRuleVisitor visitor = new MohEvaluableRuleVisitor();
                        ClassReader classReader = new ClassReader(zipFile.getInputStream(entry));
                        classReader.accept(visitor, false);
                    }
                }
                zipFile.close();
            }
        }
    } catch (IOException e) {
        log.error("Processing rule classes failed. Rule might not get registered.");
    }
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.DatasourceResourceIT.java

@Test
public void testMondrianImportExport() throws Exception {
    final String domainName = "SalesData";
    List<IMimeType> mimeTypeList = new ArrayList<IMimeType>();
    mimeTypeList.add(new MimeType("Mondrian", "mondrian.xml"));
    System.setProperty("org.osjava.sj.root", "test-res/solution1/system/simple-jndi"); //$NON-NLS-1$ //$NON-NLS-2$

    File mondrian = new File("test-res/dsw/testData/SalesData.mondrian.xml");
    RepositoryFile repoMondrianFile = new RepositoryFile.Builder(mondrian.getName()).folder(false).hidden(false)
            .build();//from  w ww.  ja  va  2 s  . co  m
    RepositoryFileImportBundle bundle1 = new RepositoryFileImportBundle.Builder().file(repoMondrianFile)
            .charSet("UTF-8").input(new FileInputStream(mondrian)).mime("mondrian.xml")
            .withParam("parameters", "Datasource=Pentaho;overwrite=true").withParam("domain-id", "SalesData")
            .build();
    MondrianImportHandler mondrianImportHandler = new MondrianImportHandler(mimeTypeList,
            PentahoSystem.get(IMondrianCatalogService.class));
    mondrianImportHandler.importFile(bundle1);

    try {
        KettleEnvironment.init();
        Props.init(Props.TYPE_PROPERTIES_EMPTY);
    } catch (Exception e) {
        // may already be initialized by another test
    }

    Domain domain = generateModel();

    ModelerWorkspace model = new ModelerWorkspace(new GwtModelerWorkspaceHelper());
    model.setModelName("ORDERS");
    model.setDomain(domain);
    model.getWorkspaceHelper().populateDomain(model);

    new ModelerService().serializeModels(domain, domainName);

    final Response salesData = new DataSourceWizardResource().doGetDSWFilesAsDownload(domainName + ".xmi");
    Assert.assertEquals(salesData.getStatus(), Response.Status.OK.getStatusCode());
    Assert.assertNotNull(salesData.getMetadata());
    Assert.assertNotNull(salesData.getMetadata().getFirst("Content-Disposition"));
    Assert.assertEquals(salesData.getMetadata().getFirst("Content-Disposition").getClass(), String.class);
    Assert.assertTrue(
            ((String) salesData.getMetadata().getFirst("Content-Disposition")).endsWith(domainName + ".zip\""));

    File file = File.createTempFile(domainName, ".zip");
    final FileOutputStream fileOutputStream = new FileOutputStream(file);
    ((StreamingOutput) salesData.getEntity()).write(fileOutputStream);
    fileOutputStream.close();

    final ZipFile zipFile = new ZipFile(file);
    final Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        final ZipEntry zipEntry = entries.nextElement();
        Assert.assertTrue(zipEntry.getName().equals(domainName + ".xmi")
                || zipEntry.getName().equals(domainName + ".mondrian.xml"));
    }
    zipFile.close();
    file.delete();
}

From source file:mobac.mapsources.loader.MapPackManager.java

public int getMapPackRevision(File mapPackFile) throws ZipException, IOException {
    ZipFile zip = new ZipFile(mapPackFile);
    try {//from  w ww .  ja va  2 s . c o  m
        ZipEntry entry = zip.getEntry("META-INF/MANIFEST.MF");
        if (entry == null)
            throw new ZipException("Unable to find MANIFEST.MF");
        Manifest mf = new Manifest(zip.getInputStream(entry));
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackRevision").trim();
        return Utilities.parseSVNRevision(mpv);
    } catch (NumberFormatException e) {
        return -1;
    } finally {
        zip.close();
    }
}

From source file:net.minecraftforge.fml.common.FMLModContainer.java

public Properties searchForVersionProperties() {
    try {/*  w w w . j a v  a2s  . c  o  m*/
        FMLLog.log(getModId(), Level.DEBUG,
                "Attempting to load the file version.properties from %s to locate a version number for %s",
                getSource().getName(), getModId());
        Properties version = null;
        if (getSource().isFile()) {
            ZipFile source = new ZipFile(getSource());
            ZipEntry versionFile = source.getEntry("version.properties");
            if (versionFile != null) {
                version = new Properties();
                version.load(source.getInputStream(versionFile));
            }
            source.close();
        } else if (getSource().isDirectory()) {
            File propsFile = new File(getSource(), "version.properties");
            if (propsFile.exists() && propsFile.isFile()) {
                version = new Properties();
                FileInputStream fis = new FileInputStream(propsFile);
                version.load(fis);
                fis.close();
            }
        }
        return version;
    } catch (Exception e) {
        Throwables.propagateIfPossible(e);
        FMLLog.log(getModId(), Level.TRACE, "Failed to find a usable version.properties file");
        return null;
    }
}

From source file:org.kalypso.commons.java.util.zip.ZipUtilities.java

/** Unzips a zip archive into a directory using the apache zip classes. */
public static void unzipApache(final File zip, final File targetDir, final boolean overwriteExisting,
        final String encoding) throws IOException {
    org.apache.tools.zip.ZipFile file = null;
    try {/*  w ww  .  j a v  a2s.c  o  m*/
        file = new org.apache.tools.zip.ZipFile(zip, encoding);

        final Enumeration<?> entries = file.getEntries();
        while (entries.hasMoreElements()) {
            final org.apache.tools.zip.ZipEntry entry = (org.apache.tools.zip.ZipEntry) entries.nextElement();
            if (entry == null)
                break;

            final File newfile = new File(targetDir, entry.getName());
            if (entry.isDirectory())
                newfile.mkdirs();
            else {
                if (!newfile.getParentFile().exists())
                    newfile.getParentFile().mkdirs();

                OutputStream os = null;
                InputStream zis = null;
                try {
                    if (!overwriteExisting && newfile.exists())
                        os = new NullOutputStream();
                    else
                        os = new BufferedOutputStream(new FileOutputStream(newfile));

                    zis = file.getInputStream(entry);
                    IOUtils.copy(zis, os);
                } finally {
                    IOUtils.closeQuietly(os);
                    IOUtils.closeQuietly(zis);
                }
            }
        }

        file.close();
    } finally {
        if (file != null)
            file.close();
    }

}

From source file:org.eclipse.koneki.ldt.core.internal.buildpath.LuaExecutionEnvironmentManager.java

public static LuaExecutionEnvironment getExecutionEnvironmentFromCompressedFile(final String filePath)
        throws CoreException {
    /*/*  w w  w. j av  a2 s . co m*/
     * Extract manifest file
     */
    ZipFile zipFile = null;
    String manifestString = null;
    try {
        zipFile = new ZipFile(filePath);
        final Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
        while (zipEntries.hasMoreElements()) {
            final ZipEntry zipEntry = zipEntries.nextElement();
            if ((!zipEntry.getName().contains("/")) //$NON-NLS-1$
                    && zipEntry.getName().endsWith(LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION)) {

                // check there are only one manifest.
                if (manifestString != null) {
                    throwException(
                            MessageFormat.format("Invalid Execution Environment : more than one \"{0}\" file.", //$NON-NLS-1$
                                    LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION),
                            null, IStatus.ERROR);
                }

                // read manifest
                final InputStream input = zipFile.getInputStream(zipEntry);
                manifestString = IOUtils.toString(input);
            }
        }
    } catch (IOException e) {
        throwException(MessageFormat.format("Unable to extract manifest from zip file {0}", filePath), e, //$NON-NLS-1$
                IStatus.ERROR);
    } finally {
        if (zipFile != null)
            try {
                zipFile.close();
            } catch (IOException e) {
                Activator.logWarning(MessageFormat.format("Unable to close zip file {0}", filePath), e); //$NON-NLS-1$
            }
    }

    // if no manifest extract
    if (manifestString == null) {
        throwException(MessageFormat.format("No manifest \"{0}\" file found", //$NON-NLS-1$
                LuaExecutionEnvironmentConstants.MANIFEST_EXTENSION), null, IStatus.ERROR);
    }

    return getLuaExecutionEnvironmentFromManifest(manifestString, null);
}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Uncompresses any zip file// w ww .  ja  v  a  2  s .c o m
 */
public static void unzip(String path_from, String path_to, String name, boolean deleteZip) {

    StringTokenizer separator = new StringTokenizer(name, ".", true);
    String file_name = separator.nextToken();

    File f = new File(path_to + file_name);

    if (f.exists())
        removeDirectory(f);

    separator = new StringTokenizer(path_to + file_name, "/", true);

    String partial_path = null;
    String total_path = separator.nextToken();

    while (separator.hasMoreElements()) {

        partial_path = separator.nextToken();
        total_path = total_path + partial_path;
        if (!new File(total_path).exists()) {

            if (separator.hasMoreElements())
                total_path = total_path + separator.nextToken();
            else
                (new File(total_path)).mkdir();

        } else
            total_path = total_path + separator.nextToken();

    }

    Enumeration<? extends ZipEntry> entries = null;
    ZipFile zipFile = null;

    try {
        String location_ead = path_from + name;
        zipFile = new ZipFile(location_ead);

        entries = zipFile.entries();

        BufferedOutputStream file;

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

            separator = new StringTokenizer(entry.getName(), "/", true);
            partial_path = null;
            total_path = "";

            while (separator.hasMoreElements()) {

                partial_path = separator.nextToken();
                total_path = total_path + partial_path;
                if (!new File(entry.getName()).exists()) {

                    if (separator.hasMoreElements()) {
                        total_path = total_path + separator.nextToken();
                        (new File(path_to + file_name + "/" + total_path)).mkdir();
                    } else {

                        file = new BufferedOutputStream(
                                new FileOutputStream(path_to + file_name + "/" + total_path));

                        System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipFile.getInputStream(entry), file);
                    }
                } else {
                    total_path = total_path + separator.nextToken();
                }
            }

        }

        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return;
    }

    if (deleteZip)
        (new File(path_from + name)).delete();

}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Unzips a .zip file, removes it from <code>files</code> and adds the extracted files to <code>files</code>.
 * //from   www . j  a  v  a 2s  . co  m
 * @param files the list of files to unzip and the files extracted from the zips
 * @param fileNames the list of filenames to go along with the list of files
 */
@SuppressWarnings("PMD.ExcessiveMethodLength")
public void unzipFiles(List<File> files, List<String> fileNames) {
    try {
        final Pattern p = Pattern.compile("\\.zip$");
        int index = 0;
        for (int i = 0; i < fileNames.size(); i++) {
            final Matcher m = p.matcher(fileNames.get(i).toLowerCase());

            if (m.find()) {
                final File file = files.get(i);
                final String fileName = file.getAbsolutePath();
                final String directoryPath = file.getParent();
                final ZipFile zipFile = new ZipFile(fileName);
                final Enumeration<? extends ZipEntry> entries = zipFile.entries();
                while (entries.hasMoreElements()) {
                    final ZipEntry entry = entries.nextElement();
                    final File entryFile = new File(directoryPath + "/" + entry.getName());

                    final InputStream fileInputStream = zipFile.getInputStream(entry);
                    final FileOutputStream fileOutputStream = new FileOutputStream(entryFile);
                    IOUtils.copy(fileInputStream, fileOutputStream);
                    IOUtils.closeQuietly(fileOutputStream);

                    files.add(entryFile);
                    fileNames.add(entry.getName());
                }
                zipFile.close();
                files.remove(index);
                fileNames.remove(index);
            }
            index++;
        }
    } catch (final IOException e) {
        throw new FileAccessException("Couldn't unzip archive.", e);
    }
}

From source file:se.bitcraze.crazyflielib.bootloader.Bootloader.java

/**
 * Basic check if a file is a Zip file/*  w w w  . j  a va2  s  .c om*/
 *
 * @param file
 * @return true if file is a Zip file, false otherwise
 */
//TODO: how can this be improved?
private boolean isZipFile(File file) {
    if (file != null && file.exists() && file.getName().endsWith(".zip")) {
        ZipFile zf = null;
        try {
            zf = new ZipFile(file);
            return zf.size() > 0;
        } catch (ZipException e) {
            mLogger.error(e.getMessage());
        } catch (IOException e) {
            mLogger.error(e.getMessage());
        } finally {
            if (zf != null) {
                try {
                    zf.close();
                } catch (IOException e) {
                    mLogger.error(e.getMessage());
                }
            }
        }
    }
    return false;
}