List of usage examples for org.apache.commons.compress.archivers.zip ZipFile getInputStream
public InputStream getInputStream(ZipArchiveEntry ze) throws IOException, ZipException
From source file:org.overlord.sramp.atom.archive.ArchiveUtils.java
/** * Unpacks the given archive file into the output directory. * @param archiveFile an archive file/* w w w.j a va2 s .c om*/ * @param toDir where to unpack the archive to * @throws IOException */ public static void unpackToWorkDir(File archiveFile, File toDir) throws IOException { ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntriesInPhysicalOrder(); while (zipEntries.hasMoreElements()) { ZipArchiveEntry entry = zipEntries.nextElement(); String entryName = entry.getName(); File outFile = new File(toDir, entryName); if (!outFile.getParentFile().exists()) { if (!outFile.getParentFile().mkdirs()) { throw new IOException(Messages.i18n.format("FAILED_TO_CREATE_PARENT_DIR", //$NON-NLS-1$ outFile.getParentFile().getCanonicalPath())); } } if (entry.isDirectory()) { if (!outFile.mkdir()) { throw new IOException( Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath())); //$NON-NLS-1$ } } else { InputStream zipStream = null; OutputStream outFileStream = null; zipStream = zipFile.getInputStream(entry); outFileStream = new FileOutputStream(outFile); try { IOUtils.copy(zipStream, outFileStream); } finally { IOUtils.closeQuietly(zipStream); IOUtils.closeQuietly(outFileStream); } } } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:org.sead.nds.repository.BagGenerator.java
public void validateBag(String bagId) { log.info("Validating Bag"); ZipFile zf = null; InputStream is = null;/* w ww . j a v a 2 s . co m*/ try { zf = new ZipFile(getBagFile(bagId)); ZipArchiveEntry entry = zf.getEntry(getValidName(bagId) + "/manifest-sha1.txt"); if (entry != null) { log.info("SHA1 hashes used"); hashtype = "SHA1 Hash"; is = zf.getInputStream(entry); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { log.debug("Hash entry: " + line); int breakIndex = line.indexOf(' '); String hash = line.substring(0, breakIndex); String path = line.substring(breakIndex + 1); log.debug("Adding: " + path + " with hash: " + hash); sha1Map.put(path, hash); line = br.readLine(); } IOUtils.closeQuietly(is); } else { entry = zf.getEntry(getValidName(bagId) + "/manifest-sha512.txt"); if (entry != null) { log.info("SHA512 hashes used"); hashtype = "SHA512 Hash"; is = zf.getInputStream(entry); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String line = br.readLine(); while (line != null) { int breakIndex = line.indexOf(' '); String hash = line.substring(0, breakIndex); String path = line.substring(breakIndex + 1); sha1Map.put(path, hash); line = br.readLine(); } IOUtils.closeQuietly(is); } } log.info("HashMap Map contains: " + sha1Map.size() + " etries"); checkFiles(sha1Map, zf); } catch (IOException io) { log.error("Could not validate Hashes", io); } catch (Exception e) { log.error("Could not validate Hashes", e); } return; }
From source file:org.sead.nds.repository.util.ValidationJob.java
private String generateFileHash(String name, ZipFile zf) { ZipArchiveEntry archiveEntry1 = zf.getEntry(name); // Error check - add file sizes to compare against supplied stats long start = System.currentTimeMillis(); InputStream inputStream = null; String realHash = null;/*from w w w. ja v a 2 s. c om*/ try { inputStream = zf.getInputStream(archiveEntry1); String hashtype = bagGenerator.getHashtype(); if (hashtype != null) { if (hashtype.equals("SHA1 Hash")) { realHash = DigestUtils.sha1Hex(inputStream); } else if (hashtype.equals("SHA512 Hash")) { realHash = DigestUtils.sha512Hex(inputStream); } } } catch (ZipException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { IOUtils.closeQuietly(inputStream); } log.debug("Retrieve/compute time = " + (System.currentTimeMillis() - start) + " ms"); // Error check - add file sizes to compare against supplied stats bagGenerator.incrementTotalDataSize(archiveEntry1.getSize()); return realHash; }
From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java
/** * Extracts content of the ZIP file to the target folder. * * @param zipFile ZIP archive//from ww w . j a va 2s . c om * @param targetDir Directory to extract files to * @param mkdirs Allow creating missing directories on the file paths * @throws IOException IO Exception * @throws FileNotFoundException */ public static void extract(File zipFile, File targetDir, boolean mkdirs) throws IOException { ZipFile zf = null; try { zf = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> zes = zf.getEntries(); while (zes.hasMoreElements()) { ZipArchiveEntry entry = zes.nextElement(); if (!entry.isDirectory()) { File targetFile = new File(targetDir, entry.getName()); if (mkdirs) { targetFile.getParentFile().mkdirs(); } InputStream is = null; try { is = zf.getInputStream(entry); copyInputStreamToFile(is, targetFile); } finally { IOUtils.closeQuietly(is); } } } } finally { ZipFile.closeQuietly(zf); } }
From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java
/** * Returns a stream for a file stored in the ZIP archive. * * @param zipFile ZIP archive/* w ww. j a va 2s.c om*/ * @param fileName Name of the file to get stream for * @return Input Stream for the requested file entry * @throws IOException IO Exception * @throws FileNotFoundException */ public static InputStream getInputStreamForFile(File zipFile, String fileName) throws IOException { ZipFile zf = null; InputStream fileInputStream = null; try { zf = new ZipFile(zipFile); ZipArchiveEntry entry = zf.getEntry(fileName); if (entry == null || entry.isDirectory()) { String msg = MessageFormat.format("No file entry is found for {0} withing the {0} archive", fileName, zipFile); throw new FileNotFoundException(msg); } final ZipFile fzf = zf; fileInputStream = new BufferedInputStream(zf.getInputStream(entry)) { @Override public void close() throws IOException { super.close(); ZipFile.closeQuietly(fzf); } }; } finally { if (fileInputStream == null) { ZipFile.closeQuietly(zf); } } return fileInputStream; }
From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java
/** * Create a CodeSetEntry that wraps a ZipEntry *//*from ww w . j a v a 2s.com*/ private CodeSetEntry csEntry(final ZipFile zip, final ZipArchiveEntry e) { IPath zipPath = new Path(e.getName()); //path relative to zip file Assert.isTrue(root.isPrefixOf(zipPath)); final IPath csPath = zipPath.removeFirstSegments(root.segmentCount()); return new CodeSetEntry() { @Override public IPath getPath() { return csPath; } @Override public String toString() { return getPath() + " in " + zipDownload; } @Override public boolean isDirectory() { return e.isDirectory(); } @Override public int getUnixMode() { return e.getUnixMode(); } @Override public InputStream getData() throws IOException { return zip.getInputStream(e); } }; }
From source file:org.xwiki.filemanager.internal.job.PackJobTest.java
@Test public void pack() throws Exception { Folder projects = mockFolder("Projects", "Pr\u00F4j\u00EA\u00E7\u021B\u0219", null, Arrays.asList("Concerto", "Resilience"), Arrays.asList("key.pub")); File key = mockFile("key.pub", "Projects"); when(fileSystem.canView(key.getReference())).thenReturn(false); mockFolder("Concerto", "Projects", Collections.<String>emptyList(), Arrays.asList("pom.xml")); File pom = mockFile("pom.xml", "m&y p?o#m.x=m$l", "Concerto"); setFileContent(pom, "foo"); Folder resilience = mockFolder("Resilience", "Projects", Arrays.asList("src"), Arrays.asList("build.xml")); when(fileSystem.canView(resilience.getReference())).thenReturn(false); mockFolder("src", "Resilience"); mockFile("build.xml"); File readme = mockFile("readme.txt", "r\u00E9\u00E0dm\u00E8.txt"); setFileContent(readme, "blah"); PackRequest request = new PackRequest(); request.setPaths(Arrays.asList(new Path(projects.getReference()), new Path(null, readme.getReference()))); request.setOutputFileReference(//from ww w . j av a2 s . c o m new AttachmentReference("out.zip", new DocumentReference("wiki", "Space", "Page"))); PackJob job = (PackJob) execute(request); ZipFile zip = new ZipFile( new java.io.File(testFolder.getRoot(), "temp/filemanager/wiki/Space/Page/out.zip")); List<String> folders = new ArrayList<String>(); Map<String, String> files = new HashMap<String, String>(); Enumeration<ZipArchiveEntry> entries = zip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.isDirectory()) { folders.add(entry.getName()); } else if (zip.canReadEntryData(entry)) { StringWriter writer = new StringWriter(); IOUtils.copy(zip.getInputStream(entry), writer); files.put(entry.getName(), writer.toString()); } } zip.close(); assertEquals(Arrays.asList(projects.getName() + '/', projects.getName() + "/Concerto/"), folders); assertEquals(2, files.size()); assertEquals("blah", files.get(readme.getName())); assertEquals("foo", files.get(projects.getName() + "/Concerto/" + pom.getName())); assertEquals(("blah" + "foo").getBytes().length, job.getStatus().getBytesWritten()); assertTrue(job.getStatus().getOutputFileSize() > 0); }
From source file:org.xwiki.filter.test.internal.ZIPFileAssertComparator.java
private static Map<String, byte[]> unzip(File filename) throws IOException { Map<String, byte[]> zipContent = new HashMap<String, byte[]>(); ZipFile zipFile = new ZipFile(filename); try {//from w w w .ja va 2 s .com Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); InputStream inputStream = zipFile.getInputStream(entry); try { zipContent.put(entry.getName(), IOUtils.toByteArray(inputStream)); } finally { inputStream.close(); } } } finally { zipFile.close(); } return zipContent; }
From source file:org.xwiki.wiki.workspacesmigrator.internal.DefaultDocumentRestorerFromAttachedXAR.java
@Override public void restoreDocumentFromAttachedXAR(DocumentReference docReference, String attachmentName, List<DocumentReference> documentsToRestore) throws XWikiException { XWikiContext xcontext = xcontextProvider.get(); XWiki xwiki = xcontext.getWiki();//ww w . j a v a2 s .c om File tempZipFile = null; try { tempZipFile = getTemporaryZipFile(docReference, attachmentName); if (tempZipFile == null) { return; } ZipFile zipFile = new ZipFile(tempZipFile); // We look for each document to restore if there is a corresponding zipEntry. Iterator<DocumentReference> itDocumentsToRestore = documentsToRestore.iterator(); while (itDocumentsToRestore.hasNext()) { DocumentReference docRef = itDocumentsToRestore.next(); // Compute what should be the filename of the document to restore String fileNameToRestore = String.format("%s/%s.xml", docRef.getLastSpaceReference().getName(), docRef.getName()); // Get the corresponding zip Entry ZipArchiveEntry zipEntry = zipFile.getEntry(fileNameToRestore); if (zipEntry != null) { // Restore the document XWikiDocument docToRestore = xwiki.getDocument(docRef, xcontext); docToRestore.fromXML(zipFile.getInputStream(zipEntry)); xwiki.saveDocument(docToRestore, xcontext); // We have restored this document itDocumentsToRestore.remove(); } } zipFile.close(); } catch (IOException e) { logger.error("Error during the decompression of [{}].", attachmentName, e); } finally { // Delete the temporary zip file if (tempZipFile != null) { tempZipFile.delete(); } } }
From source file:org.xwiki.xar.XarPackage.java
/** * Find and add the entries located in the passed XAR file. * //from www . j a va2 s. c o m * @param zipFile the XAR file * @throws IOException when failing to read the file * @throws XarException when failing to parse the XAR package */ public void read(ZipFile zipFile) throws IOException, XarException { Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries(); while (zipEntries.hasMoreElements()) { ZipArchiveEntry entry = zipEntries.nextElement(); if (!entry.isDirectory()) { InputStream stream = zipFile.getInputStream(entry); try { readEntry(stream, entry); } finally { stream.close(); } } } }