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:org.saiku.plugin.resources.PentahoRepositoryResource2.java

@GET
@Path("/zip")
public Response getResourcesAsZip(@QueryParam("directory") String directory, @QueryParam("files") String files,
        @QueryParam("type") String type) {
    try {/*from w w  w  .ja v a2 s .c  om*/
        if (StringUtils.isBlank(directory))
            return Response.ok().build();

        final String fileType = type;
        IUserContentAccess access = contentAccessFactory.getUserContentAccess(null);

        if (!access.fileExists(directory) && access.hasAccess(directory, FileAccess.READ)) {
            throw new SaikuServiceException(
                    "Access to Repository has failed File does not exist or no read right: " + directory);
        }

        IBasicFileFilter txtFilter = StringUtils.isBlank(type) ? null : new IBasicFileFilter() {
            public boolean accept(IBasicFile file) {
                return file.isDirectory() || file.getExtension().equals(fileType);
            }
        };

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(bos);

        List<IBasicFile> basicFiles = access.listFiles(directory, txtFilter);

        for (IBasicFile basicFile : basicFiles) {
            if (!basicFile.isDirectory()) {
                String entry = basicFile.getName();
                byte[] doc = IOUtils.toByteArray(basicFile.getContents());
                ZipEntry ze = new ZipEntry(entry);
                zos.putNextEntry(ze);
                zos.write(doc);

            }
        }

        zos.closeEntry();
        zos.close();
        byte[] zipDoc = bos.toByteArray();

        return Response.ok(zipDoc, MediaType.APPLICATION_OCTET_STREAM)
                .header("content-disposition", "attachment; filename = " + directory + ".zip")
                .header("content-length", zipDoc.length).build();

    } catch (Exception e) {
        log.error("Cannot zip resources " + files, e);
        String error = ExceptionUtils.getRootCauseMessage(e);
        return Response.serverError().entity(error).build();
    }

}

From source file:org.artificer.atom.archive.ArtificerArchive.java

/**
 * Pack the given S-RAMP archive entry into the ZIP.
 * @param entry an s-ramp archive entry/* w  w w  .j  ava2 s  .  c  o  m*/
 * @param zipOutputStream the zip file
 * @throws IOException
 * @throws NoSuchMethodException
 * @throws InvocationTargetException
 * @throws IllegalAccessException
 * @throws URISyntaxException
 * @throws SecurityException
 * @throws IllegalArgumentException
 * @throws JAXBException
 */
private void packEntry(ArtificerArchiveEntry entry, ZipOutputStream zipOutputStream)
        throws IOException, IllegalArgumentException, SecurityException, URISyntaxException,
        IllegalAccessException, InvocationTargetException, NoSuchMethodException, JAXBException {
    // Store the artifact content in the ZIP
    InputStream contentStream = getInputStream(entry);
    if (contentStream != null) {
        zipOutputStream.putNextEntry(new ZipEntry(entry.getPath()));
        try {
            IOUtils.copy(contentStream, zipOutputStream);
        } finally {
            IOUtils.closeQuietly(contentStream);
        }
        zipOutputStream.closeEntry();
    }

    // Store the meta-data in the ZIP
    zipOutputStream.putNextEntry(new ZipEntry(entry.getPath() + ".atom"));
    try {
        ArtificerArchiveJaxbUtils.writeMetaData(zipOutputStream, entry.getMetaData());
    } finally {
    }
    zipOutputStream.closeEntry();
}

From source file:com.gatf.executor.report.ReportHandler.java

/**
 * @param zipFile/*from   w w  w .j  av  a 2  s  .co m*/
 * @param directoryToExtractTo Provides file unzip functionality
 */
public static void zipDirectory(File directory, final String[] fileFilters, String zipFileName) {
    try {
        if (!directory.exists() || !directory.isDirectory()) {
            directory.mkdirs();
            logger.info("Invalid Directory provided for zipping...");
            return;
        }
        File zipFile = new File(directory, zipFileName);
        FileOutputStream fos = new FileOutputStream(zipFile);
        ZipOutputStream zos = new ZipOutputStream(fos);

        File[] files = directory.listFiles(new FilenameFilter() {
            public boolean accept(File folder, String name) {
                for (String fileFilter : fileFilters) {
                    return name.toLowerCase().endsWith(fileFilter);
                }
                return false;
            }
        });

        for (File file : files) {
            FileInputStream fis = new FileInputStream(file);
            ZipEntry zipEntry = new ZipEntry(file.getName());
            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();
        }

        zos.close();
        fos.close();
    } catch (IOException ioe) {
        logger.severe(ExceptionUtils.getStackTrace(ioe));
        return;
    }
}

From source file:org.apache.chemistry.opencmis.tools.specexamples.SpecExamples.java

private static void addDirectory(ZipOutputStream zout, String prefix, File sourceDir) throws IOException {

    File[] files = sourceDir.listFiles();
    LOG.debug("Create Zip, adding directory " + sourceDir.getName());

    if (null != files) {
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                addDirectory(zout, prefix + File.separator + files[i].getName(), files[i]);
            } else {
                LOG.debug("Create Zip, adding file {}", files[i].getName());
                byte[] buffer = new byte[BUFSIZE];
                FileInputStream fin = new FileInputStream(files[i]);
                try {
                    String zipEntryName = prefix + File.separator + files[i].getName();
                    LOG.debug("   adding entry " + zipEntryName);
                    zout.putNextEntry(new ZipEntry(zipEntryName));

                    int length;
                    while ((length = fin.read(buffer)) > 0) {
                        zout.write(buffer, 0, length);
                    }//  w  ww  .  jav  a 2 s  .c o  m
                } finally {
                    IOUtils.closeQuietly(fin);
                    try {
                        zout.closeEntry();
                    } catch (IOException ioe) {
                        LOG.debug("Closing zip entry failed: {}", ioe.toString(), ioe);
                    }
                }
            }
        }
    }
}

From source file:it.cnr.icar.eric.common.Utility.java

public static ZipOutputStream createZipOutputStream(String baseDir, String[] relativeFilePaths, OutputStream os)
        throws FileNotFoundException, IOException {
    if (baseDir.startsWith("file:/")) {
        baseDir = baseDir.substring(5);/*from   ww  w  .ja va 2  s.co m*/
    }
    ZipOutputStream zipoutputstream = new ZipOutputStream(os);

    zipoutputstream.setMethod(ZipOutputStream.STORED);

    for (int i = 0; i < relativeFilePaths.length; i++) {
        File file = new File(baseDir + FILE_SEPARATOR + relativeFilePaths[i]);

        byte[] buffer = new byte[1000];

        int n;

        FileInputStream fis;

        // Calculate the CRC-32 value.  This isn't strictly necessary
        //   for deflated entries, but it doesn't hurt.

        CRC32 crc32 = new CRC32();

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            crc32.update(buffer, 0, n);
        }

        fis.close();

        // Create a zip entry.

        ZipEntry zipEntry = new ZipEntry(relativeFilePaths[i]);

        zipEntry.setSize(file.length());
        zipEntry.setTime(file.lastModified());
        zipEntry.setCrc(crc32.getValue());

        // Add the zip entry and associated data.

        zipoutputstream.putNextEntry(zipEntry);

        fis = new FileInputStream(file);

        while ((n = fis.read(buffer)) > -1) {
            zipoutputstream.write(buffer, 0, n);
        }

        fis.close();

        zipoutputstream.closeEntry();
    }

    return zipoutputstream;
}

From source file:com.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ??ZIP//w w  w . j  a  v  a2s . co m
 * 
 * @return
 */
public StreamedContent generateFileAll() {
    LOGGER.info("Export all config group");
    StreamedContent file = null;

    String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
    List<String> children = nodeService.listChildren(authedNode);
    if (children != null && !children.isEmpty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            for (String groupName : children) {
                String groupPath = ZKPaths.makePath(authedNode, groupName);
                String fileName = ZKPaths.getNodeFromPath(groupPath) + ".properties";

                List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                        versionMB.getSelectedVersion(), groupName);
                List<String> lines = formatPropertyLines(groupName, items);
                if (!lines.isEmpty()) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
                    zipOutputStream.closeEntry();
                }
            }

            zipOutputStream.close();
            byte[] data = out.toByteArray();
            InputStream in = new ByteArrayInputStream(data);

            String fileName = authedNode.replace('/', '-') + ".zip";
            file = new DefaultStreamedContent(in, "application/zip", fileName, Charsets.UTF_8.name());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:com.taobao.android.utils.ZipUtils.java

/**
 * zip//  w  w  w .j av  a2 s  .  co  m
 *
 * @param zipFile
 * @param file
 * @param destPath  ?
 * @param overwrite ?
 * @throws IOException
 */
public static void addFileToZipFile(File zipFile, File outZipFile, File file, String destPath,
        boolean overwrite) throws IOException {
    byte[] buf = new byte[1024];
    ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outZipFile));
    ZipEntry entry = zin.getNextEntry();
    boolean addFile = true;
    while (entry != null) {
        boolean addEntry = true;
        String name = entry.getName();
        if (StringUtils.equalsIgnoreCase(name, destPath)) {
            if (overwrite) {
                addEntry = false;
            } else {
                addFile = false;
            }
        }
        if (addEntry) {
            ZipEntry zipEntry = null;
            if (ZipEntry.STORED == entry.getMethod()) {
                zipEntry = new ZipEntry(entry);
            } else {
                zipEntry = new ZipEntry(name);
            }
            out.putNextEntry(zipEntry);
            int len;
            while ((len = zin.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
        entry = zin.getNextEntry();
    }

    if (addFile) {
        InputStream in = new FileInputStream(file);
        // Add ZIP entry to output stream.
        ZipEntry zipEntry = new ZipEntry(destPath);
        out.putNextEntry(zipEntry);
        // Transfer bytes from the file to the ZIP file
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // Complete the entry
        out.closeEntry();
        in.close();
    }
    // Close the streams
    zin.close();
    out.close();
}

From source file:gov.nih.nci.cabig.caaers.web.ae.AdditionalInformationDocumentZipDownloadController.java

@Override
protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
        throws ServletRequestBindingException {

    Integer additionalInformationId = ServletRequestUtils.getRequiredIntParameter(request,
            "additionalInformationId");

    List<AdditionalInformationDocument> additionalInformationDocuments = additionalInformationDocumentService
            .findByAdditionalInformationId(additionalInformationId);

    File tempFile = null;//from   w w  w .  j a  v  a 2 s  . c  om
    ZipOutputStream zos = null;
    FileOutputStream fos = null;

    List<String> zipEntriesName = new ArrayList<String>();
    try {
        tempFile = File.createTempFile(
                "additionalInformationFile" + System.currentTimeMillis() + RandomUtils.nextInt(1000), ".zip");

        fos = new FileOutputStream(tempFile);
        zos = new ZipOutputStream(fos);

        for (AdditionalInformationDocument additionalInformationDocument : additionalInformationDocuments) {
            String name = getUniqueZipEntryName(additionalInformationDocument, zipEntriesName);
            zipEntriesName.add(name);
            ZipEntry zipEntry = new ZipEntry(name);
            zos.putNextEntry(zipEntry);
            IOUtils.copy(new FileInputStream(additionalInformationDocument.getFile()), zos);
            zos.closeEntry();
        }

        zos.flush();

    } catch (Exception e) {

        log.error("Unable to create temp file", e);
        return null;
    } finally {
        if (zos != null)
            IOUtils.closeQuietly(zos);
        if (fos != null)
            IOUtils.closeQuietly(fos);
    }

    if (tempFile != null) {

        FileInputStream fis = null;
        OutputStream out = null;
        try {
            fis = new FileInputStream(tempFile);
            out = response.getOutputStream();

            response.setContentType("application/x-download");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + additionalInformationId + ".zip");
            response.setHeader("Content-length", String.valueOf(tempFile.length()));
            response.setHeader("Pragma", "private");
            response.setHeader("Cache-control", "private, must-revalidate");

            IOUtils.copy(fis, out);
            out.flush();
        } catch (Exception e) {
            log.error("Error while reading zip file ", e);
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(out);
        }

        FileUtils.deleteQuietly(tempFile);
    }
    return null;
}

From source file:nl.nn.adapterframework.webcontrol.DumpIbisConsole.java

public void copyResource(ZipOutputStream zipOutputStream, String resource) {
    try {//from   w ww  .java2s. c om
        String rsc = resource;
        String fileName = directoryName + rsc;

        InputStream inputStream = servletContext.getResourceAsStream(rsc);
        if (inputStream == null) {
            log.debug("did not find resource [" + rsc + "], try again with added preceding slash");
            rsc = '/' + rsc;
            inputStream = servletContext.getResourceAsStream(rsc);
        }
        if (inputStream == null) {
            log.warn("did not find resource [" + rsc + "]");
        } else {
            zipOutputStream.putNextEntry(new ZipEntry(fileName));
            Misc.streamToStream(inputStream, zipOutputStream);
            zipOutputStream.closeEntry();
            log.debug("copied resource [" + rsc + "]");
        }
    } catch (Exception e) {
        log.error("Error copying resource", e);
    }
}

From source file:edu.ku.brc.specify.rstools.GoogleEarthExporter.java

/**
 * @param outputFile//  w ww .  j av  a2 s  .  c o m
 * @param defaultIconFile
 */
protected void createKMZ(final File outputFile, final File defaultIconFile) throws IOException {
    // now we have the KML in outputFile
    // we need to create a KMZ (zip file containing doc.kml and other files)

    // create a buffer for reading the files
    byte[] buf = new byte[1024];
    int len;

    // create the KMZ file
    File outputKMZ = File.createTempFile("sp6-export-", ".kmz");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputKMZ));

    // add the doc.kml file to the ZIP
    FileInputStream in = new FileInputStream(outputFile);
    // add ZIP entry to output stream
    out.putNextEntry(new ZipEntry("doc.kml"));
    // copy the bytes
    while ((len = in.read(buf)) > 0) {
        out.write(buf, 0, len);
    }
    // complete the entry
    out.closeEntry();
    in.close();

    // add a "files" directory to the KMZ file
    ZipEntry filesDir = new ZipEntry("files/");
    out.putNextEntry(filesDir);
    out.closeEntry();

    if (defaultIconFile != null) {
        File iconTmpFile = defaultIconFile;
        if (false) {
            // Shrink File
            ImageIcon icon = new ImageIcon(defaultIconFile.getAbsolutePath());
            BufferedImage bimage = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(),
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = bimage.createGraphics();
            g.drawImage(icon.getImage(), 0, 0, null);
            g.dispose();
            BufferedImage scaledBI = GraphicsUtils.getScaledInstance(bimage, 16, 16, true);
            iconTmpFile = File.createTempFile("sp6-export-icon-scaled", ".png");
            ImageIO.write(scaledBI, "PNG", iconTmpFile);
        }

        // add the specify32.png file (default icon file) to the ZIP (in the "files" directory)
        in = new FileInputStream(iconTmpFile);
        // add ZIP entry to output stream
        out.putNextEntry(new ZipEntry("files/specify32.png"));
        // copy the bytes
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        // complete the entry
        out.closeEntry();
        in.close();
    }

    // complete the ZIP file
    out.close();

    // now put the KMZ file where the KML output was
    FileUtils.copyFile(outputKMZ, outputFile);

    outputKMZ.delete();
}