List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry
public ZipArchiveEntry(ZipArchiveEntry entry) throws ZipException
From source file:com.fjn.helper.common.io.file.zip.zip.ZipArchiveHelper.java
private static void zipFile(ZipArchiveOutputStream out, File file, String parentInZip) { ZipArchiveEntry entry = null;/*w w w. ja v a2 s. co m*/ try { if (file.isFile()) { // out String name = FileUtil.removeFirstIfIsSparator(parentInZip + File.separator + file.getName()); entry = new ZipArchiveEntry(name); logger.info("zip file : " + name); out.putArchiveEntry(entry); FileUtil.copyFile(file, out); out.closeArchiveEntry(); } else {// ??out // ? File[] children = file.listFiles(); if (children != null) { for (int i = 0; i < children.length; i++) { zipFile(out, children[i], parentInZip + File.separator + file.getName()); } } } } catch (Exception e) { e.printStackTrace(); } }
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 w w . ja v a 2s .co m * @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.mediaworx.ziputils.Zipper.java
/** * Adds the given file to the zip archive using the given relative path. * @param zipRelativePath the path of the file relative to the zip root * @param file the file to be added * @throws IOException Exceptions from the underlying package framework are bubbled up *///from ww w . j a va2 s.com public void addFile(String zipRelativePath, File file) throws IOException { zip.putArchiveEntry(new ZipArchiveEntry(zipRelativePath)); IOUtils.copy(new FileInputStream(file), zip); zip.closeArchiveEntry(); }
From source file:adams.core.io.ZipUtils.java
/** * Creates a zip file from the specified files. * * @param output the output file to generate * @param files the files to store in the zip file * @param stripRegExp the regular expression used to strip the file names (only applied to the directory!) * @param bufferSize the buffer size to use * @return null if successful, otherwise error message *///from w ww. j a v a 2s . co m @MixedCopyright(copyright = "Apache compress commons", license = License.APACHE2, url = "http://commons.apache.org/compress/examples.html") public static String compress(File output, File[] files, String stripRegExp, int bufferSize) { String result; int i; byte[] buf; int len; ZipArchiveOutputStream out; BufferedInputStream in; FileInputStream fis; FileOutputStream fos; String filename; String msg; ZipArchiveEntry entry; in = null; fis = null; out = null; fos = null; result = null; try { // does file already exist? if (output.exists()) System.err.println("WARNING: overwriting '" + output + "'!"); // create ZIP file buf = new byte[bufferSize]; fos = new FileOutputStream(output.getAbsolutePath()); out = new ZipArchiveOutputStream(new BufferedOutputStream(fos)); for (i = 0; i < files.length; i++) { fis = new FileInputStream(files[i].getAbsolutePath()); in = new BufferedInputStream(fis); // Add ZIP entry to output stream. filename = files[i].getParentFile().getAbsolutePath(); if (stripRegExp.length() > 0) filename = filename.replaceFirst(stripRegExp, ""); if (filename.length() > 0) filename += File.separator; filename += files[i].getName(); entry = new ZipArchiveEntry(filename); entry.setSize(files[i].length()); out.putArchiveEntry(entry); // Transfer bytes from the file to the ZIP file while ((len = in.read(buf)) > 0) out.write(buf, 0, len); // Complete the entry out.closeArchiveEntry(); FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); in = null; fis = null; } // Complete the ZIP file FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); out = null; fos = null; } catch (Exception e) { msg = "Failed to generate archive '" + output + "': "; System.err.println(msg); e.printStackTrace(); result = msg + e; } finally { FileUtils.closeQuietly(in); FileUtils.closeQuietly(fis); FileUtils.closeQuietly(out); FileUtils.closeQuietly(fos); } return result; }
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 ww w. j a v a 2 s . c om*/ 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.google.jenkins.plugins.persistentmaster.volume.zip.ZipCreator.java
private void copyDirectory(String filenameInZip) throws IOException { logger.finer("Adding directory: " + filenameInZip); // entries ending in / indicate a directory ZipArchiveEntry entry = new ZipArchiveEntry(filenameInZip + "/"); // in addition, set the unix directory flag entry.setUnixMode(entry.getUnixMode() | UnixStat.DIR_FLAG); zipStream.putArchiveEntry(entry);//w w w. j ava2 s . co m zipStream.closeArchiveEntry(); }
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 .java 2 s . 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 ww w .j a v a 2 s. 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: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.j a v a 2 s .c om*/ 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.mediaworx.ziputils.Zipper.java
/** * Adds a directory entry with the given relative path to the zip. * @param zipRelativePath the path of the directory relative to the zip root * @throws IOException Exceptions from the underlying package framework are bubbled up *///from w w w . j a v a 2 s . c om public void addDirectory(String zipRelativePath) throws IOException { if (!zipRelativePath.endsWith("/")) { zipRelativePath = zipRelativePath.concat("/"); } zip.putArchiveEntry(new ZipArchiveEntry(zipRelativePath)); zip.closeArchiveEntry(); }