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:com.disney.opa.util.AttachmentUtils.java

/**
 * This method is to extract the zip files and creates attachment objects.
 * /*w w w .  j av  a  2 s .  co  m*/
 * @param attachment
 * @param fileNames
 * @param fileLabels
 * @param errors
 * @return list of attachments from the zip file
 */
public List<Attachment> processZipFile(Attachment attachment, List<String> fileNames, List<String> fileLabels,
        List<String> errors) {
    ZipFile zipFile = null;
    List<Attachment> attachments = new ArrayList<Attachment>();
    try {
        String zipFilePath = getOriginalAttachmentsPath(attachment.getProductID()) + File.separator
                + attachment.getFilename();
        zipFile = new ZipFile(zipFilePath);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String fileName = entry.getName();
            File destinationFile = new File(
                    getOriginalAttachmentsPath(attachment.getProductID()) + File.separator + fileName);
            uploadFile(zipFile.getInputStream(entry), destinationFile);
            String label = createUniqueFileLabel(fileName, null, fileLabels);
            Attachment fileAttachment = getAttachment(fileName, label, attachment.getProductID(),
                    attachment.getProductStateID(), attachment.getUserID());
            if (fileAttachment.getFileSize() == 0L) {
                errors.add("File not found, file name: " + fileName + ", in zip file: "
                        + attachment.getFilename());
            } else {
                attachments.add(fileAttachment);
            }
        }
    } catch (Exception e) {
        errors.add(
                "Error while processing zip: " + attachment.getFilename() + ", title: " + attachment.getName());
        log.error("Error while processing zip.", e);
    } finally {
        try {
            if (zipFile != null) {
                zipFile.close();
            }
        } catch (IOException e) {
        }
    }
    return attachments;
}

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/*  w ww .j  a  va 2  s .c  om*/
                        .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:net.sf.sripathi.ws.mock.util.Folder.java

public void createFilesAndFolder(ZipFile zip) {

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();
    Set<String> files = new TreeSet<String>();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (entry.getName().toLowerCase().endsWith(".wsdl") || entry.getName().toLowerCase().endsWith(".xsd"))
            files.add(entry.getName());//  w ww.  jav  a2 s.  c  om
    }

    for (String fileStr : files) {

        String[] split = fileStr.split("/");
        Folder parent = this;
        if (split.length > 1) {

            Folder sub = null;
            for (int i = 0; i < split.length - 1; i++) {

                sub = parent.getSubFolderByName(split[i]);
                if (sub == null) {
                    sub = parent.createSubFolder(split[i]);
                }
                parent = sub;
            }
        }

        File file = parent.createFile(split[split.length - 1]);
        FileOutputStream fos = null;
        InputStream zipStream = null;
        try {
            fos = new FileOutputStream(file);
            zipStream = zip.getInputStream(zip.getEntry(fileStr));
            fos.write(IOUtils.toByteArray(zipStream));
        } catch (Exception e) {
            throw new MockException("Unable to create file - " + fileStr);
        } finally {
            try {
                fos.close();
            } catch (Exception e) {
            }
            try {
                zipStream.close();
            } catch (Exception e) {
            }
        }
    }
}

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 .  ja va2 s  .  c  o 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:com.ichi2.libanki.Utils.java

public static boolean unzipFiles(ZipFile zipFile, String targetDirectory, String[] zipEntries,
        HashMap<String, String> zipEntryToFilenameMap) {
    byte[] buf = new byte[FILE_COPY_BUFFER_SIZE];
    File dir = new File(targetDirectory);
    if (!dir.exists() && !dir.mkdirs()) {
        Timber.e("Utils.unzipFiles: Could not create target directory: " + targetDirectory);
        return false;
    }/*from  www  . ja  va2 s .  c om*/
    if (zipEntryToFilenameMap == null) {
        zipEntryToFilenameMap = new HashMap<String, String>();
    }
    BufferedInputStream zis = null;
    BufferedOutputStream bos = null;
    try {
        for (String requestedEntry : zipEntries) {
            ZipEntry ze = zipFile.getEntry(requestedEntry);
            if (ze != null) {
                String name = ze.getName();
                if (zipEntryToFilenameMap.containsKey(name)) {
                    name = zipEntryToFilenameMap.get(name);
                }
                File destFile = new File(dir, name);
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists() && !parentDir.mkdirs()) {
                    return false;
                }
                if (!ze.isDirectory()) {
                    Timber.i("uncompress %s", name);
                    zis = new BufferedInputStream(zipFile.getInputStream(ze));
                    bos = new BufferedOutputStream(new FileOutputStream(destFile), FILE_COPY_BUFFER_SIZE);
                    int n;
                    while ((n = zis.read(buf, 0, FILE_COPY_BUFFER_SIZE)) != -1) {
                        bos.write(buf, 0, n);
                    }
                    bos.flush();
                    bos.close();
                    zis.close();
                }
            }
        }
    } catch (IOException e) {
        Timber.e(e, "Utils.unzipFiles: Error while unzipping archive.");
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing output stream.");
        }
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            Timber.e(e, "Utils.unzipFiles: Error while closing zip input stream.");
        }
    }
    return true;
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

public static PackageSet loadFromZip(ZipFile file) throws IOException, PackageNotFoundException {
    HashMap<String, HashMap<String, InputStream>> setMap = new HashMap<>();
    Enumeration<? extends ZipEntry> entries = file.entries();
    String setName = file.getName().substring(file.getName().lastIndexOf(File.separatorChar) + 1)
            .replace(".zip", "");
    // extract correct entries from the zip file
    while (true) {
        try {/*from   w w  w. j  a va2  s.c om*/
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // get the correct path separator (both can be used)
            char separator = (entryName.contains("/") ? '/' : '\\');
            // index of first separator used to get set name
            int index = entryName.indexOf(separator);
            // skip entry if there are no path separators (files in zip root like license, readme etc.)
            if (index < 0) {
                continue;
            }
            if (!entryName.endsWith(".yml")) {
                continue;
            }
            String[] parts = entryName.split(Pattern.quote(String.valueOf(separator)));
            String ymlName = parts[parts.length - 1].substring(0, parts[parts.length - 1].length() - 4);
            StringBuilder builder = new StringBuilder();
            int length = parts.length - 1;
            boolean conversation = false;
            if (parts[length - 1].equals("conversations")) {
                length--;
                conversation = true;
            }
            for (int i = 0; i < length; i++) {
                builder.append(parts[i] + '-');
            }
            String packName = builder.substring(0, builder.length() - 1);
            HashMap<String, InputStream> packMap = setMap.get(packName);
            if (packMap == null) {
                packMap = new HashMap<>();
                setMap.put(packName, packMap);
            }
            List<String> allowedNames = Arrays
                    .asList(new String[] { "main", "events", "conditions", "objectives", "journal", "items" });
            if (conversation) {
                packMap.put("conversations." + ymlName, file.getInputStream(entry));
            } else {
                if (allowedNames.contains(ymlName)) {
                    packMap.put(ymlName, file.getInputStream(entry));
                }
            }
        } catch (NoSuchElementException e) {
            break;
        }
    }
    PackageSet set = parseStreams(setName, setMap);
    BetonQuestEditor.getInstance().getSets().add(set);
    RootController.setPackages(BetonQuestEditor.getInstance().getSets());
    return set;
}

From source file:com.heliosdecompiler.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.launchProcess(new ProcessBuilder(
                        com.heliosdecompiler.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O",
                        "decompile.py", "-skip", "-nauto",
                        Settings.MAGIC_THROW.isEnabled() ? "-xmagicthrow" : "", "-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 {
                IOUtils.closeQuietly(zipFile);
                FileUtils.deleteQuietly(inputJar);
                FileUtils.deleteQuietly(outputJar);
            }//ww w.j  ava2s .co  m
        } 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: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();//  ww  w .jav a 2 s .  c  o  m
    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:com.simpligility.maven.plugins.android.phase09package.ApkMojo.java

private File removeDuplicatesFromJar(File in, List<String> duplicates, Set<String> duplicatesAdded,
        ZipOutputStream duplicateZos, int num) {
    String target = targetDirectory.getAbsolutePath();
    File tmp = new File(target, "unpacked-embedded-jars");
    tmp.mkdirs();/*  w w  w .  j a va 2s  .com*/
    String jarName = String.format("%s-%d.%s", Files.getNameWithoutExtension(in.getName()), num,
            Files.getFileExtension(in.getName()));
    File out = new File(tmp, jarName);

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

    // Create a new Jar file
    final FileOutputStream fos;
    final ZipOutputStream jos;
    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;
    }

    final ZipFile inZip;
    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();
            }
            //if it is duplicate, check the resource transformers
            else {
                boolean resourceTransformed = false;
                if (transformers != null) {
                    for (ResourceTransformer transformer : transformers) {
                        if (transformer.canTransformResource(entry.getName())) {
                            getLog().info("Transforming " + entry.getName() + " using "
                                    + transformer.getClass().getName());
                            InputStream currIn = inZip.getInputStream(entry);
                            transformer.processResource(entry.getName(), currIn, null);
                            currIn.close();
                            resourceTransformed = true;
                            break;
                        }
                    }
                }
                //if not handled by transformer, add (once) to duplicates jar
                if (!resourceTransformed) {
                    if (!duplicatesAdded.contains(entry.getName())) {
                        duplicatesAdded.add(entry.getName());
                        duplicateZos.putNextEntry(entry);
                        InputStream currIn = inZip.getInputStream(entry);
                        copyStreamWithoutClosing(currIn, duplicateZos);
                        currIn.close();
                        duplicateZos.closeEntry();
                    }
                }
            }
        }
    } catch (IOException e) {
        getLog().error("Cannot removing duplicates : " + e.getMessage());
        return null;
    }

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