List of usage examples for org.apache.commons.compress.archivers.zip ZipFile ZipFile
public ZipFile(String name) throws IOException
From source file:fr.acxio.tools.agia.tasks.ZipFilesTaskletTest.java
@Test public void testZipTwoFile() throws Exception { FileUtils.forceMkdir(new File("target/Z-testfiles/source")); 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/CP1-input.csv")); String aTargetFilename = "target/Z1-input.zip"; ZipFilesTasklet aTasklet = new ZipFilesTasklet(); aTasklet.setSourceBaseDirectory(new FileSystemResource("target/Z-testfiles/source/")); FileSystemResourcesFactory aSourceFactory = new FileSystemResourcesFactory(); aSourceFactory.setPattern("file:target/Z-testfiles/source/*input*.csv"); aTasklet.setSourceFactory(aSourceFactory); ExpressionResourceFactory aDestinationFactory = new ExpressionResourceFactory(); aDestinationFactory.setExpression(aTargetFilename); aTasklet.setDestinationFactory(aDestinationFactory); 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("CP0-input.csv", aEntries.nextElement().getName()); assertTrue(aEntries.hasMoreElements()); assertEquals("CP1-input.csv", aEntries.nextElement().getName()); assertFalse(aEntries.hasMoreElements()); aZipFile.close();// w w w .j a va2s. c om }
From source file:at.spardat.xma.xdelta.test.JarDeltaJarPatcherTest.java
/** * Creates a zip file with random content. * * @author S3460/* ww w. j a v a 2 s.c o m*/ * @param source the source * @return the zip file * @throws Exception the exception */ private ZipFile makeSourceZipFile(File source) throws Exception { ZipArchiveOutputStream out = new ZipArchiveOutputStream(new FileOutputStream(source)); int size = randomSize(entryMaxSize); for (int i = 0; i < size; i++) { out.putArchiveEntry(new ZipArchiveEntry("zipentry" + i)); int anz = randomSize(10); for (int j = 0; j < anz; j++) { byte[] bytes = getRandomBytes(); out.write(bytes, 0, bytes.length); } out.flush(); out.closeArchiveEntry(); } //add leeres Entry out.putArchiveEntry(new ZipArchiveEntry("zipentry" + size)); out.flush(); out.closeArchiveEntry(); out.flush(); out.finish(); out.close(); return new ZipFile(source); }
From source file:com.android.tradefed.targetprep.CdmaDeviceFlasher.java
/** * Extract the updater zip to a directory and return the path of that directory * <p />//from w w w . ja v a2s. co m * Exposed for unit testing */ protected File extractSystemZip(IDeviceBuildInfo deviceBuild) throws IOException { File updateDir = FileUtil.createTempDir(LOG_TAG); ZipFile updater = new ZipFile(deviceBuild.getDeviceImageFile().getAbsolutePath()); ZipUtil2.extractZip(updater, updateDir); return updateDir; }
From source file:com.android.tradefed.targetprep.InstallAllTestZipAppsSetup.java
/** * Extract the given zip file to a local dir. * * <p>Exposed so unit tests can mock * * @param testsZip//from ww w. java 2s. c om * @return the {@link File} referencing the zip output. * @throws IOException */ File extractZip(File testsZip) throws IOException { File testsDir = null; try (ZipFile zip = new ZipFile(testsZip)) { testsDir = FileUtil.createTempDir("tests-zip_"); ZipUtil2.extractZip(zip, testsDir); } catch (IOException e) { FileUtil.recursiveDelete(testsDir); throw e; } return testsDir; }
From source file:edu.unc.lib.deposit.normalize.Proquest2N3BagJob.java
private void normalizePackage(File packageDir, Model model, Bag depositBag) { // Generate a uuid for the main object PID primaryPID = new PID("uuid:" + UUID.randomUUID()); Resource primaryResource;/*from www. java2 s. co m*/ // Identify the important files from the deposit File dataFile = null, contentFile = null, attachmentDir = null; File[] files = packageDir.listFiles(); for (File file : files) { if (file.isDirectory()) { attachmentDir = file; } else if (file.getName().endsWith(DATA_SUFFIX)) { dataFile = file; } else { contentFile = file; } } long lastModified = -1; File zipFile = new File(packageDir.getAbsolutePath() + ".zip"); try (ZipFile zip = new ZipFile(zipFile)) { ZipArchiveEntry entry = zip.getEntry(contentFile.getName()); lastModified = entry.getTime(); } catch (IOException e) { log.error("Failed to read zip file located at {}.zip", packageDir.getAbsolutePath(), e); } if (lastModified == -1) { lastModified = zipFile.lastModified(); } DateTime modified = new DateTime(lastModified, DateTimeZone.UTC); // Deserialize the data document SAXBuilder builder = new SAXBuilder(); Element dataRoot = null; Document mods = null; try { Document dataDocument = builder.build(dataFile); dataRoot = dataDocument.getRootElement(); // Transform the data into MODS and store it to its final resting place mods = extractMods(primaryPID, dataRoot, modified); } catch (TransformerException e) { failJob(e, Type.NORMALIZATION, "Failed to transform metadata to MODS"); } catch (Exception e) { failJob(e, Type.NORMALIZATION, "Unable to deserialize the metadata file"); } // Detect if there are any attachments List<?> attachmentElements = dataRoot.getChild("DISS_content").getChildren("DISS_attachment"); if (attachmentElements == null || attachmentElements.size() == 0) { // Simple object with the content as its source data primaryResource = populateSimple(model, primaryPID, contentFile); } else { String title = mods.getRootElement().getChild("titleInfo", MODS_V3_NS).getChildText("title", MODS_V3_NS); // Has attachments, so it is an aggregate primaryResource = populateAggregate(model, primaryPID, attachmentElements, attachmentDir, contentFile, title); } // Store primary resource as child of the deposit depositBag.add(primaryResource); // Add the data file as a metadata datastream of the primary object setSourceMetadata(model, primaryResource, dataFile); // Capture other metadata, like embargoes setEmbargoUntil(model, primaryResource, dataRoot); // Creation date for the content file model.add(primaryResource, cdrprop(model, dateCreated), modified.toString(), XSDDatatype.XSDdateTime); }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void shouldExcludeEverything() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();/*from ww w .j a v a 2 s .c o m*/ Path zip = workspace.buildAndReturnOutput("//example:excludeall"); try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipArchiveEntry cake = zipFile.getEntry("cake.txt"); assertThat(cake, Matchers.nullValue()); ZipArchiveEntry taco = zipFile.getEntry("menu.txt"); assertThat(taco, Matchers.nullValue()); } }
From source file:autoupdater.FileDAO.java
public File inflateArchive(File source, File destination) throws IOException, ArchiveException { ArchiveInputStream stream = new ArchiveStreamFactory() .createArchiveInputStream(new BufferedInputStream(new FileInputStream(source))); ZipFile zipfile = new ZipFile(source); ArchiveEntry entry = null;// w ww .ja va 2 s . c o m FileOutputStream dest = null; InputStream inStream = null; if ((entry = stream.getNextEntry()) != null) { do { File destFile = new File(destination, entry.getName()); if (!destFile.getParentFile().exists()) { if (!destFile.getParentFile().mkdirs()) { throw new IOException("could not create the folders to unzip in"); } } if (!entry.isDirectory()) { try { dest = new FileOutputStream(destFile); inStream = stream; IOUtils.copyLarge(inStream, dest); } finally { if (dest != null) { dest.close(); } if (inStream != null) { inStream.close(); } } } else { if (!destFile.exists()) { if (!destFile.mkdirs()) { throw new IOException("could not create folders to unzip file"); } } } } while ((entry = stream.getNextEntry()) != null); } return destination; }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Apply delta.//from ww w . j a va 2s .c o m * * @param patch the patch * @param source the source * @param output the output * @param list the list * @param prefix the prefix * @throws IOException Signals that an I/O exception has occurred. */ public void applyDelta(ZipFile patch, ZipFile source, ZipArchiveOutputStream output, BufferedReader list, String prefix) throws IOException { String fileName = null; try { for (fileName = (next == null ? list.readLine() : next); fileName != null; fileName = (next == null ? list.readLine() : next)) { if (next != null) next = null; if (!fileName.startsWith(prefix)) { next = fileName; return; } int crcDelim = fileName.lastIndexOf(':'); int crcStart = fileName.lastIndexOf('|'); long crc = Long.valueOf(fileName.substring(crcStart + 1, crcDelim), 16); long crcSrc = Long.valueOf(fileName.substring(crcDelim + 1), 16); fileName = fileName.substring(prefix.length(), crcStart); if ("META-INF/file.list".equalsIgnoreCase(fileName)) continue; if (fileName.contains("!")) { String[] embeds = fileName.split("\\!"); ZipArchiveEntry original = getEntry(source, embeds[0], crcSrc); File originalFile = File.createTempFile("jardelta-tmp-origin-", ".zip"); File outputFile = File.createTempFile("jardelta-tmp-output-", ".zip"); Exception thrown = null; try (FileOutputStream out = new FileOutputStream(originalFile); InputStream in = source.getInputStream(original)) { int read = 0; while (-1 < (read = in.read(buffer))) { out.write(buffer, 0, read); } out.flush(); applyDelta(patch, new ZipFile(originalFile), new ZipArchiveOutputStream(outputFile), list, prefix + embeds[0] + "!"); } catch (Exception e) { thrown = e; throw e; } finally { originalFile.delete(); try (FileInputStream in = new FileInputStream(outputFile)) { if (thrown == null) { ZipArchiveEntry outEntry = copyEntry(original); output.putArchiveEntry(outEntry); int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } output.flush(); output.closeArchiveEntry(); } } finally { outputFile.delete(); } } } else { try { ZipArchiveEntry patchEntry = getEntry(patch, prefix + fileName, crc); if (patchEntry != null) { // new Entry ZipArchiveEntry outputEntry = JarDelta.entryToNewName(patchEntry, fileName); output.putArchiveEntry(outputEntry); if (!patchEntry.isDirectory()) { try (InputStream in = patch.getInputStream(patchEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } } closeEntry(output, outputEntry, crc); } else { ZipArchiveEntry sourceEntry = getEntry(source, fileName, crcSrc); if (sourceEntry == null) { throw new FileNotFoundException( fileName + " not found in " + sourceName + " or " + patchName); } if (sourceEntry.isDirectory()) { ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); closeEntry(output, outputEntry, crc); continue; } patchEntry = getPatchEntry(patch, prefix + fileName + ".gdiff", crc); if (patchEntry != null) { // changed Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); outputEntry.setTime(patchEntry.getTime()); output.putArchiveEntry(outputEntry); byte[] sourceBytes = new byte[(int) sourceEntry.getSize()]; try (InputStream sourceStream = source.getInputStream(sourceEntry)) { for (int erg = sourceStream .read(sourceBytes); erg < sourceBytes.length; erg += sourceStream .read(sourceBytes, erg, sourceBytes.length - erg)) ; } InputStream patchStream = patch.getInputStream(patchEntry); GDiffPatcher diffPatcher = new GDiffPatcher(); diffPatcher.patch(sourceBytes, patchStream, output); patchStream.close(); outputEntry.setCrc(crc); closeEntry(output, outputEntry, crc); } else { // unchanged Entry ZipArchiveEntry outputEntry = new ZipArchiveEntry(sourceEntry); output.putArchiveEntry(outputEntry); try (InputStream in = source.getInputStream(sourceEntry)) { int read = 0; while (-1 < (read = in.read(buffer))) { output.write(buffer, 0, read); } } output.flush(); closeEntry(output, outputEntry, crc); } } } catch (PatchException pe) { IOException ioe = new IOException(); ioe.initCause(pe); throw ioe; } } } } catch (Exception e) { System.err.println(prefix + fileName); throw e; } finally { source.close(); output.close(); } }
From source file:com.facebook.buck.features.zip.rules.ZipRuleIntegrationTest.java
@Test public void shouldExcludeNothing() throws IOException { ProjectWorkspace workspace = TestDataHelper.createProjectWorkspaceForScenario(this, "zip-rule", tmp); workspace.setUp();//from w w w.j a v a 2s . c om Path zip = workspace.buildAndReturnOutput("//example:excludenothing"); try (ZipFile zipFile = new ZipFile(zip.toFile())) { ZipArchiveEntry cake = zipFile.getEntry("cake.txt"); assertThat(cake, Matchers.notNullValue()); ZipArchiveEntry taco = zipFile.getEntry("menu.txt"); assertThat(taco, Matchers.notNullValue()); } }
From source file:com.android.tradefed.result.CodeCoverageReporter.java
private void fetchAppropriateMetaDataFile() { File coverageZipFile = mBuildInfo.getFile(mCoverageMetaZipFileName); Assert.assertNotNull("Failed to get the coverage metadata zipfile from the build.", coverageZipFile); CLog.d("Coverage zip file: %s", coverageZipFile.getAbsolutePath()); try {/*from ww w .j a v a 2 s . c om*/ mLocalTmpDir = FileUtil.createTempDir("emma-meta"); ZipFile zipFile = new ZipFile(coverageZipFile); ZipUtil2.extractZip(zipFile, mLocalTmpDir); File coverageMetaFile; if (mCoverageMetaFilePath == null) { coverageMetaFile = FileUtil.findFile(mLocalTmpDir, "coverage.em"); } else { coverageMetaFile = new File(mLocalTmpDir, mCoverageMetaFilePath); } if (coverageMetaFile.exists()) { mCoverageMetaFile = coverageMetaFile; CLog.d("Coverage meta data file %s", mCoverageMetaFile.getAbsolutePath()); } } catch (IOException e) { CLog.e(e); } }