List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveInputStream close
public void close() throws IOException
From source file:com.alcatel_lucent.nz.wnmsextract.reader.FileSelector.java
/** * Top unzip method. extract tarfile to constituent parts processing gzips * along the way e.g. yyyyMMdd.zip->/yyyyMMdd/INode-CH_RNC01/A2010...zip *//* w w w.j a va2s . c o m*/ protected void unzip1(File zipfile) throws FileNotFoundException { try { ZipArchiveInputStream zais = new ZipArchiveInputStream(new FileInputStream(zipfile)); ZipArchiveEntry z1 = null; while ((z1 = zais.getNextZipEntry()) != null) { if (z1.isDirectory()) { /*hack to add vcc identifier because fucking ops cant rename a simple file*/ if (z1.getName().contains("account")) identifier = ".vcc"; else identifier = ""; } else { String fn = z1.getName().substring(z1.getName().lastIndexOf("/")); File f = new File(getCalTempPath() + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = zais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); File unz = null; if (f.getName().endsWith("zip")) unz = unzip3(f); else unz = ungzip(f); if (unz != null) allfiles.add(unz); f.delete(); } } zais.close(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
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. * // w ww.j a v a2 s . c o m * @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:mj.ocraptor.extraction.tika.parser.iwork.IWorkPackageParser.java
public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { ZipArchiveInputStream zip = new ZipArchiveInputStream(stream); ZipArchiveEntry entry = zip.getNextZipEntry(); TikaImageHelper helper = new TikaImageHelper(metadata); XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); IWORKDocumentType type = null;//from w ww . j av a2 s . c o m try { while (entry != null) { // ------------------------------------------------ // // -- handle image files // ------------------------------------------------ // String entryExtension = null; try { entryExtension = FilenameUtils.getExtension(new File(entry.getName()).getName()); } catch (Exception e) { e.printStackTrace(); } if (entryExtension != null && FileType.isValidImageFileExtension(entryExtension)) { File imageFile = null; try { imageFile = TikaImageHelper.saveZipEntryToTemp(zip, entry); helper.addImage(imageFile); } catch (Exception e) { e.printStackTrace(); } finally { if (imageFile != null) { imageFile.delete(); } } } // ------------------------------------------------ // // -- // ------------------------------------------------ // if (!IWORK_CONTENT_ENTRIES.contains(entry.getName())) { entry = zip.getNextZipEntry(); continue; } InputStream entryStream = new BufferedInputStream(zip, 4096); entryStream.mark(4096); type = IWORKDocumentType.detectType(entryStream); entryStream.reset(); if (type != null) { ContentHandler contentHandler; switch (type) { case KEYNOTE: contentHandler = new KeynoteContentHandler(xhtml, metadata); break; case NUMBERS: contentHandler = new NumbersContentHandler(xhtml, metadata); break; case PAGES: contentHandler = new PagesContentHandler(xhtml, metadata); break; case ENCRYPTED: // We can't do anything for the file right now contentHandler = null; break; default: throw new TikaException("Unhandled iWorks file " + type); } metadata.add(Metadata.CONTENT_TYPE, type.getType().toString()); xhtml.startDocument(); if (contentHandler != null) { context.getSAXParser().parse(new CloseShieldInputStream(entryStream), new OfflineContentHandler(contentHandler)); } } entry = zip.getNextZipEntry(); } helper.addTextToHandler(xhtml); xhtml.endDocument(); } catch (Exception e) { // TODO: logging e.printStackTrace(); } finally { if (zip != null) { zip.close(); } if (helper != null) { helper.close(); } } }
From source file:ee.sk.digidoc.factory.SAXDigiDocFactory.java
/** * Reads in a DigiDoc file. One of fname or isSdoc must be given. * @param fname signed doc filename/*from w w w .j av a2 s .com*/ * @param isSdoc opened stream with DigiDoc data * The user must open and close it. * @param errs list of errors to fill with parsing errors. If given * then attempt is made to continue parsing on errors and return them in this list. * If not given (null) then the first error found will be thrown. * @return signed document object if successfully parsed */ private SignedDoc readSignedDocOfType(String fname, InputStream isSdoc, boolean isBdoc, List errs) throws DigiDocException { // Use an instance of ourselves as the SAX event handler SAXDigiDocFactory handler = this; m_errs = errs; DigiDocVerifyFactory.initProvider(); SAXParserFactory factory = SAXParserFactory.newInstance(); if (m_logger.isDebugEnabled()) m_logger.debug("Start reading ddoc/bdoc " + ((fname != null) ? "from file: " + fname : "from stream") + " bdoc: " + isBdoc); if (fname == null && isSdoc == null) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "No input file", null); } if (fname != null) { File inFile = new File(fname); if (!inFile.canRead() || inFile.length() == 0) { throw new DigiDocException(DigiDocException.ERR_READ_FILE, "Empty or unreadable input file", null); } } ZipFile zf = null; ZipArchiveInputStream zis = null; ZipArchiveEntry ze = null; InputStream isEntry = null; File fTmp = null; try { factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); if (isBdoc) { // bdoc parsing // must be a bdoc document ? m_doc = new SignedDoc(); m_doc.setVersion(SignedDoc.BDOC_VERSION_1_0); m_doc.setFormat(SignedDoc.FORMAT_BDOC); Enumeration eFiles = null; if (fname != null) { zf = new ZipFile(fname, "UTF-8"); eFiles = zf.getEntries(); } else if (isSdoc != null) { zis = new ZipArchiveInputStream(isSdoc, "UTF-8", true, true); } ArrayList lSigFnames = new ArrayList(); ArrayList lDataFnames = new ArrayList(); // read all entries boolean bHasMimetype = false, bManifest1 = false; int nFil = 0; while ((zf != null && eFiles.hasMoreElements()) || (zis != null && ((ze = zis.getNextZipEntry()) != null))) { nFil++; // read entry if (zf != null) { // ZipFile ze = (ZipArchiveEntry) eFiles.nextElement(); isEntry = zf.getInputStream(ze); } else { // ZipArchiveInputStream int n = 0, nTot = 0; if ((ze.getName().equals(FILE_MIMETYPE) || ze.getName().equals(FILE_MANIFEST) || (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml"))) || (nMaxBdocFilCached <= 0 || (ze.getSize() < nMaxBdocFilCached && ze.getSize() >= 0))) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { bos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip"); data = bos.toByteArray(); bos = null; isEntry = new ByteArrayInputStream(data); } else { File fCacheDir = new File(ConfigManager.instance().getStringProperty( "DIGIDOC_DF_CACHE_DIR", System.getProperty("java.io.tmpdir"))); fTmp = File.createTempFile("bdoc-data", ".tmp", fCacheDir); FileOutputStream fos = new FileOutputStream(fTmp); byte[] data = new byte[2048]; while ((n = zis.read(data)) > 0) { fos.write(data, 0, n); nTot += n; } if (m_logger.isDebugEnabled()) m_logger.debug("Read: " + nTot + " bytes from zip to: " + fTmp.getAbsolutePath()); fos.close(); isEntry = new FileInputStream(fTmp); } } if (m_logger.isDebugEnabled()) m_logger.debug("Entry: " + ze.getName() + " nlen: " + ze.getName().length() + " size: " + ze.getSize() + " dir: " + ze.isDirectory() + " comp-size: " + ze.getCompressedSize()); // mimetype file if (ze.getName().equals(FILE_MIMETYPE)) { if (m_logger.isDebugEnabled()) m_logger.debug("Check mimetype!"); checkBdocMimetype(isEntry); bHasMimetype = true; m_doc.setComment(ze.getComment()); if (nFil != 1) { m_logger.error("mimetype file is " + nFil + " file but must be first"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "mimetype file is not first zip entry", null)); } } else if (ze.getName().equals(FILE_MANIFEST)) { // manifest.xml file if (m_logger.isDebugEnabled()) m_logger.debug("Read manifest"); if (!bManifest1 && isEntry != null) { bManifest1 = true; BdocManifestParser mfparser = new BdocManifestParser(m_doc); mfparser.readManifest(isEntry); } else { m_logger.error("Found multiple manifest.xml files!"); throw new DigiDocException(DigiDocException.ERR_MULTIPLE_MANIFEST_FILES, "Found multiple manifest.xml files!", null); } } else if (ze.getName().startsWith(FILE_SIGNATURES) && ze.getName().endsWith(".xml")) { // some signature m_fileName = ze.getName(); if (m_logger.isDebugEnabled()) m_logger.debug("Reading bdoc siganture: " + m_fileName); boolean bExists = false; for (int j = 0; j < lSigFnames.size(); j++) { String s1 = (String) lSigFnames.get(j); if (s1.equals(m_fileName)) bExists = true; } if (bExists) { m_logger.error("Duplicate signature filename: " + m_fileName); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate signature filename: " + m_fileName, null)); } else lSigFnames.add(m_fileName); SAXParser saxParser = factory.newSAXParser(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); int n = 0; byte[] data = new byte[2048]; while ((n = isEntry.read(data)) > 0) bos.write(data, 0, n); data = bos.toByteArray(); bos = null; if (m_logger.isDebugEnabled()) m_logger.debug( "Parsing bdoc: " + m_fileName + " size: " + ((data != null) ? data.length : 0)); saxParser.parse(new SignatureInputStream(new ByteArrayInputStream(data)), this); if (m_logger.isDebugEnabled()) m_logger.debug("Parsed bdoc: " + m_fileName); Signature sig1 = m_doc.getLastSignature(); m_sigComment = ze.getComment(); if (sig1 != null) { sig1.setPath(m_fileName); sig1.setComment(ze.getComment()); } } else { // probably a data file if (m_logger.isDebugEnabled()) m_logger.debug("Read data file: " + ze.getName()); if (!ze.isDirectory()) { boolean bExists = false; for (int j = 0; j < lDataFnames.size(); j++) { String s1 = (String) lDataFnames.get(j); if (s1.equals(ze.getName())) bExists = true; } if (bExists) { m_logger.error("Duplicate datafile filename: " + ze.getName()); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Duplicate datafile filename: " + ze.getName(), null)); } else lDataFnames.add(ze.getName()); DataFile df = m_doc.findDataFileById(ze.getName()); if (df != null) { if (ze.getSize() > 0) df.setSize(ze.getSize()); df.setContentType(DataFile.CONTENT_BINARY); df.setFileName(ze.getName()); } else { df = new DataFile(ze.getName(), DataFile.CONTENT_BINARY, ze.getName(), "application/binary", m_doc); if (m_doc.getDataFiles() == null) m_doc.setDataFiles(new ArrayList()); m_doc.getDataFiles().add(df); //m_doc.addDataFile(df); // this does some intiailization work unnecessary here } // enable caching if requested if (isEntry != null) df.setOrCacheBodyAndCalcHashes(isEntry); df.setComment(ze.getComment()); df.setLastModDt(new Date(ze.getTime())); // fix mime type according to DataObjectFormat Signature sig1 = m_doc.getLastSignature(); if (sig1 != null) { Reference dRef = sig1.getSignedInfo().getReferenceForDataFile(df); if (dRef != null) { DataObjectFormat dof = sig1.getSignedInfo() .getDataObjectFormatForReference(dRef); if (dof != null) { df.setMimeType(dof.getMimeType()); } } } } } if (fTmp != null) { fTmp.delete(); fTmp = null; } } // while zip entries if (!bHasMimetype) { m_logger.error("No mimetype file"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "Not a BDOC format file! No mimetype file!", null)); } // if no signatures exist then copy mime-type from manifest.xml to DataFile -s if (m_doc.countSignatures() == 0) { for (int i = 0; i < m_doc.countDataFiles(); i++) { DataFile df = m_doc.getDataFile(i); if (m_doc.getManifest() != null) { for (int j = 0; j < m_doc.getManifest().getNumFileEntries(); j++) { ManifestFileEntry mfe = m_doc.getManifest().getFileEntry(j); if (mfe.getFullPath() != null && mfe.getFullPath().equals(df.getFileName())) { df.setMimeType(mfe.getMediaType()); } // if fullpath } // for } // if } // for i } } else { // ddoc parsing if (m_logger.isDebugEnabled()) m_logger.debug("Reading ddoc: " + fname + " file: " + m_fileName); m_fileName = fname; SAXParser saxParser = factory.newSAXParser(); if (fname != null) saxParser.parse(new SignatureInputStream(new FileInputStream(fname)), this); else if (isSdoc != null) saxParser.parse(isSdoc, this); } } catch (org.xml.sax.SAXParseException ex) { m_logger.error("SAX Error: " + ex); handleError(ex); } catch (Exception ex) { m_logger.error("Error reading3: " + ex); ex.printStackTrace(); /*if(ex instanceof DigiDocException){ DigiDocException dex = (DigiDocException)ex; m_logger.error("Dex: " + ex); if(dex.getNestedException() != null) { dex.getNestedException().printStackTrace(); m_logger.error("Trace: "); } }*/ handleError(ex); } finally { // cleanup try { if (isEntry != null) { isEntry.close(); isEntry = null; } if (zis != null) zis.close(); if (zf != null) zf.close(); if (fTmp != null) { fTmp.delete(); fTmp = null; } } catch (Exception ex) { m_logger.error("Error closing streams and files: " + ex); } } // compare Manifest and DataFiles boolean bErrList = (errs != null); if (errs == null) errs = new ArrayList(); boolean bOk = DigiDocVerifyFactory.verifyManifestEntries(m_doc, errs); if (m_doc == null) { m_logger.error("Error reading4: doc == null"); handleError(new DigiDocException(DigiDocException.ERR_DIGIDOC_BADXML, "This document is not in ddoc or bdoc format", null)); } if (!bErrList && errs.size() > 0) { // if error list was not used then we have to throw exception. So we will throw the first one since we can only do it once DigiDocException ex = (DigiDocException) errs.get(0); throw ex; } return m_doc; }
From source file:nz.co.kakariki.networkutils.reader.ExtractArchive.java
/** * Top unzip method./* w ww . j a v a 2s. c o m*/ */ protected static void unzip(File zipfile) throws FileNotFoundException { File path = zipfile.getParentFile(); try { ZipArchiveInputStream zais = new ZipArchiveInputStream(new FileInputStream(zipfile)); ZipArchiveEntry z1 = null; while ((z1 = zais.getNextZipEntry()) != null) { String fn = z1.getName(); if (fn.contains("/")) { fn = fn.substring(z1.getName().lastIndexOf("/")); } File f = new File(path + File.separator + fn); FileOutputStream fos = new FileOutputStream(f); BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER); int n = 0; byte[] content = new byte[BUFFER]; while (-1 != (n = zais.read(content))) { fos.write(content, 0, n); } bos.flush(); bos.close(); fos.close(); } zais.close(); zipfile.delete(); } catch (IOException ioe) { jlog.fatal("IO read error :: " + ioe); } }
From source file:org.alfresco.repo.content.transform.AppleIWorksContentTransformer.java
@Override protected void transformInternal(ContentReader reader, ContentWriter writer, TransformationOptions options) throws Exception { final String sourceMimetype = reader.getMimetype(); final String sourceExtension = getMimetypeService().getExtension(sourceMimetype); final String targetMimetype = writer.getMimetype(); if (log.isDebugEnabled()) { StringBuilder msg = new StringBuilder(); msg.append("Transforming from ").append(sourceMimetype).append(" to ").append(targetMimetype); log.debug(msg.toString());// w w w . ja v a 2 s . c o m } ZipArchiveInputStream iWorksZip = null; try { // iWorks files are zip files (at least in recent versions, iWork 09). // If it's not a zip file, the resultant ZipException will be caught as an IOException below. iWorksZip = new ZipArchiveInputStream(reader.getContentInputStream()); ZipArchiveEntry entry = null; boolean found = false; while (!found && (entry = iWorksZip.getNextZipEntry()) != null) { if (MimetypeMap.MIMETYPE_IMAGE_JPEG.equals(targetMimetype) && entry.getName().equals(QUICK_LOOK_THUMBNAIL_JPG)) { writer.putContent(iWorksZip); found = true; } else if (MimetypeMap.MIMETYPE_PDF.equals(targetMimetype) && entry.getName().equals(QUICK_LOOK_PREVIEW_PDF)) { writer.putContent(iWorksZip); found = true; } } if (!found) { throw new AlfrescoRuntimeException( "Unable to transform " + sourceExtension + " file to " + targetMimetype); } } catch (FileNotFoundException e1) { throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e1); } catch (IOException e) { throw new AlfrescoRuntimeException("Unable to transform " + sourceExtension + " file.", e); } finally { if (iWorksZip != null) { iWorksZip.close(); } } }
From source file:org.alfresco.repo.download.DownloadServiceIntegrationTest.java
private Set<String> getEntries(final NodeRef downloadNode) { return TRANSACTION_HELPER.doInTransaction(new RetryingTransactionCallback<Set<String>>() { @Override/*from ww w.j a va2 s .c o m*/ public Set<String> execute() throws Throwable { Set<String> entryNames = new TreeSet<String>(); ContentReader reader = CONTENT_SERVICE.getReader(downloadNode, ContentModel.PROP_CONTENT); ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(reader.getContentInputStream()); try { ZipArchiveEntry zipEntry = zipInputStream.getNextZipEntry(); while (zipEntry != null) { String name = zipEntry.getName(); entryNames.add(name); zipEntry = zipInputStream.getNextZipEntry(); } } finally { zipInputStream.close(); } return entryNames; } }); }
From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java
public void validateZipAndClose(InputStream in) throws IOException { ZipArchiveInputStream zip = new ZipArchiveInputStream(in); try {/*from ww w .ja v a2 s .c o m*/ byte[] buf = new byte[1024]; ZipArchiveEntry entry = zip.getNextZipEntry(); if (entry == null) throw new BadRequest("Archive is empty"); do { entry.getName(); entry.getMethod(); entry.getSize(); while (zip.read(buf, 0, buf.length) >= 0) ; entry = zip.getNextZipEntry(); } while (entry != null); } finally { zip.close(); } }
From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java
public InputStream readZipEntry(String match) throws IOException { InputStream in = this.openInputStream(); try {//from w w w. j ava 2 s . c o m ZipArchiveInputStream zip = new ZipArchiveInputStream(in); byte[] buf = new byte[1024]; ZipArchiveEntry entry = zip.getNextZipEntry(); do { if (entry.getName().equals(match)) { return zip; } long size = entry.getSize(); if (size > 0) { zip.skip(size); } else { while (zip.read(buf, 0, buf.length) >= 0) ; } entry = zip.getNextZipEntry(); } while (entry != null); zip.close(); } catch (RuntimeException | Error | IOException e) { in.close(); throw e; } return null; }
From source file:org.callimachusproject.behaviours.ZipArchiveSupport.java
public XMLEventReader createAtomFeedFromArchive(final String id, final String entryPattern) throws IOException { final FileObject file = this; final XMLEventFactory ef = XMLEventFactory.newInstance(); final byte[] buf = new byte[1024]; final ZipArchiveInputStream zip = new ZipArchiveInputStream(file.openInputStream()); return new XMLEventReaderBase() { private boolean started; private boolean ended; public void close() throws XMLStreamException { try { zip.close(); } catch (IOException e) { throw new XMLStreamException(e); }//from w w w. ja va 2 s. c o m } protected boolean more() throws XMLStreamException { try { ZipArchiveEntry entry; if (!started) { Namespace atom = ef.createNamespace(FEED.getPrefix(), FEED.getNamespaceURI()); add(ef.createStartDocument()); add(ef.createStartElement(FEED, null, Arrays.asList(atom).iterator())); add(ef.createStartElement(TITLE, null, null)); add(ef.createCharacters(file.getName())); add(ef.createEndElement(TITLE, null)); add(ef.createStartElement(ID, null, null)); add(ef.createCharacters(id)); add(ef.createEndElement(ID, null)); Attribute href = ef.createAttribute("href", file.toUri().toASCIIString()); List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", "application/zip")); add(ef.createStartElement(LINK, attrs.iterator(), null)); add(ef.createEndElement(LINK, null)); add(ef.createStartElement(UPDATED, null, null)); add(ef.createCharacters(format(new Date(file.getLastModified())))); add(ef.createEndElement(UPDATED, null)); started = true; return true; } else if (started && !ended && (entry = zip.getNextZipEntry()) != null) { String name = entry.getName(); String link = entryPattern.replace("{entry}", PercentCodec.encode(name)); MimetypesFileTypeMap mimetypes = new javax.activation.MimetypesFileTypeMap(); String type = mimetypes.getContentType(name); if (type == null || type.length() == 0) { type = "application/octet-stream"; } add(ef.createStartElement(ENTRY, null, null)); add(ef.createStartElement(TITLE, null, null)); add(ef.createCharacters(name)); add(ef.createEndElement(TITLE, null)); Attribute href = ef.createAttribute("href", link); List<Attribute> attrs = Arrays.asList(href, ef.createAttribute("type", type)); add(ef.createStartElement(LINK, attrs.iterator(), null)); add(ef.createEndElement(LINK, null)); long size = entry.getSize(); if (size > 0) { zip.skip(size); } else { while (zip.read(buf, 0, buf.length) >= 0) ; } add(ef.createEndElement(ENTRY, null)); return true; } else if (!ended) { add(ef.createEndElement(FEED, null)); add(ef.createEndDocument()); ended = true; return true; } else { return false; } } catch (IOException e) { throw new XMLStreamException(e); } } }; }