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

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

Introduction

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

Prototype

public void setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy b) 

Source Link

Document

Whether to create Unicode Extra Fields.

Usage

From source file:com.ikon.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory 
 *///w  w w . j  a  v  a 2s .  c  o  m
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by openkm");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory
 *///  www  .ja  v a 2s .c  o  m
public static void createZip(File path, String root, OutputStream os) throws IOException {
    log.debug("createZip({}, {}, {})", new Object[] { path, root, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        // Prevents java.util.zip.ZipException: ZIP file must have at least one entry
        ZipArchiveEntry zae = new ZipArchiveEntry(root + "/");
        zaos.putArchiveEntry(zae);
        zaos.closeArchiveEntry();

        createZipHelper(path, zaos, root);

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.openkm.util.ArchiveUtils.java

/**
 * Create ZIP archive from file/*from   w w w .  j  av a  2 s .c  o  m*/
 */
public static void createZip(File path, OutputStream os) throws IOException {
    log.debug("createZip({}, {})", new Object[] { path, os });

    if (path.exists() && path.canRead()) {
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(os);
        zaos.setComment("Generated by OpenKM");
        zaos.setCreateUnicodeExtraFields(UnicodeExtraFieldPolicy.ALWAYS);
        zaos.setUseLanguageEncodingFlag(true);
        zaos.setFallbackToUTF8(true);
        zaos.setEncoding("UTF-8");

        log.debug("FILE {}", path);
        ZipArchiveEntry zae = new ZipArchiveEntry(path.getName());
        zaos.putArchiveEntry(zae);
        FileInputStream fis = new FileInputStream(path);
        IOUtils.copy(fis, zaos);
        fis.close();
        zaos.closeArchiveEntry();

        zaos.flush();
        zaos.finish();
        zaos.close();
    } else {
        throw new IOException("Can't access " + path);
    }

    log.debug("createZip: void");
}

From source file:com.silverpeas.util.ZipManager.java

/**
 * Mthode permettant la cration et l'organisation d'un fichier zip en lui passant directement un
 * flux d'entre// w w w. j  a v a2s.c  o  m
 *
 * @param inputStream - flux de donnes  enregistrer dans le zip
 * @param filePathNameToCreate - chemin et nom du fichier port par les donnes du flux dans le
 * zip
 * @param outfilename - chemin et nom du fichier zip  creer ou complter
 * @throws IOException
 */
public static void compressStreamToZip(InputStream inputStream, String filePathNameToCreate, String outfilename)
        throws IOException {
    ZipArchiveOutputStream zos = null;
    try {
        zos = new ZipArchiveOutputStream(new FileOutputStream(outfilename));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding("UTF-8");
        zos.putArchiveEntry(new ZipArchiveEntry(filePathNameToCreate));
        IOUtils.copy(inputStream, zos);
        zos.closeArchiveEntry();
    } finally {
        if (zos != null) {
            IOUtils.closeQuietly(zos);
        }
    }
}

From source file:com.silverpeas.util.ZipManager.java

/**
 * Mthode compressant un dossier de faon rcursive au format zip.
 *
 * @param folderToZip - dossier  compresser
 * @param zipFile - fichier zip  creer/*ww w  . j  a v  a  2  s .  co  m*/
 * @return la taille du fichier zip gnr en octets
 * @throws FileNotFoundException
 * @throws IOException
 */
public static long compressPathToZip(File folderToZip, File zipFile) throws IOException {
    ZipArchiveOutputStream zos = null;
    try {
        // cration du flux zip
        zos = new ZipArchiveOutputStream(new FileOutputStream(zipFile));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(CharEncoding.UTF_8);
        Collection<File> folderContent = FileUtils.listFiles(folderToZip, null, true);
        for (File file : folderContent) {
            String entryName = file.getPath().substring(folderToZip.getParent().length() + 1);
            entryName = FilenameUtils.separatorsToUnix(entryName);
            zos.putArchiveEntry(new ZipArchiveEntry(entryName));
            InputStream in = new FileInputStream(file);
            IOUtils.copy(in, zos);
            zos.closeArchiveEntry();
            IOUtils.closeQuietly(in);
        }
    } finally {
        if (zos != null) {
            IOUtils.closeQuietly(zos);
        }
    }
    return zipFile.length();
}

From source file:com.silverpeas.util.ZipManager.java

/**
 * Compress a file into a zip file.//from ww w . j a v  a  2  s  .  co m
 *
 * @param filePath
 * @param zipFilePath
 * @return
 * @throws IOException
 */
public static long compressFile(String filePath, String zipFilePath) throws IOException {
    ZipArchiveOutputStream zos = new ZipArchiveOutputStream(new FileOutputStream(zipFilePath));
    InputStream in = new FileInputStream(filePath);
    try {
        // cration du flux zip
        zos = new ZipArchiveOutputStream(new FileOutputStream(zipFilePath));
        zos.setFallbackToUTF8(true);
        zos.setCreateUnicodeExtraFields(NOT_ENCODEABLE);
        zos.setEncoding(CharEncoding.UTF_8);
        String entryName = FilenameUtils.getName(filePath);
        entryName = entryName.replace(File.separatorChar, '/');
        zos.putArchiveEntry(new ZipArchiveEntry(entryName));
        IOUtils.copy(in, zos);
        zos.closeArchiveEntry();
        return new File(zipFilePath).length();
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(zos);
    }
}

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

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

    if (redirect != NO_REDIRECTION) {
        return;//  w  w w.  ja v  a  2s.  com
    }

    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:fr.itldev.koya.alfservice.KoyaContentService.java

/**
 *
 * @param nodeRefs/*from w w  w .j a  v a2 s.  c om*/
 * @return
 * @throws KoyaServiceException
 */
public File zip(List<String> nodeRefs) throws KoyaServiceException {
    File tmpZipFile = null;
    try {
        tmpZipFile = TempFileProvider.createTempFile("tmpDL", ".zip");
        FileOutputStream fos = new FileOutputStream(tmpZipFile);
        CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
        BufferedOutputStream buff = new BufferedOutputStream(checksum);
        ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(buff);
        // NOTE: This encoding allows us to workaround bug...
        // http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807
        zipStream.setEncoding("UTF-8");

        zipStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        zipStream.setLevel(Deflater.BEST_COMPRESSION);

        zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
        zipStream.setUseLanguageEncodingFlag(true);
        zipStream.setFallbackToUTF8(true);

        try {
            for (String nodeRef : nodeRefs) {
                addToZip(koyaNodeService.getNodeRef(nodeRef), zipStream, "");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } finally {
            zipStream.close();
            buff.close();
            checksum.close();
            fos.close();

        }
    } catch (IOException | WebScriptException e) {
        logger.error(e.getMessage(), e);
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }

    return tmpZipFile;
}

From source file:com.naryx.tagfusion.expression.function.file.Zip.java

public cfData execute(cfSession session, cfArgStructData argStruct, List<cfZipItem> zipItems)
        throws cfmRunTimeException {

    String destStr = getNamedStringParam(argStruct, "zipfile", null);
    if (destStr.length() == 0 || destStr == null) {
        throwException(session, "Missing the ZIPFILE argument or is an empty string.");
    }//from ww w . j  a  va2 s.c o  m

    String sourceStr = getNamedStringParam(argStruct, "source", null);
    File src = null;
    if (sourceStr != null) {
        if (sourceStr.length() == 0) {
            throwException(session, "SOURCE specified is an empty string. It is not a valid path.");
        } else {
            src = new File(sourceStr);
            // Check if src is a valid file/directory
            checkZipfile(session, src);
        }
    }

    boolean recurse = getNamedBooleanParam(argStruct, "recurse", true);
    String prefixStr = getNamedStringParam(argStruct, "prefix", "");
    String prefix = prefixStr.replace('\\', '/');
    if (prefix.length() != 0 && !prefix.endsWith("/")) {
        prefix = prefix + "/";
    }

    String newpath = getNamedStringParam(argStruct, "newpath", null);
    if (newpath != null) {
        if (newpath.length() == 0) {
            throwException(session, "NEWPATH specified is an empty string. It is not a valid path.");
        }
    }
    boolean overwrite = getNamedBooleanParam(argStruct, "overwrite", false);

    int compressionLevel = getNamedIntParam(argStruct, "compressionlevel", ZipArchiveOutputStream.DEFLATED);

    if (compressionLevel < 0 || compressionLevel > 9) {
        throwException(session,
                "Invalid COMPRESSIONLEVEL specified. Please specify a number from 0-9 (inclusive).");
    }

    String filterStr = getNamedStringParam(argStruct, "filter", null);
    FilenameFilter filter = null;
    if (filterStr != null) {
        filter = new filePatternFilter(filterStr, true);
    }

    String charset = getNamedStringParam(argStruct, "charset", System.getProperty("file.encoding"));

    // Destination file
    File zipfile = new File(destStr);

    // OVERWRITE
    if (zipfile.exists() && overwrite) {
        zipfile.delete();
    } else if (zipfile.exists() && !overwrite) {
        throwException(session, "Cannot overwrite the existing file");
    }

    ZipArchiveOutputStream zipOut = null;
    FileOutputStream fout = null;

    File parent = zipfile.getParentFile();

    if (parent != null) { // create parent directories if required
        parent.mkdirs();
    }

    try {
        fout = new FileOutputStream(zipfile);

    } catch (IOException e) {
        throwException(session,
                "Failed to create zip file: [" + zipfile.getAbsolutePath() + "]. Reason: " + e.getMessage());
    }
    try {
        zipOut = new ZipArchiveOutputStream(fout);
        zipOut.setEncoding(charset);
        zipOut.setFallbackToUTF8(true);
        zipOut.setUseLanguageEncodingFlag(true);
        zipOut.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);

        // Code for Zipparams
        if (zipItems != null) {
            Iterator<cfZipItem> srcItems = zipItems.iterator();
            cfZipItem nextItem;
            while (srcItems.hasNext()) {
                nextItem = srcItems.next();
                zipOperation(session, zipOut, nextItem.getFile(), nextItem.getRecurse(), nextItem.getPrefix(),
                        compressionLevel, nextItem.getFilter(), nextItem.getNewPath());
            }
        }

        // Code for function without zippparams
        zipOperation(session, zipOut, src, recurse, prefix, compressionLevel, filter, newpath);

    } finally {
        StreamUtil.closeStream(zipOut);
        StreamUtil.closeStream(fout);
    }

    return cfBooleanData.TRUE;

}

From source file:org.apache.ant.compress.taskdefs.Zip.java

private void configure(ZipArchiveOutputStream o) {
    o.setLevel(level);/*from  w w w .  j  a  va2  s. c o m*/
    o.setComment(comment);
    o.setFallbackToUTF8(fallBackToUTF8);
    o.setUseLanguageEncodingFlag(useLanguageEncodingFlag);
    o.setCreateUnicodeExtraFields(createUnicodeExtraFields.getPolicy());
    o.setUseZip64(zip64Mode.getPolicy());
}