List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream setEncoding
public void setEncoding(final String encoding)
From source file:com.silverpeas.util.ZipManager.java
/** * Compress a file into a zip file.// w w w . j a v a2 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:com.atolcd.web.scripts.ZipContents.java
public void createZipFile(List<String> nodeIds, OutputStream os, boolean noaccent) throws IOException { File zip = null;/* www.j av a2s .c o m*/ try { if (nodeIds != null && !nodeIds.isEmpty()) { zip = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, ZIP_EXTENSION); FileOutputStream stream = new FileOutputStream(zip); CheckedOutputStream checksum = new CheckedOutputStream(stream, new Adler32()); BufferedOutputStream buff = new BufferedOutputStream(checksum); ZipArchiveOutputStream out = new ZipArchiveOutputStream(buff); out.setEncoding(encoding); out.setMethod(ZipArchiveOutputStream.DEFLATED); out.setLevel(Deflater.BEST_COMPRESSION); if (logger.isDebugEnabled()) { logger.debug("Using encoding '" + encoding + "' for zip file."); } try { for (String nodeId : nodeIds) { NodeRef node = new NodeRef(storeRef, nodeId); addToZip(node, out, noaccent, ""); } } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { out.close(); buff.close(); checksum.close(); stream.close(); if (nodeIds.size() > 0) { InputStream in = new FileInputStream(zip); try { byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buffer)) > 0) { os.write(buffer, 0, len); } } finally { IOUtils.closeQuietly(in); } } } } } catch (Exception e) { logger.error(e.getMessage(), e); throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage()); } finally { // try and delete the temporary file if (zip != null) { zip.delete(); } } }
From source file:com.haulmont.cuba.core.app.FoldersServiceBean.java
@Override public byte[] exportFolder(Folder folder) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream); zipOutputStream.setMethod(ZipArchiveOutputStream.STORED); zipOutputStream.setEncoding(StandardCharsets.UTF_8.name()); String xml = createXStream().toXML(folder); byte[] xmlBytes = xml.getBytes(StandardCharsets.UTF_8); ArchiveEntry zipEntryDesign = newStoredEntry("folder.xml", xmlBytes); zipOutputStream.putArchiveEntry(zipEntryDesign); zipOutputStream.write(xmlBytes);/*from ww w. j a v a 2 s. c o m*/ try { zipOutputStream.closeArchiveEntry(); } catch (Exception ex) { throw new RuntimeException( String.format("Exception occurred while exporting folder %s.", folder.getName())); } zipOutputStream.close(); return byteArrayOutputStream.toByteArray(); }
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 . j a v a 2s . c o 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:fr.itldev.koya.alfservice.KoyaContentService.java
/** * * @param nodeRefs// www . ja v a 2s.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.haulmont.cuba.core.app.importexport.EntityImportExport.java
@Override public byte[] exportEntitiesToZIP(Collection<? extends Entity> entities) { String json = entitySerialization.toJson(entities, null, EntitySerializationOption.COMPACT_REPEATED_ENTITIES); byte[] jsonBytes = json.getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(byteArrayOutputStream); zipOutputStream.setMethod(ZipArchiveOutputStream.STORED); zipOutputStream.setEncoding(StandardCharsets.UTF_8.name()); ArchiveEntry singleDesignEntry = newStoredEntry("entities.json", jsonBytes); try {/* w w w .j a v a 2 s. c o m*/ zipOutputStream.putArchiveEntry(singleDesignEntry); zipOutputStream.write(jsonBytes); zipOutputStream.closeArchiveEntry(); } catch (Exception e) { throw new RuntimeException("Error on creating zip archive during entities export", e); } finally { IOUtils.closeQuietly(zipOutputStream); } return byteArrayOutputStream.toByteArray(); }
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."); }// ww w .j a v a 2s . c om 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:ee.sk.digidoc.SignedDoc.java
/** * Writes the SignedDoc to an output file * and automatically calculates DataFile sizes * and digests//from ww w. j a v a 2 s .com * @param outputFile output file name * @param fTempSdoc temporrary file, copy of original for copying items * @throws DigiDocException for all errors */ public void writeToStream(OutputStream os/*, File fTempSdoc*/) throws DigiDocException { DigiDocException ex1 = validateFormatAndVersion(); if (ex1 != null) throw ex1; try { DigiDocXmlGenFactory genFac = new DigiDocXmlGenFactory(this); if (m_format.equals(SignedDoc.FORMAT_BDOC)) { ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setEncoding("UTF-8"); if (m_logger.isDebugEnabled()) m_logger.debug("OS: " + ((os != null) ? "OK" : "NULL")); // write mimetype if (m_logger.isDebugEnabled()) m_logger.debug("Writing: " + MIMET_FILE_NAME); ZipArchiveEntry ze = new ZipArchiveEntry(MIMET_FILE_NAME); if (m_comment == null) m_comment = DigiDocGenFactory.getUserInfo(m_format, m_version); ze.setComment(m_comment); ze.setMethod(ZipArchiveEntry.STORED); java.util.zip.CRC32 crc = new java.util.zip.CRC32(); if (m_version.equals(BDOC_VERSION_1_0)) { ze.setSize(SignedDoc.MIMET_FILE_CONTENT_10.getBytes().length); crc.update(SignedDoc.MIMET_FILE_CONTENT_10.getBytes()); } if (m_version.equals(BDOC_VERSION_1_1)) { ze.setSize(SignedDoc.MIMET_FILE_CONTENT_11.getBytes().length); crc.update(SignedDoc.MIMET_FILE_CONTENT_11.getBytes()); } if (m_version.equals(BDOC_VERSION_2_1)) { ze.setSize(SignedDoc.MIMET_FILE_CONTENT_20.getBytes().length); crc.update(SignedDoc.MIMET_FILE_CONTENT_20.getBytes()); } ze.setCrc(crc.getValue()); zos.putArchiveEntry(ze); if (m_version.equals(BDOC_VERSION_1_0)) { zos.write(SignedDoc.MIMET_FILE_CONTENT_10.getBytes()); } if (m_version.equals(BDOC_VERSION_1_1)) { zos.write(SignedDoc.MIMET_FILE_CONTENT_11.getBytes()); } if (m_version.equals(BDOC_VERSION_2_1)) { zos.write(SignedDoc.MIMET_FILE_CONTENT_20.getBytes()); } zos.closeArchiveEntry(); // write manifest.xml if (m_logger.isDebugEnabled()) m_logger.debug("Writing: " + MANIF_FILE_NAME); ze = new ZipArchiveEntry(MANIF_DIR_META_INF); ze = new ZipArchiveEntry(MANIF_FILE_NAME); ze.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version)); zos.putArchiveEntry(ze); //if(m_logger.isDebugEnabled()) // m_logger.debug("Writing manif:\n" + m_manifest.toString()); zos.write(m_manifest.toXML()); zos.closeArchiveEntry(); // write data files for (int i = 0; i < countDataFiles(); i++) { DataFile df = getDataFile(i); if (m_logger.isDebugEnabled()) m_logger.debug("Writing DF: " + df.getFileName() + " content: " + df.getContentType() + " df-cache: " + ((df.getDfCacheFile() != null) ? df.getDfCacheFile().getAbsolutePath() : "NONE")); InputStream is = null; if (df.hasAccessToDataFile()) is = df.getBodyAsStream(); else is = findDataFileAsStream(df.getFileName()); if (is != null) { File dfFile = new File(df.getFileName()); String fileName = dfFile.getName(); ze = new ZipArchiveEntry(fileName); if (df.getComment() == null) df.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version)); ze.setComment(df.getComment()); ze.setSize(dfFile.length()); ze.setTime( (df.getLastModDt() != null) ? df.getLastModDt().getTime() : dfFile.lastModified()); zos.putArchiveEntry(ze); byte[] data = new byte[2048]; int nRead = 0, nTotal = 0; crc = new java.util.zip.CRC32(); while ((nRead = is.read(data)) > 0) { zos.write(data, 0, nRead); nTotal += nRead; crc.update(data, 0, nRead); } ze.setSize(nTotal); ze.setCrc(crc.getValue()); zos.closeArchiveEntry(); is.close(); } } for (int i = 0; i < countSignatures(); i++) { Signature sig = getSignature(i); String sFileName = sig.getPath(); if (sFileName == null) { if (m_version.equals(BDOC_VERSION_2_1)) sFileName = SIG_FILE_NAME_20 + (i + 1) + ".xml"; else sFileName = SIG_FILE_NAME + (i + 1) + ".xml"; } if (!sFileName.startsWith("META-INF")) sFileName = "META-INF/" + sFileName; if (m_logger.isDebugEnabled()) m_logger.debug("Writing SIG: " + sFileName + " orig: " + ((sig.getOrigContent() != null) ? "OK" : "NULL")); ze = new ZipArchiveEntry(sFileName); if (sig.getComment() == null) sig.setComment(DigiDocGenFactory.getUserInfo(m_format, m_version)); ze.setComment(sig.getComment()); String sSig = null; if (sig.getOrigContent() != null) sSig = new String(sig.getOrigContent(), "UTF-8"); else sSig = sig.toString(); if (sSig != null && !sSig.startsWith("<?xml")) sSig = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + sSig; byte[] sdata = sSig.getBytes("UTF-8"); if (m_logger.isDebugEnabled()) m_logger.debug("Writing SIG: " + sFileName + " xml:\n---\n " + ((sSig != null) ? sSig : "NULL") + "\n---\n "); ze.setSize(sdata.length); crc = new java.util.zip.CRC32(); crc.update(sdata); ze.setCrc(crc.getValue()); zos.putArchiveEntry(ze); zos.write(sdata); zos.closeArchiveEntry(); } zos.close(); } else if (m_format.equals(SignedDoc.FORMAT_DIGIDOC_XML)) { // ddoc format os.write(xmlHeader().getBytes()); for (int i = 0; i < countDataFiles(); i++) { DataFile df = getDataFile(i); df.writeToFile(os); os.write("\n".getBytes()); } for (int i = 0; i < countSignatures(); i++) { Signature sig = getSignature(i); if (sig.getOrigContent() != null) os.write(sig.getOrigContent()); else os.write(genFac.signatureToXML(sig)); os.write("\n".getBytes()); } os.write(xmlTrailer().getBytes()); } } catch (DigiDocException ex) { throw ex; // allready handled } catch (Exception ex) { DigiDocException.handleException(ex, DigiDocException.ERR_WRITE_FILE); } }
From source file:net.test.aliyun.z7.Task.java
public void doWork() throws Throwable { //init task to DB System.out.println("do Task " + index + "\t from :" + oldKey); ///*w w w . j a va 2s .c o m*/ //1. System.out.print("\t save to Local -> working... "); OSSObject ossObject = client.getObject("files-subtitle", oldKey); File rarFile = new File(this.tempPath, ossObject.getObjectMetadata().getContentDisposition()); rarFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(rarFile, false); InputStream inStream = ossObject.getObjectContent(); IOUtils.copy(inStream, fos); fos.flush(); fos.close(); System.out.print("-> finish.\n"); // //2. System.out.print("\t extract rar -> working... "); String extToosHome = "C:\\Program Files (x86)\\7-Zip"; String rarFileStr = rarFile.getAbsolutePath(); String toDir = rarFileStr.substring(0, rarFileStr.length() - ".rar".length()); // // int extract = Zip7Object.extract(extToosHome, rarFile.getAbsolutePath(), toDir); if (extract != 0) { if (extract != 2) System.out.println(); FileUtils.deleteDir(new File(toDir)); rarFile.delete(); throw new Exception("extract error."); } System.out.print("-> finish.\n"); // //3. System.out.print("\t package zip-> working... "); String zipFileName = rarFile.getAbsolutePath(); zipFileName = zipFileName.substring(0, zipFileName.length() - ".rar".length()) + ".zip"; ZipArchiveOutputStream outStream = new ZipArchiveOutputStream(new File(zipFileName)); outStream.setEncoding("GBK"); Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(), FileFilterUtils.directoryFileFilter()); StringBuffer buffer = new StringBuffer(); while (itFile.hasNext()) { File it = itFile.next(); if (it.isDirectory()) continue; String entName = it.getAbsolutePath().substring(toDir.length() + 1); ZipArchiveEntry ent = new ZipArchiveEntry(it, entName); outStream.putArchiveEntry(ent); InputStream itInStream = new FileInputStream(it); IOUtils.copy(itInStream, outStream); itInStream.close(); outStream.flush(); outStream.closeArchiveEntry(); buffer.append(ent.getName()); } outStream.flush(); outStream.close(); System.out.print("-> finish.\n"); // //4. FileUtils.deleteDir(new File(toDir)); System.out.print("\t delete temp dir -> finish.\n"); // //5.save to System.out.print("\t save to oss -> working... "); ObjectMetadata omd = ossObject.getObjectMetadata(); String contentDisposition = omd.getContentDisposition(); contentDisposition = contentDisposition.substring(0, contentDisposition.length() - ".rar".length()) + ".zip"; omd.setContentDisposition(contentDisposition); omd.setContentLength(new File(zipFileName).length()); InputStream zipInStream = new FileInputStream(zipFileName); PutObjectResult result = client.putObject("files-subtitle-format-zip", newKey, zipInStream, omd); zipInStream.close(); new File(zipFileName).delete(); System.out.print("-> OK:" + result.getETag()); System.out.print("-> finish.\n"); // //6.save files info int res = jdbc.update("update `oss-subtitle` set files=? , size=? , lastTime=now() where oss_key =?", buffer.toString(), omd.getContentLength(), newKey); System.out.println("\t save info to db -> " + res); }
From source file:no.difi.sdp.client.asice.archive.CreateZip.java
public Archive zipIt(List<AsicEAttachable> files) { ByteArrayOutputStream archive = null; ZipArchiveOutputStream zipOutputStream = null; try {/* ww w .j a v a 2 s . co m*/ archive = new ByteArrayOutputStream(); zipOutputStream = new ZipArchiveOutputStream(archive); zipOutputStream.setEncoding(Charsets.UTF_8.name()); zipOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED); for (AsicEAttachable file : files) { log.trace("Adding " + file.getFileName() + " to archive. Size in bytes before compression: " + file.getBytes().length); ZipArchiveEntry zipEntry = new ZipArchiveEntry(file.getFileName()); zipEntry.setSize(file.getBytes().length); zipOutputStream.putArchiveEntry(zipEntry); IOUtils.copy(new ByteArrayInputStream(file.getBytes()), zipOutputStream); zipOutputStream.closeArchiveEntry(); } zipOutputStream.finish(); zipOutputStream.close(); return new Archive(archive.toByteArray()); } catch (IOException e) { throw new RuntimeIOException(e); } finally { IOUtils.closeQuietly(archive); IOUtils.closeQuietly(zipOutputStream); } }