Example usage for java.util.zip ZipFile ZipFile

List of usage examples for java.util.zip ZipFile ZipFile

Introduction

In this page you can find the example usage for java.util.zip ZipFile ZipFile.

Prototype

public ZipFile(File file) throws ZipException, IOException 

Source Link

Document

Opens a ZIP file for reading given the specified File object.

Usage

From source file:de.onyxbits.raccoon.appmgr.ExtractWorker.java

private void parseResourceTable() throws IOException {
    ZipFile zf = new ZipFile(source);
    ZipEntry entry = Utils.getEntry(zf, AndroidConstants.RESOURCE_FILE);
    if (entry == null) {
        // if no resource entry has been found, we assume it is not needed by this
        // APK/*from w  w w .j av a 2  s . c o  m*/
        this.resourceTable = new ResourceTable();
        return;
    }

    this.resourceTable = new ResourceTable();

    InputStream in = zf.getInputStream(entry);
    ByteBuffer buffer = ByteBuffer.wrap(Utils.toByteArray(in));
    ResourceTableParser resourceTableParser = new ResourceTableParser(buffer);
    resourceTableParser.parse();
    this.resourceTable = resourceTableParser.getResourceTable();
}

From source file:m3.classe.M3ClassLoader.java

private DataInputStream getStreamFromJar(String name, File path) throws MAKException {
    if (!this.m_zipProblems.contains(path)) {
        try {//from   ww w .  j av  a  2  s .co m
            DataInputStream dis = null;
            ZipFile file = new ZipFile(path);
            ZipEntry entry = file.getEntry(name.replace('.', '/') + '.' + "class");
            if (entry == null) {
                entry = file.getEntry(name.replace('.', '/') + '.' + "properties");
            }
            if (entry != null)
                ;
            return new DataInputStream(file.getInputStream(entry));
        } catch (IOException e) {
            Ressource.logger.warn("Failed to get " + name + " from jar " + path
                    + " - MAK will try again using another method", e);
            this.m_zipProblems.add(path);
        }
    }
    return getStreamFromJar2(name, path);
}

From source file:averroes.JarOrganizer.java

/**
 * Process a given JAR file.//  ww w.j a  va 2  s.  c  o  m
 * 
 * @param fileName
 * @param fromApplicationArchive
 */
private void processArchive(String fileName, boolean fromApplicationArchive) {
    // Exit if the fileName is empty
    if (fileName.trim().length() <= 0) {
        return;
    }

    File file = new File(fileName);
    System.out.println("Processing " + (fromApplicationArchive ? "input" : "library") + " archive: "
            + file.getAbsolutePath());

    try {
        ZipFile archive = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = archive.entries();

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".class")) {
                addClass(archive, entry, fromApplicationArchive);
            }
        }
        archive.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.wolvereness.renumerated.Renumerated.java

private void process() throws Throwable {
    validateInput();// w ww . j  av  a  2  s  . 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.wavemaker.spinup.web.WavemakerStudioApplicationArchiveFactory.java

@Override
public ApplicationArchive getArchive() throws Exception {
    return new WavemakerStudioApplicationArchive(new ZipFile(this.studioWarFile));
}

From source file:com.asakusafw.bulkloader.testutil.UnitTestUtil.java

/**
 * Create file list from Zip file./*from   w  w w . j a  v a 2s  .  co  m*/
 * @param originalZipFile source Zip file
 * @param targetFileList target file list file
 */
public static void createFileList(File originalZipFile, File targetFileList) throws IOException {
    ZipFile zip = new ZipFile(originalZipFile);
    try {
        FileOutputStream output = new FileOutputStream(targetFileList);
        try {
            FileList.Writer writer = FileList.createWriter(output, true);
            Enumeration<? extends ZipEntry> entries = zip.entries();
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                InputStream input = zip.getInputStream(next);
                try {
                    OutputStream target = writer.openNext(FileList.content(next.getName().replace('\\', '/')));
                    try {
                        IOUtils.pipingAndClose(input, target);
                    } finally {
                        target.close();
                    }
                } finally {
                    input.close();
                }
            }
            writer.close();
        } finally {
            output.close();
        }
    } finally {
        zip.close();
    }
}

From source file:ch.ivyteam.ivy.maven.TestIarPackagingMojo.java

@Test
public void canDefineCustomInclusions() throws Exception {
    IarPackagingMojo mojo = rule.getMojo();
    File outputDir = new File(mojo.project.getBasedir(), "target");
    File customPomXml = new File(outputDir, "myCustomPom.xml");
    FileUtils.write(customPomXml, "customPomContent");

    String relativeCustomIncludePath = "target/" + customPomXml.getName();
    FileSet fs = new FileSet();
    fs.setIncludes(Arrays.asList(relativeCustomIncludePath));
    mojo.iarFileSets = new FileSet[] { fs };

    mojo.execute();/*w  w w.  j ava  2s.  com*/
    try (ZipFile archive = new ZipFile(mojo.project.getArtifact().getFile())) {
        assertThat(archive.getEntry(relativeCustomIncludePath)).as("Custom inclusions must be included")
                .isNotNull();
    }
}

From source file:com.axelor.apps.base.service.imports.importer.Importer.java

protected void unZip(File file, File directory) throws ZipException, IOException {

    File extractFile = null;/*w  ww.  j  a  v  a 2  s. c o  m*/
    FileOutputStream fileOutputStream = null;
    ZipFile zipFile = new ZipFile(file);
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        try {
            ZipEntry entry = entries.nextElement();
            InputStream entryInputStream = zipFile.getInputStream(entry);
            byte[] buffer = new byte[1024];
            int bytesRead = 0;

            extractFile = new File(directory, entry.getName());
            if (entry.isDirectory()) {
                extractFile.mkdirs();
                continue;
            } else {
                extractFile.getParentFile().mkdirs();
                extractFile.createNewFile();
            }

            fileOutputStream = new FileOutputStream(extractFile);
            while ((bytesRead = entryInputStream.read(buffer)) != -1) {
                fileOutputStream.write(buffer, 0, bytesRead);
            }

        } catch (IOException ioException) {
            log.error(ioException.getMessage());
            continue;
        } finally {
            if (fileOutputStream == null) {
                continue;
            }
            try {
                fileOutputStream.close();
            } catch (IOException e) {
            }
        }
    }

    zipFile.close();

}

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

/**
 * Load a STS file into a grid.//w ww.  jav a 2  s.  c o  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();
    }
}

From source file:io.apiman.common.plugin.PluginClassLoader.java

/**
 * Extracts a dependency from the plugin artifact ZIP and saves it to the work
 * directory.  If the dependency has already been extracted (we're re-using the
 * work directory) then this simply returns what is already there.
 * @param zipEntry a ZIP file entry//from   w  w w. j ava 2  s .  c  o  m
 * @throws IOException if an I/O error has occurred
 */
private ZipFile extractDependency(ZipEntry zipEntry) throws IOException {
    File dependencyWorkDir = new File(workDir, "lib");
    if (!dependencyWorkDir.exists()) {
        dependencyWorkDir.mkdirs();
    }
    String depFileName = new File(zipEntry.getName()).getName();
    File depFile = new File(dependencyWorkDir, depFileName);
    if (!depFile.isFile()) {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = this.pluginArtifactZip.getInputStream(zipEntry);
            output = new FileOutputStream(depFile);
            IOUtils.copy(input, output);
            output.flush();
        } catch (IOException e) {
            throw e;
        } finally {
            IOUtils.closeQuietly(input);
            IOUtils.closeQuietly(output);
        }
    }
    return new ZipFile(depFile);
}