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.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();//from www . j  a  v  a2s  .  co m

    final MultiProcessor executor = MultiProcessor.newMultiProcessor(cores - 1,
            new ThreadFactoryBuilder().setDaemon(true)
                    .setNameFormat(Renumerated.class.getName() + "-processor-%d")
                    .setUncaughtExceptionHandler(this).build());
    final Future<?> fileCopy = executor.submit(new Callable<Object>() {
        @Override
        public Object call() throws Exception {
            if (original != null) {
                if (original.exists()) {
                    original.delete();
                }
                Files.copy(input, original);
            }
            return null;
        }
    });

    final List<Pair<ZipEntry, Future<byte[]>>> fileEntries = newArrayList();
    final List<Pair<MutableObject<ZipEntry>, Future<byte[]>>> classEntries = newArrayList();
    {
        final ZipFile input = new ZipFile(this.input);
        final Enumeration<? extends ZipEntry> inputEntries = input.entries();
        while (inputEntries.hasMoreElements()) {
            final ZipEntry entry = inputEntries.nextElement();
            final Future<byte[]> future = executor.submit(new Callable<byte[]>() {
                @Override
                public byte[] call() throws Exception {
                    return ByteStreams.toByteArray(input.getInputStream(entry));
                }
            });
            if (entry.getName().endsWith(".class")) {
                classEntries.add(new MutablePair<MutableObject<ZipEntry>, Future<byte[]>>(
                        new MutableObject<ZipEntry>(entry), future));
            } else {
                fileEntries.add(new ImmutablePair<ZipEntry, Future<byte[]>>(entry, future));
            }
        }

        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> pair : classEntries) {
            final byte[] data = pair.getRight().get();
            pair.setValue(executor.submit(new Callable<byte[]>() {
                String className;
                List<String> fields;

                @Override
                public byte[] call() throws Exception {
                    try {
                        return method();
                    } catch (final Exception ex) {
                        throw new Exception(pair.getLeft().getValue().getName(), ex);
                    }
                }

                private byte[] method() throws Exception {
                    final ClassReader clazz = new ClassReader(data);
                    clazz.accept(new ClassVisitor(ASM4) {
                        @Override
                        public void visit(final int version, final int access, final String name,
                                final String signature, final String superName, final String[] interfaces) {
                            if (superName.equals("java/lang/Enum")) {
                                className = name;
                            }
                        }

                        @Override
                        public FieldVisitor visitField(final int access, final String name, final String desc,
                                final String signature, final Object value) {
                            if (className != null && (access & 0x4000) != 0) {
                                List<String> fieldNames = fields;
                                if (fieldNames == null) {
                                    fieldNames = fields = newArrayList();
                                }
                                fieldNames.add(name);
                            }
                            return null;
                        }
                    }, ClassReader.SKIP_CODE);

                    if (className == null)
                        return data;

                    final String classDescriptor = Type.getObjectType(className).getDescriptor();

                    final ClassWriter writer = new ClassWriter(0);
                    clazz.accept(new ClassVisitor(ASM4, writer) {
                        @Override
                        public MethodVisitor visitMethod(final int access, final String name, final String desc,
                                final String signature, final String[] exceptions) {
                            final MethodVisitor methodVisitor = super.visitMethod(access, name, desc, signature,
                                    exceptions);
                            if (!name.equals("<clinit>")) {
                                return methodVisitor;
                            }
                            return new MethodVisitor(ASM4, methodVisitor) {
                                final Iterator<String> it = fields.iterator();
                                boolean active;
                                String lastName;

                                @Override
                                public void visitTypeInsn(final int opcode, final String type) {
                                    if (!active && it.hasNext()) {
                                        // Initiate state machine
                                        if (opcode != NEW)
                                            throw new AssertionError("Unprepared for " + opcode + " on " + type
                                                    + " in " + className);
                                        active = true;
                                    }
                                    super.visitTypeInsn(opcode, type);
                                }

                                @Override
                                public void visitLdcInsn(final Object cst) {
                                    if (active && lastName == null) {
                                        if (!(cst instanceof String))
                                            throw new AssertionError(
                                                    "Unprepared for " + cst + " in " + className);
                                        // Switch the first constant in the Enum constructor
                                        super.visitLdcInsn(lastName = it.next());
                                    } else {
                                        super.visitLdcInsn(cst);
                                    }
                                }

                                @Override
                                public void visitFieldInsn(final int opcode, final String owner,
                                        final String name, final String desc) {
                                    if (opcode == PUTSTATIC && active && lastName != null
                                            && owner.equals(className) && desc.equals(classDescriptor)
                                            && name.equals(lastName)) {
                                        // Finish the current state machine
                                        active = false;
                                        lastName = null;
                                    }
                                    super.visitFieldInsn(opcode, owner, name, desc);
                                }
                            };
                        }
                    }, ClassReader.EXPAND_FRAMES);

                    final MutableObject<ZipEntry> key = pair.getLeft();
                    key.setValue(new ZipEntry(key.getValue().getName()));
                    return writer.toByteArray();
                }
            }));
        }

        for (final Pair<ZipEntry, Future<byte[]>> pair : fileEntries) {
            pair.getRight().get();
        }

        input.close();
    }

    fileCopy.get();

    FileOutputStream fileOut = null;
    JarOutputStream jar = null;
    try {
        jar = new JarOutputStream(fileOut = new FileOutputStream(output));
        for (final Pair<ZipEntry, Future<byte[]>> fileEntry : fileEntries) {
            jar.putNextEntry(fileEntry.getLeft());
            jar.write(fileEntry.getRight().get());
        }
        for (final Pair<MutableObject<ZipEntry>, Future<byte[]>> classEntry : classEntries) {
            final byte[] data = classEntry.getRight().get();
            final ZipEntry entry = classEntry.getLeft().getValue();
            entry.setSize(data.length);
            jar.putNextEntry(entry);
            jar.write(data);
        }
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (final IOException ex) {
            }
        }
        if (fileOut != null) {
            try {
                fileOut.close();
            } catch (final IOException ex) {
            }
        }
    }

    final Pair<Thread, Throwable> uncaught = this.uncaught;
    if (uncaught != null)
        throw new MojoExecutionException(String.format("Uncaught exception in %s", uncaught.getLeft()),
                uncaught.getRight());
}

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  ww  .  j  a  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:org.easysoa.registry.frascati.FileUtils.java

/**
 * Unzips the given jar in a temp file and returns its files' URLs Inspired
 * from AssemblyFactoryManager.processContribution() (though doesn't add it
 * to the classloader or parse composites)
 * TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ?
 * @param SCA zip or jar/*from w  ww  .  j  a  va2 s  . c om*/
 * @return unzipped composites URLs
 * @throws ManagerException
 */
public static final Set<URL> unzipAndGetFileUrls(File file) {
    try {
        // Load contribution zip file
        ZipFile zipFile = new ZipFile(file);

        // Get folder name for output
        final String folder = zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),
                zipFile.getName().length() - ".zip".length());

        Set<URL> fileURLSet = new HashSet<URL>();

        // Set directory for extracted files

        // TODO : use system temp directory but should use output folder
        // given by
        // runtime component. Will be possible once Assembly Factory modules
        // will
        // be merged

        final String tempDir = System.getProperty("java.io.tmpdir") + File.separator + folder + File.separator;

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

        // Iterate over zip entries
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            log.info("ZIP entry: " + entry.getName());

            // create directories
            if (entry.isDirectory()) {
                log.info("create directory : " + tempDir + entry.getName());
                new File(tempDir, entry.getName()).mkdirs();
            } else {
                File f = new File(tempDir, File.separator + entry.getName());
                // register jar files
                int idx = entry.getName().lastIndexOf(File.separator);
                if (idx != -1) {
                    String tmp = entry.getName().substring(0, idx);
                    log.info("create directory : " + tempDir + tmp);
                    new File(tempDir, tmp).mkdirs();
                }
                // extract entry from zip to tempDir
                copy(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(f)));
                // add to res set
                fileURLSet.add(f.toURI().toURL());
            }
        }

        return fileURLSet;

    } catch (IOException e) {
        log.error(e);
        return new HashSet<URL>(0);
    }
}

From source file:org.geoserver.kml.KMLReflectorTest.java

@Test
public void testKmzEmbededPointImageSize() throws Exception {

    WMSMapContent mapContent = createMapContext(MockData.POINTS, "big-mark");

    File temp = File.createTempFile("test", "kmz", new File("target"));
    temp.delete();//  w ww. j  a  v  a 2s . c  o  m
    temp.mkdir();
    temp.deleteOnExit();

    File zip = new File(temp, "kmz.zip");
    zip.deleteOnExit();

    // create hte map producer
    KMZMapOutputFormat mapProducer = new KMZMapOutputFormat(getWMS());
    KMLMap map = mapProducer.produceMap(mapContent);

    FileOutputStream output = new FileOutputStream(zip);
    new KMLMapResponse(new KMLEncoder(), getWMS()).write(map, output, null);

    output.flush();
    output.close();

    assertTrue(zip.exists());

    // unzip and test it
    ZipFile zipFile = new ZipFile(zip);

    ZipEntry kmlEntry = zipFile.getEntry("wms.kml");
    InputStream kmlStream = zipFile.getInputStream(kmlEntry);

    Document kmlResult = XMLUnit.buildTestDocument(new InputSource(kmlStream));

    Double scale = Double.parseDouble(XMLUnit.newXpathEngine()
            .getMatchingNodes("(//kml:Style)[1]/kml:IconStyle/kml:scale", kmlResult).item(0).getTextContent());
    assertEquals(49d / 16d, scale, 0.01);

    zipFile.close();
}

From source file:de.tarent.maven.plugins.pkg.packager.IzPackPackager.java

/**
 * Puts the embedded izpack jar from the (resource) classpath into the work
 * directory and unpacks it there.//from  ww  w  .j a  v a2  s  . co  m
 * 
 * @param l
 * @param izPackEmbeddedFile
 * @param izPackEmbeddedHomeDir
 * @throws MojoExecutionException
 */
private void unpackIzPack(Log l, File izPackEmbeddedFile, File izPackEmbeddedHomeDir)
        throws MojoExecutionException {
    l.info("storing embedded IzPack installation in " + izPackEmbeddedFile);
    Utils.storeInputStream(IzPackPackager.class.getResourceAsStream(IZPACK_EMBEDDED_JAR), izPackEmbeddedFile,
            "IOException while unpacking embedded IzPack installation.");

    l.info("unzipping embedded IzPack installation to" + izPackEmbeddedHomeDir);
    int count = 0;
    ZipFile zip = null;
    try {
        zip = new ZipFile(izPackEmbeddedFile);
        Enumeration<? extends ZipEntry> e = zip.entries();

        while (e.hasMoreElements()) {
            count++;
            ZipEntry entry = (ZipEntry) e.nextElement();
            File unpacked = new File(izPackEmbeddedHomeDir, entry.getName());
            if (entry.isDirectory()) {
                unpacked.mkdirs(); // TODO: Check success.
            } else {
                Utils.createFile(unpacked, "Unable to create ZIP file entry ");
                Utils.storeInputStream(zip.getInputStream(entry), unpacked,
                        "IOException while unpacking ZIP file entry.");
            }
        }
    } catch (IOException ioe) {
        throw new MojoExecutionException("IOException while unpacking embedded IzPack installation.", ioe);
    } finally {
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException e) {
                l.info(String.format("Error at closing zipfile %s caused by %s", izPackEmbeddedFile.getName(),
                        e.getMessage()));
            }
        }
    }
    l.info("unpacked " + count + " entries");
}

From source file:org.commonjava.maven.galley.filearc.internal.ZipPublish.java

private Boolean rewriteArchive(final File dest, final String path) {
    final boolean isJar = isJarOperation();
    final File src = new File(dest.getParentFile(), dest.getName() + ".old");
    dest.renameTo(src);/*  w  w w .  j  av  a  2 s  .c o m*/

    InputStream zin = null;
    ZipFile zfIn = null;

    FileOutputStream fos = null;
    ZipOutputStream zos = null;
    ZipFile zfOut = null;
    try {
        fos = new FileOutputStream(dest);
        zos = isJar ? new JarOutputStream(fos) : new ZipOutputStream(fos);

        zfOut = isJar ? new JarFile(dest) : new ZipFile(dest);
        zfIn = isJar ? new JarFile(src) : new ZipFile(src);

        for (final Enumeration<? extends ZipEntry> en = zfIn.entries(); en.hasMoreElements();) {
            final ZipEntry inEntry = en.nextElement();
            final String inPath = inEntry.getName();
            try {
                if (inPath.equals(path)) {
                    zin = stream;
                } else {
                    zin = zfIn.getInputStream(inEntry);
                }

                final ZipEntry entry = zfOut.getEntry(inPath);
                zos.putNextEntry(entry);
                copy(stream, zos);
            } finally {
                closeQuietly(zin);
            }
        }

        return true;
    } catch (final IOException e) {
        error = new TransferException("Failed to write path: %s to EXISTING archive: %s. Reason: %s", e, path,
                dest, e.getMessage());
    } finally {
        closeQuietly(zos);
        closeQuietly(fos);
        if (zfOut != null) {
            //noinspection EmptyCatchBlock
            try {
                zfOut.close();
            } catch (final IOException e) {
            }
        }

        if (zfIn != null) {
            //noinspection EmptyCatchBlock
            try {
                zfIn.close();
            } catch (final IOException e) {
            }
        }

        closeQuietly(stream);
    }

    return false;
}

From source file:com.denimgroup.threadfix.importer.impl.upload.SkipfishChannelImporter.java

private InputStream findSamplesFile(@Nonnull ZipFile zipFile) {
    if (zipFile.entries() == null) {
        throw new ScanFileUnavailableException("No zip entries were found in the zip file.");
    }/*from w  ww  . j  a  v a  2s  .co m*/

    Enumeration<? extends ZipEntry> entries = zipFile.entries();
    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();
        if (entry.getName().endsWith("samples.js")) {
            try {
                return zipFile.getInputStream(entry);
            } catch (IOException e) {
                log.error("IOException thrown when reading entries from zip file.", e);
            }
        }
    }

    throw new ScanFileUnavailableException("Samples.js was not found in the zip file.");
}

From source file:de.jcup.egradle.core.util.FileSupport.java

/**
 * Unzips the given zip file to the given destination directory extracting
 * only those entries the pass through the given filter.
 *
 * @param zipFile/*from   w  w w. j  a v  a  2s  .com*/
 *            the zip file to unzip
 * @param dstDir
 *            the destination directory
 * @throws IOException
 *             in case of problem
 */
public void unzip(ZipFile zipFile, File dstDir) throws IOException {

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

    try {
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.isDirectory()) {
                continue;
            }
            String entryName = entry.getName();
            File file = new File(dstDir, changeSeparator(entryName, '/', File.separatorChar));
            file.getParentFile().mkdirs();
            InputStream src = null;
            OutputStream dst = null;
            try {
                src = zipFile.getInputStream(entry);
                dst = new FileOutputStream(file);
                transferData(src, dst);
            } finally {
                if (dst != null) {
                    try {
                        dst.close();
                    } catch (IOException e) {
                    }
                }
                if (src != null) {
                    src.close();
                }
            }
        }
    } finally {
        try {
            zipFile.close();
        } catch (IOException e) {
        }
    }
}

From source file:brut.androlib.res.AndrolibResources.java

public void installFramework(File frameFile, String tag) throws AndrolibException {
    InputStream in = null;//from ww w.  ja va2  s.com
    ZipOutputStream out = null;
    try {
        ZipFile zip = new ZipFile(frameFile);
        ZipEntry entry = zip.getEntry("resources.arsc");

        if (entry == null) {
            throw new AndrolibException("Can't find resources.arsc file");
        }

        in = zip.getInputStream(entry);
        byte[] data = IOUtils.toByteArray(in);

        ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true);
        publicizeResources(data, arsc.getFlagsOffsets());

        File outFile = new File(getFrameworkDir(),
                String.valueOf(arsc.getOnePackage().getId()) + (tag == null ? "" : '-' + tag) + ".apk");

        out = new ZipOutputStream(new FileOutputStream(outFile));
        out.setMethod(ZipOutputStream.STORED);
        CRC32 crc = new CRC32();
        crc.update(data);
        entry = new ZipEntry("resources.arsc");
        entry.setSize(data.length);
        entry.setCrc(crc.getValue());
        out.putNextEntry(entry);
        out.write(data);
        zip.close();
        LOGGER.info("Framework installed to: " + outFile);
    } catch (IOException ex) {
        throw new AndrolibException(ex);
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.microsoft.tfs.client.common.ui.teambuild.commands.CreateUploadZipCommand.java

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile/* w ww.  j a  v a 2s.c  om*/
 * @param destFile
 * @throws IOException
 */
public void copyZip(final String srcFile, final String destFile) throws Exception {
    loadDefaultExcludePattern(getRootFolderInZip(srcFile));

    final ZipFile zipSrc = new ZipFile(srcFile);
    final ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destFile));

    try {
        final Enumeration<? extends ZipEntry> entries = zipSrc.entries();
        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            if (!isExcluded(LocalPath.combine(srcFile, entry.getName()), false, srcFile)) {
                final ZipEntry newEntry = new ZipEntry(entry.getName());
                out.putNextEntry(newEntry);

                final BufferedInputStream in = new BufferedInputStream(zipSrc.getInputStream(entry));
                int len;
                final byte[] buf = new byte[65536];
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
        }
        out.finish();
    } catch (final IOException e) {
        errorMsg = Messages.getString("CreateUploadZipCommand.CopyArchiveErrorMessageFormat"); //$NON-NLS-1$
        log.error("Exceptions when copying exising archive ", e); //$NON-NLS-1$
        throw e;
    } finally {
        out.close();
        zipSrc.close();
    }
}