Example usage for java.util.zip ZipEntry ZipEntry

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

Introduction

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

Prototype

public ZipEntry(ZipEntry e) 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java

private void zipDir(final IFolder sourceDir, final ZipOutputStream zos, final String path)
        throws CoreException, IOException {

    for (final IResource f : sourceDir.members()) {
        if (f.getType() == IResource.FOLDER) {
            final String prefix = path + f.getName() + "/";
            zos.putNextEntry(new ZipEntry(prefix));
            zipDir((IFolder) f, zos, prefix);
        } else if (f.getType() == IResource.FILE) {
            final String entry = path + f.getName();
            if (JarFile.MANIFEST_NAME.equals(entry)) {
                continue;
            }//from w ww . j  a v a 2  s  .com
            final InputStream fis = ((IFile) f).getContents();
            try {
                final byte[] readBuffer = new byte[8192];
                int bytesIn = 0;
                final ZipEntry anEntry = new ZipEntry(entry);
                zos.putNextEntry(anEntry);
                while ((bytesIn = fis.read(readBuffer)) != -1) {
                    zos.write(readBuffer, 0, bytesIn);
                }
            } finally {
                IOUtils.closeQuietly(fis);
            }
        }
    }
}

From source file:com.diffplug.gradle.ZipMisc.java

/**
 * Modifies only the specified entries in a zip file. 
 *
 * @param input       a source from a zip file
 * @param output      an output to a zip file
 * @param toModify      a map from path to an input stream for the entries you'd like to change
 * @param toOmit      a set of entries you'd like to leave out of the zip
 * @throws IOException//from   ww  w.  j  av  a  2 s.  c om
 */
public static void modify(ByteSource input, ByteSink output, Map<String, Function<byte[], byte[]>> toModify,
        Predicate<String> toOmit) throws IOException {
    try (ZipInputStream zipInput = new ZipInputStream(input.openBufferedStream());
            ZipOutputStream zipOutput = new ZipOutputStream(output.openBufferedStream())) {
        while (true) {
            // read the next entry
            ZipEntry entry = zipInput.getNextEntry();
            if (entry == null) {
                break;
            }

            Function<byte[], byte[]> replacement = toModify.get(entry.getName());
            if (replacement != null) {
                byte[] clean = ByteStreams.toByteArray(zipInput);
                byte[] modified = replacement.apply(clean);
                // if it's the entry being modified, enter the modified stuff
                try (InputStream replacementStream = new ByteArrayInputStream(modified)) {
                    ZipEntry newEntry = new ZipEntry(entry.getName());
                    newEntry.setComment(entry.getComment());
                    newEntry.setExtra(entry.getExtra());
                    newEntry.setMethod(entry.getMethod());
                    newEntry.setTime(entry.getTime());

                    zipOutput.putNextEntry(newEntry);
                    copy(replacementStream, zipOutput);
                }
            } else if (!toOmit.test(entry.getName())) {
                // if it isn't being modified, just copy the file stream straight-up
                ZipEntry newEntry = new ZipEntry(entry);
                newEntry.setCompressedSize(-1);
                zipOutput.putNextEntry(newEntry);
                copy(zipInput, zipOutput);
            }

            // close the entries
            zipInput.closeEntry();
            zipOutput.closeEntry();
        }
    }
}

From source file:ZipUtilTest.java

public void testUnpackEntryFromFile() throws IOException {
    final String name = "foo";
    final byte[] contents = "bar".getBytes();

    File file = File.createTempFile("temp", null);
    try {/* w w w . j av a2  s  .co m*/
        // Create the ZIP file
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file));
        try {
            zos.putNextEntry(new ZipEntry(name));
            zos.write(contents);
            zos.closeEntry();
        } finally {
            IOUtils.closeQuietly(zos);
        }

        // Test the ZipUtil
        byte[] actual = ZipUtil.unpackEntry(file, name);
        assertNotNull(actual);
        assertEquals(new String(contents), new String(actual));
    } finally {
        FileUtils.deleteQuietly(file);
    }
}

From source file:de.uzk.hki.da.pkg.ZipArchiveBuilder.java

private void addFileToArchive(String path, File srcFile, ZipOutputStream zip, boolean includeFolder)
        throws Exception {

    if (srcFile.isDirectory()) {
        addFolderToArchive(path, srcFile, zip, includeFolder);
    } else {//  w  w w .ja  v a 2 s  .  c o  m
        byte[] buf = new byte[1024];
        int len;
        FileInputStream in = new FileInputStream(srcFile);
        zip.putNextEntry(new ZipEntry(path + "/" + srcFile.getName()));
        while ((len = in.read(buf)) > 0) {
            zip.write(buf, 0, len);
        }
        in.close();
    }

    zip.flush();

}

From source file:csns.web.controller.DownloadController.java

private long addToZip(ZipOutputStream zip, String dir, Collection<File> files) throws IOException {
    files = removeDuplicates(files);// w  w  w  .  j  a v a  2  s.  c o  m

    long totalSize = 0;
    for (File file : files) {
        ZipEntry entry = new ZipEntry(dir + "/" + file.getName());
        zip.putNextEntry(entry);
        fileIO.copy(file, zip);
        zip.closeEntry();
        totalSize += entry.getCompressedSize();
    }
    return totalSize;
}

From source file:com.android.build.gradle.internal.transforms.ExtractJarsTransformTest.java

@Test
public void checkWarningForPotentialIssuesOnCaseSensitiveFileSystems() throws Exception {
    File jar = temporaryFolder.newFile("Jar with case issues.jar");
    try (JarOutputStream jarOutputStream = new JarOutputStream(
            new BufferedOutputStream(new FileOutputStream(jar)))) {
        jarOutputStream.putNextEntry(new ZipEntry("com/example/a.class"));
        jarOutputStream.closeEntry();/*from   w  ww . jav  a 2 s.co  m*/
        jarOutputStream.putNextEntry(new ZipEntry("com/example/A.class"));
        jarOutputStream.closeEntry();
        jarOutputStream.putNextEntry(new ZipEntry("com/example/B.class"));
        jarOutputStream.closeEntry();
    }
    checkWarningForCaseIssues(jar, true /*expectingWarning*/);
}

From source file:net.gbmb.collector.example.SimpleLogPush.java

private String storeArchive(Collection collection) throws IOException {
    String cid = collection.getId();
    java.util.Collection<CollectionRecord> records = collectionRecords.get(cid);

    // index//from   w ww.  ja va 2  s .c o  m
    ByteArrayOutputStream indexStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    PrintStream output = new PrintStream(indexStream);
    // zip
    ByteArrayOutputStream archiveStream = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
    ZipOutputStream zos = new ZipOutputStream(archiveStream);
    output.println("Serialize collection: " + collection.getId());
    output.println("  creation date: " + collection.getCreationDate());
    output.println("  end date:      " + collection.getEndDate());
    for (CollectionRecord cr : records) {
        output.print(cr.getRecordDate());
        output.print(" ");
        output.println(cr.getContent());
        if (cr.getAttachment() != null) {
            String attName = cr.getAttachment();
            output.println("  > " + attName);
            ZipEntry entry = new ZipEntry(cr.getAttachment());
            zos.putNextEntry(entry);
            InputStream content = temporaryStorage.get(cid, attName);
            IOUtils.copy(content, zos);
        }
    }
    // add the index file
    output.close();
    ZipEntry index = new ZipEntry("index");
    zos.putNextEntry(index);
    IOUtils.write(indexStream.toByteArray(), zos);
    // close zip
    zos.close();
    ByteArrayInputStream content = new ByteArrayInputStream(archiveStream.toByteArray());

    // send to final storage
    return finalStorage.store(cid, content);
}

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);/*from  w w  w. ja v  a2 s  .c o m*/

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

    return Optional.empty();
}

From source file:de.tor.tribes.util.AttackToTextWriter.java

private static boolean writeBlocksToZip(List<String> pBlocks, Tribe pTribe, File pPath) {
    int fileNo = 1;
    String baseFilename = pTribe.getName().replaceAll("\\W+", "");
    ZipOutputStream zout = null;//from  ww  w  .  j  a  va 2s . c o m
    try {
        zout = new ZipOutputStream(
                new FileOutputStream(FilenameUtils.concat(pPath.getPath(), baseFilename + ".zip")));
        for (String block : pBlocks) {
            String entryName = baseFilename + fileNo + ".txt";
            ZipEntry entry = new ZipEntry(entryName);
            try {
                zout.putNextEntry(entry);
                zout.write(block.getBytes());
                zout.closeEntry();
            } catch (IOException ioe) {
                logger.error("Failed to write attack to zipfile", ioe);
                return false;
            }
            fileNo++;
        }
    } catch (IOException ioe) {
        logger.error("Failed to write content to zip file", ioe);
        return false;
    } finally {
        if (zout != null) {
            try {
                zout.flush();
                zout.close();
            } catch (IOException ignored) {
            }
        }
    }
    return true;
}

From source file:de.knowwe.revisions.manager.action.DownloadRevisionZip.java

/**
 * Zips the article contents from specified date and writes the resulting
 * zip-File to the ZipOutputStream.//w w w. j ava2 s  .  c  om
 * 
 * @created 22.04.2013
 * @param date
 * @param zos
 * @throws IOException
 */
private void zipRev(Date date, ZipOutputStream zos, UserActionContext context) throws IOException {
    RevisionManager revm = RevisionManager.getRM(context);
    ArticleManager am = revm.getArticleManager(date);
    Collection<Article> articles = am.getArticles();
    for (Article article : articles) {
        zos.putNextEntry(new ZipEntry(URLEncoder.encode(article.getTitle() + ".txt", "UTF-8")));
        zos.write(article.getRootSection().getText().getBytes("UTF-8"));
        zos.closeEntry();

        // Attachments
        Collection<WikiAttachment> atts = Environment.getInstance().getWikiConnector()
                .getAttachments(article.getTitle());
        for (WikiAttachment att : atts) {
            zos.putNextEntry(new ZipEntry(URLEncoder.encode(att.getParentName(), "UTF-8") + "-att/"
                    + URLEncoder.encode(att.getFileName(), "UTF-8")));
            IOUtils.copy(att.getInputStream(), zos);
            zos.closeEntry();
        }
    }
    zos.close();
}