List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream ZipArchiveOutputStream
public ZipArchiveOutputStream(File file) throws IOException
From source file:at.spardat.xma.xdelta.JarDelta.java
/** * Main method to make {@link #computeDelta(String, String, ZipFile, ZipFile, ZipArchiveOutputStream)} available at * the command line.<br>// w w w . j a va 2s . com * usage JarDelta source target output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { if (args.length != 3) { System.err.println("usage JarDelta source target output"); return; } try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(args[2]))) { new JarDelta().computeDelta(args[0], args[1], new ZipFile(args[0]), new ZipFile(args[1]), output); } }
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;//from w ww . jav a 2 s .co 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:com.facebook.buck.zip.UnzipTest.java
@Test public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws IOException { // getFakeTime returs time with some non-zero millis. By doing division and multiplication by // 1000 we get rid of that. final long time = ZipConstants.getFakeTime() / 1000 * 1000; // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("test.exe"); entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------"))); entry.setSize(DUMMY_FILE_CONTENTS.length); entry.setMethod(ZipEntry.STORED); entry.setTime(time);//from w ww . java2 s. com zip.putArchiveEntry(entry); zip.write(DUMMY_FILE_CONTENTS); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path exe = extractFolder.toAbsolutePath().resolve("test.exe"); assertTrue(Files.exists(exe)); assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time)); assertTrue(Files.isExecutable(exe)); assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result); }
From source file:com.xpn.xwiki.plugin.packaging.AbstractPackageTest.java
/** * Create a XAR file using commons compress. * * @param docs The documents to include. * @param encodings The charset for each document. * @param packageXmlEncoding The encoding of package.xml * @return the XAR file as a byte array. */// w w w. ja v a2s .c o m protected byte[] createZipFileUsingCommonsCompress(XWikiDocument docs[], String[] encodings, String packageXmlEncoding) throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(baos); ZipArchiveEntry zipp = new ZipArchiveEntry("package.xml"); zos.putArchiveEntry(zipp); zos.write(getEncodedByteArray(getPackageXML(docs, packageXmlEncoding), packageXmlEncoding)); for (int i = 0; i < docs.length; i++) { String zipEntryName = docs[i].getSpace() + "/" + docs[i].getName(); if (docs[i].getTranslation() != 0) { zipEntryName += "." + docs[i].getLanguage(); } ZipArchiveEntry zipe = new ZipArchiveEntry(zipEntryName); zos.putArchiveEntry(zipe); String xmlCode = docs[i].toXML(false, false, false, false, getContext()); zos.write(getEncodedByteArray(xmlCode, encodings[i])); zos.closeArchiveEntry(); } zos.finish(); zos.close(); return baos.toByteArray(); }
From source file:com.gitblit.servlet.PtServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {//from w w w. j a v a2 s.com response.setContentType("application/octet-stream"); response.setDateHeader("Last-Modified", lastModified); response.setHeader("Cache-Control", "none"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", 0); boolean windows = false; try { String useragent = request.getHeader("user-agent").toString(); windows = useragent.toLowerCase().contains("windows"); } catch (Exception e) { } byte[] pyBytes; File file = runtimeManager.getFileOrFolder("tickets.pt", "${baseFolder}/pt.py"); if (file.exists()) { // custom script pyBytes = readAll(new FileInputStream(file)); } else { // default script pyBytes = readAll(getClass().getResourceAsStream("/pt.py")); } if (windows) { // windows: download zip file with pt.py and pt.cmd response.setHeader("Content-Disposition", "attachment; filename=\"pt.zip\""); OutputStream os = response.getOutputStream(); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); // add the Python script ZipArchiveEntry pyEntry = new ZipArchiveEntry("pt.py"); pyEntry.setSize(pyBytes.length); pyEntry.setUnixMode(FileMode.EXECUTABLE_FILE.getBits()); pyEntry.setTime(lastModified); zos.putArchiveEntry(pyEntry); zos.write(pyBytes); zos.closeArchiveEntry(); // add a Python launch cmd file byte[] cmdBytes = readAll(getClass().getResourceAsStream("/pt.cmd")); ZipArchiveEntry cmdEntry = new ZipArchiveEntry("pt.cmd"); cmdEntry.setSize(cmdBytes.length); cmdEntry.setUnixMode(FileMode.REGULAR_FILE.getBits()); cmdEntry.setTime(lastModified); zos.putArchiveEntry(cmdEntry); zos.write(cmdBytes); zos.closeArchiveEntry(); // add a brief readme byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt")); ZipArchiveEntry txtEntry = new ZipArchiveEntry("readme.txt"); txtEntry.setSize(txtBytes.length); txtEntry.setUnixMode(FileMode.REGULAR_FILE.getBits()); txtEntry.setTime(lastModified); zos.putArchiveEntry(txtEntry); zos.write(txtBytes); zos.closeArchiveEntry(); // cleanup zos.finish(); zos.close(); os.flush(); } else { // unix: download a tar.gz file with pt.py set with execute permissions response.setHeader("Content-Disposition", "attachment; filename=\"pt.tar.gz\""); OutputStream os = response.getOutputStream(); CompressorOutputStream cos = new CompressorStreamFactory() .createCompressorOutputStream(CompressorStreamFactory.GZIP, os); TarArchiveOutputStream tos = new TarArchiveOutputStream(cos); tos.setAddPaxHeadersForNonAsciiNames(true); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); // add the Python script TarArchiveEntry pyEntry = new TarArchiveEntry("pt"); pyEntry.setMode(FileMode.EXECUTABLE_FILE.getBits()); pyEntry.setModTime(lastModified); pyEntry.setSize(pyBytes.length); tos.putArchiveEntry(pyEntry); tos.write(pyBytes); tos.closeArchiveEntry(); // add a brief readme byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt")); TarArchiveEntry txtEntry = new TarArchiveEntry("README"); txtEntry.setMode(FileMode.REGULAR_FILE.getBits()); txtEntry.setModTime(lastModified); txtEntry.setSize(txtBytes.length); tos.putArchiveEntry(txtEntry); tos.write(txtBytes); tos.closeArchiveEntry(); // cleanup tos.finish(); tos.close(); cos.close(); os.flush(); } } catch (Exception e) { e.printStackTrace(); } }
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 .c o 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.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 {//from w ww . j a va2 s . com 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.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java
private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException { try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) { for (Path start : starts.keySet()) { final String rootEntryName = starts.get(start); Files.walkFileTree(start, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Skip pyc files. if (file.getFileName().toString().endsWith(".pyc")) return FileVisitResult.CONTINUE; String entryName = rootEntryName; String relativePath = start.relativize(file).toString(); // If empty, file is the start file. if (!relativePath.isEmpty()) { entryName = entryName + "/" + relativePath; }/*from ww w.jav a2 s .co m*/ // Zip uses forward slashes entryName = entryName.replace(File.separatorChar, '/'); ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName); if (Files.isExecutable(file)) entry.setUnixMode(0100770); else entry.setUnixMode(0100660); zos.putArchiveEntry(entry); Files.copy(file, zos); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final String dirName = dir.getFileName().toString(); // Don't include pyc files or .toolkit if (dirName.equals("__pycache__")) return FileVisitResult.SKIP_SUBTREE; ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/" + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/"); zos.putArchiveEntry(dirEntry); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } }); } } }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws InterruptedException, IOException { // getFakeTime returs time with some non-zero millis. By doing division and multiplication by // 1000 we get rid of that. long time = ZipConstants.getFakeTime() / 1000 * 1000; // Create a simple zip archive using apache's commons-compress to store executable info. try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) { ZipArchiveEntry entry = new ZipArchiveEntry("test.exe"); entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------"))); entry.setSize(DUMMY_FILE_CONTENTS.length); entry.setMethod(ZipEntry.STORED); entry.setTime(time);/*w w w. j a v a 2s . c o m*/ zip.putArchiveEntry(entry); zip.write(DUMMY_FILE_CONTENTS); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive( new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path exe = extractFolder.toAbsolutePath().resolve("test.exe"); assertTrue(Files.exists(exe)); assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time)); assertTrue(Files.isExecutable(exe)); assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result); }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Creates a zip file with random content. * * @author S3460/* w w w .j a va2s .c om*/ * @param source the source * @return the zip file * @throws Exception the exception */ private ZipFile makeSourceZipFile(File source) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(source)); int size = randomSize(entryMaxSize); for (int i = 0; i < size; i++) { out.putArchiveEntry(new ZipArchiveEntry("zipentry" + i)); int anz = randomSize(10); for (int j = 0; j < anz; j++) { byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); } out.flush(); out.closeArchiveEntry(); } //add leeres Entry out.putArchiveEntry(new ZipArchiveEntry("zipentry" + size)); out.flush(); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(source); }