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:jobhunter.persistence.Persistence.java

private Optional<List<Subscription>> _readSubscriptions(final File file) {

    try (ZipFile zfile = new ZipFile(file)) {
        l.debug("Reading subscriptions from JHF File");
        final InputStream in = zfile.getInputStream(new ZipEntry("subscriptions.xml"));

        MessageDigest md = MessageDigest.getInstance("MD5");
        DigestInputStream dis = new DigestInputStream(in, md);

        final Object obj = xstream.fromXML(dis);

        updateLastMod(file, md);//ww w  . jav  a 2 s .com

        return Optional.of(cast(obj));
    } catch (Exception e) {
        l.error("Failed to read file: {}", e.getMessage());
    }

    return Optional.empty();
}

From source file:fr.ippon.wip.config.dao.DeployConfigurationDecorator.java

/**
 * Retrieve all the configuration pasted in the deploy directory.
 * /* w ww . j  a  v a  2  s .  com*/
 * @return the configuration to deploy
 */
private synchronized void checkDeploy() {
    List<WIPConfiguration> deployedConfigurations = new ArrayList<WIPConfiguration>();
    for (File file : deployPath.listFiles(zipFilter)) {
        try {
            deployedConfigurations = unzip(new ZipFile(file));

        } catch (ZipException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    cleanDeployRepertory();
    for (WIPConfiguration newConfiguration : deployedConfigurations)
        super.create(newConfiguration);
}

From source file:de.onyxbits.raccoon.ptools.ToolSupport.java

private void unzip(File file) throws IOException {
    ZipFile zipFile = new ZipFile(file);
    try {//from   w  w w.  j  av a 2  s. c  o m
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            File entryDestination = new File(binDir, entry.getName());
            if (entry.isDirectory())
                entryDestination.mkdirs();
            else {
                entryDestination.getParentFile().mkdirs();
                InputStream in = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(entryDestination);
                IOUtils.copy(in, out);
                IOUtils.closeQuietly(in);
                out.close();
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:org.opentripplanner.graph_builder.model.GtfsBundle.java

public CsvInputSource getCsvInputSource() throws IOException {
    if (csvInputSource == null) {
        if (path != null) {
            csvInputSource = new ZipFileCsvInputSource(new ZipFile(path));
        } else if (url != null) {
            DownloadableGtfsInputSource isrc = new DownloadableGtfsInputSource();
            isrc.setUrl(url);//  w  ww  .j  a v a2 s. c  o  m
            if (cacheDirectory != null)
                isrc.setCacheDirectory(cacheDirectory);
            if (useCached != null)
                isrc.setUseCached(useCached);
            csvInputSource = isrc;
        }
    }
    return csvInputSource;
}

From source file:com.josue.lottery.eap.service.core.LotoImporter.java

private void readZip(File file) {

    ZipFile zipFile = null;/*from ww  w .j  a  v  a 2s  .  c o m*/
    try {
        logger.info("unzipping ************");

        zipFile = new ZipFile(file);

        File dataDir = new File(System.getProperty("jboss.server.data.dir"));
        File dest = new File(dataDir, "deziped.htm");

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

        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (entry.getName().endsWith(".HTM")) {

                InputStream stream = zipFile.getInputStream(entry);
                OutputStream oStr = null;
                try {
                    oStr = new FileOutputStream(dest);
                    IOUtils.copy(stream, oStr);

                    parseHtml(dest);

                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    IOUtils.closeQuietly(oStr);
                }
            }

        }
    } catch (IOException ex) {
        logger.error(ex);
    } finally {
        try {
            zipFile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:net.fabricmc.installer.installer.MultiMCInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress) throws Exception {
    File instancesDir = new File(mcDir, "instances");
    if (!instancesDir.exists()) {
        throw new FileNotFoundException(Translator.getString("install.multimc.notFound"));
    }/*  w  ww  . j a va2s . c o  m*/
    progress.updateProgress(Translator.getString("install.multimc.findInstances"), 10);
    String mcVer = version.split("-")[0];
    List<File> validInstances = new ArrayList<>();
    for (File instanceDir : instancesDir.listFiles()) {
        if (instanceDir.isDirectory()) {
            if (isValidInstance(instanceDir, mcVer)) {
                validInstances.add(instanceDir);
            }
        }
    }
    if (validInstances.isEmpty()) {
        throw new Exception(Translator.getString("install.multimc.noInstances").replace("[MCVER]", mcVer));
    }
    List<String> instanceNames = new ArrayList<>();
    for (File instance : validInstances) {
        instanceNames.add(instance.getName());
    }
    String instanceName = (String) JOptionPane.showInputDialog(null,
            Translator.getString("install.multimc.selectInstance"),
            Translator.getString("install.multimc.selectInstance"), JOptionPane.QUESTION_MESSAGE, null,
            instanceNames.toArray(), instanceNames.get(0));
    if (instanceName == null) {
        progress.updateProgress(Translator.getString("install.multimc.canceled"), 100);
        return;
    }
    progress.updateProgress(
            Translator.getString("install.multimc.installingInto").replace("[NAME]", instanceName), 25);
    File instnaceDir = null;
    for (File instance : validInstances) {
        if (instance.getName().equals(instanceName)) {
            instnaceDir = instance;
        }
    }
    if (instnaceDir == null) {
        throw new FileNotFoundException("Could not find " + instanceName);
    }
    File patchesDir = new File(instnaceDir, "patches");
    if (!patchesDir.exists()) {
        patchesDir.mkdir();
    }
    File fabricJar = new File(patchesDir, "Fabric-" + version + ".jar");
    if (!fabricJar.exists()) {
        progress.updateProgress(Translator.getString("install.client.downloadFabric"), 30);
        FileUtils.copyURLToFile(new URL("http://maven.modmuss50.me/net/fabricmc/fabric-base/" + version
                + "/fabric-base-" + version + ".jar"), fabricJar);
    }
    progress.updateProgress(Translator.getString("install.multimc.createJson"), 70);
    File fabricJson = new File(patchesDir, "fabric.json");
    if (fabricJson.exists()) {
        fabricJson.delete();
    }
    String json = readBaseJson();
    json = json.replaceAll("%VERSION%", version);

    ZipFile fabricZip = new ZipFile(fabricJar);
    ZipEntry dependenciesEntry = fabricZip.getEntry("dependencies.json");
    String fabricDeps = IOUtils.toString(fabricZip.getInputStream(dependenciesEntry), Charset.defaultCharset());
    json = json.replace("%DEPS%", stripDepsJson(fabricDeps.replace("\n", "")));
    FileUtils.writeStringToFile(fabricJson, json, Charset.defaultCharset());
    fabricZip.close();
    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:com.thoughtworks.go.server.initializers.PluginsZipInitializerTest.java

@Test
public void shouldZipAllPluginsIntoOneZipEveryTime() throws Exception {
    String expectedZipPath = TestFileUtil.createTempFile("go-plugins-all.zip").getAbsolutePath();
    File bundledPluginsDir = TestFileUtil.createTempFolder("plugins-bundled");
    File externalPluginsDir = TestFileUtil.createTempFolder("plugins-external");

    FileUtils.writeStringToFile(new File(bundledPluginsDir, "bundled1.jar"), "Bundled1");
    FileUtils.writeStringToFile(new File(bundledPluginsDir, "bundled2.jar"), "Bundled2");

    FileUtils.writeStringToFile(new File(externalPluginsDir, "external1.jar"), "External1");
    FileUtils.writeStringToFile(new File(externalPluginsDir, "external2.jar"), "External2");

    when(systemEnvironment.get(PLUGIN_GO_PROVIDED_PATH)).thenReturn(bundledPluginsDir.getAbsolutePath());
    when(systemEnvironment.get(PLUGIN_EXTERNAL_PROVIDED_PATH)).thenReturn(externalPluginsDir.getAbsolutePath());
    when(systemEnvironment.get(ALL_PLUGINS_ZIP_PATH)).thenReturn(expectedZipPath);

    pluginsZipInitializer.initialize();//from  w w  w  .ja  v a 2  s.  co m

    assertThat(expectedZipPath + " should exist", new File(expectedZipPath).exists(), is(true));
    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled1.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("bundled/bundled2.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external1.jar"), is(notNullValue()));
    assertThat(new ZipFile(expectedZipPath).getEntry("external/external2.jar"), is(notNullValue()));
}

From source file:com.aliyun.odps.local.common.utils.ArchiveUtils.java

/**
 * Given a File input it will unzip the file in a the unzip directory passed
 * as the second parameter//from w  w  w. j  a  va2  s .c  o m
 * 
 * @param inFile
 *          The zip file as input
 * @param unzipDir
 *          The unzip directory where to unzip the zip file.
 * @throws IOException
 */
public static void unZip(File inFile, File unzipDir) throws IOException {
    Enumeration<? extends ZipEntry> entries;
    ZipFile zipFile = new ZipFile(inFile);

    try {
        entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (!entry.isDirectory()) {
                InputStream in = zipFile.getInputStream(entry);
                try {
                    File file = new File(unzipDir, entry.getName());
                    if (!file.getParentFile().mkdirs()) {
                        if (!file.getParentFile().isDirectory()) {
                            throw new IOException("Mkdirs failed to create " + file.getParentFile().toString());
                        }
                    }
                    OutputStream out = new FileOutputStream(file);
                    try {
                        byte[] buffer = new byte[8192];
                        int i;
                        while ((i = in.read(buffer)) != -1) {
                            out.write(buffer, 0, i);
                        }
                    } finally {
                        out.close();
                    }
                } finally {
                    in.close();
                }
            }
        }
    } finally {
        zipFile.close();
    }
}

From source file:de.shadowhunt.subversion.internal.AbstractHelper.java

private void extractArchive(final File zip, final File prefix) throws Exception {
    final ZipFile zipFile = new ZipFile(zip);
    final Enumeration<? extends ZipEntry> enu = zipFile.entries();
    while (enu.hasMoreElements()) {
        final ZipEntry zipEntry = enu.nextElement();

        final String name = zipEntry.getName();

        final File file = new File(prefix, name);
        if (name.charAt(name.length() - 1) == Resource.SEPARATOR_CHAR) {
            if (!file.isDirectory() && !file.mkdirs()) {
                throw new IOException("can not create directory structure: " + file);
            }/*from   ww  w.  j  av  a  2  s .  com*/
            continue;
        }

        final File parent = file.getParentFile();
        if (parent != null) {
            if (!parent.isDirectory() && !parent.mkdirs()) {
                throw new IOException("can not create directory structure: " + parent);
            }
        }

        try (final InputStream is = zipFile.getInputStream(zipEntry)) {
            try (final OutputStream os = new FileOutputStream(file)) {
                IOUtils.copy(is, os);
            }
        }
    }
    zipFile.close();
}

From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java

public void executeReportTemplate(String templateId, ServerIfProvider serverIfProvider, ExportInfo exportInfo,
        int customerId, String customerName) throws Exception {
    ZipFile zipFile = null;//from   w  ww.  j  a  v a 2s  .c  om
    InputStream indexStream = null;
    InputStream requestStream = null;

    try {
        getZipFile(templateId, serverIfProvider, exportInfo, customerId);
        zipFile = new ZipFile(new File(zipFileName));

        // read the index xml
        indexStream = getInputStream(zipFile, "index.xml");
        if (indexStream != null) {
            templateIndexDef = ReportTemplateIndexDef.loadFromXML(indexStream);
        } else {
            logger.error("Unable to find the template index file.");
            throw new Exception("Unable to find the template index file.");
        }

        // read the request xml
        if (templateIndexDef != null) {
            String requestFileName = templateIndexDef.getXmlRequestFileName();
            if (requestFileName != null) {
                requestStream = getInputStream(zipFile, requestFileName);
                if (requestStream != null) {
                    templateRequestDef = ReportTemplateRequestDef.loadFromXML(requestStream);
                }
            }
        } else {
            logger.error("Unable to parse/ load the template index file.");
            throw new Exception("Unable to parse/ load the template index file.");
        }

        if (templateRequestDef != null) {
            VariableListDefinition varListDef = templateRequestDef.getVariableList();
            Map<String, VariableDefinition> varMap = null;
            if (varListDef != null) {
                varMap = varListDef.getVariables();
            }

            Map<String, String> varValues = new HashMap<String, String>();
            if (varMap != null) {
                for (String var : varMap.keySet()) {
                    VariableDefinition def = varMap.get(var);
                    if (def != null) {
                        varValues.put(var, def.getDefaultValue());
                    }
                }
            }

            ExportProgressMonitor exportProgressMonitor = new ExportProgressMonitor(templateRequestDef,
                    varValues, getDirectoryName(), ExportFormat.getEnumTypeFromExt(getExportFormat()),
                    serverIfProvider, exportInfo, customerId, customerName, templateId);
            Thread t = new Thread(exportProgressMonitor);
            t.start();

        } else {
            logger.error("Unable to parse/ load the template request file.");
            throw new Exception("Unable to parse/ load the template request file.");
        }
    } catch (Exception e) {
        logger.error("Report template execution failed.", e);
        throw new Exception("Report template execution failed");
    } finally {
        if (indexStream != null) {
            try {
                indexStream.close();
            } catch (IOException e) {
                logger.warn("Unable to close the InputStream " + indexStream);
            }
        }
        if (requestStream != null) {
            try {
                requestStream.close();
            } catch (IOException e) {
                logger.warn("Unable to close the InputStream " + requestStream);
            }
        }
        if (zipFile != null) {
            try {
                zipFile.close();
            } catch (IOException e) {
                logger.warn("Unable to close the Zip file.");
            }
        }
    }
}