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

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

Introduction

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

Prototype

public void putArchiveEntry(ArchiveEntry archiveEntry) throws IOException 

Source Link

Usage

From source file:org.springframework.boot.gradle.tasks.bundling.BootZipCopyAction.java

private void writeDirectory(ZipArchiveEntry entry, ZipArchiveOutputStream out) throws IOException {
    prepareEntry(entry, UnixStat.DIR_FLAG | UnixStat.DEFAULT_DIR_PERM);
    out.putArchiveEntry(entry);
    out.closeArchiveEntry();//from  w  w w  . j  a v  a 2  s .com
}

From source file:org.springframework.boot.gradle.tasks.bundling.BootZipCopyAction.java

private void writeClass(ZipArchiveEntry entry, ZipInputStream in, ZipArchiveOutputStream out)
        throws IOException {
    prepareEntry(entry, UnixStat.FILE_FLAG | UnixStat.DEFAULT_FILE_PERM);
    out.putArchiveEntry(entry);
    byte[] buffer = new byte[4096];
    int read;//from   w w  w . j  a  v  a2 s .c o  m
    while ((read = in.read(buffer)) > 0) {
        out.write(buffer, 0, read);
    }
    out.closeArchiveEntry();
}

From source file:org.waarp.common.tar.ZipUtility.java

/**
 * Recursive traversal to add files//from  www .j  a  va2s  . co  m
 * 
 * @param root
 * @param file
 * @param zaos
 * @param absolute
 * @throws IOException
 */
private static void recurseFiles(File root, File file, ZipArchiveOutputStream zaos, boolean absolute)
        throws IOException {
    if (file.isDirectory()) {
        // recursive call
        File[] files = file.listFiles();
        for (File file2 : files) {
            recurseFiles(root, file2, zaos, absolute);
        }
    } else if ((!file.getName().endsWith(".zip")) && (!file.getName().endsWith(".ZIP"))) {
        String filename = null;
        if (absolute) {
            filename = file.getAbsolutePath().substring(root.getAbsolutePath().length());
        } else {
            filename = file.getName();
        }
        ZipArchiveEntry zae = new ZipArchiveEntry(filename);
        zae.setSize(file.length());
        zaos.putArchiveEntry(zae);
        FileInputStream fis = new FileInputStream(file);
        IOUtils.copy(fis, zaos);
        zaos.closeArchiveEntry();
    }
}

From source file:org.waarp.common.tar.ZipUtility.java

/**
 * Recursive traversal to add files//from  ww w.j  av  a  2  s  .  co  m
 * 
 * @param file
 * @param zaos
 * @throws IOException
 */
private static void addFile(File file, ZipArchiveOutputStream zaos) throws IOException {
    String filename = null;
    filename = file.getName();
    ZipArchiveEntry zae = new ZipArchiveEntry(filename);
    zae.setSize(file.length());
    zaos.putArchiveEntry(zae);
    FileInputStream fis = new FileInputStream(file);
    IOUtils.copy(fis, zaos);
    zaos.closeArchiveEntry();
}

From source file:org.xwiki.filemanager.internal.job.PackJob.java

/**
 * Packs a file./*w w  w .jav  a 2s .c o  m*/
 * 
 * @param fileReference the file to add to the ZIP archive
 * @param zip the ZIP archive to add the file to
 * @param pathPrefix the file path
 */
private void packFile(DocumentReference fileReference, ZipArchiveOutputStream zip, String pathPrefix) {
    org.xwiki.filemanager.File file = fileSystem.getFile(fileReference);
    if (file != null && fileSystem.canView(fileReference)) {
        try {
            String path = pathPrefix + file.getName();
            this.logger.info("Packing file [{}]", path);
            zip.putArchiveEntry(new ZipArchiveEntry(path));
            IOUtils.copy(file.getContent(), zip);
            zip.closeArchiveEntry();
            getStatus().setBytesWritten(zip.getBytesWritten());
        } catch (IOException e) {
            this.logger.warn("Failed to pack file [{}].", fileReference, e);
        }
    }
}

From source file:org.xwiki.filemanager.internal.job.PackJob.java

/**
 * Packs a folder.//from  ww  w .  j av  a 2s . c om
 * 
 * @param folderReference the folder to add to the ZIP archive
 * @param zip the ZIP archive to add the folder to
 * @param pathPrefix the folder path
 */
private void packFolder(DocumentReference folderReference, ZipArchiveOutputStream zip, String pathPrefix) {
    Folder folder = fileSystem.getFolder(folderReference);
    if (folder != null && fileSystem.canView(folderReference)) {
        List<DocumentReference> childFolderReferences = folder.getChildFolderReferences();
        List<DocumentReference> childFileReferences = folder.getChildFileReferences();
        notifyPushLevelProgress(childFolderReferences.size() + childFileReferences.size() + 1);

        try {
            String path = pathPrefix + folder.getName() + '/';
            this.logger.info("Packing folder [{}]", path);
            zip.putArchiveEntry(new ZipArchiveEntry(path));
            zip.closeArchiveEntry();
            notifyStepPropress();

            for (DocumentReference childFolderReference : childFolderReferences) {
                packFolder(childFolderReference, zip, path);
                notifyStepPropress();
            }

            for (DocumentReference childFileReference : childFileReferences) {
                packFile(childFileReference, zip, path);
                notifyStepPropress();
            }
        } catch (IOException e) {
            this.logger.warn("Failed to pack folder [{}].", folderReference, e);
        } finally {
            notifyPopLevelProgress();
        }
    }
}

From source file:org.xwiki.xar.XarPackage.java

/**
 * Write and add the package descriptor to the passed ZIP stream.
 * /*from   w  w w . j  a v a  2s. c  om*/
 * @param zipStream the ZIP stream in which to write
 * @param encoding the encoding to use to write the descriptor
 * @throws XarException when failing to parse the descriptor
 * @throws IOException when failing to read the file
 */
public void write(ZipArchiveOutputStream zipStream, String encoding) throws XarException, IOException {
    ZipArchiveEntry zipentry = new ZipArchiveEntry(XarModel.PATH_PACKAGE);
    zipStream.putArchiveEntry(zipentry);

    try {
        write((OutputStream) zipStream, encoding);
    } finally {
        zipStream.closeArchiveEntry();
    }
}

From source file:org.zuinnote.hadoop.office.format.common.writer.msexcel.internal.EncryptedZipEntrySource.java

public void setInputStream(InputStream is) throws IOException {
    this.tmpFile = TempFile.createTempFile("hadoopoffice-protected", ".zip");

    ZipArchiveInputStream zis = new ZipArchiveInputStream(is);
    FileOutputStream fos = new FileOutputStream(tmpFile);
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos);
    ZipArchiveEntry ze;/*  w  w  w. jav a 2 s. c  om*/
    while ((ze = (ZipArchiveEntry) zis.getNextEntry()) != null) {
        // rewrite zip entries to match the size of the encrypted data (with padding)
        ZipArchiveEntry zeNew = new ZipArchiveEntry(ze.getName());
        zeNew.setComment(ze.getComment());
        zeNew.setExtra(ze.getExtra());
        zeNew.setTime(ze.getTime());
        zos.putArchiveEntry(zeNew);
        FilterOutputStream fos2 = new FilterOutputStream(zos) {
            // do not close underlyzing ZipOutputStream
            @Override
            public void close() {
            }
        };
        OutputStream nos;
        if (this.ciEncoder != null) { // encrypt if needed
            nos = new CipherOutputStream(fos2, this.ciEncoder);
        } else { // do not encrypt
            nos = fos2;
        }
        IOUtils.copy(zis, nos);
        nos.close();
        if (fos2 != null) {
            fos2.close();
        }
        zos.closeArchiveEntry();

    }
    zos.close();
    fos.close();
    zis.close();
    IOUtils.closeQuietly(is);
    this.zipFile = new ZipFile(this.tmpFile);

}

From source file:server.Folder.java

/**
 * Create a zipped folder containing those OSDs and subfolders (recursively) which the
 * validator allows. <br/>/*from www .j a  va2  s.c  o m*/
 * Zip file encoding compatibility is difficult to achieve.<br/>
 * Using Cp437 as encoding will generate zip archives which can be unpacked with MS Windows XP
 * system utilities and also with the Linux unzip tool v6.0 (although the unzip tool will list them
 * as corrupted filenames with "?" in place for the special characters, it should unpack them
 * correctly). In tests, 7zip was unable to unpack those archives without messing up the filenames
 * - it requires UTF8 as encoding, as far as I can tell.<br/>
 * see: http://commons.apache.org/compress/zip.html#encoding<br/>
 * to manually test this, use: https://github.com/dewarim/GrailsBasedTesting
 * @param folderDao data access object for Folder objects
 * @param latestHead if set to true, only add objects with latestHead=true, if set to false include only
 *                   objects with latestHead=false, if set to null: include everything regardless of
 *                   latestHead status.
 * @param latestBranch if set to true, only add objects with latestBranch=true, if set to false include only
 *                   objects with latestBranch=false, if set to null: include everything regardless of
 *                     latestBranch status.
 * @param validator a Validator object which should be configured for the current user to check if access
 *                  to objects and folders inside the given folder is allowed. The content of this folder
 *                  will be filtered before it is added to the archive.
 * @return the zip archive of the given folder
 */
public ZippedFolder createZippedFolder(FolderDAO folderDao, Boolean latestHead, Boolean latestBranch,
        Validator validator) {
    String repositoryName = HibernateSession.getLocalRepositoryName();
    final File sysTempDir = new File(System.getProperty("java.io.tmpdir"));
    File tempFolder = new File(sysTempDir, UUID.randomUUID().toString());
    if (!tempFolder.mkdirs()) {
        throw new CinnamonException(("error.create.tempFolder.fail"));
    }

    List<Folder> folders = new ArrayList<Folder>();
    folders.add(this);
    folders.addAll(folderDao.getSubfolders(this, true));
    folders = validator.filterUnbrowsableFolders(folders);
    log.debug("# of folders found: " + folders.size());
    // create zip archive:
    ZippedFolder zippedFolder;
    try {
        File zipFile = File.createTempFile("cinnamonArchive", "zip");
        zippedFolder = new ZippedFolder(zipFile, this);

        final OutputStream out = new FileOutputStream(zipFile);
        ZipArchiveOutputStream zos = (ZipArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream(ArchiveStreamFactory.ZIP, out);
        String encoding = ConfThreadLocal.getConf().getField("zipFileEncoding", "Cp437");

        log.debug("current file.encoding: " + System.getProperty("file.encoding"));
        log.debug("current Encoding for ZipArchive: " + zos.getEncoding() + "; will now set: " + encoding);
        zos.setEncoding(encoding);
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);

        for (Folder folder : folders) {

            String path = folder.fetchPath().replace(fetchPath(), name); // do not include the parent folders up to root.
            log.debug("zipFolderPath: " + path);
            File currentFolder = new File(tempFolder, path);
            if (!currentFolder.mkdirs()) {
                // log.warn("failed  to create folder for: "+currentFolder.getAbsolutePath());
            }
            List<ObjectSystemData> osds = validator.filterUnbrowsableObjects(
                    folderDao.getFolderContent(folder, false, latestHead, latestBranch));
            if (osds.size() > 0) {
                zippedFolder.addToFolders(folder); // do not add empty folders as they are excluded automatically.
            }
            for (ObjectSystemData osd : osds) {
                if (osd.getContentSize() == null) {
                    continue;
                }
                zippedFolder.addToObjects(osd);
                File outFile = osd.createFilenameFromName(currentFolder);
                // the name in the archive should be the path without the temp folder part prepended.
                String zipEntryPath = outFile.getAbsolutePath().replace(tempFolder.getAbsolutePath(), "");
                if (zipEntryPath.startsWith(File.separator)) {
                    zipEntryPath = zipEntryPath.substring(1);
                }
                log.debug("zipEntryPath: " + zipEntryPath);

                zipEntryPath = zipEntryPath.replaceAll("\\\\", "/");
                zos.putArchiveEntry(new ZipArchiveEntry(zipEntryPath));
                IOUtils.copy(new FileInputStream(osd.getFullContentPath(repositoryName)), zos);
                zos.closeArchiveEntry();
            }
        }
        zos.close();
    } catch (Exception e) {
        log.debug("Failed to create zipFolder:", e);
        throw new CinnamonException("error.zipFolder.fail", e.getLocalizedMessage());
    }
    return zippedFolder;
}

From source file:ThirdParty.zip.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 zOut 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
 * @origin http://developer-tips.hubpages.com/hub/Zipping-and-Unzipping-Nested-Directories-in-Java-using-Apache-Commons-Compress
 * @date 2012-09-05/*from   ww  w  . ja  va  2  s . c om*/
 * @author Robin Spark
 * @throws IOException If anything goes wrong
 */
private static void addFileToZip(ZipArchiveOutputStream zOut, File path, String base) throws IOException {
    File f = path;
    String entryName = base + f.getName();
    ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName);

    zOut.putArchiveEntry(zipEntry);

    if (f.isFile()) {
        FileInputStream fInputStream = null;
        try {
            fInputStream = new FileInputStream(f);
            IOUtils.copy(fInputStream, zOut);
            zOut.closeArchiveEntry();
        } finally {
            IOUtils.closeQuietly(fInputStream);
        }

    } else {
        zOut.closeArchiveEntry();
        File[] children = f.listFiles();

        if (children != null) {
            for (File child : children) {
                addFileToZip(zOut, child, entryName + "/");
            }
        }
    }
}