Example usage for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry

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

Introduction

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

Prototype

public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException 

Source Link

Document

Creates a new zip entry with fields taken from the specified zip entry.

Usage

From source file:org.ugent.caagt.genestacker.io.ZIPWriter.java

/**
 * Creates a ZIP package containing 3 files for every schedule in the given Pareto frontier:
 * <ul>/*from  w  w w  . j av a 2 s .  co m*/
 *  <li>a graph visualisation using the requested graph file format</li>
 *  <li>a dot source file used to generate the visualisation</li>
 *  <li>an XML file describing the schedule</li>
 * </ul>
 *
 * @param pf Pareto frontier
 * @param format graph file format (e.g. PDF)
 * @param colorScheme graph color scheme
 * @param outputFile output file (extension ".zip" is appended if not already contained in the file name)
 * 
 * @throws IOException if any IO errors occur
 * @throws ArchiveException if the ZIP file can not be created
 * @throws GenestackerException if any problems occur with the Gene Stacker config file
 */
public void createZIP(ParetoFrontier pf, GraphFileFormat format, GraphColorScheme colorScheme,
        String outputFile) throws IOException, ArchiveException, GenestackerException {
    // format outputFile string
    if (!outputFile.endsWith(".zip")) {
        outputFile += ".zip";
    }
    // name of folder inside ZIP (same as ZIP without extension)
    String inZIPFolder = outputFile.substring(0, outputFile.lastIndexOf('.'));
    if (inZIPFolder.indexOf('/') != -1) {
        inZIPFolder = inZIPFolder.substring(outputFile.lastIndexOf('/') + 1);
    }
    // create ZIP archive
    CrossingSchemeGraphWriter graphWriter = new CrossingSchemeGraphWriter(format, colorScheme);
    CrossingSchemeXMLWriter xmlWriter = new CrossingSchemeXMLWriter();
    try (OutputStream out = new FileOutputStream(new File(outputFile));
            ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);) {
        // add files
        int numScheme = 0;
        for (Map.Entry<Integer, Set<CrossingScheme>> gen : pf.getSchemes().entrySet()) {
            Set<CrossingScheme> schemes = gen.getValue();
            for (CrossingScheme s : schemes) {
                numScheme++;
                // create xml
                File xml = Files.createTempFile("scheme-", ".xml").toFile();
                xmlWriter.write(s, xml);
                // create graph
                File graph = Files.createTempFile("scheme-", "." + format).toFile();
                File graphvizSource = graphWriter.write(s, graph);
                // copy xml, diagram and graphviz source to zip file
                os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + ".xml"));
                IOUtils.copy(new FileInputStream(xml), os);
                os.closeArchiveEntry();
                // only copy graph if successfully created!
                if (graph.exists()) {
                    os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + "." + format));
                    IOUtils.copy(new FileInputStream(graph), os);
                    os.closeArchiveEntry();
                }
                os.putArchiveEntry(new ZipArchiveEntry(inZIPFolder + "/scheme" + numScheme + ".graphviz"));
                IOUtils.copy(new FileInputStream(graphvizSource), os);
                os.closeArchiveEntry();
                // delete temp files
                xml.delete();
                graph.delete();
            }
        }
    }
}

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

/**
 * Recursive traversal to add files/*from   w ww .j av  a2s .c o  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/*w  w  w.j av a2s  .c  o  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./*from  w  ww.  java  2 s .  c  om*/
 * 
 * @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  w w  w.ja v a 2  s. c  o m*/
 * 
 * @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.filter.xar.internal.output.XARWikiWriter.java

public OutputStream newEntry(LocalDocumentReference reference) throws FilterException {
    StringBuilder path = new StringBuilder();

    // Add space path
    addSpacePath(path, reference.getParent());

    // Add document name
    path.append(escapeXARPath(reference.getName()));

    // Add language
    if (reference.getLocale() != null && !reference.getLocale().equals(Locale.ROOT)) {
        path.append('.');
        path.append(reference.getLocale());
    }//from  w w w  . j a  va  2  s .  co m

    // Add extension
    path.append(".xml");

    String entryName = path.toString();

    ZipArchiveEntry zipentry = new ZipArchiveEntry(entryName);
    try {
        this.zipStream.putArchiveEntry(zipentry);
    } catch (IOException e) {
        throw new FilterException("Failed to add a new zip entry for [" + path + "]", e);
    }

    this.xarPackage.addEntry(reference, entryName);

    return this.zipStream;
}

From source file:org.xwiki.wikistream.xar.internal.output.XARWikiWriter.java

public OutputStream newEntry(LocalDocumentReference reference) throws WikiStreamException {
    StringBuilder path = new StringBuilder();

    // Add space name
    path.append(reference.getParent().getName()).append('/');

    // Add document name
    path.append(reference.getName());//from w  ww.  ja  v a  2s .co m

    // Add language
    if (reference.getLocale() != null && !reference.getLocale().equals(Locale.ROOT)) {
        path.append('.');
        path.append(reference.getLocale());
    }

    // Add extension
    path.append(".xml");

    ZipArchiveEntry zipentry = new ZipArchiveEntry(path.toString());
    try {
        this.zipStream.putArchiveEntry(zipentry);
    } catch (IOException e) {
        throw new WikiStreamException("Failed to add a new zip entry for [" + path + "]", e);
    }

    this.xarPackage.addEntry(reference);

    return this.zipStream;
}

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

/**
 * Write and add the package descriptor to the passed ZIP stream.
 * // w  ww . j  a va  2s  . co  m
 * @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;/*  www  .j a v a 2  s .  co m*/
    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/>/*  w w  w.j a v  a2  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;
}