List of usage examples for java.util.zip ZipFile getInputStream
public InputStream getInputStream(ZipEntry entry) throws IOException
From source file:com.facebook.buck.android.AndroidBinaryIntegrationTest.java
@Test public void testLibraryMetadataChecksum() throws IOException { String target = "//apps/sample:app_cxx_lib_asset"; workspace.runBuckCommand("build", target).assertSuccess(); Path pathToZip = workspace/*from w w w.java 2s . com*/ .getPath(BuildTargets.getGenPath(filesystem, BuildTargetFactory.newInstance(target), "%s.apk")); ZipFile file = new ZipFile(pathToZip.toFile()); ZipEntry metadata = file.getEntry("assets/lib/metadata.txt"); assertNotNull(metadata); BufferedReader contents = new BufferedReader(new InputStreamReader(file.getInputStream(metadata))); String line = contents.readLine(); byte[] buffer = new byte[512]; while (line != null) { // Each line is of the form <filename> <filesize> <SHA256 checksum> String[] tokens = line.split(" "); assertSame(tokens.length, 3); String filename = tokens[0]; int filesize = Integer.parseInt(tokens[1]); String checksum = tokens[2]; ZipEntry lib = file.getEntry("assets/lib/" + filename); assertNotNull(lib); InputStream is = file.getInputStream(lib); ByteArrayOutputStream out = new ByteArrayOutputStream(); while (filesize > 0) { int read = is.read(buffer, 0, Math.min(buffer.length, filesize)); assertTrue(read >= 0); out.write(buffer, 0, read); filesize -= read; } String actualChecksum = Hashing.sha256().hashBytes(out.toByteArray()).toString(); assertEquals(checksum, actualChecksum); is.close(); out.close(); line = contents.readLine(); } file.close(); contents.close(); }
From source file:de.shadowhunt.subversion.internal.AbstractHelper.java
private void extractArchive(final File zip, final File prefix) throws Exception { final ZipFile zipFile = new ZipFile(zip); final Enumeration<? extends ZipEntry> enu = zipFile.entries(); while (enu.hasMoreElements()) { final ZipEntry zipEntry = enu.nextElement(); final String name = zipEntry.getName(); final File file = new File(prefix, name); if (name.charAt(name.length() - 1) == Resource.SEPARATOR_CHAR) { if (!file.isDirectory() && !file.mkdirs()) { throw new IOException("can not create directory structure: " + file); }//from www . j a v a 2 s . c o m continue; } final File parent = file.getParentFile(); if (parent != null) { if (!parent.isDirectory() && !parent.mkdirs()) { throw new IOException("can not create directory structure: " + parent); } } try (final InputStream is = zipFile.getInputStream(zipEntry)) { try (final OutputStream os = new FileOutputStream(file)) { IOUtils.copy(is, os); } } } zipFile.close(); }
From source file:de.tudarmstadt.ukp.clarin.webanno.project.page.ProjectPage.java
private void actionImportProject(List<FileUpload> exportedProjects, boolean aGenerateUsers) { Project importedProject = new Project(); // import multiple projects! for (FileUpload exportedProject : exportedProjects) { InputStream tagInputStream; try {/* w w w .j ava 2s. com*/ tagInputStream = exportedProject.getInputStream(); if (!ZipUtils.isZipStream(tagInputStream)) { error("Invalid ZIP file"); return; } File zipFfile = exportedProject.writeToTempFile(); if (!ImportUtil.isZipValidWebanno(zipFfile)) { error("Incompatible to webanno ZIP file"); } ZipFile zip = new ZipFile(zipFfile); InputStream projectInputStream = null; for (Enumeration zipEnumerate = zip.entries(); zipEnumerate.hasMoreElements();) { ZipEntry entry = (ZipEntry) zipEnumerate.nextElement(); if (entry.toString().replace("/", "").startsWith(ImportUtil.EXPORTED_PROJECT) && entry.toString().replace("/", "").endsWith(".json")) { projectInputStream = zip.getInputStream(entry); break; } } // projectInputStream = // uploadedFile.getInputStream(); String text = IOUtils.toString(projectInputStream, "UTF-8"); de.tudarmstadt.ukp.clarin.webanno.model.export.Project importedProjectSetting = JSONUtil .getJsonConverter().getObjectMapper() .readValue(text, de.tudarmstadt.ukp.clarin.webanno.model.export.Project.class); importedProject = ImportUtil.createProject(importedProjectSetting, repository, userRepository); Map<de.tudarmstadt.ukp.clarin.webanno.model.export.AnnotationFeature, AnnotationFeature> featuresMap = ImportUtil .createLayer(importedProject, importedProjectSetting, userRepository, annotationService); ImportUtil.createSourceDocument(importedProjectSetting, importedProject, repository, userRepository, featuresMap); ImportUtil.createMiraTemplate(importedProjectSetting, automationService, featuresMap); ImportUtil.createCrowdJob(importedProjectSetting, repository, importedProject); ImportUtil.createAnnotationDocument(importedProjectSetting, importedProject, repository); ImportUtil.createProjectPermission(importedProjectSetting, importedProject, repository, aGenerateUsers, userRepository); /* * for (TagSet tagset : importedProjectSetting.getTagSets()) { * ImportUtil.createTagset(importedProject, tagset, projectRepository, * annotationService); } */ // add source document content ImportUtil.createSourceDocumentContent(zip, importedProject, repository); // add annotation document content ImportUtil.createAnnotationDocumentContent(zip, importedProject, repository); // create curation document content ImportUtil.createCurationDocumentContent(zip, importedProject, repository); // create project log ImportUtil.createProjectLog(zip, importedProject, repository); // create project guideline ImportUtil.createProjectGuideline(zip, importedProject, repository); // cretae project META-INF ImportUtil.createProjectMetaInf(zip, importedProject, repository); } catch (IOException e) { error("Error Importing Project " + ExceptionUtils.getRootCauseMessage(e)); } } projectDetailForm.setModelObject(importedProject); SelectionModel selectedProjectModel = new SelectionModel(); selectedProjectModel.project = importedProject; projectSelectionForm.setModelObject(selectedProjectModel); projectDetailForm.setVisible(true); RequestCycle.get().setResponsePage(getPage()); }
From source file:com.dsh105.commodus.data.Updater.java
/** * Part of Zip-File-Extractor, modified by Gravity for use with Bukkit *//*from w w w. j a v a 2s . c o m*/ private void unzip(String file) { try { final File fSourceZip = new File(file); final String zipPath = file.substring(0, file.length() - 4); ZipFile zipFile = new ZipFile(fSourceZip); Enumeration<? extends ZipEntry> e = zipFile.entries(); while (e.hasMoreElements()) { ZipEntry entry = e.nextElement(); File destinationFilePath = new File(zipPath, entry.getName()); destinationFilePath.getParentFile().mkdirs(); if (entry.isDirectory()) { continue; } else { final BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); int b; final byte buffer[] = new byte[Updater.BYTE_SIZE]; final FileOutputStream fos = new FileOutputStream(destinationFilePath); final BufferedOutputStream bos = new BufferedOutputStream(fos, Updater.BYTE_SIZE); while ((b = bis.read(buffer, 0, Updater.BYTE_SIZE)) != -1) { bos.write(buffer, 0, b); } bos.flush(); bos.close(); bis.close(); final String name = destinationFilePath.getName(); if (name.endsWith(".jar") && this.pluginFile(name)) { destinationFilePath.renameTo( new File(this.plugin.getDataFolder().getParent(), this.updateFolder + "/" + name)); } } entry = null; destinationFilePath = null; } e = null; zipFile.close(); zipFile = null; // Move any plugin data folders that were included to the right place, Bukkit won't do this for us. for (final File dFile : new File(zipPath).listFiles()) { if (dFile.isDirectory()) { if (this.pluginFile(dFile.getName())) { final File oFile = new File(this.plugin.getDataFolder().getParent(), dFile.getName()); // Get current dir final File[] contents = oFile.listFiles(); // List of existing files in the current dir for (final File cFile : dFile.listFiles()) // Loop through all the files in the new dir { boolean found = false; for (final File xFile : contents) // Loop through contents to see if it exists { if (xFile.getName().equals(cFile.getName())) { found = true; break; } } if (!found) { // Move the new file into the current dir cFile.renameTo(new File(oFile.getCanonicalFile() + "/" + cFile.getName())); } else { // This file already exists, so we don't need it anymore. cFile.delete(); } } } } dFile.delete(); } new File(zipPath).delete(); fSourceZip.delete(); } catch (final IOException ex) { this.plugin.getLogger() .warning("The auto-updater tried to unzip a new update file, but was unsuccessful."); this.result = Updater.UpdateResult.FAIL_DOWNLOAD; ex.printStackTrace(); } new File(file).delete(); }
From source file:mobac.mapsources.loader.MapPackManager.java
/** * Calculate the md5sum on all files in the map pack file (except those in META-INF) and their filenames inclusive * path in the map pack file).//from w w w . j a v a 2 s . c o m * * @param mapPackFile * @return * @throws IOException * @throws NoSuchAlgorithmException */ public String generateMappackMD5(File mapPackFile) throws IOException, NoSuchAlgorithmException { ZipFile zip = new ZipFile(mapPackFile); try { Enumeration<? extends ZipEntry> entries = zip.entries(); MessageDigest md5Total = MessageDigest.getInstance("MD5"); MessageDigest md5 = MessageDigest.getInstance("MD5"); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (entry.isDirectory()) continue; // Do not hash files from META-INF String name = entry.getName(); if (name.toUpperCase().startsWith("META-INF")) continue; md5.reset(); InputStream in = zip.getInputStream(entry); byte[] data = Utilities.getInputBytes(in); in.close(); // name = name.replaceAll("\\\\", "/"); byte[] digest = md5.digest(data); log.trace("Hashsum " + Hex.encodeHexString(digest) + " includes \"" + name + "\""); md5Total.update(digest); md5Total.update(name.getBytes()); } String md5sum = Hex.encodeHexString(md5Total.digest()); log.trace("md5sum of " + mapPackFile.getName() + ": " + md5sum); return md5sum; } finally { zip.close(); } }
From source file:org.bigbluebuttonproject.fileupload.document.ZipDocumentHandler.java
/** * This method extracts the zip file given to the destDir. It uses ZipFile API * to parse through the files in the zip file. * Only files that the zip file can have are .jpg, .png and .gif formats. * /* ww w . ja va 2 s . c om*/ * @param fileInput pointing to the zip file * @param destDir directory where extracted files should go */ public void convert(File fileInput, File destDir) { try { // Setup the ZipFile used to read entries ZipFile zf = new ZipFile(fileInput.getAbsolutePath()); // Ensure the extraction directories exist // File directoryStructure = new File(destDir); if (!destDir.exists()) { destDir.mkdirs(); } // Loop through all entries in the zip and extract as necessary ZipEntry currentEntry; for (Enumeration entries = zf.entries(); entries.hasMoreElements();) { currentEntry = (ZipEntry) entries.nextElement(); if (!currentEntry.isDirectory()) { File fileEntry = new File(currentEntry.getName()); String fileName = fileEntry.getName().toLowerCase(); // Make sure to only deal with image files if ((fileName.endsWith(".jpg")) || (fileName.endsWith(".png")) || (fileName.endsWith(".gif"))) { // extracts the corresponding file in dest Directory copyInputStream(zf.getInputStream(currentEntry), new BufferedOutputStream( new FileOutputStream(destDir + File.separator + fileEntry.getName()))); } } } } catch (Exception e) { if (log.isErrorEnabled()) { log.error("Could not load zip document for " + fileInput.getName(), e); } } }
From source file:com.pari.mw.api.execute.reports.template.ReportTemplateRunner.java
private InputStream getInputStream(ZipFile zipFile, String entryFileName) throws Exception { ZipEntry topLevelFolder = null; ZipEntry specificEntry = null; InputStream ipStream = null;/* w w w. ja v a2 s.c om*/ Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { topLevelFolder = entries.nextElement(); if (topLevelFolder.isDirectory()) { break; } } if (topLevelFolder != null) { String lookupFile = topLevelFolder + entryFileName; specificEntry = zipFile.getEntry(lookupFile); } if (specificEntry != null) { ipStream = zipFile.getInputStream(specificEntry); } return ipStream; }
From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java
@Test public void setRootfileExtendsContainerXml() throws Exception { UCFPackage container = new UCFPackage(); container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE); container.addResource("Hello there", "helloworld.txt", "text/plain"); container.addResource("<html><body><h1>Yo</h1></body></html>", "helloworld.html", "text/html"); String containerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ex='http://example.com/' xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n" + " <rootFiles>\n" + " <rootFile ex:extraAnnotation='hello' media-type=\"text/html\" full-path=\"helloworld.html\"/>\n" + " </rootFiles>\n" + " <ex:example>more example</ex:example>\n" + "</container>\n"; // Should overwrite setRootFile() container.addResource(containerXml, "META-INF/container.xml", "text/xml"); assertEquals("helloworld.html", container.getRootFiles().get(0).getPath()); container.setRootFile("helloworld.txt"); assertEquals("helloworld.html", container.getRootFiles().get(0).getPath()); assertEquals("helloworld.txt", container.getRootFiles().get(1).getPath()); container.save(tmpFile);//from w w w . ja v a 2s. com // // String expectedContainerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" // + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n" // + " <rootFiles>\n" // + " <rootFile xmlns:ex=\"http://example.com/\" media-type=\"text/html\" full-path=\"helloworld.html\" ex:extraAnnotation=\"hello\"/>\n" // + " <rootFile media-type=\"text/plain\" full-path=\"helloworld.txt\"/>\n" // + " </rootFiles>\n" // + " <ex:example xmlns:ex=\"http://example.com/\">more example</ex:example>\n" // + // "</container>\n"; ZipFile zipFile = new ZipFile(tmpFile); ZipEntry manifestEntry = zipFile.getEntry("META-INF/container.xml"); InputStream manifestStream = zipFile.getInputStream(manifestEntry); //System.out.println(IOUtils.toString(manifestStream, "UTF-8")); /* <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#"> <rootFiles> <rootFile xmlns:ex="http://example.com/" full-path="helloworld.html" media-type="text/html" ex:extraAnnotation="hello"/> <rootFile full-path="helloworld.txt" media-type="text/plain"/> </rootFiles> <ex:example xmlns:ex="http://example.com/">more example</ex:example> </container> */ Document doc = parseXml(manifestStream); assertEquals(CONTAINER_NS, doc.getRootElement().getNamespace()); // Should work, but we'll avoid testing it (TAVERNA-920) //assertEquals("", doc.getRootElement().getNamespacePrefix()); //assertEquals("container", doc.getRootElement().getQualifiedName()); assertEquals("container", doc.getRootElement().getName()); assertXpathEquals("helloworld.html", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@full-path"); assertXpathEquals("text/html", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@media-type"); assertXpathEquals("hello", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@ex:extraAnnotation"); assertXpathEquals("helloworld.txt", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[2]/@full-path"); assertXpathEquals("text/plain", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[2]/@media-type"); assertXpathEquals("more example", doc.getRootElement(), "/c:container/ex:example"); // Check order Element first = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[1]"); //assertEquals("rootFiles", first.getQualifiedName()); assertEquals("rootFiles", first.getName()); Element second = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[2]"); assertEquals("ex:example", second.getQualifiedName()); }
From source file:org.apache.taverna.scufl2.ucfpackage.TestUCFPackage.java
@Test public void addResourceContainerXml() throws Exception { UCFPackage container = new UCFPackage(); container.setPackageMediaType(UCFPackage.MIME_WORKFLOW_BUNDLE); container.addResource("Hello there", "helloworld.txt", "text/plain"); container.addResource("Soup for everyone", "soup.txt", "text/plain"); container.setRootFile("helloworld.txt"); assertEquals("helloworld.txt", container.getRootFiles().get(0).getPath()); String containerXml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" + "<container xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:ns3=\"http://www.w3.org/2001/04/xmlenc#\">\n" + " <ex:example xmlns:ex=\"http://example.com/\">first example</ex:example>\n" + " <rootFiles>\n" + " <rootFile xmlns:ex=\"http://example.com/\" media-type=\"text/plain\" full-path=\"soup.txt\" ex:extraAnnotation=\"hello\"/>\n" + " </rootFiles>\n" + " <ex:example xmlns:ex=\"http://example.com/\">second example</ex:example>\n" + " <ex:example xmlns:ex=\"http://example.com/\">third example</ex:example>\n" + "</container>\n"; // Should overwrite setRootFile() container.addResource(containerXml, "META-INF/container.xml", "text/xml"); assertEquals("soup.txt", container.getRootFiles().get(0).getPath()); container.save(tmpFile);// w w w . ja v a 2 s . c o m ZipFile zipFile = new ZipFile(tmpFile); ZipEntry manifestEntry = zipFile.getEntry("META-INF/container.xml"); InputStream manifestStream = zipFile.getInputStream(manifestEntry); //System.out.println(IOUtils.toString(manifestStream, "UTF-8")); /* <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <container xmlns="urn:oasis:names:tc:opendocument:xmlns:container" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#" xmlns:ns3="http://www.w3.org/2001/04/xmlenc#"> <ex:example xmlns:ex="http://example.com/">first example</ex:example> <rootFiles> <rootFile xmlns:ex="http://example.com/" full-path="soup.txt" media-type="text/plain" ex:extraAnnotation="hello"/> </rootFiles> <ex:example xmlns:ex="http://example.com/">second example</ex:example> <ex:example xmlns:ex="http://example.com/">third example</ex:example> </container> */ Document doc = parseXml(manifestStream); assertEquals(CONTAINER_NS, doc.getRootElement().getNamespace()); // Should work, but we'll ignore testing these (TAVERNA-920) //assertEquals("", doc.getRootElement().getNamespacePrefix()); //assertEquals("container", doc.getRootElement().getQualifiedName()); assertEquals("container", doc.getRootElement().getName()); assertXpathEquals("soup.txt", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@full-path"); assertXpathEquals("text/plain", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@media-type"); assertXpathEquals("hello", doc.getRootElement(), "/c:container/c:rootFiles/c:rootFile[1]/@ex:extraAnnotation"); assertXpathEquals("first example", doc.getRootElement(), "/c:container/ex:example[1]"); assertXpathEquals("second example", doc.getRootElement(), "/c:container/ex:example[2]"); assertXpathEquals("third example", doc.getRootElement(), "/c:container/ex:example[3]"); // Check order Element first = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[1]"); assertEquals("ex:example", first.getQualifiedName()); Element second = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[2]"); // Should work, but we'll ignore testing these (TAVERNA-920) //assertEquals("rootFiles", second.getQualifiedName()); assertEquals("rootFiles", second.getName()); Element third = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[3]"); assertEquals("ex:example", third.getQualifiedName()); Element fourth = (Element) xpathSelectElement(doc.getRootElement(), "/c:container/*[4]"); assertEquals("ex:example", fourth.getQualifiedName()); }
From source file:edu.stanford.epad.common.util.EPADFileUtils.java
/** * Unzip the specified file.// w ww .j a v a 2 s .c om * * @param zipFilePath String path to zip file. * @throws IOException during zip or read process. */ public static void extractFolder(String zipFilePath) throws IOException { ZipFile zipFile = null; try { int BUFFER = 2048; File file = new File(zipFilePath); zipFile = new ZipFile(file); String newPath = zipFilePath.substring(0, zipFilePath.length() - 4); makeDirs(new File(newPath)); Enumeration<?> zipFileEntries = zipFile.entries(); while (zipFileEntries.hasMoreElements()) { ZipEntry entry = (ZipEntry) zipFileEntries.nextElement(); String currentEntry = entry.getName(); File destFile = new File(newPath, currentEntry); File destinationParent = destFile.getParentFile(); // create the parent directory structure if needed makeDirs(destinationParent); InputStream is = null; BufferedInputStream bis = null; FileOutputStream fos = null; BufferedOutputStream bos = null; try { if (destFile.exists() && destFile.isDirectory()) continue; if (!entry.isDirectory()) { int currentByte; byte data[] = new byte[BUFFER]; is = zipFile.getInputStream(entry); bis = new BufferedInputStream(is); fos = new FileOutputStream(destFile); bos = new BufferedOutputStream(fos, BUFFER); while ((currentByte = bis.read(data, 0, BUFFER)) != -1) { bos.write(data, 0, currentByte); } bos.flush(); } } finally { IOUtils.closeQuietly(bis); IOUtils.closeQuietly(is); IOUtils.closeQuietly(bos); IOUtils.closeQuietly(fos); } if (currentEntry.endsWith(".zip")) { extractFolder(destFile.getAbsolutePath()); } } } catch (Exception e) { log.warning("Failed to unzip: " + zipFilePath, e); throw new IllegalStateException(e); } finally { if (zipFile != null) zipFile.close(); } }