Example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream closeArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream closeArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream closeArchiveEntry.

Prototype

public void closeArchiveEntry() throws IOException 

Source Link

Document

Writes all necessary data for this entry.

Usage

From source file:cz.cuni.mff.ufal.AllBitstreamZipArchiveReader.java

@Override
public void generate() throws IOException, SAXException, ProcessingException {

    if (redirect != NO_REDIRECTION) {
        return;//from  www.  j  ava2  s.  c  o m
    }

    String name = item.getName() + ".zip";

    try {

        // first write everything to a temp file
        String tempDir = ConfigurationManager.getProperty("upload.temp.dir");
        String fn = tempDir + File.separator + "SWORD." + item.getID() + "." + UUID.randomUUID().toString()
                + ".zip";
        OutputStream outStream = new FileOutputStream(new File(fn));
        ZipArchiveOutputStream zip = new ZipArchiveOutputStream(outStream);
        zip.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zip.setLevel(Deflater.NO_COMPRESSION);
        ConcurrentMap<String, AtomicInteger> usedFilenames = new ConcurrentHashMap<String, AtomicInteger>();

        Bundle[] originals = item.getBundles("ORIGINAL");
        if (needsZip64) {
            zip.setUseZip64(Zip64Mode.Always);
        }
        for (Bundle original : originals) {
            Bitstream[] bss = original.getBitstreams();
            for (Bitstream bitstream : bss) {
                String filename = bitstream.getName();
                String uniqueName = createUniqueFilename(filename, usedFilenames);
                ZipArchiveEntry ze = new ZipArchiveEntry(uniqueName);
                zip.putArchiveEntry(ze);
                InputStream is = bitstream.retrieve();
                Utils.copy(is, zip);
                zip.closeArchiveEntry();
                is.close();
            }
        }
        zip.close();

        File file = new File(fn);
        zipFileSize = file.length();

        zipInputStream = new TempFileInputStream(file);
    } catch (AuthorizeException e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("You do not have permissions to access one or more files.");
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        throw new ProcessingException("Could not create ZIP, please download the files one by one. "
                + "The error has been stored and will be solved by our technical team.");
    }

    // Log download statistics
    for (int bitstreamID : bitstreamIDs) {
        DSpaceApi.updateFileDownloadStatistics(userID, bitstreamID);
    }

    response.setDateHeader("Last-Modified", item.getLastModified().getTime());

    // Try and make the download file name formated for each browser.
    try {
        String agent = request.getHeader("USER-AGENT");
        if (agent != null && agent.contains("MSIE")) {
            name = URLEncoder.encode(name, "UTF8");
        } else if (agent != null && agent.contains("Mozilla")) {
            name = MimeUtility.encodeText(name, "UTF8", "B");
        }
    } catch (UnsupportedEncodingException see) {
        name = "item_" + item.getID() + ".zip";
    }
    response.setHeader("Content-Disposition", "attachment;filename=" + name);

    byte[] buffer = new byte[BUFFER_SIZE];
    int length = -1;

    try {
        response.setHeader("Content-Length", String.valueOf(this.zipFileSize));

        while ((length = this.zipInputStream.read(buffer)) > -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
    } finally {
        try {
            if (this.zipInputStream != null) {
                this.zipInputStream.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (IOException ioe) {
            // Closing the stream threw an IOException but do we want this to propagate up to Cocoon?
            // No point since the user has already got the file contents.
            log.warn("Caught IO exception when closing a stream: " + ioe.getMessage());
        }
    }

}

From source file:com.iisigroup.cap.log.TimeFolderSizeRollingFileAppender.java

public void zipFiles(List<String> fileList, String destUrl) throws IOException {

    FileUtils.forceMkdir(new File(FilenameUtils.getFullPathNoEndSeparator(destUrl)));
    BufferedInputStream origin = null;
    FileOutputStream fos = null;/*from   w w  w  .jav  a  2 s.  c  om*/
    BufferedOutputStream bos = null;
    ZipArchiveOutputStream out = null;
    byte data[] = new byte[BUFFER];
    try {
        fos = new FileOutputStream(destUrl);
        bos = new BufferedOutputStream(fos);
        out = new ZipArchiveOutputStream(bos);

        for (String fName : fileList) {
            File file = new File(fName);
            FileInputStream fi = new FileInputStream(file);
            origin = new BufferedInputStream(fi, BUFFER);
            ZipArchiveEntry entry = new ZipArchiveEntry(file.getName());
            out.putArchiveEntry(entry);
            int count;
            while ((count = origin.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
            out.closeArchiveEntry();
            fi.close();
            origin.close();
        }

    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
            }
        }
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException e) {
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
            }
        }
        if (origin != null) {
            try {
                origin.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 * Creates and writes a ZIP archive entry file for the given indicator.
 *
 * @param zipOutput ZIP output where the entry goes into.
 * @param indSubject The indicator whose for whom the entry is written.
 * @param index 0-based index of the indicator (in the indicator list received from dataabse) that is being written.
 *
 * @throws IOException If any sort of output stream writing error occurs.
 * @throws XMLStreamException Thrown by methods from the {@link XMLStreamWriter} that is used by called methods.
 *///  w ww. j a v a 2 s  .  c o m
private void createAndWriteDatasetEntry(ZipArchiveOutputStream zipOutput, SubjectDTO indSubject, int index)
        throws IOException, XMLStreamException {

    String id = indSubject.getObjectValue(Predicates.SKOS_NOTATION);
    if (StringUtils.isEmpty(id)) {
        id = URIUtil.extractURILabel(indSubject.getUri());
    }

    ZipArchiveEntry entry = new ZipArchiveEntry("datasets/" + id + ".rdf");
    zipOutput.putArchiveEntry(entry);
    writeDatasetEntry(zipOutput, indSubject, index);
    zipOutput.closeArchiveEntry();
}

From source file:fr.acxio.tools.agia.tasks.ZipFilesTasklet.java

protected void zipResource(Resource sSourceResource, ZipArchiveOutputStream sZipArchiveOutputStream,
        StepContribution sContribution, ChunkContext sChunkContext) throws IOException, ZipFilesException {
    // TODO : use a queue to reduce the callstack overhead
    if (sSourceResource.exists()) {
        File aSourceFile = sSourceResource.getFile();
        String aSourcePath = aSourceFile.getCanonicalPath();

        if (!aSourcePath.startsWith(sourceBaseDirectoryPath)) {
            throw new ZipFilesException(
                    "Source file " + aSourcePath + " does not match base directory " + sourceBaseDirectoryPath);
        }/*from ww  w.  ja  v  a  2s  .c  o  m*/

        if (sContribution != null) {
            sContribution.incrementReadCount();
        }
        String aZipEntryName = aSourcePath.substring(sourceBaseDirectoryPath.length() + 1);
        sZipArchiveOutputStream.putArchiveEntry(new ZipArchiveEntry(aZipEntryName));
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Zipping {} to {}", sSourceResource.getFile().getCanonicalPath(), aZipEntryName);
        }
        if (aSourceFile.isFile()) {
            InputStream aInputStream = sSourceResource.getInputStream();
            IOUtils.copy(aInputStream, sZipArchiveOutputStream);
            aInputStream.close();
            sZipArchiveOutputStream.closeArchiveEntry();
        } else {
            sZipArchiveOutputStream.closeArchiveEntry();
            for (File aFile : aSourceFile
                    .listFiles((FileFilter) (recursive ? TrueFileFilter.TRUE : FileFileFilter.FILE))) {
                zipResource(new FileSystemResource(aFile), sZipArchiveOutputStream, sContribution,
                        sChunkContext);
            }
        }
        if (sContribution != null) {
            sContribution.incrementWriteCount(1);
        }
    } else if (LOGGER.isInfoEnabled()) {
        LOGGER.info("{} does not exist", sSourceResource.getFilename());
    }
}

From source file:cn.vlabs.clb.server.ui.frameservice.document.handler.GetMultiDocsContentHandler.java

private void readDocuments(List<DocVersion> dvlist, String zipFileName, HttpServletRequest request,
        HttpServletResponse response) throws FileContentNotFoundException {
    DocumentFacade df = AppFacade.getDocumentFacade();
    OutputStream os = null;//w w w .  ja va2s .  co m
    InputStream is = null;
    ZipArchiveOutputStream zos = null;
    try {
        if (dvlist != null) {
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/zip");
            String headerValue = ResponseHeaderUtils.buildResponseHeader(request, zipFileName, true);
            response.setHeader("Content-Disposition", headerValue);
            os = response.getOutputStream();
            zos = new ZipArchiveOutputStream(os);
            zos.setEncoding("utf-8");
            Map<String, Boolean> dupMap = new HashMap<String, Boolean>();
            GridFSDBFile dbfile = null;
            int i = 1;
            for (DocVersion dv : dvlist) {
                dbfile = df.readDocContent(dv);
                if (dbfile != null) {
                    String filename = dbfile.getFilename();
                    ZipArchiveEntry entry = null;
                    if (dupMap.get(filename) != null) {
                        entry = new ZipArchiveEntry((i + 1) + "-" + filename);

                    } else {
                        entry = new ZipArchiveEntry(filename);
                    }
                    entry.setSize(dbfile.getLength());
                    zos.putArchiveEntry(entry);
                    is = dbfile.getInputStream();
                    FileCopyUtils.copy(is, zos);
                    zos.closeArchiveEntry();
                    dupMap.put(filename, true);
                }
                i++;
            }
            zos.finish();
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(os);
        IOUtils.closeQuietly(is);
    }
}

From source file:at.spardat.xma.xdelta.JarDelta.java

/**
 * Compute delta.// www  . j av  a  2s  . c o m
 *
 * @param source the source
 * @param target the target
 * @param output the output
 * @param list the list
 * @param prefix the prefix
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void computeDelta(ZipFile source, ZipFile target, ZipArchiveOutputStream output, PrintWriter list,
        String prefix) throws IOException {
    try {
        for (Enumeration<ZipArchiveEntry> enumer = target.getEntries(); enumer.hasMoreElements();) {
            calculatedDelta = null;
            ZipArchiveEntry targetEntry = enumer.nextElement();
            ZipArchiveEntry sourceEntry = findBestSource(source, target, targetEntry);
            String nextEntryName = prefix + targetEntry.getName();
            if (sourceEntry != null && zipFilesPattern.matcher(sourceEntry.getName()).matches()
                    && !equal(sourceEntry, targetEntry)) {
                nextEntryName += "!";
            }
            nextEntryName += "|" + Long.toHexString(targetEntry.getCrc());
            if (sourceEntry != null) {
                nextEntryName += ":" + Long.toHexString(sourceEntry.getCrc());
            } else {
                nextEntryName += ":0";
            }
            list.println(nextEntryName);
            if (targetEntry.isDirectory()) {
                if (sourceEntry == null) {
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    output.closeArchiveEntry();
                }
            } else {
                if (sourceEntry == null || sourceEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE
                        || targetEntry.getSize() <= Delta.DEFAULT_CHUNK_SIZE) { // new Entry od. alter Eintrag od. neuer Eintrag leer
                    ZipArchiveEntry outputEntry = entryToNewName(targetEntry, prefix + targetEntry.getName());
                    output.putArchiveEntry(outputEntry);
                    try (InputStream in = target.getInputStream(targetEntry)) {
                        int read = 0;
                        while (-1 < (read = in.read(buffer))) {
                            output.write(buffer, 0, read);
                        }
                        output.flush();
                    }
                    output.closeArchiveEntry();
                } else {
                    if (!equal(sourceEntry, targetEntry)) {
                        if (zipFilesPattern.matcher(sourceEntry.getName()).matches()) {
                            File embeddedTarget = File.createTempFile("jardelta-tmp", ".zip");
                            File embeddedSource = File.createTempFile("jardelta-tmp", ".zip");
                            try (FileOutputStream out = new FileOutputStream(embeddedSource);
                                    InputStream in = source.getInputStream(sourceEntry);
                                    FileOutputStream out2 = new FileOutputStream(embeddedTarget);
                                    InputStream in2 = target.getInputStream(targetEntry)) {
                                int read = 0;
                                while (-1 < (read = in.read(buffer))) {
                                    out.write(buffer, 0, read);
                                }
                                out.flush();
                                read = 0;
                                while (-1 < (read = in2.read(buffer))) {
                                    out2.write(buffer, 0, read);
                                }
                                out2.flush();
                                computeDelta(new ZipFile(embeddedSource), new ZipFile(embeddedTarget), output,
                                        list, prefix + sourceEntry.getName() + "!");
                            } finally {
                                embeddedSource.delete();
                                embeddedTarget.delete();
                            }
                        } else {
                            ZipArchiveEntry outputEntry = new ZipArchiveEntry(
                                    prefix + targetEntry.getName() + ".gdiff");
                            outputEntry.setTime(targetEntry.getTime());
                            outputEntry.setComment("" + targetEntry.getCrc());
                            output.putArchiveEntry(outputEntry);
                            if (calculatedDelta != null) {
                                output.write(calculatedDelta);
                                output.flush();
                            } else {
                                try (ByteArrayOutputStream outbytes = new ByteArrayOutputStream()) {
                                    Delta d = new Delta();
                                    DiffWriter diffWriter = new GDiffWriter(new DataOutputStream(outbytes));
                                    int sourceSize = (int) sourceEntry.getSize();
                                    byte[] sourceBytes = new byte[sourceSize];
                                    try (InputStream sourceStream = source.getInputStream(sourceEntry)) {
                                        for (int erg = sourceStream.read(
                                                sourceBytes); erg < sourceBytes.length; erg += sourceStream
                                                        .read(sourceBytes, erg, sourceBytes.length - erg))
                                            ;
                                    }
                                    d.compute(sourceBytes, target.getInputStream(targetEntry), diffWriter);
                                    output.write(outbytes.toByteArray());
                                }
                            }
                            output.closeArchiveEntry();
                        }
                    }
                }
            }
        }
    } finally {
        source.close();
        target.close();
    }
}

From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java

/**
 * Creates a zip entry for the path specified with a name built from the base
 * passed in and the file/directory name. If the path is a directory, a
 * recursive call is made such that the full directory is added to the zip.
 *
 * @param z_out The zip file's output stream
 * @param path The filesystem path of the file/directory being added
 * @param base The base prefix to for the name of the zip file entry
 * @throws IOException If anything goes wrong
 *//*from ww  w. ja  v a2  s . c o  m*/
private void addFileToZip(ZipArchiveOutputStream z_out, String path, String base) throws IOException {
    File f = new File(path);
    String entryName = base + f.getName();
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

    z_out.putArchiveEntry(zipEntry);

    if (f.isFile()) {
        FileInputStream fInputStream = null;
        try {
            fInputStream = new FileInputStream(f);
            org.apache.commons.compress.utils.IOUtils.copy(fInputStream, z_out, 65535);
            z_out.closeArchiveEntry();
        } finally {
            fInputStream.close();
        }
    } else {
        z_out.closeArchiveEntry();
        File[] children = f.listFiles();

        if (children != null) {
            for (File child : children) {
                LOGGER.debug("ZIP Adding " + child.getName());
                addFileToZip(z_out, child.getAbsolutePath(), entryName + "/");
            }
        }
    }
}

From source file:eionet.cr.util.odp.ODPDatasetsPacker.java

/**
 *
 * @param zipOutput/*from  www .j  a v a  2  s .c  o m*/
 * @throws XMLStreamException
 * @throws IOException
 */
private void createAndWriteManifestEntry(ZipArchiveOutputStream zipOutput)
        throws XMLStreamException, IOException {

    ZipArchiveEntry entry = new ZipArchiveEntry("manifest.xml");
    zipOutput.putArchiveEntry(entry);

    // Prepare STAX indenting writer based on a Java XMLStreamWriter that is based on the given zipped output.
    XMLStreamWriter xmlWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(zipOutput, ENCODING);
    IndentingXMLStreamWriter writer = new IndentingXMLStreamWriter(xmlWriter);

    int i = 1;
    writeManifestHeader(writer);
    for (SubjectDTO indicatorSubject : indicatorSubjects) {
        writeOdpAction(writer, indicatorSubject, i++);
    }
    writeManifestFooter(writer);

    zipOutput.closeArchiveEntry();
}

From source file:es.ucm.fdi.util.archive.ZipFormat.java

public void create(ArrayList<File> sources, File destFile, File baseDir) throws IOException {

    // to avoid modifying input argument
    ArrayList<File> toAdd = new ArrayList<>(sources);
    ZipArchiveOutputStream zos = null;

    try {/*from   w ww.  j  a  va  2  s  . c o m*/
        zos = new ZipArchiveOutputStream(new FileOutputStream(destFile));
        zos.setMethod(ZipArchiveOutputStream.DEFLATED);
        byte[] b = new byte[1024];

        //log.debug("Creating zip file: "+ficheroZip.getName());
        for (int i = 0; i < toAdd.size(); i++) {
            // note: cannot use foreach because sources gets modified
            File file = toAdd.get(i);

            // zip standard uses fw slashes instead of backslashes, always
            String baseName = baseDir.getAbsolutePath() + '/';
            String fileName = file.getAbsolutePath().substring(baseName.length());
            if (file.isDirectory()) {
                fileName += '/';
            }
            ZipArchiveEntry entry = new ZipArchiveEntry(fileName);

            // skip directories - after assuring that their children *will* be included.
            if (file.isDirectory()) {
                //log.debug("\tAdding dir "+fileName);
                for (File child : file.listFiles()) {
                    toAdd.add(child);
                }
                zos.putArchiveEntry(entry);
                continue;
            }

            //log.debug("\tAdding file "+fileName);

            // Add the zip entry and associated data.
            zos.putArchiveEntry(entry);

            int n;
            try (FileInputStream fis = new FileInputStream(file)) {
                while ((n = fis.read(b)) > -1) {
                    zos.write(b, 0, n);
                }
                zos.closeArchiveEntry();
            }
        }
    } finally {
        if (zos != null) {
            zos.finish();
            zos.close();
        }
    }
}

From source file:com.atolcd.web.scripts.ZipContents.java

public void addToZip(NodeRef node, ZipArchiveOutputStream out, boolean noaccent, String path)
        throws IOException {
    QName nodeQnameType = this.nodeService.getType(node);

    // Special case : links
    if (this.dictionaryService.isSubClass(nodeQnameType, ApplicationModel.TYPE_FILELINK)) {
        NodeRef linkDestinationNode = (NodeRef) nodeService.getProperty(node,
                ContentModel.PROP_LINK_DESTINATION);
        if (linkDestinationNode == null) {
            return;
        }/* w w  w .  j  a  v  a2  s. c o m*/

        // Duplicate entry: check if link is not in the same space of the link destination
        if (nodeService.getPrimaryParent(node).getParentRef()
                .equals(nodeService.getPrimaryParent(linkDestinationNode).getParentRef())) {
            return;
        }

        nodeQnameType = this.nodeService.getType(linkDestinationNode);
        node = linkDestinationNode;
    }

    String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME);
    nodeName = noaccent ? unAccent(nodeName) : nodeName;

    if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_CONTENT)) {
        ContentReader reader = contentService.getReader(node, ContentModel.PROP_CONTENT);
        if (reader != null) {
            InputStream is = reader.getContentInputStream();

            String filename = path.isEmpty() ? nodeName : path + '/' + nodeName;

            ZipArchiveEntry entry = new ZipArchiveEntry(filename);
            entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime());

            entry.setSize(reader.getSize());
            out.putArchiveEntry(entry);

            byte buffer[] = new byte[BUFFER_SIZE];
            while (true) {
                int nRead = is.read(buffer, 0, buffer.length);
                if (nRead <= 0) {
                    break;
                }

                out.write(buffer, 0, nRead);
            }
            is.close();
            out.closeArchiveEntry();
        } else {
            logger.warn("Could not read : " + nodeName + "content");
        }
    } else if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_FOLDER)
            && !this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_SYSTEM_FOLDER)) {
        List<ChildAssociationRef> children = nodeService.getChildAssocs(node);
        if (children.isEmpty()) {
            String folderPath = path.isEmpty() ? nodeName + '/' : path + '/' + nodeName + '/';
            out.putArchiveEntry(new ZipArchiveEntry(new ZipEntry(folderPath)));
        } else {
            for (ChildAssociationRef childAssoc : children) {
                NodeRef childNodeRef = childAssoc.getChildRef();

                addToZip(childNodeRef, out, noaccent, path.isEmpty() ? nodeName : path + '/' + nodeName);
            }
        }
    } else {
        logger.info("Unmanaged type: " + nodeQnameType.getPrefixedQName(this.namespaceService) + ", filename: "
                + nodeName);
    }
}