List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry getName
public String getName()
From source file:org.overlord.sramp.atom.archive.ArchiveUtils.java
/** * Unpacks the given archive file into the output directory. * @param archiveFile an archive file//from ww w .j ava2 s . c o m * @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", //$NON-NLS-1$ outFile.getParentFile().getCanonicalPath())); } } if (entry.isDirectory()) { if (!outFile.mkdir()) { throw new IOException( Messages.i18n.format("FAILED_TO_CREATE_DIR", outFile.getCanonicalPath())); //$NON-NLS-1$ } } 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.phoenicis.tools.archive.Zip.java
/** * Uncompress a tar/*from w w w . j a v a 2s . c om*/ * * @param countingInputStream to count the number of byte extracted * @param outputDir The directory where files should be extracted * @return A list of extracted files * @throws ArchiveException if the process fails */ private List<File> uncompress(final InputStream inputStream, CountingInputStream countingInputStream, final File outputDir, long finalSize, Consumer<ProgressEntity> stateCallback) { final List<File> uncompressedFiles = new LinkedList<>(); try (InputStream cursorInputStream = new CursorFinderInputStream(inputStream, ZIP_MAGICK_BYTE); ArchiveInputStream debInputStream = new ArchiveStreamFactory().createArchiveInputStream("zip", cursorInputStream)) { ZipArchiveEntry entry; while ((entry = (ZipArchiveEntry) debInputStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { LOGGER.info(String.format("Attempting to write output directory %s.", outputFile.getAbsolutePath())); if (!outputFile.exists()) { LOGGER.info(String.format("Attempting to createPrefix output directory %s.", outputFile.getAbsolutePath())); Files.createDirectories(outputFile.toPath()); } } else { LOGGER.info(String.format("Creating output file %s.", outputFile.getAbsolutePath())); outputFile.getParentFile().mkdirs(); try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) { IOUtils.copy(debInputStream, outputFileStream); } } uncompressedFiles.add(outputFile); stateCallback.accept(new ProgressEntity.Builder() .withPercent((double) countingInputStream.getCount() / (double) finalSize * (double) 100) .withProgressText("Extracting " + outputFile.getName()).build()); } return uncompressedFiles; } catch (IOException | org.apache.commons.compress.archivers.ArchiveException e) { throw new ArchiveException("Unable to extract the file", e); } }
From source file:org.seasar.robot.extractor.impl.ZipExtractor.java
@Override public ExtractData getText(final InputStream in, final Map<String, String> params) { if (in == null) { throw new RobotSystemException("The inputstream is null."); }// w w w . j a v a 2 s . c o m final MimeTypeHelper mimeTypeHelper = SingletonS2Container.getComponent("mimeTypeHelper"); if (mimeTypeHelper == null) { throw new RobotSystemException("MimeTypeHelper is unavailable."); } final ExtractorFactory extractorFactory = SingletonS2Container.getComponent("extractorFactory"); if (extractorFactory == null) { throw new RobotSystemException("ExtractorFactory is unavailable."); } final StringBuilder buf = new StringBuilder(1000); ArchiveInputStream ais = null; try { ais = archiveStreamFactory.createArchiveInputStream(in); ZipArchiveEntry entry = null; while ((entry = (ZipArchiveEntry) ais.getNextEntry()) != null) { final String filename = entry.getName(); final String mimeType = mimeTypeHelper.getContentType(null, filename); if (mimeType != null) { final Extractor extractor = extractorFactory.getExtractor(mimeType); if (extractor != null) { try { final Map<String, String> map = new HashMap<String, String>(); map.put(TikaMetadataKeys.RESOURCE_NAME_KEY, filename); buf.append(extractor.getText(new IgnoreCloseInputStream(ais), map).getContent()); buf.append('\n'); } catch (final Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception in an internal extractor.", e); } } } } } } catch (final Exception e) { if (buf.length() == 0) { throw new ExtractException("Could not extract a content.", e); } } finally { IOUtils.closeQuietly(ais); } return new ExtractData(buf.toString()); }
From source file:org.slc.sli.ingestion.landingzone.validation.ZipFileValidator.java
@Override public boolean isValid(File zipFile, AbstractMessageReport report, ReportStats reportStats, Source source, Map<String, Object> parameters) { boolean isValid = false; // we know more of our source LOG.info("Validating zipFile: {}", zipFile.getAbsolutePath()); ZipFile zf = null;/*from w w w. ja v a2 s .c om*/ try { zf = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> zes = zf.getEntries(); while (zes.hasMoreElements()) { ZipArchiveEntry ze = zes.nextElement(); LOG.debug(" ZipArchiveEntry: name: {}, size {}", ze.getName(), ze.getSize()); if (isDirectory(ze)) { report.error(reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0010, zipFile.getName()); return false; } if (ze.getName().endsWith(".ctl")) { isValid = true; } } // no manifest (.ctl file) found in the zip file if (!isValid) { report.error(reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0009, zipFile.getName()); } } catch (UnsupportedZipFeatureException ex) { report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0022, zipFile.getName()); isValid = false; } catch (FileNotFoundException ex) { report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0020, zipFile.getName()); isValid = false; } catch (IOException ex) { LOG.warn("Caught IO exception processing " + zipFile.getAbsolutePath()); report.error(ex, reportStats, new FileSource(zipFile.getName()), BaseMessageCode.BASE_0021, zipFile.getName()); isValid = false; } finally { ZipFile.closeQuietly(zf); } return isValid; }
From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java
/** * Extracts content of the ZIP file to the target folder. * * @param zipFile ZIP archive// w w w.j ava2 s . c o m * @param targetDir Directory to extract files to * @param mkdirs Allow creating missing directories on the file paths * @throws IOException IO Exception * @throws FileNotFoundException */ public static void extract(File zipFile, File targetDir, boolean mkdirs) throws IOException { ZipFile zf = null; try { zf = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> zes = zf.getEntries(); while (zes.hasMoreElements()) { ZipArchiveEntry entry = zes.nextElement(); if (!entry.isDirectory()) { File targetFile = new File(targetDir, entry.getName()); if (mkdirs) { targetFile.getParentFile().mkdirs(); } InputStream is = null; try { is = zf.getInputStream(entry); copyInputStreamToFile(is, targetFile); } finally { IOUtils.closeQuietly(is); } } } } finally { ZipFile.closeQuietly(zf); } }
From source file:org.slc.sli.ingestion.landingzone.ZipFileUtil.java
/** * Retrieves a name of the first .ctl file found in the zip archive. * * @param zipFile ZIP file to scan//from w ww . ja v a 2 s. c o m * @return A filename representing the control file. * @throws IOException IO Exception */ public static String getControlFileName(File zipFile) throws IOException { ZipFile zf = null; try { zf = new ZipFile(zipFile); Enumeration<ZipArchiveEntry> zes = zf.getEntries(); while (zes.hasMoreElements()) { ZipArchiveEntry entry = zes.nextElement(); if (!entry.isDirectory() && entry.getName().endsWith(".ctl")) { return entry.getName(); } } } finally { ZipFile.closeQuietly(zf); } return null; }
From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java
@Override public <T> T each(Processor<T> processor) throws Exception { T result = null;/*from w w w. j a va2 s . c o m*/ ZipFile zip = new ZipFile(zipDownload.getFile()); try { Enumeration<ZipArchiveEntry> iter = zip.getEntries(); while (iter.hasMoreElements() && result == null) { ZipArchiveEntry el = iter.nextElement(); Path zipPath = new Path(el.getName()); if (root.isPrefixOf(zipPath)) { String key = zipPath.removeFirstSegments(root.segmentCount()).toString(); if ("".equals(key)) { //path maches exactly, this means we hit the root of the // code set. Do not store it because the root of a codeset // is not actually an element of the codeset! } else { CodeSetEntry cse = csEntry(zip, el); result = processor.doit(cse); if (result != null) { //Bail out early when result found return result; } } } } return result; } finally { try { zip.close(); } catch (IOException e) { } } }
From source file:org.springframework.ide.eclipse.boot.wizard.content.ZipFileCodeSet.java
/** * Create a CodeSetEntry that wraps a ZipEntry *//*from w w w . j av a 2 s. co m*/ private CodeSetEntry csEntry(final ZipFile zip, final ZipArchiveEntry e) { IPath zipPath = new Path(e.getName()); //path relative to zip file Assert.isTrue(root.isPrefixOf(zipPath)); final IPath csPath = zipPath.removeFirstSegments(root.segmentCount()); return new CodeSetEntry() { @Override public IPath getPath() { return csPath; } @Override public String toString() { return getPath() + " in " + zipDownload; } @Override public boolean isDirectory() { return e.isDirectory(); } @Override public int getUnixMode() { return e.getUnixMode(); } @Override public InputStream getData() throws IOException { return zip.getInputStream(e); } }; }
From source file:org.waarp.common.tar.ZipUtility.java
/** * Extract all files from Tar into the specified directory * /*w w w . j a v a 2s. c o m*/ * @param tarFile * @param directory * @return the list of extracted filenames * @throws IOException */ public static List<String> unZip(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); ZipArchiveInputStream in = new ZipArchiveInputStream(inputStream); ZipArchiveEntry entry = in.getNextZipEntry(); while (entry != null) { if (entry.isDirectory()) { entry = in.getNextZipEntry(); continue; } File curfile = new File(directory, entry.getName()); File parent = curfile.getParentFile(); if (!parent.exists()) { parent.mkdirs(); } OutputStream out = new FileOutputStream(curfile); IOUtils.copy(in, out); out.close(); result.add(entry.getName()); entry = in.getNextZipEntry(); } in.close(); return result; }
From source file:org.xwiki.filemanager.internal.job.PackJobTest.java
@Test public void pack() throws Exception { Folder projects = mockFolder("Projects", "Pr\u00F4j\u00EA\u00E7\u021B\u0219", null, Arrays.asList("Concerto", "Resilience"), Arrays.asList("key.pub")); File key = mockFile("key.pub", "Projects"); when(fileSystem.canView(key.getReference())).thenReturn(false); mockFolder("Concerto", "Projects", Collections.<String>emptyList(), Arrays.asList("pom.xml")); File pom = mockFile("pom.xml", "m&y p?o#m.x=m$l", "Concerto"); setFileContent(pom, "foo"); Folder resilience = mockFolder("Resilience", "Projects", Arrays.asList("src"), Arrays.asList("build.xml")); when(fileSystem.canView(resilience.getReference())).thenReturn(false); mockFolder("src", "Resilience"); mockFile("build.xml"); File readme = mockFile("readme.txt", "r\u00E9\u00E0dm\u00E8.txt"); setFileContent(readme, "blah"); PackRequest request = new PackRequest(); request.setPaths(Arrays.asList(new Path(projects.getReference()), new Path(null, readme.getReference()))); request.setOutputFileReference(/*from w w w .j a v a 2s.c om*/ new AttachmentReference("out.zip", new DocumentReference("wiki", "Space", "Page"))); PackJob job = (PackJob) execute(request); ZipFile zip = new ZipFile( new java.io.File(testFolder.getRoot(), "temp/filemanager/wiki/Space/Page/out.zip")); List<String> folders = new ArrayList<String>(); Map<String, String> files = new HashMap<String, String>(); Enumeration<ZipArchiveEntry> entries = zip.getEntries(); while (entries.hasMoreElements()) { ZipArchiveEntry entry = entries.nextElement(); if (entry.isDirectory()) { folders.add(entry.getName()); } else if (zip.canReadEntryData(entry)) { StringWriter writer = new StringWriter(); IOUtils.copy(zip.getInputStream(entry), writer); files.put(entry.getName(), writer.toString()); } } zip.close(); assertEquals(Arrays.asList(projects.getName() + '/', projects.getName() + "/Concerto/"), folders); assertEquals(2, files.size()); assertEquals("blah", files.get(readme.getName())); assertEquals("foo", files.get(projects.getName() + "/Concerto/" + pom.getName())); assertEquals(("blah" + "foo").getBytes().length, job.getStatus().getBytesWritten()); assertTrue(job.getStatus().getOutputFileSize() > 0); }