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:ch.jamiete.hilda.plugins.PluginManager.java

/**
 * Attempts to load plugin data from the {@code plugin.json} file.
 * @param file//from w  ww  .  j  av a  2 s  .co m
 * @return the plugin data or {@code null} if no data could be loaded
 * @throws IllegalArgumentException if any of the conditions of a plugin data file are not met
 */
private PluginData loadPluginData(final File file) {
    PluginData data = null;

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

        while (entries.hasMoreElements()) {
            final ZipEntry entry = entries.nextElement();
            final InputStream stream = zipFile.getInputStream(entry);

            if (entry.getName().equals("plugin.json")) {
                data = new Gson().fromJson(IOUtils.toString(stream, Charset.defaultCharset()),
                        PluginData.class);

                Sanity.nullCheck(data.name, "A plugin must define its name.");
                Sanity.nullCheck(data.mainClass, "A plugin must define its main class.");
                Sanity.nullCheck(data.version, "A plugin must define its version.");
                Sanity.nullCheck(data.author, "A plugin must define its author.");

                data.pluginFile = file;

                if (data.dependencies == null) {
                    data.dependencies = new String[0];
                }
            }
        }

        zipFile.close();
    } catch (final Exception ex) {
        Hilda.getLogger().log(Level.SEVERE,
                "Encountered exception when trying to load plugin JSON for " + file.getName(), ex);
    }

    return data;
}

From source file:simpleserver.minecraft.MinecraftWrapper.java

private boolean verifyMinecraftJar() {
    if (getServerJar() != SERVER_JAR) {
        return true;
    }// w  w w .j  a va2  s . c om

    boolean valid = false;
    try {
        ZipFile jar = new ZipFile(SERVER_JAR);
        valid = jar.size() > 200;
        jar.close();
    } catch (IOException e) {
    }

    return valid;
}

From source file:com.flexive.tests.disttools.DistPackageTest.java

private ZipFile getDistFile() throws IOException {
    final String name = System.getProperty("flexive.test.dist.file");
    Assert.assertTrue(StringUtils.isNotBlank(name), "flexive.test.dist.file property not set.");
    return new ZipFile(name);
}

From source file:hudson.model.DirectoryBrowserSupportTest.java

@Issue("JENKINS-19752")
@Test/*  w  ww  .j  a v a 2s. c  o m*/
public void zipDownload() throws Exception {
    FreeStyleProject p = j.createFreeStyleProject();
    p.setScm(new SingleFileSCM("artifact.out", "Hello world!"));
    p.getPublishersList().add(new ArtifactArchiver("*", "", true));
    assertEquals(Result.SUCCESS, p.scheduleBuild2(0).get().getResult());

    HtmlPage page = j.createWebClient().goTo("job/" + p.getName() + "/lastSuccessfulBuild/artifact/");
    Page download = page.getAnchorByHref("./*zip*/archive.zip").click();
    File zipfile = download((UnexpectedPage) download);

    ZipFile readzip = new ZipFile(zipfile);

    InputStream is = readzip.getInputStream(readzip.getEntry("archive/artifact.out"));

    // ZipException in case of JENKINS-19752
    assertFalse("Downloaded zip file must not be empty", is.read() == -1);

    is.close();
    readzip.close();
    zipfile.delete();
}

From source file:com.dreikraft.axbo.sound.SoundPackageUtil.java

/**
 * Extracts the packageFile and writes its content in temporary directory
 *
 * @param packageFile the packageFile (zip format)
 * @param tempDir the tempDir directory//w  ww  .  jav a2  s .co m
 */
public static void extractPackage(File packageFile, File tempDir) throws SoundPackageException {

    if (packageFile == null) {
        throw new SoundPackageException(new IllegalArgumentException("missing package file"));
    }

    ZipFile packageZip = null;
    try {
        packageZip = new ZipFile(packageFile);
        Enumeration<?> entries = packageZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            String entryName = entry.getName();
            if (log.isDebugEnabled()) {
                log.debug("ZipEntry name: " + entryName);
            }
            if (entry.isDirectory()) {
                File dir = new File(tempDir, entryName);
                if (dir.mkdirs())
                    log.info("successfully created dir: " + dir.getAbsolutePath());
            } else {
                FileUtil.createFileFromInputStream(getPackageEntryStream(packageFile, entryName),
                        tempDir + File.separator + entryName);
            }
        }
    } catch (FileNotFoundException ex) {
        throw new SoundPackageException(ex);
    } catch (IOException ex) {
        throw new SoundPackageException(ex);
    } finally {
        try {
            if (packageZip != null)
                packageZip.close();
        } catch (IOException ex) {
            log.error(ex.getMessage(), ex);
        }
    }
}

From source file:gdt.data.entity.facet.ExtensionHandler.java

public static String loadIcon(Entigrator entigrator, String extension$, String resource$) {
    try {//from   ww w .jav  a  2  s  . c  o m

        //System.out.println("ExtensionHandler:loadIcon:extension="+extension$+" handler="+handlerClass$);
        Sack extension = entigrator.getEntityAtKey(extension$);
        String lib$ = extension.getElementItemAt("field", "lib");
        String jar$ = entigrator.getEntihome() + "/" + extension$ + "/" + lib$;
        //      System.out.println("ExtensionHandler:loadIcon:jar="+jar$);
        ZipFile zf = new ZipFile(jar$);
        Enumeration<? extends ZipEntry> entries = zf.entries();
        ZipEntry ze;
        String[] sa;
        while (entries.hasMoreElements()) {
            try {
                ze = entries.nextElement();
                sa = ze.getName().split("/");
                //         System.out.println("ExtensionHandler:loadIcon:zip entry="+sa[sa.length-1]);
                if (resource$.equals(sa[sa.length - 1])) {
                    InputStream is = zf.getInputStream(ze);
                    //            System.out.println("ExtensionHandler:loadIcon:input stream="+is.toString());
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    byte[] b = new byte[1024];
                    int bytesRead = 0;
                    while ((bytesRead = is.read(b)) != -1) {
                        bos.write(b, 0, bytesRead);
                    }
                    byte[] ba = bos.toByteArray();
                    is.close();
                    return Base64.encodeBase64String(ba);
                }
            } catch (Exception e) {

            }
        }
        return null;
    } catch (Exception e) {
        Logger.getLogger(ExtensionHandler.class.getName()).severe(e.toString());
        return null;
    }

}

From source file:io.druid.java.util.common.CompressionUtils.java

/**
 * Unzip the pulled file to an output directory. This is only expected to work on zips with lone files, and is not intended for zips with directory structures.
 *
 * @param pulledFile The file to unzip/*from w  ww.  ja v  a2 s  .com*/
 * @param outDir     The directory to store the contents of the file.
 *
 * @return a FileCopyResult of the files which were written to disk
 *
 * @throws IOException
 */
public static FileUtils.FileCopyResult unzip(final File pulledFile, final File outDir) throws IOException {
    if (!(outDir.exists() && outDir.isDirectory())) {
        throw new ISE("outDir[%s] must exist and be a directory", outDir);
    }
    log.info("Unzipping file[%s] to [%s]", pulledFile, outDir);
    final FileUtils.FileCopyResult result = new FileUtils.FileCopyResult();
    try (final ZipFile zipFile = new ZipFile(pulledFile)) {
        final Enumeration<? extends ZipEntry> enumeration = zipFile.entries();
        while (enumeration.hasMoreElements()) {
            final ZipEntry entry = enumeration.nextElement();
            final File outFile = new File(outDir, entry.getName());

            validateZipOutputFile(pulledFile.getCanonicalPath(), outFile, outDir);

            result.addFiles(FileUtils.retryCopy(new ByteSource() {
                @Override
                public InputStream openStream() throws IOException {
                    return new BufferedInputStream(zipFile.getInputStream(entry));
                }
            }, outFile, FileUtils.IS_EXCEPTION, DEFAULT_RETRY_COUNT).getFiles());
        }
    }
    return result;
}

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

/**
 * Copy zip file and remove ignored files
 *
 * @param srcFile/*  ww  w . j av a2  s.c o  m*/
 * @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();
    }
}

From source file:com.codelanx.codelanxlib.util.Reflections.java

/**
 * Checks whether or not there is a plugin on the server with the name of
 * the passed {@code name} paramater. This method achieves this by scanning
 * the plugins folder and reading the {@code plugin.yml} files of any
 * respective jarfiles in the directory.
 * /*from   w  ww .ja  va 2s.c  o  m*/
 * @since 0.1.0
 * @version 0.1.0
 * 
 * @param name The name of the plugin as specified in the {@code plugin.yml}
 * @return The {@link File} for the plugin jarfile, or {@code null} if not
 *         found
 */
public static File findPluginJarfile(String name) {
    File plugins = new File("plugins");
    Exceptions.illegalState(plugins.isDirectory(), "'plugins' isn't a directory! (wat)");
    for (File f : plugins.listFiles((File pathname) -> {
        return pathname.getPath().endsWith(".jar");
    })) {
        try (InputStream is = new FileInputStream(f); ZipInputStream zi = new ZipInputStream(is)) {
            ZipEntry ent = null;
            while ((ent = zi.getNextEntry()) != null) {
                if (ent.getName().equalsIgnoreCase("plugin.yml")) {
                    break;
                }
            }
            if (ent == null) {
                continue; //no plugin.yml found
            }
            ZipFile z = new ZipFile(f);
            try (InputStream fis = z.getInputStream(ent);
                    InputStreamReader fisr = new InputStreamReader(fis);
                    BufferedReader scan = new BufferedReader(fisr)) {
                String in;
                while ((in = scan.readLine()) != null) {
                    if (in.startsWith("name: ")) {
                        if (in.substring(6).equalsIgnoreCase(name)) {
                            return f;
                        }
                    }
                }
            }
        } catch (IOException ex) {
            Debugger.error(ex, "Error reading plugin jarfiles");
        }
    }
    return null;
}

From source file:es.eucm.eadandroid.homeapp.repository.resourceHandler.RepoResourceHandler.java

/**
 * Uncompresses any zip file/*from  w w  w .  j av  a2 s  . co  m*/
 */
public static void unzip(String path_from, String path_to, String name, boolean deleteZip) {

    StringTokenizer separator = new StringTokenizer(name, ".", true);
    String file_name = separator.nextToken();

    File f = new File(path_to + file_name);

    if (f.exists())
        removeDirectory(f);

    separator = new StringTokenizer(path_to + file_name, "/", true);

    String partial_path = null;
    String total_path = separator.nextToken();

    while (separator.hasMoreElements()) {

        partial_path = separator.nextToken();
        total_path = total_path + partial_path;
        if (!new File(total_path).exists()) {

            if (separator.hasMoreElements())
                total_path = total_path + separator.nextToken();
            else
                (new File(total_path)).mkdir();

        } else
            total_path = total_path + separator.nextToken();

    }

    Enumeration<? extends ZipEntry> entries = null;
    ZipFile zipFile = null;

    try {
        String location_ead = path_from + name;
        zipFile = new ZipFile(location_ead);

        entries = zipFile.entries();

        BufferedOutputStream file;

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            separator = new StringTokenizer(entry.getName(), "/", true);
            partial_path = null;
            total_path = "";

            while (separator.hasMoreElements()) {

                partial_path = separator.nextToken();
                total_path = total_path + partial_path;
                if (!new File(entry.getName()).exists()) {

                    if (separator.hasMoreElements()) {
                        total_path = total_path + separator.nextToken();
                        (new File(path_to + file_name + "/" + total_path)).mkdir();
                    } else {

                        file = new BufferedOutputStream(
                                new FileOutputStream(path_to + file_name + "/" + total_path));

                        System.err.println("Extracting file: " + entry.getName());
                        copyInputStream(zipFile.getInputStream(entry), file);
                    }
                } else {
                    total_path = total_path + separator.nextToken();
                }
            }

        }

        zipFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        return;
    }

    if (deleteZip)
        (new File(path_from + name)).delete();

}