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.comcast.video.dawg.show.video.VideoSnap.java

/**
 * Retrieve the images with input device ids from cache and stores it in zip
 * output stream./*from  w w  w .  j a va 2s.c o m*/
 *
 * @param capturedImageIds
 *            Ids of captures images
 * @param deviceMacs
 *            Mac address of selected devices
 * @param response
 *            http servelet response
 * @param session
 *            http session.
 */
public void addImagesToZipFile(String[] capturedImageIds, String[] deviceMacs, HttpServletResponse response,
        HttpSession session) {

    UniqueIndexedCache<BufferedImage> imgCache = getClientCache(session).getImgCache();

    response.setHeader("Content-Disposition",
            "attachment; filename=\"" + "Images_" + getCurrentDateAndTime() + ".zip\"");
    response.setContentType("application/zip");

    ServletOutputStream serveletOutputStream = null;
    ZipOutputStream zipOutputStream = null;

    try {
        serveletOutputStream = response.getOutputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        zipOutputStream = new ZipOutputStream(byteArrayOutputStream);

        BufferedImage image;
        ZipEntry zipEntry;
        ByteArrayOutputStream imgByteArrayOutputStream = null;

        for (int i = 0; i < deviceMacs.length; i++) {
            // Check whether id of captured image is null or not
            if (!StringUtils.isEmpty(capturedImageIds[i])) {
                image = imgCache.getItem(capturedImageIds[i]);
                zipEntry = new ZipEntry(deviceMacs[i].toUpperCase() + "." + IMG_FORMAT);
                zipOutputStream.putNextEntry(zipEntry);
                imgByteArrayOutputStream = new ByteArrayOutputStream();
                ImageIO.write(image, IMG_FORMAT, imgByteArrayOutputStream);
                imgByteArrayOutputStream.flush();
                zipOutputStream.write(imgByteArrayOutputStream.toByteArray());
                zipOutputStream.closeEntry();
            }
        }

        zipOutputStream.flush();
        zipOutputStream.close();
        serveletOutputStream.write(byteArrayOutputStream.toByteArray());
    } catch (IOException ioe) {
        LOGGER.error("Image zipping failed !!!", ioe);
    } finally {
        IOUtils.closeQuietly(zipOutputStream);
    }
}

From source file:au.org.ala.biocache.service.DownloadService.java

/**
 * Writes the supplied download to the supplied output stream. It will include all the appropriate citations etc.
 * //from   w  w w .j  av a  2  s  .  co  m
 * @param dd
 * @param requestParams
 * @param ip
 * @param out
 * @param includeSensitive
 * @param fromIndex
 * @throws Exception
 */
private void writeQueryToStream(DownloadDetailsDTO dd, DownloadRequestParams requestParams, String ip,
        OutputStream out, boolean includeSensitive, boolean fromIndex, boolean limit) throws Exception {

    String filename = requestParams.getFile();
    String originalParams = requestParams.toString();
    //Use a zip output stream to include the data and citation together in the download
    ZipOutputStream zop = new ZipOutputStream(out);
    String suffix = requestParams.getFileType().equals("shp") ? "zip" : requestParams.getFileType();
    zop.putNextEntry(new java.util.zip.ZipEntry(filename + "." + suffix));
    //put the facets
    if ("all".equals(requestParams.getQa())) {
        requestParams.setFacets(new String[] { "assertions", "data_resource_uid" });
    } else {
        requestParams.setFacets(new String[] { "data_resource_uid" });
    }
    Map<String, Integer> uidStats = null;
    try {
        if (fromIndex)
            uidStats = searchDAO.writeResultsFromIndexToStream(requestParams, zop, includeSensitive, dd, limit);
        else
            uidStats = searchDAO.writeResultsToStream(requestParams, zop, 100, includeSensitive, dd);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    } finally {
        unregisterDownload(dd);
    }
    zop.closeEntry();

    //add the Readme for the data field descriptions
    zop.putNextEntry(new java.util.zip.ZipEntry("README.html"));
    zop.write(("For more information about the fields that are being downloaded please consult <a href='"
            + dataFieldDescriptionURL + "'>Download Fields</a>.").getBytes());

    //add the readme for the Shape file header mappings if necessary
    if (dd.getHeaderMap() != null) {
        zop.putNextEntry(new java.util.zip.ZipEntry("Shape-README.html"));
        zop.write(
                ("The name of features is limited to 10 characters. Listed below are the mappings of feature name to download field:")
                        .getBytes());
        zop.write(("<table><td><b>Feature</b></td><td><b>Download Field<b></td>").getBytes());
        for (String key : dd.getHeaderMap().keySet()) {
            zop.write(("<tr><td>" + key + "</td><td>" + dd.getHeaderMap().get(key) + "</td></tr>").getBytes());
        }
        zop.write(("</table>").getBytes());
        //logger.debug("JSON::: " + objectMapper.writeValueAsString(dd));
    }

    //Add the data citation to the download
    if (uidStats != null && !uidStats.isEmpty() && citationsEnabled) {
        //add the citations for the supplied uids
        zop.putNextEntry(new java.util.zip.ZipEntry("citation.csv"));
        try {
            getCitations(uidStats, zop, requestParams.getSep(), requestParams.getEsc());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        zop.closeEntry();
    } else {
        logger.debug("Not adding citation. Enabled: " + citationsEnabled + " uids: " + uidStats);
    }
    zop.flush();
    zop.close();

    //now construct the sourceUrl for the log event
    String sourceUrl = originalParams.contains("qid:") ? webservicesRoot + "?" + requestParams.toString()
            : webservicesRoot + "?" + originalParams;

    //logger.debug("UID stats : " + uidStats);
    //log the stats to ala logger        
    LogEventVO vo = new LogEventVO(1002, requestParams.getReasonTypeId(), requestParams.getSourceTypeId(),
            requestParams.getEmail(), requestParams.getReason(), ip, null, uidStats, sourceUrl);
    logger.log(RestLevel.REMOTE, vo);
}

From source file:org.apache.roller.weblogger.ui.struts2.editor.WeblogExport.java

/**
 * Returns an output stream to the client of all uploaded resource files as
 * a ZIP archive./*  w  w  w .  j a v a2s. c o  m*/
 */
public void exportResources() {
    SimpleDateFormat dateFormat;
    dateFormat = new SimpleDateFormat("MMddyyyy'T'HHmmss");

    StringBuilder fileName;
    fileName = new StringBuilder();
    fileName.append(getActionWeblog().getHandle());
    fileName.append("-resources-");
    fileName.append(dateFormat.format(System.currentTimeMillis()));
    fileName.append(".zip");

    if (!response.isCommitted()) {
        response.reset();

        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName.toString() + "\"");

        try {
            MediaFileManager fmgr = WebloggerFactory.getWeblogger().getMediaFileManager();

            List<MediaFile> resources = new ArrayList<MediaFile>();

            // Load the contents of any sub-directories
            for (MediaFileDirectory mdir : fmgr.getMediaFileDirectories(getActionWeblog())) {
                loadResources(resources, mdir);
            }

            // Load the files at the root of the specific upload directory
            loadResources(resources, null);

            // Create a buffer for reading the files
            byte[] buffer;
            buffer = new byte[1024];

            ServletOutputStream servletOutput;
            servletOutput = response.getOutputStream();

            ZipOutputStream zipOutput;
            zipOutput = new ZipOutputStream(servletOutput);

            for (MediaFile resource : resources) {
                InputStream input;
                input = resource.getInputStream();

                // Add a new ZIP entry to output stream
                zipOutput.putNextEntry(new ZipEntry(resource.getPath()));

                int length;
                while ((length = input.read(buffer)) > 0) {
                    zipOutput.write(buffer, 0, length);
                }

                // Cleanup the entry
                input.close();
                zipOutput.closeEntry();
            }

            // Cleanup the output stream
            zipOutput.flush();
            zipOutput.close();
        } catch (Exception e) {
            log.error("Error exporting resources: " + e.getMessage());
        }
    }
}

From source file:com.castlemock.web.basis.web.mvc.controller.project.ProjectsOverviewController.java

/**
 * The method provides the functionality to update, delete and export projects. It bases the requested functionality based
 * on the provided action.//from   w  w w .j a  v a 2  s. c  o m
 * @param action The action is used to determined which action/functionality the perform.
 * @param projectModifierCommand The project overview command contains which ids going to be updated, deleted or exported.
 * @param response The HTTP servlet response
 * @return The model depending in which action was requested.
 */
@PreAuthorize("hasAuthority('READER') or hasAuthority('MODIFIER') or hasAuthority('ADMIN')")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView projectFunctionality(@RequestParam String action,
        @ModelAttribute ProjectModifierCommand projectModifierCommand, HttpServletResponse response) {
    LOGGER.debug("Project action requested: " + action);
    if (EXPORT_PROJECTS.equalsIgnoreCase(action)) {
        if (projectModifierCommand.getProjects().length == 0) {
            return redirect();
        }

        ZipOutputStream zipOutputStream = null;
        InputStream inputStream = null;
        final String outputFilename = tempFilesFolder + SLASH + "exported-projects-" + new Date().getTime()
                + ".zip";
        try {
            zipOutputStream = new ZipOutputStream(new FileOutputStream(outputFilename));
            for (String project : projectModifierCommand.getProjects()) {
                final String[] projectData = project.split(SLASH);
                if (projectData.length != 2) {
                    continue;
                }

                final String projectTypeUrl = projectData[0];
                final String projectId = projectData[1];
                final String exportedProject = projectServiceFacade.exportProject(projectTypeUrl, projectId);
                final byte[] data = exportedProject.getBytes();
                final String filename = "exported-project-" + projectTypeUrl + "-" + projectId + ".xml";
                zipOutputStream.putNextEntry(new ZipEntry(filename));
                zipOutputStream.write(data, 0, data.length);
                zipOutputStream.closeEntry();
            }
            zipOutputStream.close();

            inputStream = new FileInputStream(outputFilename);
            IOUtils.copy(inputStream, response.getOutputStream());

            response.setContentType("application/zip");
            response.flushBuffer();
            return null;
        } catch (IOException exception) {
            LOGGER.error("Unable to export multiple projects and zip them", exception);
        } finally {
            if (zipOutputStream != null) {
                try {
                    zipOutputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the zip output stream", exception);
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException exception) {
                    LOGGER.error("Unable to close the input stream", exception);
                }
            }
            fileManager.deleteUploadedFile(outputFilename);
        }
    } else if (DELETE_PROJECTS.equalsIgnoreCase(action)) {
        List<ProjectDto> projects = new LinkedList<ProjectDto>();
        for (String project : projectModifierCommand.getProjects()) {
            final String[] projectData = project.split(SLASH);

            if (projectData.length != 2) {
                continue;
            }

            final String projectTypeUrl = projectData[0];
            final String projectId = projectData[1];
            final ProjectDto projectDto = projectServiceFacade.findOne(projectTypeUrl, projectId);
            projects.add(projectDto);
        }
        ModelAndView model = createPartialModelAndView(DELETE_PROJECTS_PAGE);
        model.addObject(PROJECTS, projects);
        model.addObject(DELETE_PROJECTS_COMMAND, new DeleteProjectsCommand());
        return model;
    }

    return redirect();
}

From source file:it.eng.spagobi.tools.downloadFiles.service.DownloadZipAction.java

public void createZipFromFiles(Vector<File> files, String outputFileName, String folderName)
        throws IOException {
    logger.debug("IN");
    ZipOutputStream out = new ZipOutputStream(new FileOutputStream(outputFileName));
    // Compress the files 
    for (Iterator iterator = files.iterator(); iterator.hasNext();) {
        File file = (File) iterator.next();

        FileInputStream in = new FileInputStream(file);

        String fileName = file.getName();
        // The name to Inssert: remove the parameter folder
        //         int lastIndex=folderName.length();
        //         String fileToInsert=fileName.substring(lastIndex+1);

        logger.debug("Adding to zip entry " + fileName);
        ZipEntry zipEntry = new ZipEntry(fileName);

        // Add ZIP entry to output stream. 
        out.putNextEntry(zipEntry);/*from   w w w. j a  va 2  s .  c  o m*/

        // 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();
    }
    // Complete the ZIP file 
    out.close();
    logger.debug("OUT");
}

From source file:fr.univrouen.poste.services.ZipService.java

public void writeZip(List<PosteCandidature> posteCandidatures, OutputStream destStream)
        throws IOException, SQLException {

    ZipOutputStream out = new ZipOutputStream(destStream);

    for (PosteCandidature posteCandidature : posteCandidatures) {
        String folderName = posteCandidature.getPoste().getNumEmploi().concat("/");
        folderName = folderName.concat(posteCandidature.getCandidat().getNom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getPrenom().concat("-"));
        folderName = folderName.concat(posteCandidature.getCandidat().getNumCandidat().concat("/"));
        for (PosteCandidatureFile posteCandidatureFile : posteCandidature.getCandidatureFiles()) {
            String fileName = posteCandidatureFile.getId().toString().concat("-")
                    .concat(posteCandidatureFile.getFilename());
            String folderFileName = folderName.concat(fileName);
            out.putNextEntry(new ZipEntry(folderFileName));
            InputStream inputStream = posteCandidatureFile.getBigFile().getBinaryFile().getBinaryStream();
            BufferedInputStream bufInputStream = new BufferedInputStream(inputStream, BUFFER);
            byte[] bytes = new byte[BUFFER];
            int length;
            while ((length = bufInputStream.read(bytes)) >= 0) {
                out.write(bytes, 0, length);
            }//from  ww w. j av a 2s  .  c  om
            out.closeEntry();
        }
    }
    out.close();
}

From source file:net.rptools.lib.io.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;//from  w ww.  j a va  2  s  .c  o  m

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    InputStream is = null;

    // Create the new file
    File newFile = new File(tmpDir, new GUID() + ".pak");
    ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
    try {
        saveTimer.start(CONTENT_FILE);
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            is = getFileAsInputStream(CONTENT_FILE); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop(CONTENT_FILE);

        saveTimer.start(PROPERTY_FILE);
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            xstream.toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop(PROPERTY_FILE);

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            is = getFileAsInputStream(path); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    //                  if (entry.getName().endsWith(".png") ||
                    //                        entry.getName().endsWith(".gif") ||
                    //                        entry.getName().endsWith(".jpeg"))
                    //                     zout.setLevel(Deflater.NO_COMPRESSION); // none needed for images as they are already compressed
                    //                  else
                    //                     zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
                    zout.putNextEntry(entry);
                    is = getFileAsInputStream(entry.getName()); // When copying, always use an InputStream
                    IOUtils.copy(is, zout);
                    IOUtils.closeQuietly(is);
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        IOUtils.closeQuietly(zout);
        zout = null;
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir, new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                saveTimer.start("backup file");
                FileUtil.copyFile(file, backupFile);
                file.delete();
                saveTimer.stop("backup file");
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file)) {
            saveTimer.start("backup newFile");
            FileUtil.copyFile(newFile, file);
            saveTimer.stop("backup newFile");
        }
        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zout);
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:com.wegas.core.jcr.content.ContentConnector.java

/**
 * Compress directory and children to ZipOutputStream. Warning: metadatas
 * are not included due to zip limitation
 *
 * @param out  a ZipOutputStream to write files to
 * @param path root path to compress/*www .  j a  va2s .  co  m*/
 * @throws RepositoryException
 * @throws IOException
 */
public void zipDirectory(ZipOutputStream out, String path) throws RepositoryException, IOException {
    AbstractContentDescriptor node = DescriptorFactory.getDescriptor(path, this);
    DirectoryDescriptor root;
    if (node.isDirectory()) {
        root = (DirectoryDescriptor) node;
    } else {
        return;
    }
    List<AbstractContentDescriptor> list = root.list();

    ZipEntry entry;
    for (AbstractContentDescriptor item : list) {
        entry = item.getZipEntry();
        try {
            out.putNextEntry(entry);
        } catch (ZipException ex) {
            logger.warn("error");
        }
        if (item.isDirectory()) {
            zipDirectory(out, item.getFullPath());
        } else {
            byte[] write = ((FileDescriptor) item).getBytesData();
            out.write(write, 0, write.length);
        }
    }
    out.closeEntry();
}