Example usage for java.util.zip ZipOutputStream closeEntry

List of usage examples for java.util.zip ZipOutputStream closeEntry

Introduction

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

Prototype

public void closeEntry() throws IOException 

Source Link

Document

Closes the current ZIP entry and positions the stream for writing the next entry.

Usage

From source file:com.mobicage.rogerthat.mfr.dal.Streamable.java

public String toBase64() {
    try {//www  . j a  va2 s . com
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            ZipOutputStream zip = new ZipOutputStream(bos);
            try {
                zip.setLevel(9);
                zip.putNextEntry(new ZipEntry("entry"));
                try {
                    ObjectOutput out = new ObjectOutputStream(zip);
                    try {
                        out.writeObject(this);
                    } finally {
                        out.flush();
                    }
                } finally {
                    zip.closeEntry();
                }
                zip.flush();
                return Base64.encodeBase64URLSafeString(bos.toByteArray());
            } finally {
                zip.close();
            }
        } finally {
            bos.close();
        }
    } catch (IOException e) {
        log.log((Level.SEVERE), "IO Error while serializing member", e);
        return null;
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobMailNotificationImpl.java

protected void zipOutput(ReportExecutionJob job, ReportOutput output, ZipOutputStream zipOut)
        throws IOException {
    zipOut.putNextEntry(new ZipEntry(output.getFilename()));
    DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut);
    zipOut.closeEntry();

    for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
        ReportOutput child = (ReportOutput) it.next();
        String childName = getChildrenFolderName(job, output.getFilename()) + '/' + child.getFilename();
        zipOut.putNextEntry(new ZipEntry(childName));
        DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut);
        zipOut.closeEntry();//w  w  w  . java2s.c  o  m
    }
}

From source file:com.serotonin.mango.rt.maint.work.ReportWorkItem.java

private void addFileAttachment(EmailContent emailContent, String name, File file) {
    if (file != null) {
        if (reportConfig.isZipData()) {
            try {
                File zipFile = File.createTempFile("tempZIP", ".zip");
                ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
                zipOut.putNextEntry(new ZipEntry(name));

                FileInputStream in = new FileInputStream(file);
                StreamUtils.transfer(in, zipOut);
                in.close();/*from   w ww.j a  va 2 s . c om*/

                zipOut.closeEntry();
                zipOut.close();

                emailContent.addAttachment(new EmailAttachment.FileAttachment(name + ".zip", zipFile));

                filesToDelete.add(zipFile);
            } catch (IOException e) {
                LOG.error("Failed to create zip file", e);
            }
        } else
            emailContent.addAttachment(new EmailAttachment.FileAttachment(name, file));

        filesToDelete.add(file);
    }
}

From source file:net.firejack.platform.core.utils.ArchiveUtils.java

/**
 * @param zipFile/*from   w  w w.j  a  v a2  s .c o m*/
 * @param files
 * @throws java.io.IOException
 */
public static void addFilesToZip(File zipFile, Map<String, File> files) throws IOException {
    // get a temp file
    File tempFile = File.createTempFile(zipFile.getName(), null);
    // delete it, otherwise you cannot rename your existing zip to it.
    FileUtils.deleteQuietly(tempFile);

    boolean renameOk = zipFile.renameTo(tempFile);
    if (!renameOk) {
        throw new RuntimeException(
                "could not rename the file " + zipFile.getAbsolutePath() + " to " + tempFile.getAbsolutePath());
    }

    ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));

    ZipEntry entry = zin.getNextEntry();
    while (entry != null) {
        String name = entry.getName();
        boolean notInFiles = true;
        for (Map.Entry<String, File> e : files.entrySet()) {
            if (e.getKey().equals(name)) {
                notInFiles = false;
                break;
            }
        }
        if (notInFiles) {
            out.putNextEntry(new ZipEntry(name));
            IOUtils.copy(zin, out);
        }
        entry = zin.getNextEntry();
    }
    // Close the streams
    zin.close();
    // Compress the files
    for (Map.Entry<String, File> e : files.entrySet()) {
        InputStream in = new FileInputStream(e.getValue());
        // Add ZIP entry to output stream.
        out.putNextEntry(new ZipEntry(e.getKey()));
        // Transfer bytes from the file to the ZIP file

        IOUtils.copy(in, out);
        // Complete the entry
        out.closeEntry();
        IOUtils.closeQuietly(in);
    }
    // Complete the ZIP file
    IOUtils.closeQuietly(out);
    FileUtils.deleteQuietly(tempFile);
}

From source file:edu.dfci.cccb.mev.dataset.rest.controllers.WorkspaceController.java

@RequestMapping(value = "/export/zip", method = POST, consumes = "multipart/form-data")
@ResponseStatus(OK)//from   w  w  w  .j a v a  2s. c o  m
public byte[] export(@RequestParam("name") String name, @RequestParam("rows") List<String> rows,
        @RequestParam("columns") List<String> columns, @RequestParam("rowSelections") String jsonRowSelections,
        @RequestParam("columnSelections") String jsonColumnSelections,
        @RequestParam("analyses") String[] analyses, HttpServletResponse response)
        throws DatasetException, IOException {
    log.info(String.format("Offline %s, %s, %s, %s", name, rows, columns, analyses));

    //creating byteArray stream, make it bufforable and passing this buffor to ZipOutputStream
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
    ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

    //nw zip entry for dataset
    Dataset dataset = workspace.get(name);
    zipOutputStream.putNextEntry(new ZipEntry("dataset.json"));
    IOUtils.copy(new ByteArrayInputStream(mapper.writeValueAsBytes(dataset)), zipOutputStream);
    zipOutputStream.closeEntry();

    zipAnnotations(name, "row", zipOutputStream);
    zipAnnotations(name, "column", zipOutputStream);

    if (dataset.values() instanceof IFlatFileValues) {
        IFlatFileValues values = (IFlatFileValues) dataset.values();
        zipOutputStream.putNextEntry(new ZipEntry("values.bin"));
        InputStream valuesIs = values.asInputStream();
        IOUtils.copy(valuesIs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        valuesIs.close();
    }

    //new zip entry and copying inputstream with file to zipOutputStream, after all closing streams
    int i = 0;
    for (String analysis : analyses) {
        InputStream analysisOs = new ByteArrayInputStream(analysis.getBytes(StandardCharsets.UTF_8));
        zipOutputStream.putNextEntry(new ZipEntry(String.format("analysis_%d.json", i)));
        JsonNode analysisJson = mapper.readTree(analysis);
        IOUtils.copy(analysisOs, zipOutputStream);
        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        analysisOs.close();
        i++;
    }
    zipOutputStream.flush();
    zipOutputStream.close();

    byte[] ret = byteArrayOutputStream.toByteArray();
    IOUtils.closeQuietly(bufferedOutputStream);
    IOUtils.closeQuietly(byteArrayOutputStream);

    response.setContentLength(ret.length);
    response.setContentType("application/zip"); //or something more generic...
    response.setHeader("Accept-Ranges", "bytes");
    response.setStatus(HttpServletResponse.SC_OK);
    response.addHeader("Content-Disposition", String.format("attachment; filename=\"%s.zip\"", name));
    return ret;
}

From source file:md.archivers.ZIPArchiver.java

private void zipDirectory(File zipFile, File directory) throws FileNotFoundException, IOException {
    ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
    FileInputStream fin = null;/*from   w  w  w .j  a v  a 2s  .com*/
    for (File d : directory.listFiles()) {
        for (File f : d.listFiles()) {
            zos.putNextEntry(new ZipEntry(createNameForZip(f)));
            try {
                fin = new FileInputStream(f);
                IOUtils.copy(fin, zos);
            } finally {
                if (fin != null)
                    fin.close();
            }
            zos.closeEntry();
        }
    }
    zos.close();
}

From source file:gov.nih.nci.caarray.application.fileaccess.FileAccessUtils.java

/**
 * Adds the given file to the given zip output stream using the given name as the zip entry name. This method will
 * NOT call finish on the zip output stream at the end.
 * /* ww  w .  ja  va 2  s .c o  m*/
 * @param zos the zip output stream to add the file to. This stream must already be open.
 * @param file the file to put in the zip.
 * @param name the name to use for this zip entry.
 * @param addAsStored if true, then the file will be added to the zip as a STORED entry (e.g. without applying
 *            compression to it); if false, then the file will be added to the zip as a DEFLATED entry.
 * @throws IOException if there is an error writing to the stream
 */
public void writeZipEntry(ZipOutputStream zos, File file, String name, boolean addAsStored) throws IOException {
    final ZipEntry ze = new ZipEntry(name);
    ze.setMethod(addAsStored ? ZipEntry.STORED : ZipEntry.DEFLATED);
    if (addAsStored) {
        ze.setSize(file.length());
        ze.setCrc(FileUtils.checksumCRC32(file));
    }
    zos.putNextEntry(ze);
    final InputStream is = FileUtils.openInputStream(file);
    IOUtils.copy(is, zos);
    zos.closeEntry();
    zos.flush();
    IOUtils.closeQuietly(is);
}

From source file:com.jaspersoft.jasperserver.api.engine.scheduling.quartz.ReportExecutionJobFileSavingImpl.java

private Map<String, byte[]> zipFile(ReportExecutionJob job, ReportOutput output, boolean useFolderHierarchy)
        throws IOException {
    String attachmentName;//from  w w  w  .ja  v  a 2 s  .com
    DataContainer attachmentData;

    if (output.getChildren().isEmpty()) {
        attachmentName = output.getFilename();
        attachmentData = output.getData();
    } else { // use zip format
        attachmentData = job.createDataContainer();
        boolean close = true;
        ZipOutputStream zipOut = new ZipOutputStream(attachmentData.getOutputStream());
        try {
            zipOut.putNextEntry(new ZipEntry(output.getFilename()));
            DataContainerStreamUtil.pipeDataAndCloseInput(output.getData().getInputStream(), zipOut);
            zipOut.closeEntry();

            for (Iterator it = output.getChildren().iterator(); it.hasNext();) {
                ReportOutput child = (ReportOutput) it.next();
                String childName = child.getFilename();
                if (useFolderHierarchy)
                    childName = getChildrenFolderName(job, output.getFilename()) + '/' + childName;
                zipOut.putNextEntry(new ZipEntry(childName));
                DataContainerStreamUtil.pipeDataAndCloseInput(child.getData().getInputStream(), zipOut);
                zipOut.closeEntry();
            }

            zipOut.finish();
            zipOut.flush();

            close = false;
            zipOut.close();
        } catch (IOException e) {
            throw new JSExceptionWrapper(e);
        } finally {
            if (close) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("Error closing stream", e);
                }
            }
        }
        attachmentName = output.getFilename() + ".zip";
    }
    Map result = new HashMap<String, InputStream>();
    result.put(attachmentName, IOUtils.toByteArray(attachmentData.getInputStream()));
    return result;
}

From source file:gdt.data.entity.ArchiveHandler.java

private static void appendToZip(String directoryToZip$, File file, ZipOutputStream zos) {
    try {//from  ww  w.j a  v  a 2 s .c om
        FileInputStream fis = new FileInputStream(file);
        String zipFile$ = file.getPath().substring(directoryToZip$.length() + 1, file.getPath().length());
        //System.out.println("Writing '" + zipFile$ + "' to zip file");
        ZipEntry zipEntry = new ZipEntry(zipFile$);
        zos.putNextEntry(zipEntry);
        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zos.write(bytes, 0, length);
        }
        zos.closeEntry();
        fis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}

From source file:org.carlspring.strongbox.artifact.generator.NugetPackageGenerator.java

private void createRandomNupkgFile(ZipOutputStream zos) throws IOException {
    ZipEntry ze = new ZipEntry("lib/random-size-file");
    zos.putNextEntry(ze);/*  w  w w  .  j  av a  2s .  co m*/

    RandomInputStream ris = new RandomInputStream(true, 1000000);

    byte[] buffer = new byte[4096];
    int len;
    while ((len = ris.read(buffer)) > 0) {
        zos.write(buffer, 0, len);
    }

    ris.close();
    zos.closeEntry();
}