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:com.l2jfree.gameserver.script.faenor.FaenorScriptEngine.java

private void loadPackages() {
    File packDirectory = new File(Config.DATAPACK_ROOT, PACKAGE_DIRECTORY);

    FileFilter fileFilter = new FileFilter() {
        @Override//w  w w .  j  a  v  a 2  s. c  o  m
        public boolean accept(File file) {
            return file.getName().endsWith(".zip");
        }
    };

    File[] files = packDirectory.listFiles(fileFilter);
    if (files == null)
        return;
    ZipFile zipPack;

    for (File element : files) {
        try {
            zipPack = new ZipFile(element);
        } catch (ZipException e) {
            _log.error(e.getMessage(), e);
            continue;
        } catch (IOException e) {
            _log.error(e.getMessage(), e);
            continue;
        }

        ScriptPackage module = new ScriptPackage(zipPack);

        List<ScriptDocument> scripts = module.getScriptFiles();
        for (ScriptDocument script : scripts) {
            _scripts.add(script);
        }

        try {
            zipPack.close();
        } catch (IOException e) {
        }
    }
}

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  va2 s.  com*/
                        .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:com.liferay.mobile.sdk.core.tests.MobileSDKCoreTests.java

private void checkJar(File jar, boolean src) throws Exception {
    assertTrue(jar.exists());/*from   w w w .j  a v a 2 s . c om*/

    final ZipFile zipFile = new ZipFile(jar);
    final ZipEntry manifest = zipFile.getEntry("META-INF/MANIFEST.MF");

    assertNotNull(manifest);

    final String manifestContents = CoreUtil.readStreamToString(zipFile.getInputStream(manifest));

    assertTrue(manifestContents.startsWith("Manifest-Version: 1.0"));

    boolean valid = false;

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

    while (entries.hasMoreElements()) {
        final String entryName = entries.nextElement().getName();

        if (entryName.startsWith(PACKAGE.split("\\.")[0]) && entryName.endsWith(src ? ".java" : ".class")) {
            valid = true;
            break;
        }
    }

    zipFile.close();

    assertTrue(valid);
}

From source file:com.github.promeg.configchecker.Main.java

/**
 * Tries to open an input file as a Zip archive (jar/apk) with a
 * "classes.dex" inside./*from  www.ja va 2s.  c  o  m*/
 */
void openInputFileAsZip(String fileName, List<String> dexFiles) throws IOException {
    ZipFile zipFile;

    // Try it as a zip file.
    try {
        zipFile = new ZipFile(fileName);
    } catch (FileNotFoundException fnfe) {
        // not found, no point in retrying as non-zip.
        System.err.println("Unable to open '" + fileName + "': " + fnfe.getMessage());
        throw fnfe;
    } catch (ZipException ze) {
        // not a zip
        return;
    }

    // Open and add all files matching "classes.*\.dex" in the zip file.
    for (ZipEntry entry : Collections.list(zipFile.entries())) {
        if (entry.getName().matches("classes.*\\.dex")) {
            dexFiles.add(openDexFile(zipFile, entry).getAbsolutePath());
        }
    }

    zipFile.close();
}

From source file:com.samczsun.helios.transformers.disassemblers.KrakatauDisassembler.java

public boolean disassembleClassNode(ClassNode cn, byte[] b, StringBuilder output) {
    if (Helios.ensurePython2Set()) {
        File inputJar = null;/*from   w  w  w .  j  a  va  2s .co m*/
        File outputZip = null;
        String processLog = null;

        try {
            inputJar = Files.createTempFile("kdisin", ".jar").toFile();
            outputZip = Files.createTempFile("kdisout", ".zip").toFile();

            Map<String, byte[]> data = Helios.getAllLoadedData();
            data.put(cn.name + ".class", b);

            Utils.saveClasses(inputJar, data);

            Process process = Helios.launchProcess(new ProcessBuilder(
                    com.samczsun.helios.Settings.PYTHON2_LOCATION.get().asString(), "-O", "disassemble.py",
                    "-path", inputJar.getAbsolutePath(), "-out", outputZip.getAbsolutePath(),
                    cn.name + ".class", Settings.ROUNDTRIP.isEnabled() ? "-roundtrip" : "")
                            .directory(Constants.KRAKATAU_DIR));

            processLog = Utils.readProcess(process);

            ZipFile zipFile = new ZipFile(outputZip);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            byte[] disassembled = null;
            while (entries.hasMoreElements()) {
                ZipEntry next = entries.nextElement();
                if (next.getName().equals(cn.name + ".j")) {
                    disassembled = IOUtils.toByteArray(zipFile.getInputStream(next));
                }
            }
            zipFile.close();
            output.append(new String(disassembled, "UTF-8"));
            return true;
        } catch (Exception e) {
            output.append(parseException(e)).append(processLog);
            return false;
        } finally {
            FileUtils.deleteQuietly(inputJar);
            FileUtils.deleteQuietly(outputZip);
        }
    } else {
        output.append("You need to set the location of Python 2.x");
    }
    return false;
}

From source file:de.thischwa.pmcms.server.ZipProxyServlet.java

@Override
public void init(ServletConfig config) throws ServletException {
    zipPathToSkip = config.getInitParameter("zipPathToSkip");
    String fileParam = config.getInitParameter("file");
    if (StringUtils.isBlank(fileParam))
        throw new IllegalArgumentException("No file parameter found!");
    File file = null;/*  w  ww . ja  va2  s. c  o  m*/
    zipInfo = new HashMap<String, ZipEntry>();
    try {
        file = new File(config.getInitParameter("file"));
        if (!file.exists()) {
            throw new ServletException(String.format("Zip-file not found: %s", file.getPath()));
        }
        zipFile = new ZipFile(file);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry ze = entries.nextElement();
            String entryName = ze.getName();
            if (zipPathToSkip != null)
                entryName = entryName.substring(zipPathToSkip.length() + 1);
            if (entryName.startsWith("/"))
                entryName = entryName.substring(1);
            zipInfo.put(entryName, ze);
        }
        logger.debug("Found entries in zip: " + zipInfo.size());
    } catch (IOException e) {
        throw new ServletException("Couldn't read the zip file: " + e.getMessage(), e);
    }
    logger.info(String.format("ZipProxyServlet initialzed with file [%s] and path to skip [%s]", file.getPath(),
            zipPathToSkip));
}

From source file:com.github.ukase.toolkit.CompoundTemplateLoader.java

@Autowired
public CompoundTemplateLoader(UkaseSettings settings) throws IOException {
    File templates = settings.getTemplates();
    externalLoader = templates == null ? null : new FileTemplateLoader(templates);

    if (settings.getJar() == null) {
        zip = null;/*  w  w w .ja  v a 2 s  .co m*/
        return;
    }

    zip = new ZipFile(settings.getJar());
    zip.stream().forEach(this::registerResource);
}

From source file:asciidoc.maven.plugin.tools.ZipHelper.java

public void unzipArchive(File archive, File outputDir) {
    try {//from w w  w .j a  v a2  s  .co  m
        ZipFile zipfile = new ZipFile(archive);
        for (Enumeration<? extends ZipEntry> e = zipfile.entries(); e.hasMoreElements();) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            unzipEntry(zipfile, entry, outputDir);
        }
    } catch (Exception e) {
        this.log.error("Error while extracting file " + archive, e);
    }
}

From source file:com.gettingagile.tisugly.analyzer.ASMAnalyzer.java

private void loadClassesFromClasspathArchiveFile(File classpathElement) throws IOException {
    ZipFile f = new ZipFile(classpathElement.getAbsolutePath());
    Enumeration<? extends ZipEntry> en = f.entries();
    while (en.hasMoreElements()) {
        ZipEntry e = en.nextElement();
        String name = e.getName();
        if (name.endsWith(".class")) {
            new ClassReader(f.getInputStream(e)).accept(dependencyVisitor, 0);
        }//from   ww w . j ava2  s.co  m
    }
}

From source file:azkaban.execapp.ProjectVersion.java

public synchronized void setupProjectFiles(ProjectLoader projectLoader, File projectDir, Logger logger,
        ExecutableFlow flow) throws ProjectManagerException, IOException {
    String projectVersion = String.valueOf(projectId) + "." + String.valueOf(version);
    if (installedDir == null) {
        installedDir = new File(projectDir, projectVersion);
    }//from   w w w.j  a v a2 s  .com

    if (!installedDir.exists()) {

        logger.info("First time executing new project. Setting up in directory " + installedDir.getPath());

        File tempDir = new File(projectDir, "_temp." + projectVersion + "." + System.currentTimeMillis());
        tempDir.mkdirs();
        ProjectFileHandler projectFileHandler = null;
        FileOutputStream fos = null;
        try {
            projectFileHandler = projectLoader.getUploadedFile(projectId, version);
            if ("zip".equals(projectFileHandler.getFileType())) {
                logger.info("Downloading zip file.");
                ZipFile zip = new ZipFile(projectFileHandler.getLocalFile());
                Utils.unzip(zip, tempDir);
                fos = new FileOutputStream(
                        new File(tempDir.getAbsolutePath() + File.separator + "projectname"));
                fos.write(flow.getProjectName().getBytes());
                tempDir.renameTo(installedDir);
            } else {
                throw new IOException("The file type hasn't been decided yet.");
            }
        } finally {
            if (projectFileHandler != null) {
                projectFileHandler.deleteLocalFile();
            }
            if (fos != null) {
                fos.close();
            }
        }
    }
}