List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry setSize
public void setSize(long size)
From source file:com.facebook.buck.zip.UnzipTest.java
@Test public void testExtractSymlink() throws IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // 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("link.txt"); entry.setUnixMode((int) MoreFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry);/*from ww w. j a v a 2 s.c o m*/ zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable. Path extractFolder = tmpFolder.newFolder(); Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
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 . j a va2 s . 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 = 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.gitblit.servlet.PtServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from w ww .j a v a 2 s.c om*/ 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.haulmont.cuba.core.app.FoldersServiceBean.java
protected ArchiveEntry newStoredEntry(String name, byte[] data) { ZipArchiveEntry zipEntry = new ZipArchiveEntry(name); zipEntry.setSize(data.length); zipEntry.setCompressedSize(zipEntry.getSize()); CRC32 crc32 = new CRC32(); crc32.update(data);/*from www . j a v a 2s . c o m*/ zipEntry.setCrc(crc32.getValue()); return zipEntry; }
From source file:com.amazon.aws.samplecode.travellog.util.DataExtractor.java
public void run() { try {//from w w w. j a v a 2 s . com //Create temporary directory File tmpDir = File.createTempFile("travellog", ""); tmpDir.delete(); //Wipe out temporary file to replace with a directory tmpDir.mkdirs(); logger.log(Level.INFO, "Extract temp dir: " + tmpDir); //Store journal to props file Journal journal = dao.getJournal(); Properties journalProps = buildProps(journal); File journalFile = new File(tmpDir, "journal"); journalProps.store(new FileOutputStream(journalFile), ""); //Iterate through entries and grab related photos List<Entry> entries = dao.getEntries(journal); int entryIndex = 1; int imageFileIndex = 1; for (Entry entry : entries) { Properties entryProps = buildProps(entry); File entryFile = new File(tmpDir, "entry." + (entryIndex++)); entryProps.store(new FileOutputStream(entryFile), ""); List<Photo> photos = dao.getPhotos(entry); int photoIndex = 1; for (Photo photo : photos) { Properties photoProps = buildProps(photo); InputStream photoData = S3PhotoUtil.loadOriginalPhoto(photo); String imageFileName = "imgdata." + (imageFileIndex++); File imageFile = new File(tmpDir, imageFileName); FileOutputStream outputStream = new FileOutputStream(imageFile); IOUtils.copy(photoData, outputStream); photoProps.setProperty("file", imageFileName); outputStream.close(); photoData.close(); File photoFile = new File(tmpDir, "photo." + (entryIndex - 1) + "." + (photoIndex++)); photoProps.store(new FileOutputStream(photoFile), ""); } List<Comment> comments = dao.getComments(entry); int commentIndex = 1; for (Comment comment : comments) { Properties commentProps = buildProps(comment); File commentFile = new File(tmpDir, "comment." + (entryIndex - 1) + "." + commentIndex++); commentProps.store(new FileOutputStream(commentFile), ""); } } //Bundle up the folder as a zip final File zipOut; //If we have an output path store locally if (outputPath != null) { zipOut = new File(outputPath); } else { //storing to S3 zipOut = File.createTempFile("export", ".zip"); } zipOut.getParentFile().mkdirs(); //make sure directory structure is in place ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipOut); //Create the zip file File[] files = tmpDir.listFiles(); for (File file : files) { ZipArchiveEntry archiveEntry = new ZipArchiveEntry(file.getName()); byte[] fileData = FileUtils.readFileToByteArray(file); archiveEntry.setSize(fileData.length); zaos.putArchiveEntry(archiveEntry); zaos.write(fileData); zaos.flush(); zaos.closeArchiveEntry(); } zaos.close(); //If outputpath if (outputPath == null) { TravelLogStorageObject obj = new TravelLogStorageObject(); obj.setBucketName(bucketName); obj.setStoragePath(storagePath); obj.setData(FileUtils.readFileToByteArray(zipOut)); obj.setMimeType("application/zip"); S3StorageManager mgr = new S3StorageManager(); mgr.store(obj, false, null); //Store with full redundancy and default permissions } } catch (Exception e) { logger.log(Level.SEVERE, e.getMessage(), e); } }
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 a2 s .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:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractSymlink() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // 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("link.txt"); entry.setUnixMode((int) MostFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); zip.putArchiveEntry(entry);//from w ww . ja va2s . c o m zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
From source file:com.atolcd.web.scripts.ZipContents.java
public void addToZip(NodeRef node, ZipArchiveOutputStream out, boolean noaccent, String path) throws IOException { QName nodeQnameType = this.nodeService.getType(node); // Special case : links if (this.dictionaryService.isSubClass(nodeQnameType, ApplicationModel.TYPE_FILELINK)) { NodeRef linkDestinationNode = (NodeRef) nodeService.getProperty(node, ContentModel.PROP_LINK_DESTINATION); if (linkDestinationNode == null) { return; }/*from w ww. ja v a 2 s .c o m*/ // Duplicate entry: check if link is not in the same space of the link destination if (nodeService.getPrimaryParent(node).getParentRef() .equals(nodeService.getPrimaryParent(linkDestinationNode).getParentRef())) { return; } nodeQnameType = this.nodeService.getType(linkDestinationNode); node = linkDestinationNode; } String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_NAME); nodeName = noaccent ? unAccent(nodeName) : nodeName; if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_CONTENT)) { ContentReader reader = contentService.getReader(node, ContentModel.PROP_CONTENT); if (reader != null) { InputStream is = reader.getContentInputStream(); String filename = path.isEmpty() ? nodeName : path + '/' + nodeName; ZipArchiveEntry entry = new ZipArchiveEntry(filename); entry.setTime(((Date) nodeService.getProperty(node, ContentModel.PROP_MODIFIED)).getTime()); entry.setSize(reader.getSize()); out.putArchiveEntry(entry); byte buffer[] = new byte[BUFFER_SIZE]; while (true) { int nRead = is.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } is.close(); out.closeArchiveEntry(); } else { logger.warn("Could not read : " + nodeName + "content"); } } else if (this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_FOLDER) && !this.dictionaryService.isSubClass(nodeQnameType, ContentModel.TYPE_SYSTEM_FOLDER)) { List<ChildAssociationRef> children = nodeService.getChildAssocs(node); if (children.isEmpty()) { String folderPath = path.isEmpty() ? nodeName + '/' : path + '/' + nodeName + '/'; out.putArchiveEntry(new ZipArchiveEntry(new ZipEntry(folderPath))); } else { for (ChildAssociationRef childAssoc : children) { NodeRef childNodeRef = childAssoc.getChildRef(); addToZip(childNodeRef, out, noaccent, path.isEmpty() ? nodeName : path + '/' + nodeName); } } } else { logger.info("Unmanaged type: " + nodeQnameType.getPrefixedQName(this.namespaceService) + ", filename: " + nodeName); } }
From source file:com.facebook.buck.util.unarchive.UnzipTest.java
@Test public void testExtractBrokenSymlinkWithOwnerExecutePermissions() throws InterruptedException, IOException { assumeThat(Platform.detect(), Matchers.is(Matchers.not(Platform.WINDOWS))); // 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("link.txt"); entry.setUnixMode((int) MostFiles.S_IFLNK); String target = "target.txt"; entry.setSize(target.getBytes(Charsets.UTF_8).length); entry.setMethod(ZipEntry.STORED); // Mark the file as being executable. Set<PosixFilePermission> filePermissions = ImmutableSet.of(PosixFilePermission.OWNER_EXECUTE); long externalAttributes = entry.getExternalAttributes() + (MorePosixFilePermissions.toMode(filePermissions) << 16); entry.setExternalAttributes(externalAttributes); zip.putArchiveEntry(entry);/* w ww . j a v a 2s. com*/ zip.write(target.getBytes(Charsets.UTF_8)); zip.closeArchiveEntry(); } Path extractFolder = tmpFolder.newFolder(); ArchiveFormat.ZIP.getUnarchiver().extractArchive(new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), ExistingFileMode.OVERWRITE); Path link = extractFolder.toAbsolutePath().resolve("link.txt"); assertTrue(Files.isSymbolicLink(link)); assertThat(Files.readSymbolicLink(link).toString(), Matchers.equalTo("target.txt")); }
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);//www. ja v a 2 s .co 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); }