List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry isDirectory
public boolean isDirectory()
From source file:com.amaze.filemanager.asynchronous.asynctasks.compress.TarHelperTask.java
@Override void addElements(ArrayList<CompressedObjectParcelable> elements) { TarArchiveInputStream tarInputStream = null; try {/*from w w w. j av a 2 s. c om*/ tarInputStream = new TarArchiveInputStream(new FileInputStream(filePath)); TarArchiveEntry entry; while ((entry = tarInputStream.getNextTarEntry()) != null) { String name = entry.getName(); if (!CompressedHelper.isEntryPathValid(name)) { continue; } if (name.endsWith(SEPARATOR)) name = name.substring(0, name.length() - 1); boolean isInBaseDir = relativePath.equals("") && !name.contains(SEPARATOR); boolean isInRelativeDir = name.contains(SEPARATOR) && name.substring(0, name.lastIndexOf(SEPARATOR)).equals(relativePath); if (isInBaseDir || isInRelativeDir) { elements.add(new CompressedObjectParcelable(entry.getName(), entry.getLastModifiedDate().getTime(), entry.getSize(), entry.isDirectory())); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:hudson.gridmaven.MavenBuilder.java
public void getAndUntar(FileSystem fs, String src, String targetPath) throws FileNotFoundException, IOException { BufferedOutputStream dest = null; InputStream tarArchiveStream = new FSDataInputStream(fs.open(new Path(src))); TarArchiveInputStream tis = new TarArchiveInputStream(new BufferedInputStream(tarArchiveStream)); TarArchiveEntry entry = null; try {/*from w w w .ja v a2s .c o m*/ while ((entry = tis.getNextTarEntry()) != null) { int count; File outputFile = new File(targetPath, entry.getName()); if (entry.isDirectory()) { // entry is a directory if (!outputFile.exists()) { outputFile.mkdirs(); } } else { // entry is a file byte[] data = new byte[BUFFER_MAX]; FileOutputStream fos = new FileOutputStream(outputFile); dest = new BufferedOutputStream(fos, BUFFER_MAX); while ((count = tis.read(data, 0, BUFFER_MAX)) != -1) { dest.write(data, 0, count); } dest.flush(); dest.close(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (dest != null) { dest.flush(); dest.close(); } tis.close(); } }
From source file:com.platform.APIClient.java
public boolean tryExtractTar(File inputFile) { String extractFolderName = MainActivity.app.getFilesDir().getAbsolutePath() + bundlesFileName + "/" + extractedFolder;/*from w ww . j a v a2 s. c o m*/ boolean result = false; TarArchiveInputStream debInputStream = null; try { final InputStream is = new FileInputStream(inputFile); debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is); TarArchiveEntry entry = null; while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) { final String outPutFileName = entry.getName().replace("./", ""); final File outputFile = new File(extractFolderName, outPutFileName); if (!entry.isDirectory()) { FileUtils.writeByteArrayToFile(outputFile, org.apache.commons.compress.utils.IOUtils.toByteArray(debInputStream)); } } result = true; } catch (Exception e) { e.printStackTrace(); } finally { try { if (debInputStream != null) debInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return result; }
From source file:in.neoandroid.neoupdate.neoUpdate.java
private boolean downloadAPKFromNPK() { try {//from w ww. j a v a2s .c o m String apkName = apkUpdatePath.path.replace("/", ""); GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl)); //FileInputStream npkFile = new FileInputStream(baseUrl); TarArchiveInputStream input = new TarArchiveInputStream(npkFile); TarArchiveEntry ae; while ((ae = input.getNextTarEntry()) != null) { if (!ae.isDirectory() && ae.getName().equalsIgnoreCase(apkName)) { String apkPath = tmpDir + apkUpdatePath.path; boolean status = downloadFile(apkUpdatePath, apkPath, input, ae); input.close(); return status; } } input.close(); } catch (Exception e) { e.printStackTrace(); } return false; }
From source file:in.neoandroid.neoupdate.neoUpdate.java
private String getMetaFromNPK() { try {// w w w. java 2 s. co m GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl)); //FileInputStream npkFile = new FileInputStream(baseUrl); TarArchiveInputStream input = new TarArchiveInputStream(npkFile); TarArchiveEntry ae; while ((ae = input.getNextTarEntry()) != null) { if (ae.isDirectory()) Log.e("[neoUpdate]", "Dir: " + ae.getName()); else Log.e("[neoUpdate]", "File: " + ae.getName()); if (ae.getName().equalsIgnoreCase("neoupdate.json")) { byte buff[] = new byte[(int) ae.getSize()]; input.read(buff); input.close(); return new String(buff); } } input.close(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:in.neoandroid.neoupdate.neoUpdate.java
private String processFromNPK() { try {/*from w w w.java 2s . co m*/ GZIPInputStream npkFile = new GZIPInputStream(new FileInputStream(baseUrl)); //FileInputStream npkFile = new FileInputStream(baseUrl); TarArchiveInputStream input = new TarArchiveInputStream(npkFile); TarArchiveEntry ae; while ((ae = input.getNextTarEntry()) != null && filesToDownload.size() > 0 && !stopped) { if (ae.isDirectory()) { Log.e("[neoUpdate]", "Dir: " + ae.getName()); } else { Log.e("[neoUpdate]", "File: " + ae.getName()); String filename = ae.getName(); NewAsset asset = findAndGetAsset(filename); if (asset != null) { downloadFile(asset, null, input, ae); publishProgress((float) (totalFilesToDownload - filesToDownload.size()) / (float) totalFilesToDownload); } } } input.close(); } catch (Exception e) { e.printStackTrace(); return "Unknown Error: Update Failed!"; } return "Success"; }
From source file:com.amaze.filemanager.asynchronous.asynctasks.compress.GzipHelperTask.java
@Override void addElements(ArrayList<CompressedObjectParcelable> elements) { TarArchiveInputStream tarInputStream = null; try {//from w w w. j a v a 2 s . c om tarInputStream = new TarArchiveInputStream( new GzipCompressorInputStream(new FileInputStream(filePath))); TarArchiveEntry entry; while ((entry = tarInputStream.getNextTarEntry()) != null) { String name = entry.getName(); if (!CompressedHelper.isEntryPathValid(name)) { AppConfig.toast(context.get(), context.get().getString(R.string.multiple_invalid_archive_entries)); continue; } if (name.endsWith(SEPARATOR)) name = name.substring(0, name.length() - 1); boolean isInBaseDir = relativePath.equals("") && !name.contains(SEPARATOR); boolean isInRelativeDir = name.contains(SEPARATOR) && name.substring(0, name.lastIndexOf(SEPARATOR)).equals(relativePath); if (isInBaseDir || isInRelativeDir) { elements.add(new CompressedObjectParcelable(entry.getName(), entry.getLastModifiedDate().getTime(), entry.getSize(), entry.isDirectory())); } } } catch (IOException e) { e.printStackTrace(); } }
From source file:com.facebook.buck.util.unarchive.Untar.java
@VisibleForTesting ImmutableSet<Path> extractArchive(Path archiveFile, ProjectFilesystem filesystem, Path filesystemRelativePath, Optional<Path> stripPath, ExistingFileMode existingFileMode, PatternsMatcher entriesToExclude, boolean writeSymlinksAfterCreatingFiles) throws IOException { ImmutableSet.Builder<Path> paths = ImmutableSet.builder(); HashSet<Path> dirsToTidy = new HashSet<>(); TreeMap<Path, Long> dirCreationTimes = new TreeMap<>(); DirectoryCreator creator = new DirectoryCreator(filesystem); // On windows, we create hard links instead of symlinks. This is fine, but the // destination file may not exist yet, which is an error. So, just hold onto the paths until // all files are extracted, and /then/ try to do the links Map<Path, Path> windowsSymlinkMap = new HashMap<>(); try (TarArchiveInputStream archiveStream = getArchiveInputStream(archiveFile)) { TarArchiveEntry entry; while ((entry = archiveStream.getNextTarEntry()) != null) { String entryName = entry.getName(); if (entriesToExclude.matchesAny(entryName)) { continue; }//from w ww. jav a2 s.c o m Path destFile = Paths.get(entryName); Path destPath; if (stripPath.isPresent()) { if (!destFile.startsWith(stripPath.get())) { continue; } destPath = filesystemRelativePath.resolve(stripPath.get().relativize(destFile)).normalize(); } else { destPath = filesystemRelativePath.resolve(destFile).normalize(); } if (entry.isDirectory()) { dirsToTidy.add(destPath); mkdirs(creator, destPath); dirCreationTimes.put(destPath, entry.getModTime().getTime()); } else if (entry.isSymbolicLink()) { if (writeSymlinksAfterCreatingFiles) { recordSymbolicLinkForWindows(creator, destPath, entry, windowsSymlinkMap); } else { writeSymbolicLink(creator, destPath, entry); } paths.add(destPath); setAttributes(filesystem, destPath, entry); } else if (entry.isFile()) { writeFile(creator, archiveStream, destPath); paths.add(destPath); setAttributes(filesystem, destPath, entry); } } writeWindowsSymlinks(creator, windowsSymlinkMap); } catch (CompressorException e) { throw new IOException(String.format("Could not get decompressor for archive at %s", archiveFile), e); } setDirectoryModificationTimes(filesystem, dirCreationTimes); ImmutableSet<Path> filePaths = paths.build(); if (existingFileMode == ExistingFileMode.OVERWRITE_AND_CLEAN_DIRECTORIES) { // Clean out directories of files that were not in the archive tidyDirectories(filesystem, dirsToTidy, filePaths); } return filePaths; }
From source file:gdt.data.entity.ArchiveHandler.java
private void getTarEntries(TarArchiveEntry tarEntry, Stack<TarArchiveEntry> s, String root$) { if (tarEntry == null) return;/*from w w w . j a v a 2 s . c o m*/ if (tarEntry.isDirectory()) { try { TarArchiveEntry[] tea = tarEntry.getDirectoryEntries(); if (tea != null) { for (TarArchiveEntry aTea : tea) { getTarEntries(aTea, s, root$); } } } catch (Exception e) { LOGGER.severe(":getTarEntities:" + e.toString()); } } else { String entryName$; entryName$ = tarEntry.getName().substring(root$.length()); tarEntry.setName(entryName$); s.push(tarEntry); } }
From source file:edu.harvard.iq.dvn.core.web.study.AddFilesPage.java
private List<StudyFileEditBean> createStudyFilesFromTar(File uploadedInputFile) { List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>(); File dir = new File(uploadedInputFile.getParentFile(), study.getId().toString()); if (!dir.exists()) { dir.mkdir();//from ww w .j a v a2 s. c om } List<File> directoriesToDelete = new ArrayList<File>(); File unzippedFile = null; TarArchiveInputStream tiStream = null; FileOutputStream tempOutStream = null; String unzipError = ""; if (GzipUtils.isCompressedFilename(uploadedInputFile.getName())) { try { GZIPInputStream zippedInput = new GZIPInputStream(new FileInputStream(uploadedInputFile)); unzippedFile = new File(dir, "unzipped-file-" + UUID.randomUUID()); FileOutputStream unzippedOutput = new FileOutputStream(unzippedFile); byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = zippedInput.read(dataBuffer)) > 0) { unzippedOutput.write(dataBuffer, 0, i); unzippedOutput.flush(); } tiStream = new TarArchiveInputStream(new FileInputStream(unzippedFile)); } catch (Exception ex) { unzipError = " A common gzip extension was found but is the file corrupt?"; } } else if (BZip2Utils.isCompressedFilename(uploadedInputFile.getName())) { try { BZip2CompressorInputStream zippedInput = new BZip2CompressorInputStream( new FileInputStream(uploadedInputFile)); unzippedFile = new File(dir, "unzipped-file-" + UUID.randomUUID()); FileOutputStream unzippedOutput = new FileOutputStream(unzippedFile); byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = zippedInput.read(dataBuffer)) > 0) { unzippedOutput.write(dataBuffer, 0, i); unzippedOutput.flush(); } tiStream = new TarArchiveInputStream(new FileInputStream(unzippedFile)); } catch (Exception ex) { unzipError = " A common bzip2 extension was found but is the file corrupt?"; } } else { try { // no need to decompress, carry on tiStream = new TarArchiveInputStream(new FileInputStream(uploadedInputFile)); } catch (FileNotFoundException ex) { unzipError = " Is the tar file corrupt?"; } } TarArchiveEntry tEntry = null; if (tiStream == null) { String msg = "Problem reading uploaded file." + unzipError; setTarValidationErrorMessage(msg); uploadedInputFile.delete(); fbList = new ArrayList<StudyFileEditBean>(); return fbList; } try { while ((tEntry = tiStream.getNextTarEntry()) != null) { String fileEntryName = tEntry.getName(); if (!tEntry.isDirectory()) { if (fileEntryName != null && !fileEntryName.equals("")) { String dirName = null; String finalFileName = fileEntryName; int ind = fileEntryName.lastIndexOf('/'); if (ind > -1) { finalFileName = fileEntryName.substring(ind + 1); if (ind > 0) { dirName = fileEntryName.substring(0, ind); dirName = dirName.replace('/', '-'); } } else { finalFileName = fileEntryName; } // only process normal tar entries, not the ones that start with "._" because they were created on a mac: // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files if (!finalFileName.startsWith("._")) { File tempUploadedFile = null; try { tempUploadedFile = FileUtil.createTempFile(dir, finalFileName); } catch (Exception ex) { Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex); String msg = "Problem creating temporary file."; setTarValidationErrorMessage(msg); } tempOutStream = new FileOutputStream(tempUploadedFile); byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = tiStream.read(dataBuffer)) > 0) { tempOutStream.write(dataBuffer, 0, i); tempOutStream.flush(); } tempOutStream.close(); try { StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile, studyService.generateFileSystemNameSequence(), study); tempFileBean.setSizeFormatted(tempUploadedFile.length()); if (dirName != null) { tempFileBean.getFileMetadata().setCategory(dirName); } fbList.add(tempFileBean); setTarValidationErrorMessage(null); } catch (Exception ex) { String msg = "Problem preparing files for ingest. Is the tar file corrupt?"; setTarValidationErrorMessage(msg); uploadedInputFile.delete(); tempUploadedFile.delete(); fbList = new ArrayList<StudyFileEditBean>(); } } } } else { File directory = new File(dir, fileEntryName); directory.mkdir(); directoriesToDelete.add(directory); } } } catch (IOException ex) { String msg = "Problem reading tar file. Is it corrupt?"; setTarValidationErrorMessage(msg); } // teardown and cleanup try { tiStream.close(); } catch (IOException ex) { Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex); } if (tiStream != null) { try { tiStream.close(); } catch (IOException ex) { Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex); } } if (tempOutStream != null) { try { tempOutStream.close(); } catch (IOException ex) { Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex); } } uploadedInputFile.delete(); if (unzippedFile != null) { unzippedFile.delete(); } for (File dirToDelete : directoriesToDelete) { if (dirToDelete.exists()) { try { FileUtils.forceDelete(dirToDelete); } catch (IOException ex) { Logger.getLogger(AddFilesPage.class.getName()).log(Level.SEVERE, null, ex); } } } return fbList; }