List of usage examples for org.apache.commons.compress.archivers.zip ZipFile closeQuietly
public static void closeQuietly(ZipFile zipfile)
From source file:com.android.tradefed.util.ZipUtil2Test.java
@Test public void testExtractFileFromZip() throws Exception { final File zip = getTestDataFile("permission-test"); final String fileName = "rwxr-x--x"; ZipFile zipFile = null;//from w w w . j a va 2 s .c om try { zipFile = new ZipFile(zip); File extracted = ZipUtil2.extractFileFromZip(zipFile, fileName); mTempFiles.add(extracted); verifyFilePermission(extracted, fileName); } finally { ZipFile.closeQuietly(zipFile); } }
From source file:com.android.tradefed.util.ZipUtil2Test.java
@Test public void testExtractZip() throws Exception { final File zip = getTestDataFile("permission-test"); final File destDir = createTempDir("ZipUtil2Test"); ZipFile zipFile = null;// ww w .j a v a 2s . c om try { zipFile = new ZipFile(zip); ZipUtil2.extractZip(zipFile, destDir); // now loop over files to verify for (File file : destDir.listFiles()) { // the pmierssion-test.zip file has no hierarchy inside verifyFilePermission(file); } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:com.android.repository.util.InstallerUtil.java
/** * Unzips the given zipped input stream into the given directory. * * @param in The (zipped) input stream. * @param out The directory into which to expand the files. Must exist. * @param fop The {@link FileOp} to use for file operations. * @param expectedSize Compressed size of the stream. * @param progress Currently only used for logging. * @throws IOException If we're unable to read or write. *//*from w w w .j a v a2 s .co m*/ public static void unzip(@NonNull File in, @NonNull File out, @NonNull FileOp fop, long expectedSize, @NonNull ProgressIndicator progress) throws IOException { if (!fop.exists(out) || !fop.isDirectory(out)) { throw new IllegalArgumentException("out must exist and be a directory."); } // ZipFile requires an actual (not mock) file, so make sure we have a real one. in = fop.ensureRealFile(in); progress.setText("Unzipping..."); ZipFile zipFile = new ZipFile(in); try { Enumeration entries = zipFile.getEntries(); progress.setFraction(0); while (entries.hasMoreElements()) { ZipArchiveEntry entry = (ZipArchiveEntry) entries.nextElement(); String name = entry.getName(); File entryFile = new File(out, name); progress.setSecondaryText(name); if (entry.isUnixSymlink()) { ByteArrayOutputStream targetByteStream = new ByteArrayOutputStream(); readZipEntry(zipFile, entry, targetByteStream, expectedSize, progress); Path linkPath = fop.toPath(entryFile); Path linkTarget = fop.toPath(new File(targetByteStream.toString())); Files.createSymbolicLink(linkPath, linkTarget); } else if (entry.isDirectory()) { if (!fop.exists(entryFile)) { if (!fop.mkdirs(entryFile)) { progress.logWarning("failed to mkdirs " + entryFile); } } } else { if (!fop.exists(entryFile)) { File parent = entryFile.getParentFile(); if (parent != null && !fop.exists(parent)) { fop.mkdirs(parent); } if (!fop.createNewFile(entryFile)) { throw new IOException("Failed to create file " + entryFile); } } OutputStream unzippedOutput = fop.newFileOutputStream(entryFile); if (readZipEntry(zipFile, entry, unzippedOutput, expectedSize, progress)) { return; } if (!fop.isWindows()) { // get the mode and test if it contains the executable bit int mode = entry.getUnixMode(); //noinspection OctalInteger if ((mode & 0111) != 0) { try { fop.setExecutablePermission(entryFile); } catch (IOException ignore) { } } } } } } finally { ZipFile.closeQuietly(zipFile); } }
From source file:com.mirth.connect.util.ArchiveUtils.java
/** * Extracts folders/files from a zip archive using zip-optimized code from commons-compress. *//* www . jav a 2s. c o m*/ private static void extractZipArchive(File archiveFile, File destinationFolder) throws CompressException { ZipFile zipFile = null; try { zipFile = new ZipFile(archiveFile); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry entry = null; byte[] buffer = new byte[BUFFER_SIZE]; for (; entries.hasMoreElements(); entry = entries.nextElement()) { File outputFile = new File( destinationFolder.getAbsolutePath() + IOUtils.DIR_SEPARATOR + entry.getName()); if (entry.isDirectory()) { FileUtils.forceMkdir(outputFile); } else { InputStream inputStream = zipFile.getInputStream(entry); OutputStream outputStream = FileUtils.openOutputStream(outputFile); try { IOUtils.copyLarge(inputStream, outputStream, buffer); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(outputStream); } } } } catch (Exception e) { throw new CompressException(e); } finally { ZipFile.closeQuietly(zipFile); } }
From source file:de.catma.ui.repository.wizard.FileTypePanel.java
private ArrayList<SourceDocumentResult> makeSourceDocumentResultsFromInputFile(TechInfoSet inputTechInfoSet) throws MalformedURLException, IOException { ArrayList<SourceDocumentResult> output = new ArrayList<SourceDocumentResult>(); FileType inputFileType = FileType.getFileType(inputTechInfoSet.getMimeType()); if (inputFileType != FileType.ZIP) { SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult(); String sourceDocumentID = repository.getIdFromURI(inputTechInfoSet.getURI()); outputSourceDocumentResult.setSourceDocumentID(sourceDocumentID); SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult.getSourceDocumentInfo(); outputSourceDocumentInfo.setTechInfoSet(new TechInfoSet(inputTechInfoSet)); outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet()); outputSourceDocumentInfo.getTechInfoSet().setFileType(inputFileType); output.add(outputSourceDocumentResult); } else { //TODO: put this somewhere sensible URI uri = inputTechInfoSet.getURI(); ZipFile zipFile = new ZipFile(uri.getPath()); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); String tempDir = ((CatmaApplication) UI.getCurrent()).getTempDirectory(); IDGenerator idGenerator = new IDGenerator(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); String fileName = FilenameUtils.getName(entry.getName()); String fileId = idGenerator.generate(); File entryDestination = new File(tempDir, fileId); if (entryDestination.exists()) { entryDestination.delete(); }/*from ww w . j a va2 s .com*/ entryDestination.getParentFile().mkdirs(); if (entry.isDirectory()) { entryDestination.mkdirs(); } else { BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(entryDestination)); IOUtils.copy(bis, bos); IOUtils.closeQuietly(bis); IOUtils.closeQuietly(bos); SourceDocumentResult outputSourceDocumentResult = new SourceDocumentResult(); URI newURI = entryDestination.toURI(); String repositoryId = repository.getIdFromURI(newURI); // we need to do this as a catma:// is appended outputSourceDocumentResult.setSourceDocumentID(repositoryId); SourceDocumentInfo outputSourceDocumentInfo = outputSourceDocumentResult .getSourceDocumentInfo(); TechInfoSet newTechInfoSet = new TechInfoSet(fileName, null, newURI); // TODO: MimeType detection ? FileType newFileType = FileType.getFileTypeFromName(fileName); newTechInfoSet.setFileType(newFileType); outputSourceDocumentInfo.setTechInfoSet(newTechInfoSet); outputSourceDocumentInfo.setContentInfoSet(new ContentInfoSet()); output.add(outputSourceDocumentResult); } } ZipFile.closeQuietly(zipFile); } for (SourceDocumentResult sdr : output) { TechInfoSet sdrTechInfoSet = sdr.getSourceDocumentInfo().getTechInfoSet(); String sdrSourceDocumentId = sdr.getSourceDocumentID(); ProtocolHandler protocolHandler = getProtocolHandlerForUri(sdrTechInfoSet.getURI(), sdrSourceDocumentId, sdrTechInfoSet.getMimeType()); String mimeType = protocolHandler.getMimeType(); sdrTechInfoSet.setMimeType(mimeType); FileType sdrFileType = FileType.getFileType(mimeType); sdrTechInfoSet.setFileType(sdrFileType); if (sdrFileType.isCharsetSupported()) { Charset charset = Charset.forName(protocolHandler.getEncoding()); sdrTechInfoSet.setCharset(charset); } else { sdrTechInfoSet.setFileOSType(FileOSType.INDEPENDENT); } loadSourceDocumentAndContent(sdr); } return output; }
From source file:com.silverpeas.util.ZipManager.java
/** * Indicates the number of files (not directories) inside the archive. * * @param archive the archive whose content is analyzed. * @return the number of files (not directories) inside the archive. *///from w ww .j a v a 2s . c o m public static int getNbFiles(File archive) { ZipFile zipFile = null; int nbFiles = 0; try { zipFile = new ZipFile(archive); @SuppressWarnings("unchecked") Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry ze = entries.nextElement(); if (!ze.isDirectory()) { nbFiles++; } } } catch (IOException ioe) { SilverTrace.warn("util", "ZipManager.getNbFiles()", "util.EXE_ERROR_WHILE_COUNTING_FILE", "sourceFile = " + archive.getPath(), ioe); } finally { if (zipFile != null) { ZipFile.closeQuietly(zipFile); } } return nbFiles; }
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 w w. j a v a 2 s . co 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.fujitsu.dc.core.bar.BarFileInstaller.java
/** * bar?????./*w w w . ja v a 2 s.c o m*/ * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw DcCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryNames.toString()); } return entryCount; } catch (DcCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw DcCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw DcCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (DcCoreException e) { throw e; } catch (RuntimeException e) { throw DcCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:io.personium.core.bar.BarFileInstaller.java
/** * bar?????./*ww w. j a va 2s . c o m*/ * <ul> * <li>bar????</li> * <li>bar???????</li> * <li>TODO bar??????</li> * </ul>. * @param barFile ????bar?File * @returns bar? */ private long checkBarFileContents(File barFile) { // bar? checkBarFileSize(barFile); ZipFile zipFile = null; try { zipFile = new ZipFile(barFile, "UTF-8"); Enumeration<ZipArchiveEntry> entries = zipFile.getEntries(); ZipArchiveEntry zae = null; long entryCount = 0; String entryName = null; try { long maxBarEntryFileSize = getMaxBarEntryFileSize(); // ?? Map<String, String> requiredBarFiles = setupBarFileOrder(); while (entries.hasMoreElements()) { zae = entries.nextElement(); entryName = zae.getName(); log.info("read: " + entryName); if (!zae.isDirectory()) { // ??????bar? entryCount++; // bar?? checkBarFileEntrySize(zae, entryName, maxBarEntryFileSize); // Box????? if (zae.getName().endsWith("/" + BarFileReadRunner.MANIFEST_JSON)) { checkAndReadManifest(entryName, zae, zipFile); } } // bar??????? if (!checkBarFileStructures(zae, requiredBarFiles)) { throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES.params(entryName); } } if (!requiredBarFiles.isEmpty()) { StringBuilder entryNames = new StringBuilder(); Object[] requiredFileNames = requiredBarFiles.keySet().toArray(); for (int i = 0; i < requiredFileNames.length; i++) { if (i > 0) { entryNames.append(" " + requiredFileNames[i]); } else { entryNames.append(requiredFileNames[i]); } } throw PersoniumCoreException.BarInstall.BAR_FILE_INVALID_STRUCTURES .params(entryNames.toString()); } return entryCount; } catch (PersoniumCoreException e) { throw e; } catch (Exception e) { log.info(e.getMessage(), e.fillInStackTrace()); throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_READ.params(entryName); } } catch (FileNotFoundException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params("barFile"); } catch (ZipException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (IOException e) { throw PersoniumCoreException.BarInstall.BAR_FILE_CANNOT_OPEN.params(e.getMessage()); } catch (PersoniumCoreException e) { throw e; } catch (RuntimeException e) { throw PersoniumCoreException.Server.UNKNOWN_ERROR; } finally { ZipFile.closeQuietly(zipFile); } }
From source file:com.taobao.android.builder.tools.zip.ZipUtils.java
public static List<String> listZipEntries(File zipFile) { List<String> list = new ArrayList<String>(); ZipFile zip;//w ww . j a v a2 s .c o m try { zip = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> en = zip.getEntries(); ZipArchiveEntry ze = null; while (en.hasMoreElements()) { ze = en.nextElement(); String name = ze.getName(); name = StringUtils.replace(name, "/", "."); if (name.endsWith(".class")) { list.add(name); } } if (null != zip) { ZipFile.closeQuietly(zip); } } catch (IOException e) { } return list; }