List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream finish
public void finish() throws IOException
From source file:net.larry1123.elec.util.logger.LoggerDirectoryHandler.java
public void zipLogs() throws IOException { File zipFile = getDirectoryPath().resolve(getDateFormatFromMilli(System.currentTimeMillis()) + ".zip") .toFile();// www. j a v a2 s . c o m ZipArchiveOutputStream archiveOutputStream = new ZipArchiveOutputStream(zipFile); // Collection<File> files = FileUtils.listFiles(directory, new String[] {getConfig().getFileType()}, false); // for (File file : files) { // packFile(file, archiveOutputStream); // } for (Map.Entry<Logger, UtilFileHandler> loggerUtilFileHandlerEntry : streamHandlerHashMap.entrySet()) { Logger logger = loggerUtilFileHandlerEntry.getKey(); UtilFileHandler utilFileHandler = loggerUtilFileHandlerEntry.getValue(); // Stop the steam and make sure it is all to disk first utilFileHandler.close(); File file = getFileForLogger(logger); packFile(file, archiveOutputStream); // Restart the stream utilFileHandler.setOutputStream(makeFileOutputStreamForLogger(logger)); } archiveOutputStream.finish(); archiveOutputStream.close(); }
From source file:com.glaf.core.util.ZipUtils.java
/** * /* w w w . ja v a2 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:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Creates a zip file with random content. * * @author S3460/* w w w.ja va 2s . c o m*/ * @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); }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java
/** * Creates a zip file at the specified path with the contents of the * specified directory./* w ww .j a va 2 s . com*/ * @param Input directory path. The directory were is located directory to archive. * @param The full path of the zip file. * @return the checksum accordig to fr.gael.dhus.datastore.processing.impl.zip.digest variable. * @throws IOException If anything goes wrong */ protected Map<String, String> processZip(String inpath, File output) throws IOException { // Retrieve configuration settings String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(","); int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel(); FileOutputStream fOut = null; BufferedOutputStream bOut = null; ZipArchiveOutputStream tOut = null; MultipleDigestOutputStream dOut = null; try { fOut = new FileOutputStream(output); if ((algorithms != null) && (algorithms.length > 0)) { try { dOut = new MultipleDigestOutputStream(fOut, algorithms); bOut = new BufferedOutputStream(dOut); } catch (NoSuchAlgorithmException e) { logger.error("Problem computing checksum algorithms.", e); dOut = null; bOut = new BufferedOutputStream(fOut); } } else bOut = new BufferedOutputStream(fOut); tOut = new ZipArchiveOutputStream(bOut); tOut.setLevel(compressionLevel); addFileToZip(tOut, inpath, ""); } finally { try { tOut.finish(); tOut.close(); bOut.close(); if (dOut != null) dOut.close(); fOut.close(); } catch (Exception e) { logger.error("Exception raised during ZIP stream close", e); } } if (dOut != null) { Map<String, String> checksums = new HashMap<String, String>(); for (String algorithm : algorithms) { String chk = dOut.getMessageDigestAsHexadecimalString(algorithm); if (chk != null) checksums.put(algorithm, chk); } return checksums; } return null; }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Writes a modified version of zip_Source into target. * * @author S3460//from w w w. j a v a 2 s .c o m * @param zipSource the zip source * @param target the target * @return the zip file * @throws Exception the exception */ private ZipFile makeTargetZipFile(ZipFile zipSource, File target) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(target)); for (Enumeration<ZipArchiveEntry> enumer = zipSource.getEntries(); enumer.hasMoreElements();) { ZipArchiveEntry sourceEntry = enumer.nextElement(); out.putArchiveEntry(new ZipArchiveEntry(sourceEntry.getName())); byte[] oldBytes = toBytes(zipSource, sourceEntry); byte[] newBytes = getRandomBytes(); byte[] mixedBytes = mixBytes(oldBytes, newBytes); out.write(mixedBytes, 0, mixedBytes.length); out.flush(); out.closeArchiveEntry(); } out.putArchiveEntry(new ZipArchiveEntry("zipentry" + entryMaxSize + 1)); byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); out.flush(); out.closeArchiveEntry(); out.putArchiveEntry(new ZipArchiveEntry("zipentry" + (entryMaxSize + 2))); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(targetFile); }
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 va 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.citytechinc.cq.component.maven.util.ComponentMojoUtil.java
/** * Add files to the already constructed Archive file by creating a new * Archive file, appending the contents of the existing Archive file to it, * and then adding additional entries for the newly constructed artifacts. * /* www . java 2s. c om*/ * @param classList * @param classLoader * @param classPool * @param buildDirectory * @param componentPathBase * @param defaultComponentPathSuffix * @param defaultComponentGroup * @param existingArchiveFile * @param tempArchiveFile * @throws OutputFailureException * @throws IOException * @throws InvalidComponentClassException * @throws InvalidComponentFieldException * @throws ParserConfigurationException * @throws TransformerException * @throws ClassNotFoundException * @throws CannotCompileException * @throws NotFoundException * @throws SecurityException * @throws NoSuchFieldException * @throws IllegalArgumentException * @throws IllegalAccessException * @throws InvocationTargetException * @throws NoSuchMethodException * @throws InstantiationException */ public static void buildArchiveFileForProjectAndClassList(List<CtClass> classList, WidgetRegistry widgetRegistry, TouchUIWidgetRegistry touchUIWidgetRegistry, ClassLoader classLoader, ClassPool classPool, File buildDirectory, String componentPathBase, String defaultComponentPathSuffix, String defaultComponentGroup, File existingArchiveFile, File tempArchiveFile, ComponentNameTransformer transformer, boolean generateTouchUiDialogs) throws OutputFailureException, IOException, InvalidComponentClassException, InvalidComponentFieldException, ParserConfigurationException, TransformerException, ClassNotFoundException, CannotCompileException, NotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException, TouchUIDialogWriteException, TouchUIDialogGenerationException { if (!existingArchiveFile.exists()) { throw new OutputFailureException("Archive file does not exist"); } if (tempArchiveFile.exists()) { tempArchiveFile.delete(); } tempArchiveFile.createNewFile(); deleteTemporaryComponentOutputDirectory(buildDirectory); /* * Create archive input stream */ ZipArchiveInputStream existingInputStream = new ZipArchiveInputStream( new FileInputStream(existingArchiveFile)); /* * Create a zip archive output stream for the temp file */ ZipArchiveOutputStream tempOutputStream = new ZipArchiveOutputStream(tempArchiveFile); /* * Iterate through all existing entries adding them to the new archive */ ZipArchiveEntry curArchiveEntry; Set<String> existingArchiveEntryNames = new HashSet<String>(); while ((curArchiveEntry = existingInputStream.getNextZipEntry()) != null) { existingArchiveEntryNames.add(curArchiveEntry.getName().toLowerCase()); getLog().debug("Current File Name: " + curArchiveEntry.getName()); tempOutputStream.putArchiveEntry(curArchiveEntry); IOUtils.copy(existingInputStream, tempOutputStream); tempOutputStream.closeArchiveEntry(); } /* * Create content.xml within temp archive */ ContentUtil.buildContentFromClassList(classList, tempOutputStream, existingArchiveEntryNames, buildDirectory, componentPathBase, defaultComponentPathSuffix, defaultComponentGroup, transformer); /* * Create Dialogs within temp archive */ DialogUtil.buildDialogsFromClassList(transformer, classList, tempOutputStream, existingArchiveEntryNames, widgetRegistry, classLoader, classPool, buildDirectory, componentPathBase, defaultComponentPathSuffix); if (generateTouchUiDialogs) { TouchUIDialogUtil.buildDialogsFromClassList(classList, classLoader, classPool, touchUIWidgetRegistry, transformer, buildDirectory, componentPathBase, defaultComponentPathSuffix, tempOutputStream, existingArchiveEntryNames); } /* * Create edit config within temp archive */ EditConfigUtil.buildEditConfigFromClassList(classList, tempOutputStream, existingArchiveEntryNames, buildDirectory, componentPathBase, defaultComponentPathSuffix, transformer); /* * Copy temp archive to the original archive position */ tempOutputStream.finish(); existingInputStream.close(); tempOutputStream.close(); existingArchiveFile.delete(); tempArchiveFile.renameTo(existingArchiveFile); }
From source file:com.gitblit.servlet.PtServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {/*from ww w . j av a 2 s.co 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:es.ucm.fdi.util.archive.ZipFormat.java
public void create(ArrayList<File> sources, File destFile, File baseDir) throws IOException { // to avoid modifying input argument ArrayList<File> toAdd = new ArrayList<>(sources); ZipArchiveOutputStream zos = null; try {//from w w w . j av a 2s. co m zos = new ZipArchiveOutputStream(new FileOutputStream(destFile)); zos.setMethod(ZipArchiveOutputStream.DEFLATED); byte[] b = new byte[1024]; //log.debug("Creating zip file: "+ficheroZip.getName()); for (int i = 0; i < toAdd.size(); i++) { // note: cannot use foreach because sources gets modified File file = toAdd.get(i); // zip standard uses fw slashes instead of backslashes, always String baseName = baseDir.getAbsolutePath() + '/'; String fileName = file.getAbsolutePath().substring(baseName.length()); if (file.isDirectory()) { fileName += '/'; } ZipArchiveEntry entry = new ZipArchiveEntry(fileName); // skip directories - after assuring that their children *will* be included. if (file.isDirectory()) { //log.debug("\tAdding dir "+fileName); for (File child : file.listFiles()) { toAdd.add(child); } zos.putArchiveEntry(entry); continue; } //log.debug("\tAdding file "+fileName); // Add the zip entry and associated data. zos.putArchiveEntry(entry); int n; try (FileInputStream fis = new FileInputStream(file)) { while ((n = fis.read(b)) > -1) { zos.write(b, 0, n); } zos.closeArchiveEntry(); } } } finally { if (zos != null) { zos.finish(); zos.close(); } } }
From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java
/** * Creates a zip file at the specified path with the contents of the * specified directory.// w ww. ja va 2 s. c om * * @param Input directory path. The directory were is located directory to * archive. * @param The full path of the zip file. * @return the checksum accordig to * fr.gael.dhus.datastore.processing.impl.zip.digest variable. * @throws IOException If anything goes wrong */ private Map<String, String> processZip(String inpath, File output) throws IOException { // Retrieve configuration settings String[] algorithms = cfgManager.getDownloadConfiguration().getChecksumAlgorithms().split(","); int compressionLevel = cfgManager.getDownloadConfiguration().getCompressionLevel(); FileOutputStream fOut = null; BufferedOutputStream bOut = null; ZipArchiveOutputStream tOut = null; MultipleDigestOutputStream dOut = null; try { fOut = new FileOutputStream(output); if ((algorithms != null) && (algorithms.length > 0)) { try { dOut = new MultipleDigestOutputStream(fOut, algorithms); bOut = new BufferedOutputStream(dOut); } catch (NoSuchAlgorithmException e) { LOGGER.error("Problem computing checksum algorithms.", e); dOut = null; bOut = new BufferedOutputStream(fOut); } } else bOut = new BufferedOutputStream(fOut); tOut = new ZipArchiveOutputStream(bOut); tOut.setLevel(compressionLevel); addFileToZip(tOut, inpath, ""); } finally { try { tOut.finish(); tOut.close(); bOut.close(); if (dOut != null) dOut.close(); fOut.close(); } catch (Exception e) { LOGGER.error("Exception raised during ZIP stream close", e); } } if (dOut != null) { Map<String, String> checksums = new HashMap<String, String>(); for (String algorithm : algorithms) { String chk = dOut.getMessageDigestAsHexadecimalString(algorithm); if (chk != null) checksums.put(algorithm, chk); } return checksums; } return null; }