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:net.sourceforge.jweb.maven.mojo.PropertiesOverideMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (disabled) {
        this.getLog().info("plugin was disabled");
        return;/*from  w  ww. j ava  2 s. com*/
    }
    processConfiguration();
    if (replacements.isEmpty()) {
        this.getLog().info("Nothing to replace with");
        return;
    }

    String name = this.builddir.getAbsolutePath() + File.separator + this.finalName + "." + this.packing;//the final package
    this.getLog().debug("final artifact: " + name);// the final package

    try {
        File finalWarFile = new File(name);
        File tempFile = File.createTempFile(finalWarFile.getName(), null);
        tempFile.delete();//check deletion
        boolean renameOk = finalWarFile.renameTo(tempFile);
        if (!renameOk) {
            getLog().error("Can not rename file, please check.");
            return;
        }

        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(finalWarFile));
        ZipFile zipFile = new ZipFile(tempFile);
        Enumeration<? extends ZipEntry> entries = zipFile.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();
            if (acceptMime(entry)) {
                getLog().info("applying replacements for " + entry.getName());
                InputStream inputStream = zipFile.getInputStream(entry);
                String src = IOUtils.toString(inputStream, encoding);
                //do replacement
                for (Entry<String, String> e : replacements.entrySet()) {
                    src = src.replaceAll("#\\{" + e.getKey() + "}", e.getValue());
                }
                out.putNextEntry(new ZipEntry(entry.getName()));
                IOUtils.write(src, out, encoding);
                inputStream.close();
            } else {
                //not repalce, just put entry back to out zip
                out.putNextEntry(entry);
                InputStream inputStream = zipFile.getInputStream(entry);
                byte[] buf = new byte[512];
                int len = -1;
                while ((len = inputStream.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                inputStream.close();
                continue;
            }
        }
        zipFile.close();
        out.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.datos.vfs.provider.zip.ZipFileSystem.java

protected ZipFile createZipFile(final File file) throws FileSystemException {
    try {//w  w w  .  j a  va2s  .  co m
        return new ZipFile(file);
    } catch (final IOException ioe) {
        throw new FileSystemException("vfs.provider.zip/open-zip-file.error", file, ioe);
    }
}

From source file:net.sf.zekr.engine.translation.TranslationData.java

/**
 * Verify the zip archive and close the zip file handle finally.
 * //from   ww w  . ja  va  2 s .  c o  m
 * @return <code>true</code> if translation verified, <code>false</code> otherwise.
 * @throws IOException
 */
public boolean verify() throws IOException {
    ZipFile zf = new ZipFile(archiveFile);
    ZipEntry ze = zf.getEntry(file);
    if (ze == null) {
        logger.error("Load failed. No proper entry found in \"" + archiveFile.getName() + "\".");
        return false;
    }

    byte[] textBuf = new byte[(int) ze.getSize()];
    boolean result;
    result = verify(zf.getInputStream(ze), textBuf);
    zf.close();
    return result;
}

From source file:de.egore911.versioning.deployer.performer.PerformCopy.java

private boolean copy(String uri, String target, String targetFilename) {
    URL url;/* ww w  .  j ava 2  s.co  m*/
    try {
        url = new URL(uri);
    } catch (MalformedURLException e) {
        LOG.error("Invalid URI: {}", e.getMessage(), e);
        return false;
    }
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        int response = connection.getResponseCode();

        int lastSlash = uri.lastIndexOf('/');
        if (lastSlash < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        int lastDot = uri.lastIndexOf('.');
        if (lastDot < 0) {
            LOG.error("Invalid URI: {}", uri);
            return false;
        }

        String filename;
        if (StringUtils.isEmpty(targetFilename)) {
            filename = uri.substring(lastSlash + 1);
        } else {
            filename = targetFilename;
        }

        XmlHolder xmlHolder = XmlHolder.getInstance();
        XPathExpression finalNameXpath = xmlHolder.xPath.compile("/project/build/finalName/text()");

        if (response == HttpURLConnection.HTTP_OK) {
            String downloadFilename = UrlUtil.concatenateUrlWithSlashes(target, filename);

            File downloadFile = new File(downloadFilename);
            FileUtils.forceMkdir(downloadFile.getParentFile());
            try (InputStream in = connection.getInputStream();
                    FileOutputStream out = new FileOutputStream(downloadFilename)) {
                IOUtils.copy(in, out);
            }
            LOG.debug("Downloaded {} to {}", url, downloadFilename);

            if (StringUtils.isEmpty(targetFilename)) {
                // Check if finalName if exists in pom.xml
                String destFile = null;
                try (ZipFile zipFile = new ZipFile(downloadFilename)) {
                    Enumeration<? extends ZipEntry> entries = zipFile.entries();
                    while (entries.hasMoreElements()) {
                        ZipEntry entry = entries.nextElement();
                        if (entry.getName().endsWith("/pom.xml")) {

                            String finalNameInPom;
                            try (InputStream inputStream = zipFile.getInputStream(entry)) {
                                try {
                                    MavenXpp3Reader mavenreader = new MavenXpp3Reader();
                                    Model model = mavenreader.read(inputStream);
                                    finalNameInPom = model.getBuild().getFinalName();
                                } catch (Exception e) {
                                    Document doc = xmlHolder.documentBuilder.parse(inputStream);
                                    finalNameInPom = (String) finalNameXpath.evaluate(doc,
                                            XPathConstants.STRING);
                                }
                            }

                            if (StringUtils.isNotEmpty(finalNameInPom)) {
                                destFile = UrlUtil.concatenateUrlWithSlashes(target,
                                        finalNameInPom + "." + uri.substring(lastDot + 1));
                            }
                            break;
                        }
                    }
                }

                // Move file to finalName if existed in pom.xml
                if (destFile != null) {
                    try {
                        File dest = new File(destFile);
                        if (dest.exists()) {
                            FileUtils.forceDelete(dest);
                        }
                        FileUtils.moveFile(downloadFile.getAbsoluteFile(), dest.getAbsoluteFile());
                        LOG.debug("Moved file from {} to {}", downloadFilename, destFile);
                    } catch (IOException e) {
                        LOG.error("Failed to move file to it's final name: {}", e.getMessage(), e);
                    }
                }
            }

            return true;
        } else {
            LOG.error("Could not download file: {}", uri);
            return false;
        }
    } catch (SAXException | IOException | XPathExpressionException e) {
        LOG.error("Could not download file ({}): {}", uri, e.getMessage(), e);
        return false;
    }
}

From source file:com.genericworkflownodes.knime.nodes.io.outputfile.OutputFileNodeModel.java

/**
 * {@inheritDoc}//from  w  ww .  ja va2s.  c  om
 */
@Override
protected void loadInternals(final File internDir, final ExecutionMonitor exec)
        throws IOException, CanceledExecutionException {
    ZipFile zip = new ZipFile(new File(internDir, "loadeddata"));

    @SuppressWarnings("unchecked")
    Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zip.entries();

    int BUFFSIZE = 2048;
    byte[] BUFFER = new byte[BUFFSIZE];

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

        if (entry.getName().equals("rawdata.bin")) {
            int size = (int) entry.getSize();
            byte[] data = new byte[size];
            InputStream in = zip.getInputStream(entry);
            int len;
            int totlen = 0;
            while ((len = in.read(BUFFER, 0, BUFFSIZE)) >= 0) {
                System.arraycopy(BUFFER, 0, data, totlen, len);
                totlen += len;
            }
            this.data = new String(data);
        }
    }
    zip.close();
}

From source file:com.sshtools.j2ssh.authentication.UserGridCredential.java

private static void checkCACertificates(CoGProperties cogproperties) throws IOException {
    // check the directories exist and create if they don't
    String globusDir = System.getProperty("user.home") + "/.globus";
    if (!(new File(globusDir).exists())) {
        boolean success = (new File(globusDir).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + globusDir);
        }/*from   w ww  .ja v  a2  s . co  m*/
    }
    String caCertLocations = globusDir + "/certificates";
    File caCertLocationsF = new File(caCertLocations);
    if (!caCertLocationsF.exists()) {
        boolean success = (new File(caCertLocations).mkdir());
        if (!success) {
            throw new IOException("Couldn't create directory: " + caCertLocations);
        }
    }
    if (!caCertLocationsF.isDirectory()) {
        throw new IOException("Location: " + caCertLocations + " is not a directory");
    }
    File tmp = null;
    try {
        // save the zipfile temporarily
        tmp = File.createTempFile("certificates", ".zip");
        copyFile(thisDummy.getClass().getResourceAsStream("certificates.zip"), new FileOutputStream(tmp));
        ZipFile zf = new ZipFile(tmp);
        try {
            Enumeration e = zf.entries();
            while (e.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) e.nextElement();
                String name = ze.getName();
                if (!(new File(caCertLocations + File.separator + name).exists())) {
                    copyFile(zf.getInputStream(ze),
                            new FileOutputStream(new File(caCertLocations + File.separator + name)));
                }
            }
        } finally {
            if (zf != null)
                zf.close();
        }
    } catch (IOException e) {
        throw new IOException("Couldn't load certificates... " + e);
    } finally {
        // delete temp file
        if (tmp != null) {
            if (tmp.exists())
                tmp.delete();
        }
    }
}

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

@Test
public void canExcludeEmptyDirectories() throws Exception {
    IarPackagingMojo mojo = rule.getMojo();
    mojo.iarIncludesEmptyDirs = false;//from  www . j a v  a  2 s  .c  o m
    mojo.execute();

    try (ZipFile archive = new ZipFile(mojo.project.getArtifact().getFile())) {
        assertThat(archive.getEntry("src_hd")).as("Empty directory should be excluded by mojo configuration")
                .isNull();
    }
}

From source file:ch.entwine.weblounge.maven.MyGengoI18nImport.java

private ZipFile extractZipFileFromConn(URLConnection conn) {
    if (conn != null) {
        try {//from   w w  w.j  a  v  a2  s .  c o  m
            File temp = File.createTempFile("mygengo-i18n", ".zip");
            temp.deleteOnExit();
            FileOutputStream fos = new FileOutputStream(temp);
            IOUtils.copy(conn.getInputStream(), fos);
            return new ZipFile(temp);
        } catch (IOException e) {
            log.error("Error reading zip file from response.");
            return null;
        }
    } else {
        return null;
    }
}

From source file:de.dfki.km.perspecting.obie.corpus.LabeledTextCorpus.java

public Reader getGroundTruth(final URI uri) throws Exception {
    if (labelFileMediaType == MediaType.DIRECTORY) {
        return new StringReader(FileUtils.readFileToString(new File(uri)));
    } else if (labelFileMediaType == MediaType.ZIP) {
        ZipFile zipFile = new ZipFile(labelFolder);
        String[] entryName = uri.toURL().getFile().split("/");
        ZipEntry entry = zipFile.getEntry(URLDecoder.decode(entryName[entryName.length - 1], "utf-8"));

        if (entry != null) {
            log.info("found labels for: " + uri.toString());
        } else {/*w w w  . j  a  v a2s  . co m*/
            throw new Exception("did not found labels for: " + uri.toString());
        }
        return new InputStreamReader(zipFile.getInputStream(entry));
    } else {
        throw new Exception("Unsupported media format for labels: " + labelFileMediaType + ". "
                + "Please use zip or plain directories instead.");
    }
}

From source file:com.openmeap.file.FileOperationManagerImplTest.java

/**
 * Validates that a zip file can be extracted and at a prefix location within the store.
 * @throws FileOperationException/*w  w w .  j av  a  2  s. c  o  m*/
 * @throws IOException
 */
@Test
public void testUnzip() throws FileOperationException, IOException {
    mgr.begin();
    mgr.unzipFile(new ZipFile(this.getClass().getResource("zipped.zip").getFile()), "");
    mgr.commit();
    Assert.assertTrue(new File(STOREDIR + File.separator + "zipped/alpha.txt").exists());
    Assert.assertTrue(new File(STOREDIR + File.separator + "zipped/quick-fox.txt").exists());

    mgr.begin();
    mgr.unzipFile(new ZipFile(this.getClass().getResource("zipped.zip").getFile()), "prefix");
    mgr.commit();
    Assert.assertTrue(new File(STOREDIR + File.separator + "prefix/zipped/alpha.txt").exists());
    Assert.assertTrue(new File(STOREDIR + File.separator + "prefix/zipped/quick-fox.txt").exists());
}