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:com.samczsun.helios.transformers.decompilers.KrakatauDecompiler.java

public boolean decompile(ClassNode classNode, byte[] bytes, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        if (Helios.ensureJavaRtSet()) {
            File inputJar = null;
            File outputJar = null;
            ZipFile zipFile = null;
            Process createdProcess;
            String log = "";

            try {
                inputJar = Files.createTempFile("kdein", ".jar").toFile();
                outputJar = Files.createTempFile("kdeout", ".zip").toFile();
                Map<String, byte[]> loadedData = Helios.getAllLoadedData();
                loadedData.put(classNode.name + ".class", bytes);
                Utils.saveClasses(inputJar, loadedData);

                createdProcess = Helios//from   www  . j  a  va  2 s . c o m
                        .launchProcess(new ProcessBuilder(Settings.PYTHON2_LOCATION.get().asString(), "-O",
                                "decompile.py", "-skip", "-nauto", "-path", buildPath(inputJar), "-out",
                                outputJar.getAbsolutePath(), classNode.name + ".class")
                                        .directory(Constants.KRAKATAU_DIR));

                log = Utils.readProcess(createdProcess);

                System.out.println(log);

                zipFile = new ZipFile(outputJar);
                ZipEntry zipEntry = zipFile.getEntry(classNode.name + ".java");
                if (zipEntry == null)
                    throw new IllegalArgumentException("Class failed to decompile (no class in output zip)");
                InputStream inputStream = zipFile.getInputStream(zipEntry);
                byte[] data = IOUtils.toByteArray(inputStream);
                output.append(new String(data, "UTF-8"));
                return true;
            } catch (Exception e) {
                output.append(parseException(e)).append("\n").append(log);
                return false;
            } finally {
                if (zipFile != null) {
                    try {
                        zipFile.close();
                    } catch (IOException e) {
                    }
                }
                if (inputJar != null) {
                    if (!inputJar.delete()) {
                        inputJar.deleteOnExit();
                    }
                }
                if (outputJar != null) {
                    if (!outputJar.delete()) {
                        outputJar.deleteOnExit();
                    }
                }
            }
        } else {
            output.append("You need to set the location of rt.jar");
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:br.univali.celine.lms.utils.zip.Zip.java

public void unzip(File zipFile, File dir) throws Exception {

    InputStream is = null;/*from   w  w w . j a va 2s. c om*/
    OutputStream os = null;
    ZipFile zip = null;

    try {

        zip = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        byte[] buffer = new byte[2048];
        int currentEntry = 0;

        while (e.hasMoreElements()) {

            ZipEntry zipEntry = (ZipEntry) e.nextElement();
            File file = new File(dir, zipEntry.getName());
            currentEntry++;

            if (zipEntry.isDirectory()) {

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

                continue;

            }

            if (!file.getParentFile().exists())
                file.getParentFile().mkdirs();

            try {

                int bytesLidos = 0;

                is = zip.getInputStream(zipEntry);
                os = new FileOutputStream(file);

                if (is == null)
                    throw new ZipException("Erro ao ler a entrada do zip: " + zipEntry.getName());

                while ((bytesLidos = is.read(buffer)) > 0)
                    os.write(buffer, 0, bytesLidos);

                if (listener != null)
                    listener.unzip((100 * currentEntry) / zip.size());

            } finally {

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

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

            }
        }

    } finally {

        if (zip != null)
            try {
                zip.close();
            } catch (Exception e) {
            }

    }

}

From source file:com.wolvereness.overmapped.OverMapped.java

private void readClasses(final MultiProcessor executor, final Map<String, ByteClass> byteClasses,
        final List<Pair<ZipEntry, byte[]>> fileEntries)
        throws ZipException, IOException, InterruptedException, ExecutionException, MojoFailureException {
    final List<Future<ByteClass>> classBuffer = newArrayList();
    final List<Future<Pair<ZipEntry, byte[]>>> fileBuffer = newArrayList();

    final ZipFile zipInput = new ZipFile(input);
    final Enumeration<? extends ZipEntry> zipEntries = zipInput.entries();
    while (zipEntries.hasMoreElements()) {
        final ZipEntry zipEntry = zipEntries.nextElement();
        if (ByteClass.isClass(zipEntry.getName())) {
            classBuffer.add(executor.submit(new Callable<ByteClass>() {
                @Override//from   w w w. ja  v a  2s.co m
                public ByteClass call() throws Exception {
                    return new ByteClass(zipEntry.getName(), zipInput.getInputStream(zipEntry));
                }
            }));
        } else {
            fileBuffer.add(executor.submit(new Callable<Pair<ZipEntry, byte[]>>() {
                @Override
                public Pair<ZipEntry, byte[]> call() throws Exception {
                    return new ImmutablePair<ZipEntry, byte[]>(new ZipEntry(zipEntry),
                            ByteStreams.toByteArray(zipInput.getInputStream(zipEntry)));
                }
            }));
        }
    }

    for (final Future<Pair<ZipEntry, byte[]>> file : fileBuffer) {
        fileEntries.add(file.get());
    }
    for (final Future<ByteClass> clazzFuture : classBuffer) {
        ByteClass clazz = clazzFuture.get();
        clazz = byteClasses.put(clazz.getToken(), clazz);
        if (clazz != null)
            throw new MojoFailureException(
                    String.format("Duplicate class definition %s - %s", clazz, clazzFuture.get()));
    }

    zipInput.close();
}

From source file:com.photon.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates) {
    File target = new File(project.getBasedir(), "target");
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();//www  . j  a  v a 2  s . com
    File out = new File(tmp, in.getName());

    if (out.exists()) {
        return out;
    }
    try {
        out.createNewFile();
    } catch (IOException e) {
        e.printStackTrace();
    }

    // Create a new Jar file
    FileOutputStream fos = null;
    ZipOutputStream jos = null;
    try {
        fos = new FileOutputStream(out);
        jos = new ZipOutputStream(fos);
    } catch (FileNotFoundException e1) {
        getLog().error(
                "Cannot remove duplicates : the output file " + out.getAbsolutePath() + " does not found");
        return null;
    }

    ZipFile inZip = null;
    try {
        inZip = new ZipFile(in);
        Enumeration<? extends ZipEntry> entries = inZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            // If the entry is not a duplicate, copy.
            if (!duplicates.contains(entry.getName())) {
                // copy the entry header to jos
                jos.putNextEntry(entry);
                InputStream currIn = inZip.getInputStream(entry);
                copyStreamWithoutClosing(currIn, jos);
                currIn.close();
                jos.closeEntry();
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

    try {
        if (inZip != null) {
            inZip.close();
        }
        jos.close();
        fos.close();
        jos = null;
        fos = null;
    } catch (IOException e) {
        // ignore it.
    }
    getLog().info(in.getName() + " rewritten without duplicates : " + out.getAbsolutePath());
    return out;
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void unzip(final File zipFile, final File destDir) throws MojoExecutionException {

    try {//from   www. j  av a 2 s . c  o  m
        final ZipFile zip = new ZipFile(zipFile);
        try {
            final Enumeration<? extends ZipEntry> enu = zip.entries();
            while (enu.hasMoreElements()) {
                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 = new BufferedInputStream(zip.getInputStream(entry));
                    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();
        }

    } catch (final IOException ex) {
        throw new MojoExecutionException("Error unzipping event store archive: " + zipFile, ex);
    }
}

From source file:org.apache.tez.history.parser.ATSFileParser.java

/**
 * Read zip file contents. Every file can contain "dag", "vertices", "tasks", "task_attempts"
 *
 * @param atsFile// w  ww  .  j  av a  2s .  co  m
 * @throws IOException
 * @throws JSONException
 */
private void parseATSZipFile(File atsFile)
        throws IOException, JSONException, TezException, InterruptedException {
    final ZipFile atsZipFile = new ZipFile(atsFile);
    try {
        Enumeration<? extends ZipEntry> zipEntries = atsZipFile.entries();
        while (zipEntries.hasMoreElements()) {
            ZipEntry zipEntry = zipEntries.nextElement();
            LOG.debug("Processing " + zipEntry.getName());
            InputStream inputStream = atsZipFile.getInputStream(zipEntry);
            JSONObject jsonObject = readJson(inputStream);

            //This json can contain dag, vertices, tasks, task_attempts
            JSONObject dagJson = jsonObject.optJSONObject(Constants.DAG);
            if (dagJson != null) {
                //TODO: support for multiple dags per ATS file later.
                dagInfo = DagInfo.create(dagJson);
            }

            //Process vertex
            JSONArray vertexJson = jsonObject.optJSONArray(Constants.VERTICES);
            if (vertexJson != null) {
                processVertices(vertexJson);
            }

            //Process task
            JSONArray taskJson = jsonObject.optJSONArray(Constants.TASKS);
            if (taskJson != null) {
                processTasks(taskJson);
            }

            //Process task attempts
            JSONArray attemptsJson = jsonObject.optJSONArray(Constants.TASK_ATTEMPTS);
            if (attemptsJson != null) {
                processAttempts(attemptsJson);
            }

            //Process application (mainly versionInfo)
            JSONObject tezAppJson = jsonObject.optJSONObject(Constants.APPLICATION);
            if (tezAppJson != null) {
                processApplication(tezAppJson);
            }
        }
    } finally {
        atsZipFile.close();
    }
}

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 {/*w w  w.  ja  v a2s.c  o m*/
        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.jboss.tools.project.examples.ProjectExamplesActivator.java

public static boolean extractZipFile(File file, File destination, IProgressMonitor monitor) {
    ZipFile zipFile = null;
    destination.mkdirs();/*from  ww  w  . ja va2  s  . com*/
    try {
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            if (monitor.isCanceled()) {
                return false;
            }
            ZipEntry entry = (ZipEntry) entries.nextElement();
            if (entry.isDirectory()) {
                monitor.setTaskName("Extracting " + entry.getName());
                File dir = new File(destination, entry.getName());
                dir.mkdirs();
                continue;
            }
            monitor.setTaskName("Extracting " + entry.getName());
            File entryFile = new File(destination, entry.getName());
            entryFile.getParentFile().mkdirs();
            InputStream in = null;
            OutputStream out = null;
            try {
                in = zipFile.getInputStream(entry);
                out = new FileOutputStream(entryFile);
                copy(in, out);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }
    } catch (IOException e) {
        ProjectExamplesActivator.log(e);
        return false;
    } finally {
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return true;
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {//  w w w.  ja  va  2  s.  co m
        destination.getParentFile().mkdirs();
        Enumeration zipFileEntries = zip.entries();

        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            // grab a zip file entry
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            File destFile = new File(destination, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

            // create the parent directory structure if needed
            destinationParent.mkdirs();

            if (!entry.isDirectory()) {
                BufferedInputStream is = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    fos = new FileOutputStream(destFile);
                    dest = new BufferedOutputStream(fos, BUFFER);

                    // read and write until last byte is encountered
                    while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                        dest.write(data, 0, currentByte);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}

From source file:abfab3d.io.input.STSReader.java

/**
 * Load a STS file into a grid.//from  w  w  w.  j a  v  a 2 s  . co  m
 *
 * @param file The zip file
 * @return
 * @throws java.io.IOException
 */
public AttributeGrid loadGrid(String file) throws IOException {

    ZipFile zip = null;

    try {
        zip = new ZipFile(file);

        ZipEntry entry = zip.getEntry("manifest.xml");
        if (entry == null) {
            throw new IOException("Cannot find manifest.xml in top level");
        }

        InputStream is = zip.getInputStream(entry);
        mf = parseManifest(is);

        if (mf == null) {
            throw new IOException("Could not parse manifest file");
        }
        /*
                    AttributeGrid ret_val = new ArrayAttributeGridByte(mf.getGridSizeX(),mf.getGridSizeY(),mf.getGridSizeZ(),mf.getVoxelSize(),mf.getVoxelSize());
                
                    double[] bounds = new double[6];
                
                    bounds[0] = mf.getOriginX();
                    bounds[1] = mf.getOriginX() + mf.getGridSizeX() * mf.getVoxelSize();
                    bounds[2] = mf.getOriginY();
                    bounds[3] = mf.getOriginY() + mf.getGridSizeY() * mf.getVoxelSize();
                    bounds[4] = mf.getOriginZ();
                    bounds[5] = mf.getOriginZ() + mf.getGridSizeZ() * mf.getVoxelSize();
                    ret_val.setGridBounds(bounds);
                
                    List<Channel> channels = mf.getChannels();
                
                    for(Channel chan : channels) {
        if (chan.getType().getId() == Channel.Type.DENSITY.getId()) {
            SlicesReader sr = new SlicesReader();
            sr.readSlices(ret_val,zip,chan.getSlices(),0,0,mf.getGridSizeY());
        }
                    }
        */
        return null;
    } finally {
        if (zip != null)
            zip.close();
    }
}