List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(String name) throws IOException
From source file:com.liferay.blade.cli.command.InstallExtensionCommandTest.java
private static void _testJarsDiff(File warFile1, File warFile2) throws IOException { DifferenceCalculator differenceCalculator = new DifferenceCalculator(warFile1, warFile2); differenceCalculator.setFilenameRegexToIgnore(Collections.singleton(".*META-INF.*")); differenceCalculator.setIgnoreTimestamps(true); Differences differences = differenceCalculator.getDifferences(); if (!differences.hasDifferences()) { return;//from w ww .j a v a 2s .c o m } StringBuilder message = new StringBuilder(); message.append("WAR "); message.append(warFile1); message.append(" and "); message.append(warFile2); message.append(" do not match:"); message.append(System.lineSeparator()); boolean realChange; Map<String, ZipArchiveEntry> added = differences.getAdded(); Map<String, ZipArchiveEntry[]> changed = differences.getChanged(); Map<String, ZipArchiveEntry> removed = differences.getRemoved(); if (added.isEmpty() && !changed.isEmpty() && removed.isEmpty()) { realChange = false; ZipFile zipFile1 = null; ZipFile zipFile2 = null; try { zipFile1 = new ZipFile(warFile1); zipFile2 = new ZipFile(warFile2); for (Map.Entry<String, ZipArchiveEntry[]> entry : changed.entrySet()) { ZipArchiveEntry[] zipArchiveEntries = entry.getValue(); ZipArchiveEntry zipArchiveEntry1 = zipArchiveEntries[0]; ZipArchiveEntry zipArchiveEntry2 = zipArchiveEntries[0]; if (zipArchiveEntry1.isDirectory() && zipArchiveEntry2.isDirectory() && (zipArchiveEntry1.getSize() == zipArchiveEntry2.getSize()) && (zipArchiveEntry1.getCompressedSize() <= 2) && (zipArchiveEntry2.getCompressedSize() <= 2)) { // Skip zipdiff bug continue; } try (InputStream inputStream1 = zipFile1 .getInputStream(zipFile1.getEntry(zipArchiveEntry1.getName())); InputStream inputStream2 = zipFile2 .getInputStream(zipFile2.getEntry(zipArchiveEntry2.getName()))) { List<String> lines1 = StringTestUtil.readLines(inputStream1); List<String> lines2 = StringTestUtil.readLines(inputStream2); message.append(System.lineSeparator()); message.append("--- "); message.append(zipArchiveEntry1.getName()); message.append(System.lineSeparator()); message.append("+++ "); message.append(zipArchiveEntry2.getName()); message.append(System.lineSeparator()); Patch<String> diff = DiffUtils.diff(lines1, lines2); for (Delta<String> delta : diff.getDeltas()) { message.append('\t'); message.append(delta.getOriginal()); message.append(System.lineSeparator()); message.append('\t'); message.append(delta.getRevised()); message.append(System.lineSeparator()); } } realChange = true; break; } } finally { ZipFile.closeQuietly(zipFile1); ZipFile.closeQuietly(zipFile2); } } else { realChange = true; } Assert.assertFalse(message.toString(), realChange); }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void shouldCopyFromGenruleOutput() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();//from w w w . j av a 2 s . c om Path zip = workspace.buildAndReturnOutput("//example:copy_zip"); try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipInspector inspector = new ZipInspector(zip); inspector.assertFileExists("copy_out/cake.txt"); } }
From source file:io.webfolder.cdp.ChromiumDownloader.java
private static void unpack(File archive, File destionation) throws IOException { try (ZipFile zip = new ZipFile(archive)) { Map<File, String> symLinks = new LinkedHashMap<>(); Enumeration<ZipArchiveEntry> iterator = zip.getEntries(); // Top directory name we are going to ignore String parentDirectory = iterator.nextElement().getName(); // Iterate files & folders while (iterator.hasMoreElements()) { ZipArchiveEntry entry = iterator.nextElement(); String name = entry.getName().substring(parentDirectory.length()); File outputFile = new File(destionation, name); if (name.startsWith("interactive_ui_tests")) { continue; }//from w w w . j a v a 2s. co m if (entry.isUnixSymlink()) { symLinks.put(outputFile, zip.getUnixSymlink(entry)); } else if (!entry.isDirectory()) { if (!outputFile.getParentFile().isDirectory()) { outputFile.getParentFile().mkdirs(); } try (FileOutputStream outStream = new FileOutputStream(outputFile)) { IOUtils.copy(zip.getInputStream(entry), outStream); } } // Set permission if (!entry.isUnixSymlink() && outputFile.exists()) try { Files.setPosixFilePermissions(outputFile.toPath(), modeToPosixPermissions(entry.getUnixMode())); } catch (Exception e) { // ignore } } for (Map.Entry<File, String> entry : symLinks.entrySet()) { try { Path source = Paths.get(entry.getKey().getAbsolutePath()); Path target = source.getParent().resolve(entry.getValue()); if (!source.toFile().exists()) Files.createSymbolicLink(source, target); } catch (Exception e) { // ignore } } } }
From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java
@Test public void testZipDirectoriesNotRecursive() throws Exception { FileUtils.forceMkdir(new File("target/Z-testfiles/source/subdir")); FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/CP0-input.csv")); FileUtils.copyFile(new File("src/test/resources/testFiles/input.csv"), new File("target/Z-testfiles/source/subdir/CP1-input.csv")); String aTargetFilename = "target/Z4-input.zip"; ZipFilesTasklet aTasklet = new ZipFilesTasklet(); aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/")); FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory(); aSourceFactory.setPattern("file:target/Z-testfiles/source/"); aTasklet.setSourceFactory(aSourceFactory); ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory(); aDestinationFactory.setExpression(aTargetFilename); aTasklet.setDestinationFactory(aDestinationFactory); aTasklet.setRecursive(false);/*w w w .j a v a 2s. com*/ assertFalse(new File(aTargetFilename).exists()); StepContribution aStepContribution = mock(StepContribution.class); assertEquals(RepeatStatus.FINISHED, aTasklet.execute(aStepContribution, null)); verify(aStepContribution, times(2)).incrementReadCount(); verify(aStepContribution, times(2)).incrementWriteCount(1); assertTrue(new File(aTargetFilename).exists()); ZipFile aZipFile = new ZipFile(new File(aTargetFilename)); Enumeration<ZipArchiveEntry> aEntries = aZipFile.getEntries(); assertTrue(aEntries.hasMoreElements()); assertEquals("source", aEntries.nextElement().getName()); assertTrue(aEntries.hasMoreElements()); assertEquals("source/CP0-input.csv", aEntries.nextElement().getName()); assertFalse(aEntries.hasMoreElements()); aZipFile.close(); }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void shouldOverwriteDuplicates() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();/* w ww .j av a2 s . com*/ Path zip = workspace.buildAndReturnOutput("//example:overwrite_duplicates"); try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipInspector inspector = new ZipInspector(zip); inspector.assertFileContents(Paths.get("cake.txt"), "Cake :)"); } }
From source file:autoupdater.DownloadLatestZipFromRepo.java
/** * Aggregation method for downloading and unzipping. * * @param mavenJarFile the maven jar file to download update for * @return the downloaded {@code MavenJarFile} * @throws MalformedURLException//from w ww .j a v a 2 s . c o m * @throws IOException * @throws XMLStreamException */ private static MavenJarFile downloadAndUnzipJar(MavenJarFile mavenJarFile) throws MalformedURLException, IOException, XMLStreamException { boolean isWindows = false; if (System.getProperty("os.name").toLowerCase(new Locale("en")).contains("win")) { isWindows = true; } URL archiveURL; String folderName; // get the archive url if (isWindows) { archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".zip", false); folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"), archiveURL.getFile().lastIndexOf(".zip")); } else { archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".tar.gz", false); if (archiveURL != null) { folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"), archiveURL.getFile().lastIndexOf(".tar.gz")); } else { archiveURL = WebDAO.getUrlOfZippedVersion(downloadURL, ".zip", false); folderName = archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"), archiveURL.getFile().lastIndexOf(".zip")); isWindows = true; // zip file, handling is same as for windows } } // special fix for tools with separate versions for windows and unix if (folderName.endsWith("-windows")) { folderName = folderName.substring(0, folderName.indexOf("-windows")); } else if (folderName.endsWith("-mac_and_linux")) { folderName = folderName.substring(0, folderName.indexOf("-mac_and_linux")); } // set up the folder to save the new download in File downloadFolder; if (isWindows) { downloadFolder = new File( fileDAO.getLocationToDownloadOnDisk(new File(mavenJarFile.getAbsoluteFilePath()).getParent()), folderName); } else { downloadFolder = fileDAO .getLocationToDownloadOnDisk(new File(mavenJarFile.getAbsoluteFilePath()).getParent()); } if (!downloadFolder.exists()) { if (!downloadFolder.mkdirs()) { throw new IOException("could not make the directories needed to download the file in"); } } // create an empty dummy file so that progress can be monitored downloadedFile = new File(downloadFolder, archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/"))); // download and unzip the file if (isWindows) { downloadedFile = fileDAO.writeStreamToDisk(archiveURL.openStream(), archiveURL.getFile().substring(archiveURL.getFile().lastIndexOf("/")), downloadFolder); fileDAO.unzipFile(new ZipFile(downloadedFile), downloadFolder.getParentFile()); } else { fileDAO.unGzipAndUntarFile(new GZIPInputStream(archiveURL.openStream()), downloadedFile); } // get the new jar file MavenJarFile newMavenJar; if (isWindows) { newMavenJar = fileDAO.getMavenJarFileFromFolderWithArtifactId(downloadFolder, mavenJarFile.getArtifactId()); } else { newMavenJar = fileDAO.getMavenJarFileFromFolderWithArtifactId(new File(downloadFolder, folderName), mavenJarFile.getArtifactId()); } // delete the downloaded zip file if (deletePreviousVersion) { if (!downloadedFile.delete()) { throw new IOException("could not delete the zip file"); } } return newMavenJar; }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void testOrderInZipSrcsAffectsResults() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();/*from w ww . ja v a 2 s . c om*/ Path zip = workspace.buildAndReturnOutput("//example:overwrite_duplicates_in_different_order"); try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipInspector inspector = new ZipInspector(zip); inspector.assertFileContents(Paths.get("cake.txt"), "Guten Tag"); } }
From source file:com.facebook.buck.util.unarchive.Unzip.java
/** Unzips a file to a destination and returns the paths of the written files. */ @Override/*from w w w . j a v a 2s . co m*/ public ImmutableSet<Path> extractArchive(Path archiveFile, ProjectFilesystem filesystem, Path relativePath, Optional<Path> stripPrefix, PatternsMatcher entriesToExclude, ExistingFileMode existingFileMode) throws IOException { // We want to remove stale contents of directories listed in {@code archiveFile}, but avoid // deleting and // re-creating any directories that already exist. We *also* want to avoid a full recursive // scan of listed directories, since that's almost as slow as deleting. So we preprocess the // contents of {@code archiveFile} and then scan the existing filesystem to remove stale // artifacts. ImmutableSet.Builder<Path> filesWritten = ImmutableSet.builder(); try (ZipFile zip = new ZipFile(archiveFile.toFile())) { SortedMap<Path, ZipArchiveEntry> pathMap; if (stripPrefix.isPresent()) { pathMap = getZipFilePathsStrippingPrefix(zip, relativePath, stripPrefix.get(), entriesToExclude); } else { pathMap = getZipFilePaths(zip, relativePath, entriesToExclude); } // A zip file isn't required to list intermediate paths (e.g., it can contain "foo/" and // "foo/bar/baz"), but we need to know not to delete those intermediates, so fill them in. for (SortedMap.Entry<Path, ZipArchiveEntry> p : new ArrayList<>(pathMap.entrySet())) { if (!isTopLevel(p.getKey(), pathMap)) { fillIntermediatePaths(p.getKey(), pathMap); } } DirectoryCreator creator = new DirectoryCreator(filesystem); for (SortedMap.Entry<Path, ZipArchiveEntry> p : pathMap.entrySet()) { Path target = p.getKey(); ZipArchiveEntry entry = p.getValue(); if (entry.isDirectory()) { extractDirectory(existingFileMode, pathMap, creator, target); } else { extractFile(filesWritten, zip, creator, target, entry); } } } return filesWritten.build(); }
From source file:com.google.dart.tools.update.core.internal.UpdateUtils.java
/** * Unzip a zip file, notifying the given monitor along the way. *///from w ww .ja va2 s . c om public static void unzip(File zipFile, File destination, String taskName, IProgressMonitor monitor) throws IOException { ZipFile zip = new ZipFile(zipFile); //TODO (pquitslund): add real progress units if (monitor != null) { monitor.beginTask(taskName, 1); } Enumeration<ZipArchiveEntry> e = zip.getEntries(); while (e.hasMoreElements()) { ZipArchiveEntry entry = e.nextElement(); File file = new File(destination, entry.getName()); if (entry.isDirectory()) { file.mkdirs(); } else { InputStream is = zip.getInputStream(entry); File parent = file.getParentFile(); if (parent != null && parent.exists() == false) { parent.mkdirs(); } FileOutputStream os = new FileOutputStream(file); try { IOUtils.copy(is, os); } finally { os.close(); is.close(); } file.setLastModified(entry.getTime()); int mode = entry.getUnixMode(); if ((mode & EXEC_MASK) != 0) { file.setExecutable(true); } } } //TODO (pquitslund): fix progress units if (monitor != null) { monitor.worked(1); monitor.done(); } }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Run jar patcher./*from w w w .j av a 2s . c om*/ * * @param originalName the original name * @param targetName the target name * @param originalZip the original zip * @param newZip the new zip * @param comparefiles the comparefiles * @throws Exception the exception */ private void runJarPatcher(String originalName, String targetName, ZipFile originalZip, ZipFile newZip, boolean comparefiles) throws Exception { try (ZipArchiveOutputStream output = new ZipArchiveOutputStream(new FileOutputStream(patchFile))) { new JarDelta().computeDelta(originalName, targetName, originalZip, newZip, output); } ZipFile patch = new ZipFile(patchFile); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { patch.close(); throw new IOException("Invalid patch - list entry 'META-INF/file.list' not found"); } BufferedReader patchlist = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = patchlist.readLine(); String sourceName = next; next = patchlist.readLine(); new JarPatcher(patchFile.getName(), sourceName).applyDelta(patch, new ZipFile(originalName), new ZipArchiveOutputStream(new FileOutputStream(resultFile)), patchlist); if (comparefiles) { compareFiles(new ZipFile(targetName), new ZipFile(resultFile)); } }