List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry setTime
public void setTime(long time)
From source file:com.gitblit.utils.CompressionUtils.java
/** * Zips the contents of the tree at the (optionally) specified revision and * the (optionally) specified basepath to the supplied outputstream. * //w ww . j a v a 2s . c om * @param repository * @param basePath * if unspecified, entire repository is assumed. * @param objectId * if unspecified, HEAD is assumed. * @param os * @return true if repository was successfully zipped to supplied output * stream */ public static boolean zip(Repository repository, String basePath, String objectId, OutputStream os) { RevCommit commit = JGitUtils.getCommit(repository, objectId); if (commit == null) { return false; } boolean success = false; RevWalk rw = new RevWalk(repository); TreeWalk tw = new TreeWalk(repository); try { tw.reset(); tw.addTree(commit.getTree()); ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setComment("Generated by Gitblit"); if (!StringUtils.isEmpty(basePath)) { PathFilter f = PathFilter.create(basePath); tw.setFilter(f); } tw.setRecursive(true); MutableObjectId id = new MutableObjectId(); ObjectReader reader = tw.getObjectReader(); long modified = commit.getAuthorIdent().getWhen().getTime(); while (tw.next()) { FileMode mode = tw.getFileMode(0); if (mode == FileMode.GITLINK || mode == FileMode.TREE) { continue; } tw.getObjectId(id, 0); ZipArchiveEntry entry = new ZipArchiveEntry(tw.getPathString()); entry.setSize(reader.getObjectSize(id, Constants.OBJ_BLOB)); entry.setComment(commit.getName()); entry.setUnixMode(mode.getBits()); entry.setTime(modified); zos.putArchiveEntry(entry); ObjectLoader ldr = repository.open(id); ldr.copyTo(zos); zos.closeArchiveEntry(); } zos.finish(); success = true; } catch (IOException e) { error(e, repository, "{0} failed to zip files from commit {1}", commit.getName()); } finally { tw.release(); rw.dispose(); } return success; }
From source file:com.cloudbees.jenkins.support.SupportPlugin.java
public static void writeBundle(OutputStream outputStream, final List<Component> components) throws IOException { StringBuilder manifest = new StringBuilder(); StringWriter errors = new StringWriter(); PrintWriter errorWriter = new PrintWriter(errors); appendManifestHeader(manifest);//from ww w.j a va 2 s .co m List<Content> contents = appendManifestContents(manifest, errorWriter, components); contents.add(new StringContent("manifest.md", manifest.toString())); try { try (BulkChange change = new BulkChange(ContentMappings.get()); ZipArchiveOutputStream binaryOut = new ZipArchiveOutputStream( new BufferedOutputStream(outputStream, 16384))) { Optional<ContentFilter> maybeFilter = getContentFilter(); Optional<FilteredOutputStream> maybeFilteredOut = maybeFilter .map(filter -> new FilteredOutputStream(binaryOut, filter)); OutputStream textOut = maybeFilteredOut.map(OutputStream.class::cast).orElse(binaryOut); OutputStreamSelector selector = new OutputStreamSelector(() -> binaryOut, () -> textOut); IgnoreCloseOutputStream unfilteredOut = new IgnoreCloseOutputStream(binaryOut); IgnoreCloseOutputStream filteredOut = new IgnoreCloseOutputStream(selector); for (Content content : contents) { if (content == null) { continue; } final String name = maybeFilter.map(filter -> filter.filter(content.getName())) .orElseGet(content::getName); final ZipArchiveEntry entry = new ZipArchiveEntry(name); entry.setTime(content.getTime()); try { binaryOut.putArchiveEntry(entry); binaryOut.flush(); OutputStream out = content.shouldBeFiltered() ? filteredOut : unfilteredOut; if (content instanceof PrefilteredContent && maybeFilter.isPresent()) { ((PrefilteredContent) content).writeTo(out, maybeFilter.get()); } else { content.writeTo(out); } out.flush(); } catch (Throwable e) { String msg = "Could not attach ''" + name + "'' to support bundle"; logger.log(Level.WARNING, msg, e); errorWriter.println(msg); errorWriter .println("-----------------------------------------------------------------------"); errorWriter.println(); SupportLogFormatter.printStackTrace(e, errorWriter); errorWriter.println(); } finally { maybeFilteredOut.ifPresent(FilteredOutputStream::reset); selector.reset(); binaryOut.closeArchiveEntry(); } } errorWriter.close(); String errorContent = errors.toString(); if (StringUtils.isNotBlank(errorContent)) { try { binaryOut.putArchiveEntry(new ZipArchiveEntry("manifest/errors.txt")); textOut.write(errorContent.getBytes(StandardCharsets.UTF_8)); textOut.flush(); binaryOut.closeArchiveEntry(); } catch (IOException e) { logger.log(Level.WARNING, "Could not write manifest/errors.txt to zip archive", e); } } binaryOut.flush(); change.commit(); } } finally { outputStream.flush(); } }
From source file:hudson.util.io.ZipArchiver.java
@Override public void visitSymlink(final File f, final String target, final String relativePath) throws IOException { int mode = IOUtils.lmode(f); ZipArchiveEntry zae = new ZipArchiveEntry(relativePath); if (mode != -1) { zae.setUnixMode(mode);/*from ww w. j ava 2 s. c o m*/ } zae.setTime(f.lastModified()); zip.putArchiveEntry(zae); zip.write(target.getBytes(StandardCharsets.UTF_8), 0, target.length()); zip.closeArchiveEntry(); entriesWritten++; }
From source file:io.github.zlika.reproducible.ZipStripper.java
private ZipArchiveEntry filterZipEntry(ZipArchiveEntry entry) { // Set times/* www .j a v a2 s.co m*/ entry.setCreationTime(FileTime.fromMillis(0)); entry.setLastAccessTime(FileTime.fromMillis(0)); entry.setLastModifiedTime(FileTime.fromMillis(0)); entry.setTime(0); // Remove extended timestamps for (ZipExtraField field : entry.getExtraFields()) { if (field instanceof X5455_ExtendedTimestamp) { entry.removeExtraField(field.getHeaderId()); } } return entry; }
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; }/*w w w .j a v a 2 s .co 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.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); zip.putArchiveEntry(entry);//from w w w. j a v a 2 s. c om 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 {/*w ww . j a v a 2s . c o m*/ 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:fr.itldev.koya.alfservice.KoyaContentService.java
private void addToZip(NodeRef node, ZipArchiveOutputStream out, 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; }/* w w w. j ava 2 s .com*/ // 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; } /** * TODO test name/title export result. */ String nodeName = (String) nodeService.getProperty(node, ContentModel.PROP_TITLE); nodeName = nodeName.replaceAll("([\\\"\\\\*\\\\\\>\\<\\?\\/\\:\\|]+)", "_"); // 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); try { byte buffer[] = new byte[8192]; while (true) { int nRead = is.read(buffer, 0, buffer.length); if (nRead <= 0) { break; } out.write(buffer, 0, nRead); } } catch (Exception exception) { logger.error(exception.getMessage(), exception); } finally { 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(folderPath)); out.closeArchiveEntry(); } else { for (ChildAssociationRef childAssoc : children) { NodeRef childNodeRef = childAssoc.getChildRef(); addToZip(childNodeRef, out, 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 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); zip.putArchiveEntry(entry);/*from w w w. j a v a2 s. c om*/ 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:fr.ortolang.diffusion.api.content.ContentResource.java
private ResponseBuilder handleExport(boolean followSymlink, String filename, String format, final List<String> paths, final Pattern pattern) throws UnsupportedEncodingException { ResponseBuilder builder;/*from ww w . ja va 2 s .c o m*/ switch (format) { case "zip": { LOGGER.log(Level.FINE, "exporting using format zip"); builder = Response.ok(); builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "utf-8") + ".zip"); builder.type("application/zip"); StreamingOutput stream = output -> { try (ZipArchiveOutputStream out = new ZipArchiveOutputStream(output)) { for (String path : paths) { try { String key = resolveContentPath(path); ArchiveEntryFactory factory = (name, time, size) -> { ZipArchiveEntry entry = new ZipArchiveEntry(name); if (time != -1) { entry.setTime(time); } if (size != -1) { entry.setSize(size); } return entry; }; exportToArchive(key, out, factory, PathBuilder.fromPath(path), false, pattern); } catch (AccessDeniedException e) { LOGGER.log(Level.FINEST, "access denied during export to zip", e); } catch (BrowserServiceException | CoreServiceException | AliasNotFoundException | KeyNotFoundException | OrtolangException e) { LOGGER.log(Level.INFO, "unable to export path to zip", e); } catch (InvalidPathException e) { LOGGER.log(Level.FINEST, "invalid path during export to zip", e); } catch (PathNotFoundException e) { LOGGER.log(Level.FINEST, "path not found during export to zip", e); } catch (ExportToArchiveIOException e) { LOGGER.log(Level.SEVERE, "unexpected IO error during export to archive, stopping export", e); break; } } } }; builder.entity(stream); break; } case "tar": { LOGGER.log(Level.FINE, "exporting using format tar"); builder = Response.ok(); builder.header("Content-Disposition", "attachment; filename*=UTF-8''" + URLEncoder.encode(filename, "utf-8") + ".tar.gz"); builder.type("application/x-gzip"); StreamingOutput stream = output -> { try (GzipCompressorOutputStream gout = new GzipCompressorOutputStream(output); TarArchiveOutputStream out = new TarArchiveOutputStream(gout)) { for (String path : paths) { try { String key = resolveContentPath(path); ArchiveEntryFactory factory = (name, time, size) -> { TarArchiveEntry entry = new TarArchiveEntry(name); if (time != -1) { entry.setModTime(time); } if (size != -1) { entry.setSize(size); } return entry; }; exportToArchive(key, out, factory, PathBuilder.fromPath(path), false, pattern); } catch (BrowserServiceException | CoreServiceException | AliasNotFoundException | KeyNotFoundException | OrtolangException e) { LOGGER.log(Level.INFO, "unable to export path to tar", e); } catch (InvalidPathException e) { LOGGER.log(Level.FINEST, "invalid path during export to tar", e); } catch (PathNotFoundException e) { LOGGER.log(Level.FINEST, "path not found during export to tar", e); } catch (ExportToArchiveIOException e) { LOGGER.log(Level.SEVERE, "unexpected IO error during export to archive, stopping export", e); break; } } } }; builder.entity(stream); break; } default: builder = Response.status(Status.BAD_REQUEST).entity("export format [" + format + "] is not supported"); } return builder; }