List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream closeArchiveEntry
public void closeArchiveEntry() throws IOException
From source file:cz.muni.fi.xklinec.zipstream.PostponedEntry.java
/** * Writes whole entry to the ZIPArchiveOutputStream. * Optionally recomputes CRC32 checksum. * //from ww w .j av a 2 s. c o m * @param zop * @param recomputeCrc * @throws IOException */ public void dump(ZipArchiveOutputStream zop, boolean recomputeCrc) throws IOException { ZipArchiveEntry zen = (ZipArchiveEntry) ze.clone(); // recompute CRC? if (recomputeCrc) { crc.reset(); crc.update(byteData); ze.setCrc(crc.getValue()); } zop.putArchiveEntry(zen); zop.write(byteData, 0, byteData.length); zop.closeArchiveEntry(); zop.flush(); }
From source file:fr.gael.ccsds.sip.archive.ZipArchiveManager.java
/** * Produces Zip compressed archive.//from w w w .j av a 2 s . co m */ @Override public File copy(final File src, final File zip_file, final String dst) throws Exception { if (zip_file.exists()) { final FileInputStream fis = new FileInputStream(zip_file); final ZipArchiveInputStream zis = new ZipArchiveInputStream(fis); final File tempFile = File.createTempFile("updateZip", "zip"); final FileOutputStream fos = new FileOutputStream(tempFile); final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos); // copy the existing entries ZipArchiveEntry nextEntry; while ((nextEntry = zis.getNextZipEntry()) != null) { zos.putArchiveEntry(nextEntry); IOUtils.copy(zis, zos); zos.closeArchiveEntry(); } // create the new entry final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst); entry.setSize(src.length()); zos.putArchiveEntry(entry); final FileInputStream sfis = new FileInputStream(src); IOUtils.copy(sfis, zos); sfis.close(); zos.closeArchiveEntry(); zos.finish(); zis.close(); fis.close(); zos.close(); // Rename the new file over the old boolean status = zip_file.delete(); File saved_tempFile = tempFile; status = tempFile.renameTo(zip_file); // Copy the new file over the old if the renaming failed if (!status) { final FileInputStream tfis = new FileInputStream(saved_tempFile); final FileOutputStream tfos = new FileOutputStream(zip_file); final byte[] buf = new byte[1024]; int i = 0; while ((i = tfis.read(buf)) != -1) { tfos.write(buf, 0, i); } tfis.close(); tfos.close(); saved_tempFile.delete(); } return zip_file; } else { final FileOutputStream fos = new FileOutputStream(zip_file); final ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos); final ZipArchiveEntry entry = new ZipArchiveEntry(src, dst); entry.setSize(src.length()); zos.putArchiveEntry(entry); final FileInputStream sfis = new FileInputStream(src); IOUtils.copy(sfis, zos); sfis.close(); zos.closeArchiveEntry(); zos.finish(); zos.close(); fos.close(); } return zip_file; }
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. * //from www .j a v a2 s . c o 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.sic.bb.jenkins.plugins.sicci_for_xcode.util.ExtendedFile.java
private static void zipDirectory(File file, String path, ZipArchiveOutputStream zipStream) throws IOException, InterruptedException { if (path == null) path = new String(); else if (!path.isEmpty()) path += File.separatorChar; ZipArchiveEntry zipEntry = new ZipArchiveEntry(file, path + file.getName()); zipEntry.setUnixMode(PosixAPI.get().stat(file.getAbsolutePath()).mode()); /* TODO: archiving symlinks doesn't work atm zipEntry.setUnixMode(PosixAPI.get().stat(file.getAbsolutePath()).mode()); // www. j av a2 s .c om if(Util.isSymlink(file)) { zipEntry = new ZipArchiveEntry(path + file.getName()); zipEntry.setUnixMode(PosixAPI.get().stat(file.getAbsolutePath()).mode()); AsiExtraField field = new AsiExtraField(); field.setLinkedFile(path + file.getName()); zipEntry.addExtraField(field); zipStream.putArchiveEntry(zipEntry); zipStream.closeArchiveEntry(); return; } */ zipStream.putArchiveEntry(zipEntry); if (!file.isDirectory()) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); Util.copyStream(fileInputStream, zipStream); } finally { IOUtils.closeQuietly(fileInputStream); zipStream.closeArchiveEntry(); } } else { zipStream.closeArchiveEntry(); String[] entries = file.list(); if (entries != null) for (String entry : entries) zipDirectory(new File(file, entry), path + file.getName(), zipStream); } }
From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java
/** * Writes a provided file to a provided archive output stream at a path * determined by the class of the component. * /*from ww w.j av a 2s .c om*/ * @param file * @param componentClass * @param archiveStream * @param reservedNames A list of files which already exist within the Zip * Archive. If a file already exists for a particular component, * it is left untouched. * @param componentPathBase * @throws IOException * @throws ClassNotFoundException */ public static void writeElementToArchiveFile(ComponentNameTransformer transformer, File file, CtClass componentClass, ZipArchiveOutputStream archiveStream, Set<String> reservedNames, String componentPathBase, String defaultComponentPathSuffix, String path) throws IOException, ClassNotFoundException { String editConfigFilePath = ComponentMojoUtil.getComponentBasePathForComponentClass(componentClass, componentPathBase) + "/" + ComponentMojoUtil.getComponentPathSuffixForComponentClass(componentClass, defaultComponentPathSuffix) + "/" + ComponentMojoUtil.getComponentNameForComponentClass(transformer, componentClass) + path; if (!reservedNames.contains(editConfigFilePath.toLowerCase())) { ZipArchiveEntry entry = new ZipArchiveEntry(file, editConfigFilePath); archiveStream.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file), archiveStream); archiveStream.closeArchiveEntry(); } else { ComponentMojoUtil.getLog().debug("Existing file found at " + editConfigFilePath); } }
From source file:net.larry1123.elec.util.logger.LoggerDirectoryHandler.java
protected void packFile(File file, ZipArchiveOutputStream zipArchiveOutputStream) throws IOException { String relative = getDirectoryPath().relativize(file.toPath()).toString(); // Make an Entry in the archive ArchiveEntry archiveEntry = zipArchiveOutputStream.createArchiveEntry(file, relative); FileInputStream fileInputStream = FileUtils.openInputStream(file); zipArchiveOutputStream.putArchiveEntry(archiveEntry); // Copy file content into archive IOUtils.copy(fileInputStream, zipArchiveOutputStream); zipArchiveOutputStream.closeArchiveEntry(); }
From source file:com.gitblit.servlet.PtServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/* w w w .ja 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:at.spardat.xma.xdelta.JarDelta.java
/** * Computes the binary differences of two zip files. For all files contained in source and target which * are not equal, the binary difference is caluclated by using * {@link com.nothome.delta.Delta#compute(byte[], InputStream, DiffWriter)}. * If the files are equal, nothing is written to the output for them. * Files contained only in target and files to small for {@link com.nothome.delta.Delta} are copied to output. * Files contained only in source are ignored. * At last a list of all files contained in target is written to <code>META-INF/file.list</code> in output. * * @param sourceName the original zip file * @param targetName a modification of the original zip file * @param source the original zip file/*from w w w . j a va 2 s . c o m*/ * @param target a modification of the original zip file * @param output the zip file where the patches have to be written to * @throws IOException if an error occurs reading or writing any entry in a zip file */ public void computeDelta(String sourceName, String targetName, ZipFile source, ZipFile target, ZipArchiveOutputStream output) throws IOException { ByteArrayOutputStream listBytes = new ByteArrayOutputStream(); PrintWriter list = new PrintWriter(new OutputStreamWriter(listBytes)); list.println(sourceName); list.println(targetName); computeDelta(source, target, output, list, ""); list.close(); ZipArchiveEntry listEntry = new ZipArchiveEntry("META-INF/file.list"); output.putArchiveEntry(listEntry); output.write(listBytes.toByteArray()); output.closeArchiveEntry(); output.finish(); output.flush(); }
From source file:com.glaf.core.util.ZipUtils.java
/** * /* ww w . j a v a 2 s. c o m*/ * ?zip? * * @param files * ? * * @param zipFilePath * ?zip ,"/var/data/aa.zip"; */ public static void compressFile(File[] files, String zipFilePath) { if (files != null && files.length > 0) { if (isEndsWithZip(zipFilePath)) { ZipArchiveOutputStream zaos = null; try { File zipFile = new File(zipFilePath); zaos = new ZipArchiveOutputStream(zipFile); // Use Zip64 extensions for all entries where they are // required zaos.setUseZip64(Zip64Mode.AsNeeded); for (File file : files) { if (file != null) { ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName()); zaos.putArchiveEntry(zipArchiveEntry); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[BUFFER]; int len = -1; while ((len = is.read(buffer)) != -1) { zaos.write(buffer, 0, len); } // Writes all necessary data for this entry. zaos.closeArchiveEntry(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeStream(is); } } } zaos.finish(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeStream(zaos); } } } }
From source file:com.amazon.aws.samplecode.travellog.util.DataExtractor.java
public void run() { try {/*from w w w. j av a 2s .c o m*/ //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); } }