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

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

Introduction

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

Prototype

public void setFallbackToUTF8(boolean b) 

Source Link

Document

Whether to fall back to UTF and the language encoding flag if the file name cannot be encoded using the specified encoding.

Usage

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//from   www. ja va  2 s . co 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.ikon.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory 
 */// www .  j av  a 2 s  .  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.silverpeas.util.ZipManager.java

/**
 * Mthode compressant un dossier de faon rcursive au format zip.
 *
 * @param folderToZip - dossier  compresser
 * @param zipFile - fichier zip  creer//w w  w  . java2  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.openkm.util.ArchiveUtils.java

/**
 * Recursively create ZIP archive from directory
 *//*from   w w w .jav a2s  .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 a va 2  s.co  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

/**
 * Compress a file into a zip file.//  www.  j a v  a2s .c om
 *
 * @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:fr.itldev.koya.alfservice.KoyaContentService.java

/**
 *
 * @param nodeRefs//from ww w . j a  va 2 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.");
    }//  w w  w . ja  v a2  s .com

    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 ww.  j  av  a  2  s  .  c  o m*/
    o.setComment(comment);
    o.setFallbackToUTF8(fallBackToUTF8);
    o.setUseLanguageEncodingFlag(useLanguageEncodingFlag);
    o.setCreateUnicodeExtraFields(createUnicodeExtraFields.getPolicy());
    o.setUseZip64(zip64Mode.getPolicy());
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.SerializationBean.java

private void serializeContentToZip(SerializationReport serializationReport, Session session,
        SerializationConfiguration serializationConfiguration, String filePath, String filename,
        ContentObjectCriteria contentObjectCriteria) throws Exception {

    File zipFile = createSerializationFile(filePath, filename);

    OutputStream out = null;//from  w  ww.ja v  a  2s  .  c  o  m
    ZipArchiveOutputStream os = null;

    try {
        out = new FileOutputStream(zipFile);
        os = (ZipArchiveOutputStream) new ArchiveStreamFactory().createArchiveOutputStream("zip", out);

        os.setFallbackToUTF8(true);

        addContentToZip(os, serializationReport, session, serializationConfiguration, filename,
                contentObjectCriteria);

        os.finish();
        os.close();
    } catch (Exception e) {
        serializationReport.getErrors().add(e.getMessage());

        throw e;
    } finally {

        if (out != null) {
            org.apache.commons.io.IOUtils.closeQuietly(out);

            out = null;
        }

        if (os != null) {
            org.apache.commons.io.IOUtils.closeQuietly(os);

            os = null;
        }

        if (CollectionUtils.isNotEmpty(serializationReport.getErrors())) {
            //Delete zipfile
            if (zipFile != null && zipFile.exists()) {
                zipFile.delete();
            }
        }

        zipFile = null;

    }

}