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.apache.ant.compress.resources.ZipResource.java
/** * Return an InputStream for reading the contents of this Resource. * @return an InputStream object.// ww w . ja v a 2 s. c o m * @throws IOException if the zip file cannot be opened, * or the entry cannot be read. */ public InputStream getInputStream() throws IOException { if (isReference()) { return ((Resource) getCheckedRef()).getInputStream(); } File f = getZipfile(); if (f == null) { return super.getInputStream(); } final ZipFile z = new ZipFile(f, getEncoding()); ZipArchiveEntry ze = z.getEntry(getName()); if (ze == null) { z.close(); throw new BuildException("no entry " + getName() + " in " + getArchive()); } return new FilterInputStream(z.getInputStream(ze)) { public void close() throws IOException { FileUtils.close(in); z.close(); } protected void finalize() throws Throwable { try { close(); } finally { super.finalize(); } } }; }
From source file:org.apache.ant.compress.taskdefs.Unzip.java
protected void expandFile(FileUtils fileUtils, File srcF, File dir) { log("Expanding: " + srcF + " into " + dir, Project.MSG_INFO); ZipFile zf = null; FileNameMapper mapper = getMapper(); if (!srcF.exists()) { throw new BuildException("Unable to expand " + srcF + " as the file does not exist", getLocation()); }//from w w w. jav a 2 s . co m try { zf = new ZipFile(srcF, getEncoding(), true); boolean empty = true; Enumeration e = zf.getEntries(); while (e.hasMoreElements()) { empty = false; ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement(); if (getSkipUnreadableEntries() && !zf.canReadEntryData(ze)) { log(Messages.skippedIsUnreadable(ze)); continue; } log("extracting " + ze.getName(), Project.MSG_DEBUG); InputStream is = null; try { extractFile(fileUtils, srcF, dir, is = zf.getInputStream(ze), ze.getName(), new Date(ze.getTime()), ze.isDirectory(), mapper); } finally { FileUtils.close(is); } } if (empty && getFailOnEmptyArchive()) { throw new BuildException("archive '" + srcF + "' is empty"); } log("expand complete", Project.MSG_VERBOSE); } catch (IOException ioe) { throw new BuildException("Error while expanding " + srcF.getPath() + "\n" + ioe.toString(), ioe); } finally { ZipFile.closeQuietly(zf); } }
From source file:org.apache.brooklyn.rest.resources.CatalogResource.java
@Override @Beta//from w w w. jav a 2 s . c o m public Response createFromArchive(byte[] zipInput) { if (!Entitlements.isEntitled(mgmt().getEntitlementManager(), Entitlements.ROOT, null)) { throw WebResourceUtils.forbidden("User '%s' is not authorized to add catalog item", Entitlements.getEntitlementContext().user()); } BundleMaker bm = new BundleMaker(mgmtInternal()); File f = null, f2 = null; try { f = Os.newTempFile("brooklyn-posted-archive", "zip"); try { Files.write(zipInput, f); } catch (IOException e) { Exceptions.propagate(e); } ZipFile zf; try { zf = new ZipFile(f); } catch (IOException e) { throw new IllegalArgumentException("Invalid ZIP/JAR archive: " + e); } ZipArchiveEntry bom = zf.getEntry("catalog.bom"); if (bom == null) { bom = zf.getEntry("/catalog.bom"); } if (bom == null) { throw new IllegalArgumentException("Archive must contain a catalog.bom file in the root"); } String bomS; try { bomS = Streams.readFullyString(zf.getInputStream(bom)); } catch (IOException e) { throw new IllegalArgumentException("Error reading catalog.bom from ZIP/JAR archive: " + e); } try { zf.close(); } catch (IOException e) { log.debug("Swallowed exception closing zipfile. Full error logged at trace: {}", e.getMessage()); log.trace("Exception closing zipfile", e); } VersionedName vn = BasicBrooklynCatalog.getVersionedName(BasicBrooklynCatalog.getCatalogMetadata(bomS)); Manifest mf = bm.getManifest(f); if (mf == null) { mf = new Manifest(); } String bundleNameInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME); if (Strings.isNonBlank(bundleNameInMF)) { if (!bundleNameInMF.equals(vn.getSymbolicName())) { throw new IllegalArgumentException("JAR MANIFEST symbolic-name '" + bundleNameInMF + "' does not match '" + vn.getSymbolicName() + "' defined in BOM"); } } else { bundleNameInMF = vn.getSymbolicName(); mf.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, bundleNameInMF); } String bundleVersionInMF = mf.getMainAttributes().getValue(Constants.BUNDLE_VERSION); if (Strings.isNonBlank(bundleVersionInMF)) { if (!bundleVersionInMF.equals(vn.getVersion().toString())) { throw new IllegalArgumentException("JAR MANIFEST version '" + bundleVersionInMF + "' does not match '" + vn.getVersion() + "' defined in BOM"); } } else { bundleVersionInMF = vn.getVersion().toString(); mf.getMainAttributes().putValue(Constants.BUNDLE_VERSION, bundleVersionInMF); } if (mf.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION) == null) { mf.getMainAttributes().putValue(Attributes.Name.MANIFEST_VERSION.toString(), "1.0"); } f2 = bm.copyAddingManifest(f, mf); BasicManagedBundle bundleMetadata = new BasicManagedBundle(bundleNameInMF, bundleVersionInMF, null); Bundle bundle; try (FileInputStream f2in = new FileInputStream(f2)) { bundle = ((ManagementContextInternal) mgmt()).getOsgiManager().get() .installUploadedBundle(bundleMetadata, f2in, false); } catch (Exception e) { throw Exceptions.propagate(e); } Iterable<? extends CatalogItem<?, ?>> catalogItems = MutableList .copyOf(((ManagementContextInternal) mgmt()).getOsgiManager().get().loadCatalogBom(bundle)); return buildCreateResponse(catalogItems); } catch (RuntimeException ex) { throw WebResourceUtils.badRequest(ex); } finally { if (f != null) f.delete(); if (f2 != null) f2.delete(); } }
From source file:org.apache.tika.parser.pkg.ZipContainerDetector.java
/** * OpenDocument files, along with EPub files and ASiC ones, have a * mimetype entry in the root of their Zip file. This entry contains * the mimetype of the overall file, stored as a single string. *//* ww w .j a va 2 s . co m*/ private static MediaType detectOpenDocument(ZipFile zip) { try { ZipArchiveEntry mimetype = zip.getEntry("mimetype"); if (mimetype != null) { try (InputStream stream = zip.getInputStream(mimetype)) { return MediaType.parse(IOUtils.toString(stream, UTF_8)); } } else { return null; } } catch (IOException e) { return null; } }
From source file:org.apache.tika.server.CXFTestBase.java
protected Map<String, String> readZipArchive(InputStream inputStream) throws IOException { Map<String, String> data = new HashMap<String, String>(); Path tempFile = writeTemporaryArchiveFile(inputStream, "zip"); ZipFile zip = new ZipFile(tempFile.toFile()); Enumeration<ZipArchiveEntry> entries = zip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(zip.getInputStream(entry), bos); data.put(entry.getName(), DigestUtils.md5Hex(bos.toByteArray())); }/*from w w w. j a va 2 s. co m*/ zip.close(); Files.delete(tempFile); return data; }
From source file:org.apache.tika.server.CXFTestBase.java
protected String readArchiveText(InputStream inputStream) throws IOException { Path tempFile = writeTemporaryArchiveFile(inputStream, "zip"); ZipFile zip = new ZipFile(tempFile.toFile()); zip.getEntry(UnpackerResource.TEXT_FILENAME); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOUtils.copy(zip.getInputStream(zip.getEntry(UnpackerResource.TEXT_FILENAME)), bos); zip.close();/* w w w. java2 s .co m*/ Files.delete(tempFile); return bos.toString(UTF_8.name()); }
From source file:org.apache.wookie.w3c.util.WidgetPackageUtils.java
/** * Retrieves the Manifest entry as a String * @param zipFile the zip file from which to extract the manifest * @return a String representing the manifest contents * @throws IOException/*w w w . java 2 s . c o m*/ */ public static String extractManifest(ZipFile zipFile) throws IOException { ZipArchiveEntry entry = zipFile.getEntry(IW3CXMLConfiguration.MANIFEST_FILE); return IOUtils.toString(zipFile.getInputStream(entry), "UTF-8"); }
From source file:org.apache.wookie.w3c.util.WidgetPackageUtils.java
/** * uses apache commons compress to unpack all the zip entries into a target folder * partly adapted from the examples on the apache commons compress site, and an * example of generic Zip unpacking. Note this iterates over the ZipArchiveEntry enumeration rather * than use the more typical ZipInputStream parsing model, as according to the doco it will * more reliably read the entries correctly. More info here: http://commons.apache.org/compress/zip.html * @param zipfile the Zip File to unpack * @param targetFolder the folder into which to unpack the Zip file * @throws IOException// w ww . ja v a 2s . c o m */ @SuppressWarnings("unchecked") public static void unpackZip(ZipFile zipfile, File targetFolder) throws IOException { targetFolder.mkdirs(); BufferedOutputStream out = null; InputStream in = null; ZipArchiveEntry zipEntry; Enumeration entries = zipfile.getEntries(); try { while (entries.hasMoreElements()) { zipEntry = (ZipArchiveEntry) entries.nextElement(); // Don't add directories - use mkdirs instead if (!zipEntry.isDirectory()) { File outFile = new File(targetFolder, zipEntry.getName()); // Ensure that the parent Folder exists if (!outFile.getParentFile().exists()) { outFile.getParentFile().mkdirs(); } // Read the entry in = new BufferedInputStream(zipfile.getInputStream(zipEntry)); out = new BufferedOutputStream(new FileOutputStream(outFile)); IOUtils.copy(in, out); // Restore time stamp outFile.setLastModified(zipEntry.getTime()); // Close File out.close(); // Close Stream in.close(); } } } // We'll catch this exception to close the file otherwise it remains locked catch (IOException ex) { if (in != null) { in.close(); } if (out != null) { out.flush(); out.close(); } // And throw it again throw ex; } }
From source file:org.artificer.atom.archive.ArchiveUtils.java
/** * Unpacks the given archive file into the output directory. * @param archiveFile an archive file/* w ww . j a va2s . 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", outFile.getParentFile().getCanonicalPath())); } } if (entry.isDirectory()) { if (outFile.isDirectory()) { // Do nothing - already created. } else if (outFile.isFile()) { throw new IOException( Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath())); } else if (!outFile.mkdir()) { throw new IOException( Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath())); } } 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.beangle.commons.archiver.ZipUtils.java
public static List<String> unzip(final File zipFile, final String destination, String encoding) { List<String> fileNames = CollectUtils.newArrayList(); String dest = destination;//from w w w. j a v a2 s . co m if (!destination.endsWith(File.separator)) { dest = destination + File.separator; } ZipFile file; try { file = null; if (null == encoding) file = new ZipFile(zipFile); else file = new ZipFile(zipFile, encoding); @SuppressWarnings("unchecked") Enumeration<ZipArchiveEntry> en = file.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); File f = new File(dest, ze.getName()); if (ze.isDirectory()) { f.mkdirs(); continue; } else { f.getParentFile().mkdirs(); InputStream is = file.getInputStream(ze); OutputStream os = new FileOutputStream(f); IOUtils.copy(is, os); is.close(); os.close(); fileNames.add(f.getAbsolutePath()); } } file.close(); } catch (IOException e) { e.printStackTrace(); } return fileNames; }