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:ee.ria.xroad.common.asic.AsicHelper.java

private static void addEntry(ZipOutputStream zip, String name, byte[] data) throws IOException {
    zip.putNextEntry(new ZipEntry(name));
    zip.write(data);/*from   w w  w. jav  a 2 s  .c  o  m*/
}

From source file:com.esofthead.mycollab.vaadin.resources.StreamDownloadResourceSupportExtDrive.java

private void addFileToZip(String path, Content res, ZipOutputStream zip) throws Exception {
    byte[] buf = new byte[1024];
    InputStream contentStream;//from   w  w w  .j a  v a  2  s  . co m
    if (!res.isExternalResource()) {
        contentStream = resourceService.getContentStream(res.getPath());
    } else {
        ExternalResourceService service = ResourceUtils.getExternalResourceService(ResourceUtils.getType(res));
        contentStream = service.download(ResourceUtils.getExternalDrive(res), res.getPath());
    }
    if (path.length() == 0)
        path = res.getName();
    else
        path += "/" + res.getName();
    zip.putNextEntry(new ZipEntry(path));
    int byteLength;
    while ((byteLength = contentStream.read(buf)) > 0) {
        zip.write(buf, 0, byteLength);
    }
}

From source file:com.adobe.communities.ugc.migration.export.GenericExportServlet.java

protected void exportContent(Resource rootNode, final String rootPath) throws IOException, ServletException {

    final String relPath = rootNode.getPath()
            .substring(rootNode.getPath().indexOf(rootPath) + rootPath.length());
    String entryName = relPath.isEmpty() ? "root.json" : relPath + ".json";
    responseWriter = new OutputStreamWriter(zip);
    final JSONWriter writer = new JSONWriter(responseWriter);
    writer.setTidy(true);// w ww.  j  a v  a 2 s.  c  o m
    try {
        if (rootNode.isResourceType(VotingSocialComponent.VOTING_RESOURCE_TYPE)) {
            if (rootNode.hasChildren()) {
                zip.putNextEntry(new ZipEntry(entryName));
                final JSONWriter tallyNode = writer.object();
                tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE);
                tallyNode.value(ContentTypeDefinitions.LABEL_TALLY);
                tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT);
                final JSONWriter responseArray = tallyNode.array();
                UGCExportHelper.extractTally(responseArray, rootNode, "Voting");
                tallyNode.endArray();
                writer.endObject();
                responseWriter.flush();
                zip.closeEntry();
            }
        } else if (rootNode.isResourceType(RatingSocialComponent.RATING_RESOURCE_TYPE)) {
            if (rootNode.hasChildren()) {
                zip.putNextEntry(new ZipEntry(entryName));
                final JSONWriter tallyNode = writer.object();
                tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE);
                tallyNode.value(ContentTypeDefinitions.LABEL_TALLY);
                tallyNode.key(ContentTypeDefinitions.LABEL_CONTENT);
                final JSONWriter responseArray = tallyNode.array();
                UGCExportHelper.extractTally(responseArray, rootNode, "Rating");
                tallyNode.endArray();
                writer.endObject();
                responseWriter.flush();
                zip.closeEntry();
            }
        } else if (rootNode.isResourceType(Calendar.RESOURCE_TYPE)) {
            final CommentSystem commentSystem = rootNode.adaptTo(CommentSystem.class);
            int commentSize = commentSystem.countComments();
            if (commentSize == 0) {
                return;
            }
            List<com.adobe.cq.social.commons.Comment> comments = commentSystem.getComments(0, commentSize);
            zip.putNextEntry(new ZipEntry(entryName));
            final JSONWriter calendarNode = writer.object();
            calendarNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE);
            calendarNode.value(ContentTypeDefinitions.LABEL_CALENDAR);
            calendarNode.key(ContentTypeDefinitions.LABEL_CONTENT);
            JSONWriter eventObjects = calendarNode.array();
            for (final com.adobe.cq.social.commons.Comment comment : comments) {
                final Resource eventResource = comment.getResource();
                UGCExportHelper.extractEvent(eventObjects.object(), eventResource,
                        rootNode.getResourceResolver(), responseWriter, socialUtils);
                eventObjects.endObject();
            }
            calendarNode.endArray();
            writer.endObject();
            responseWriter.flush();
            zip.closeEntry();
        } else if (rootNode.isResourceType(Comment.COMMENTCOLLECTION_RESOURCETYPE)) {
            final CommentSystem commentSystem = rootNode.adaptTo(CommentSystem.class);
            int commentSize = commentSystem.countComments();
            if (commentSize == 0) {
                return;
            }

            List<com.adobe.cq.social.commons.Comment> comments = commentSystem.getComments(0, commentSize);
            zip.putNextEntry(new ZipEntry(entryName));
            final JSONWriter commentsNode = writer.object();
            commentsNode.key(ContentTypeDefinitions.LABEL_CONTENT_TYPE);
            if (rootNode.isResourceType(Journal.RESOURCE_TYPE)) {
                commentsNode.value(ContentTypeDefinitions.LABEL_JOURNAL);
            } else if (rootNode.isResourceType(QnaPost.RESOURCE_TYPE)) {
                commentsNode.value(ContentTypeDefinitions.LABEL_QNA_FORUM);
            } else if (rootNode.isResourceType(Forum.RESOURCE_TYPE)) {
                commentsNode.value(ContentTypeDefinitions.LABEL_FORUM);
            } else if (rootNode.isResourceType(FileLibrary.RESOURCE_TYPE_FILELIBRARY)) {
                commentsNode.value(ContentTypeDefinitions.LABEL_FILELIBRARY);
            } else {
                commentsNode.value(ContentTypeDefinitions.LABEL_COMMENTS);
            }
            commentsNode.key(ContentTypeDefinitions.LABEL_CONTENT);
            commentsNode.object();
            for (final com.adobe.cq.social.commons.Comment comment : comments) {
                commentsNode.key(comment.getId());
                final JSONWriter postObject = commentsNode.object();
                UGCExportHelper.extractComment(postObject, comment, rootNode.getResourceResolver(),
                        responseWriter, socialUtils);
                commentsNode.endObject();
            }
            commentsNode.endObject();
            writer.endObject();
            responseWriter.flush();
            zip.closeEntry();
        } else {
            for (final Resource resource : rootNode.getChildren()) {
                exportContent(resource, rootPath);
            }
        }
    } catch (final JSONException e) {
        throw new ServletException(e);
    }
}

From source file:gov.nih.nci.caarray.services.external.v1_0.grid.client.GridDataApiUtils.java

private static void addToZip(TransferServiceContextReference transferRef, ZipOutputStream zostream)
        throws IOException, DataTransferException {
    TransferServiceContextClient tclient = null;
    try {//w ww . j  av a  2  s  .co  m
        tclient = new TransferServiceContextClient(transferRef.getEndpointReference());
        DataTransferDescriptor dd = tclient.getDataTransferDescriptor();
        zostream.putNextEntry(new ZipEntry(dd.getDataDescriptor().getName()));
        readFully(dd, zostream, true);
    } finally {
        if (tclient != null) {
            tclient.destroy();
        }
    }
}

From source file:JarUtils.java

/**
 * This recursive method writes all matching files and directories to
 * the jar output stream.//from w  w w .j a  v  a2s  .  c om
 */
private static void jar(File src, String prefix, JarInfo info) throws IOException {

    JarOutputStream jout = info.out;
    if (src.isDirectory()) {
        // create / init the zip entry
        prefix = prefix + src.getName() + "/";
        ZipEntry entry = new ZipEntry(prefix);
        entry.setTime(src.lastModified());
        entry.setMethod(JarOutputStream.STORED);
        entry.setSize(0L);
        entry.setCrc(0L);
        jout.putNextEntry(entry);
        jout.closeEntry();

        // process the sub-directories
        File[] files = src.listFiles(info.filter);
        for (int i = 0; i < files.length; i++) {
            jar(files[i], prefix, info);
        }
    } else if (src.isFile()) {
        // get the required info objects
        byte[] buffer = info.buffer;

        // create / init the zip entry
        ZipEntry entry = new ZipEntry(prefix + src.getName());
        entry.setTime(src.lastModified());
        jout.putNextEntry(entry);

        // dump the file
        FileInputStream in = new FileInputStream(src);
        int len;
        while ((len = in.read(buffer, 0, buffer.length)) != -1) {
            jout.write(buffer, 0, len);
        }
        in.close();
        jout.closeEntry();
    }
}

From source file:de.thorstenberger.examServer.webapp.action.PDFBulkExport.java

/**
 * Call the taskmodel-core-view application via http for every user, that has processed the given task. Streams a zip
 * archive with all rendered pdf files to <code>os</code>.
 *
 * @param tasklets/*from  www . jav a 2 s  .  com*/
 *          all tasklets to render
 * @param os
 *          the outputstream the zip shall be written to
 * @param pdfExporter
 * @throws IOException
 */
private void renderAllPdfs(final List<Tasklet> tasklets, final OutputStream os, final PDFExporter pdfExporter)
        throws IOException {
    // create zip with all generated pdfs
    final ZipOutputStream zos = new ZipOutputStream(os);

    // fetch pdf for every user/tasklet
    // render a pdf for every user that has a tasklet for the current task
    for (final Tasklet tasklet : tasklets) {
        final String userId = tasklet.getUserId();

        if (!tasklet.hasOrPassedStatus(Status.INPROGRESS)) {
            log.info(String.format("Skipping PDF for user %s, last try has no contents.", userId));
            continue;
        }
        log.debug("exporting pdf for " + userId);

        // add new zipentry (for next pdf)
        if (!addGeneratedPDFS(tasklet, userId, zos)) {
            final String filename = userId + ".pdf";
            final ZipEntry ze = new ZipEntry(filename);
            zos.putNextEntry(ze);
            // fetch the generated pdf from taskmodel-core-view
            pdfExporter.renderPdf(tasklet, filename, zos);
            // close this zipentry
            zos.closeEntry();
        }
    }
    zos.close();
}

From source file:com.xpn.xwiki.export.html.HtmlPackager.java

/**
 * Add rendered document to ZIP stream.//from  w ww .j av a 2s  .  com
 * 
 * @param pageName the name (used with {@link com.xpn.xwiki.XWiki#getDocument(String, XWikiContext)}) of the page to
 *            render.
 * @param zos the ZIP output stream.
 * @param context the XWiki context.
 * @param vcontext the Velocity context.
 * @throws XWikiException error when rendering document.
 * @throws IOException error when rendering document.
 */
private void renderDocument(String pageName, ZipOutputStream zos, XWikiContext context,
        VelocityContext vcontext) throws XWikiException, IOException {
    @SuppressWarnings("unchecked")
    EntityReferenceResolver<String> resolver = Utils.getComponent(EntityReferenceResolver.class);
    DocumentReference docReference = new DocumentReference(resolver.resolve(pageName, EntityType.DOCUMENT));
    XWikiDocument doc = context.getWiki().getDocument(docReference, context);

    String zipname = doc.getDocumentReference().getWikiReference().getName();
    for (EntityReference space : doc.getDocumentReference().getSpaceReferences()) {
        zipname += POINT + space.getName();
    }
    zipname += POINT + doc.getDocumentReference().getName();
    String language = doc.getLanguage();
    if (language != null && language.length() != 0) {
        zipname += POINT + language;
    }

    zipname += ".html";

    ZipEntry zipentry = new ZipEntry(zipname);
    zos.putNextEntry(zipentry);

    String originalDatabase = context.getDatabase();
    try {
        context.setDatabase(doc.getDocumentReference().getWikiReference().getName());
        context.setDoc(doc);
        vcontext.put(VCONTEXT_DOC, doc.newDocument(context));
        vcontext.put(VCONTEXT_CDOC, vcontext.get(VCONTEXT_DOC));

        XWikiDocument tdoc = doc.getTranslatedDocument(context);
        context.put(CONTEXT_TDOC, tdoc);
        vcontext.put(VCONTEXT_TDOC, tdoc.newDocument(context));

        String content = context.getWiki().evaluateTemplate("view.vm", context);

        zos.write(content.getBytes(context.getWiki().getEncoding()));
        zos.closeEntry();
    } finally {
        context.setDatabase(originalDatabase);
    }
}

From source file:it.reply.orchestrator.service.ToscaServiceImpl.java

/**
 * Utility to zip an inputStream.//  www  .  j a  v  a  2s. c  o  m
 * 
 */
public static void zip(@Nonnull InputStream fileStream, @Nonnull Path outputPath) throws IOException {
    FileUtil.touch(outputPath);
    try (ZipOutputStream zipOutputStream = new ZipOutputStream(
            new BufferedOutputStream(Files.newOutputStream(outputPath)))) {
        zipOutputStream.putNextEntry(new ZipEntry("definition.yml"));
        ByteStreams.copy(fileStream, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
    }
}

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);//from  ww  w. j  a va2 s  .  c o m
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), Paths.get("output.jar"),
            ImmutableSet.of(Paths.get("input.jar")), /* main class */ null, Paths.get("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context));

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:controller.GaleriaController.java

@br.com.caelum.vraptor.Path("galeria/zipGaleria/{galeriaId}")
public Download zipGaleria(long galeriaId) {
    validator.ensure(sessao.getIdsPermitidosDeGalerias().contains(galeriaId),
            new SimpleMessage("galeria", "Acesso negado"));
    Galeria galeria = new Galeria();
    galeria.setId(galeriaId);/*  w  w  w .  jav a  2  s.co m*/
    List<Imagem> imagens = imagemDao.listByGaleria(galeria);

    validator.addIf(imagens == null || imagens.isEmpty(), new SimpleMessage("galeria", "Galeria vazia"));
    validator.onErrorRedirectTo(UsuarioController.class).viewGaleria(galeriaId);

    List<Path> paths = new ArrayList<>();
    for (Imagem imagem : imagens) {
        String realPath = servletContext.getRealPath("/");
        java.nio.file.Path imagemPath = new File(realPath + "/" + UPLOAD_DIR + "/" + imagem.getFileName())
                .toPath();
        paths.add(imagemPath);
    }

    byte buffer[] = new byte[2048];
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos)) {
        zos.setMethod(ZipOutputStream.DEFLATED);
        zos.setLevel(5);
        for (Path path : paths) {

            try (FileInputStream fis = new FileInputStream(path.toFile());
                    BufferedInputStream bis = new BufferedInputStream(fis)) {
                String pathFileName = path.getFileName().toString();
                zos.putNextEntry(new ZipEntry(pathFileName));

                int bytesRead;
                while ((bytesRead = bis.read(buffer)) != -1) {
                    zos.write(buffer, 0, bytesRead);
                }

                zos.closeEntry();
                zos.flush();
            } catch (IOException e) {
                result.include("mensagem", "Erro no download do zip");
                result.forwardTo(UsuarioController.class).viewGaleria(galeriaId);
                return null;
            }
        }
        zos.finish();
        byte[] zip = baos.toByteArray();

        Download download = new ByteArrayDownload(zip, "application/zip",
                sessao.getUsuario().getNome() + ".zip");
        return download;

        //zipDownload = new ZipDownload(sessao.getUsuario().getNome() + ".zip", paths);
        //return zipDownloadBuilder.build();
    } catch (IOException e) {
        result.include("mensagem", "Erro no download do zip");
        result.forwardTo(UsuarioController.class).viewGaleria(galeriaId);
        return null;
    }
}