List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveOutputStream write
public void write(byte[] b, int offset, int length) throws IOException
From source file:com.jaeksoft.searchlib.crawler.web.spider.DownloadItem.java
public void writeToZip(ZipArchiveOutputStream zipOutput) throws IOException { if (contentInputStream == null) return;//w w w . j av a 2s . c om String[] domainParts = StringUtils.split(uri.getHost(), '.'); StringBuilder path = new StringBuilder(); for (int i = domainParts.length - 1; i >= 0; i--) { path.append(domainParts[i]); path.append('/'); } String[] pathParts = StringUtils.split(uri.getPath(), '/'); for (int i = 0; i < pathParts.length - 1; i++) { if (StringUtils.isEmpty(pathParts[i])) continue; path.append(pathParts[i]); path.append('/'); } if (contentDispositionFilename != null) path.append(contentDispositionFilename); else { String lastPart = pathParts == null || pathParts.length == 0 ? null : pathParts[pathParts.length - 1]; if (StringUtils.isEmpty(lastPart)) path.append("index"); else path.append(lastPart); } if (uri.getPath().endsWith("/")) path.append("/_index"); String query = uri.getQuery(); String fragment = uri.getFragment(); if (!StringUtils.isEmpty(query) || !StringUtils.isEmpty(fragment)) { CRC32 crc32 = new CRC32(); if (!StringUtils.isEmpty(query)) crc32.update(query.getBytes()); if (!StringUtils.isEmpty(fragment)) crc32.update(fragment.getBytes()); path.append('.'); path.append(crc32.getValue()); } ZipArchiveEntry zipEntry = new ZipArchiveEntry(path.toString()); zipOutput.putArchiveEntry(zipEntry); BufferedInputStream bis = null; byte[] buffer = new byte[65536]; try { bis = new BufferedInputStream(contentInputStream); int l; while ((l = bis.read(buffer)) != -1) zipOutput.write(buffer, 0, l); zipOutput.closeArchiveEntry(); } finally { IOUtils.close(bis); } }
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 av 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; } /** * 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.naryx.tagfusion.expression.function.file.Zip.java
/** * Performing Zip() operation/*from ww w . j av a2s . co m*/ * * @param session * @param zipfile * @param src * @param recurse * @param prefixx * @param compLvl * @param filter * @param overwrite * @param newpath * @throws cfmRunTimeException * @throws IOException */ protected void zipOperation(cfSession session, ZipArchiveOutputStream zipOut, File src, boolean recurse, String prefix, int compLvl, FilenameFilter filter, String newpath) throws cfmRunTimeException { if (src != null) { FileInputStream nextFileIn; ZipArchiveEntry nextEntry = null; byte[] buffer = new byte[4096]; int readBytes; zipOut.setLevel(compLvl); try { List<File> files = new ArrayList<File>(); int srcDirLen; if (src.isFile()) { String parentPath = src.getParent(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; files.add(src); } else { String parentPath = src.getAbsolutePath(); srcDirLen = parentPath.endsWith(File.separator) ? parentPath.length() : parentPath.length() + 1; getFiles(src, files, recurse, filter); } int noFiles = files.size(); File nextFile; boolean isDir; for (int i = 0; i < noFiles; i++) { nextFile = (File) files.get(i); isDir = nextFile.isDirectory(); if (noFiles == 1 && newpath != null) { // NEWPATH nextEntry = new ZipArchiveEntry(newpath.replace('\\', '/') + (isDir ? "/" : "")); } else { // PREFIX nextEntry = new ZipArchiveEntry( prefix + nextFile.getAbsolutePath().substring(srcDirLen).replace('\\', '/') + (isDir ? "/" : "")); } try { zipOut.putArchiveEntry(nextEntry); } catch (IOException e) { throwException(session, "Failed to add entry to zip file [" + nextEntry + "]. Reason: " + e.getMessage()); } if (!isDir) { nextEntry.setTime(nextFile.lastModified()); nextFileIn = new FileInputStream(nextFile); try { while (nextFileIn.available() > 0) { readBytes = nextFileIn.read(buffer); zipOut.write(buffer, 0, readBytes); } zipOut.flush(); } catch (IOException e) { throwException(session, "Failed to write entry [" + nextEntry + "] to zip file. Reason: " + e.getMessage()); } finally { // nextEntry close StreamUtil.closeStream(nextFileIn); } } zipOut.closeArchiveEntry(); } } catch (IOException ioe) { throwException(session, "Failed to create zip file: " + ioe.getMessage()); } } }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Apply delta.//from w ww. j av a 2 s . c o m * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException( fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream .read(sourceBytes, erg, sourceBytes.length - erg)) ; } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } }
From source file:org.apache.sis.internal.maven.Assembler.java
/** * Adds the given file in the ZIP file. If the given file is a directory, then this method * recursively adds all files contained in this directory. This method is invoked for zipping * the "application/sis-console/src/main/artifact" directory and sub-directories before to zip * the Pack200 file./*from ww w .j ava 2 s . c o m*/ */ private void appendRecursively(final File file, String relativeFile, final ZipArchiveOutputStream out, final byte[] buffer) throws IOException { if (file.isDirectory()) { relativeFile += '/'; } final ZipArchiveEntry entry = new ZipArchiveEntry(file, relativeFile); if (file.canExecute()) { entry.setUnixMode(0744); } out.putArchiveEntry(entry); if (!entry.isDirectory()) { final FileInputStream in = new FileInputStream(file); try { int n; while ((n = in.read(buffer)) >= 0) { out.write(buffer, 0, n); } } finally { in.close(); } } out.closeArchiveEntry(); if (entry.isDirectory()) { for (final String filename : file.list(this)) { appendRecursively(new File(file, filename), relativeFile.concat(filename), out, buffer); } } }
From source file:org.itstechupnorth.walrus.base.ArticleBuffer.java
public void saveTo(ZipArchiveOutputStream out) throws IOException { saving = true;// w w w . j a v a 2s .com final int originalPosition = buffer.position(); // System.out.println(moniker() + "saving@" + buffer.position()); try { buffer.flip(); encoder.reset(); final String name = NAME_PREFIX + getTitleHash() + NAME_SUFFIX; final ZipArchiveEntry entry = new ZipArchiveEntry(name); entry.setComment(getTitle()); out.putArchiveEntry(entry); outBuffer.clear(); boolean more = true; while (more) { final CoderResult result = encoder.encode(buffer, outBuffer, true); out.write(outBuffer.array(), 0, outBuffer.position()); outBuffer.clear(); more = CoderResult.OVERFLOW.equals(result); } out.closeArchiveEntry(); } finally { buffer.clear(); buffer.position(originalPosition); // System.out.println(moniker() + "saved@" + buffer.position()); saving = false; } }
From source file:org.ngrinder.common.util.CompressionUtil.java
/** * Zip the given src into the given output stream. * // ww w . ja v a 2 s . co m * @param src * src to be zipped * @param os * output stream * @param charsetName * character set to be used * @param includeSrc * true if src will be included. * @throws IOException * IOException */ public static void zip(File src, OutputStream os, String charsetName, boolean includeSrc) throws IOException { ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setEncoding(charsetName); FileInputStream fis; int length; ZipArchiveEntry ze; byte[] buf = new byte[8 * 1024]; String name; Stack<File> stack = new Stack<File>(); File root; if (src.isDirectory()) { if (includeSrc) { stack.push(src); root = src.getParentFile(); } else { File[] fs = src.listFiles(); for (int i = 0; i < fs.length; i++) { stack.push(fs[i]); } root = src; } } else { stack.push(src); root = src.getParentFile(); } while (!stack.isEmpty()) { File f = stack.pop(); name = toPath(root, f); if (f.isDirectory()) { File[] fs = f.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) { stack.push(fs[i]); } else { stack.add(0, fs[i]); } } } else { ze = new ZipArchiveEntry(name); zos.putArchiveEntry(ze); fis = new FileInputStream(f); while ((length = fis.read(buf, 0, buf.length)) >= 0) { zos.write(buf, 0, length); } fis.close(); zos.closeArchiveEntry(); } } zos.close(); }
From source file:org.ngrinder.common.util.CompressionUtils.java
/** * Zip the given src into the given output stream. * * @param src src to be zipped// ww w .j ava2 s. c o m * @param os output stream * @param charsetName character set to be used * @param includeSrc true if src will be included. * @throws IOException IOException */ public static void zip(File src, OutputStream os, String charsetName, boolean includeSrc) throws IOException { ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setEncoding(charsetName); FileInputStream fis = null; int length; ZipArchiveEntry ze; byte[] buf = new byte[8 * 1024]; String name; Stack<File> stack = new Stack<File>(); File root; if (src.isDirectory()) { if (includeSrc) { stack.push(src); root = src.getParentFile(); } else { File[] fs = checkNotNull(src.listFiles()); for (int i = 0; i < fs.length; i++) { stack.push(fs[i]); } root = src; } } else { stack.push(src); root = src.getParentFile(); } while (!stack.isEmpty()) { File f = stack.pop(); name = toPath(root, f); if (f.isDirectory()) { File[] fs = checkNotNull(f.listFiles()); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) { stack.push(fs[i]); } else { stack.add(0, fs[i]); } } } else { ze = new ZipArchiveEntry(name); zos.putArchiveEntry(ze); try { fis = new FileInputStream(f); while ((length = fis.read(buf, 0, buf.length)) >= 0) { zos.write(buf, 0, length); } } finally { IOUtils.closeQuietly(fis); } zos.closeArchiveEntry(); } } zos.close(); }
From source file:org.ngrinder.script.util.CompressionUtil.java
public void zip(File src, OutputStream os, String charsetName, boolean includeSrc) throws IOException { ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os); zos.setEncoding(charsetName);/*from w w w. j a v a 2 s . c o m*/ FileInputStream fis; int length; ZipArchiveEntry ze; byte[] buf = new byte[8 * 1024]; String name; Stack<File> stack = new Stack<File>(); File root; if (src.isDirectory()) { if (includeSrc) { stack.push(src); root = src.getParentFile(); } else { File[] fs = src.listFiles(); for (int i = 0; i < fs.length; i++) { stack.push(fs[i]); } root = src; } } else { stack.push(src); root = src.getParentFile(); } while (!stack.isEmpty()) { File f = stack.pop(); name = toPath(root, f); if (f.isDirectory()) { File[] fs = f.listFiles(); for (int i = 0; i < fs.length; i++) { if (fs[i].isDirectory()) stack.push(fs[i]); else stack.add(0, fs[i]); } } else { ze = new ZipArchiveEntry(name); zos.putArchiveEntry(ze); fis = new FileInputStream(f); while ((length = fis.read(buf, 0, buf.length)) >= 0) { zos.write(buf, 0, length); } fis.close(); zos.closeArchiveEntry(); } } zos.close(); }
From source file:org.onehippo.forge.content.exim.repository.jaxrs.util.ZipCompressUtils.java
/** * Add a ZIP entry to {@code zipOutput} with the given {@code entryName} and {@code bytes} starting from * {@code offset} in {@code length}./*from w w w.j av a 2s .c o m*/ * @param entryName ZIP entry name * @param bytes the byte array to fill in for the ZIP entry * @param offset the starting offset index to read from the byte array * @param length the length to read from the byte array * @param zipOutput ZipArchiveOutputStream instance * @throws IOException if IO exception occurs */ public static void addEntryToZip(String entryName, byte[] bytes, int offset, int length, ZipArchiveOutputStream zipOutput) throws IOException { ZipArchiveEntry entry = new ZipArchiveEntry(entryName); entry.setSize(length); try { zipOutput.putArchiveEntry(entry); zipOutput.write(bytes, offset, length); } finally { zipOutput.closeArchiveEntry(); } }