List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry getName
public String getName()
From source file:org.anurag.compress.ExtractTarFile.java
public ExtractTarFile(final Context ctx, final Item zFile, final int width, String extractDir, final File file, final int mode) { // TODO Auto-generated constructor stub running = false;//from www .ja v a 2 s. c o m errors = false; prog = 0; read = 0; final Dialog dialog = new Dialog(ctx, Constants.DIALOG_STYLE); dialog.setCancelable(true); dialog.setContentView(R.layout.extract_file); dialog.getWindow().getAttributes().width = width; DEST = extractDir; final ProgressBar progress = (ProgressBar) dialog.findViewById(R.id.zipProgressBar); final TextView to = (TextView) dialog.findViewById(R.id.zipFileName); final TextView from = (TextView) dialog.findViewById(R.id.zipLoc); final TextView cfile = (TextView) dialog.findViewById(R.id.zipSize); final TextView zsize = (TextView) dialog.findViewById(R.id.zipNoOfFiles); final TextView status = (TextView) dialog.findViewById(R.id.zipFileLocation); if (extractDir == null) to.setText(ctx.getString(R.string.extractingto) + " Cache directory"); else to.setText(ctx.getString(R.string.extractingto) + " " + DEST); from.setText(ctx.getString(R.string.extractingfrom) + " " + file.getName()); if (mode == 2) { //TAR ENTRY HAS TO BE SHARED VIA BLUETOOTH,ETC... TextView t = null;//= (TextView)dialog.findViewById(R.id.preparing); t.setText(ctx.getString(R.string.preparingtoshare)); } try { if (file.getName().endsWith(".tar.gz")) tar = new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(file))); else tar = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(file))); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); tar = null; } final Handler handle = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: progress.setProgress(0); cfile.setText(ctx.getString(R.string.extractingfile) + " " + name); break; case 1: status.setText(name); progress.setProgress((int) prog); break; case 2: try { tar.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (running) { dialog.dismiss(); if (mode == 0) { //after extracting file ,it has to be opened.... new OpenFileDialog(ctx, Uri.parse(dest)); } else if (mode == 2) { //FILE HAS TO BE SHARED.... new BluetoothChooser(ctx, new File(dest).getAbsolutePath(), null); } else { if (errors) Toast.makeText(ctx, ctx.getString(R.string.errorinext), Toast.LENGTH_SHORT).show(); Toast.makeText(ctx, ctx.getString(R.string.fileextracted), Toast.LENGTH_SHORT).show(); } } break; case 3: zsize.setText(size); progress.setMax((int) max); break; case 4: status.setText(ctx.getString(R.string.preparing)); break; case 5: running = false; Toast.makeText(ctx, ctx.getString(R.string.extaborted), Toast.LENGTH_SHORT).show(); } } }; final Thread thread = new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub if (running) { if (DEST == null) { DEST = Environment.getExternalStorageDirectory() + "/Android/data/org.anurag.file.quest"; new File(DEST).mkdirs(); } TarArchiveEntry ze; try { while ((ze = tar.getNextTarEntry()) != null) { if (ze.isDirectory()) continue; handle.sendEmptyMessage(4); if (!zFile.isDirectory()) { //EXTRACTING A SINGLE FILE FROM AN ARCHIVE.... if (ze.getName().equalsIgnoreCase(zFile.t_getEntryName())) { try { //SENDING CURRENT FILE NAME.... try { name = zFile.getName(); } catch (Exception e) { name = zFile.t_getEntryName(); } handle.sendEmptyMessage(0); dest = DEST; dest = dest + "/" + name; FileOutputStream out = new FileOutputStream((dest)); max = ze.getSize(); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); InputStream fin = tar; while ((read = fin.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); fin.close(); break; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); //errors = true; } catch (IOException e) { errors = true; } } } else { //EXTRACTING A DIRECTORY FROM TAR ARCHIVE.... String p = zFile.getPath(); if (p.startsWith("/")) p = p.substring(1, p.length()); if (ze.getName().startsWith(p)) { prog = 0; dest = DEST; name = ze.getName(); String path = name; name = name.substring(name.lastIndexOf("/") + 1, name.length()); handle.sendEmptyMessage(0); String foname = zFile.getPath(); if (!foname.startsWith("/")) foname = "/" + foname; if (!path.startsWith("/")) path = "/" + path; path = path.substring(foname.lastIndexOf("/"), path.lastIndexOf("/")); if (!path.startsWith("/")) path = "/" + path; dest = dest + path; new File(dest).mkdirs(); dest = dest + "/" + name; FileOutputStream out; try { max = ze.getSize(); out = new FileOutputStream((dest)); size = AppBackup.size(max, ctx); handle.sendEmptyMessage(3); // InputStream fin = tar; while ((read = tar.read(data)) != -1 && running) { out.write(data, 0, read); prog += read; name = AppBackup.status(prog, ctx); handle.sendEmptyMessage(1); } out.flush(); out.close(); //fin.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); // errors = true; } catch (IOException e) { errors = true; } catch (Exception e) { //errors = true; } } } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); errors = true; } handle.sendEmptyMessage(2); } } }); /* Button cancel = (Button)dialog.findViewById(R.id.calcelButton); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub dialog.dismiss(); handle.sendEmptyMessage(5); } }); Button st = (Button)dialog.findViewById(R.id.extractButton); st.setVisibility(View.GONE);*/ dialog.show(); running = true; thread.start(); dialog.setCancelable(false); progress.setVisibility(View.VISIBLE); }
From source file:org.anurag.compress.TarManager.java
/** * /* w ww . j a v a 2s.c om*/ * THE DIRECTORY ENTRIES CANNOT BE SKIPPED LIKE WE SKIPPED IN * RAR OR ZIP MANAGER.... * * @return * @throws IOException */ public ArrayList<Item> generateList() { list = new ArrayList<Item>(); TarArchiveEntry entry; try { if (f.getName().endsWith(".tar.gz")) tar = new TarArchiveInputStream( new GZIPInputStream(new BufferedInputStream(new FileInputStream(f)))); else if (f.getName().endsWith(".tar.bz2") || f.getName().endsWith(".TAR.BZ2")) tar = new TarArchiveInputStream( new BZip2CompressorInputStream(new BufferedInputStream(new FileInputStream(f)))); else tar = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(f))); while ((entry = tar.getNextTarEntry()) != null) { boolean added = false; int len = list.size(); String name = entry.getName(); if (name.startsWith("/")) name = name.substring(1, name.length()); if (entry.isDirectory()) name = name.substring(0, name.length() - 1); if (path.equalsIgnoreCase("/")) { while (name.contains("/")) name = name.substring(0, name.lastIndexOf("/")); for (int i = 0; i < len; ++i) { if (list.get(i).getName().equalsIgnoreCase(name)) { added = true; break; } } if (!added && !name.equalsIgnoreCase("")) list.add(new Item(entry, name, "", ctx)); } else { try { name = name.substring(path.length() + 1, name.length()); while (name.contains("/")) name = name.substring(0, name.lastIndexOf("/")); if (len > 0) { for (int i = 0; i < len; ++i) if (list.get(i).getName().equalsIgnoreCase(name)) { added = true; break; } if (!added && entry.getName().startsWith(path)) list.add(new Item(entry, name, path, ctx)); } else if (entry.getName().startsWith(path)) list.add(new Item(entry, name, path, ctx)); } catch (Exception e) { } } } tar.close(); sort(); return list; } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); return null; } }
From source file:org.apache.bookkeeper.tests.integration.utils.DockerUtils.java
public static void dumpContainerLogDirToTarget(DockerClient docker, String containerId, String path) { final int readBlockSize = 10000; try (InputStream dockerStream = docker.copyArchiveFromContainerCmd(containerId, path).exec(); TarArchiveInputStream stream = new TarArchiveInputStream(dockerStream)) { TarArchiveEntry entry = stream.getNextTarEntry(); while (entry != null) { if (entry.isFile()) { File output = new File(getTargetDirectory(containerId), entry.getName().replace("/", "-")); try (FileOutputStream os = new FileOutputStream(output)) { byte[] block = new byte[readBlockSize]; int read = stream.read(block, 0, readBlockSize); while (read > -1) { os.write(block, 0, read); read = stream.read(block, 0, readBlockSize); }//from w ww .j ava2s .c o m } } entry = stream.getNextTarEntry(); } } catch (RuntimeException | IOException e) { LOG.error("Error reading bk logs from container {}", containerId, e); } }
From source file:org.apache.camel.dataformat.tarfile.TarFileDataFormat.java
@Override public Object unmarshal(Exchange exchange, InputStream stream) throws Exception { if (usingIterator) { return new TarIterator(exchange.getIn(), stream); } else {//from www. ja v a 2 s. co m InputStream is = exchange.getIn().getMandatoryBody(InputStream.class); TarArchiveInputStream tis = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream(ArchiveStreamFactory.TAR, new BufferedInputStream(is)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { TarArchiveEntry entry = tis.getNextTarEntry(); if (entry != null) { exchange.getOut().setHeader(FILE_NAME, entry.getName()); IOHelper.copy(tis, baos); } entry = tis.getNextTarEntry(); if (entry != null) { throw new IllegalStateException("Tar file has more than 1 entry."); } return baos.toByteArray(); } finally { IOHelper.close(tis, baos); } } }
From source file:org.apache.camel.dataformat.tarfile.TarIterator.java
private Message getNextElement() { Message answer = null;/*from w ww .java 2s . c o m*/ if (tarInputStream != null) { try { TarArchiveEntry current = getNextEntry(); if (current != null) { LOGGER.debug("read tarEntry {}", current.getName()); answer = new DefaultMessage(); answer.getHeaders().putAll(inputMessage.getHeaders()); answer.setHeader("tarFileName", current.getName()); answer.setHeader(Exchange.FILE_NAME, current.getName()); if (current.getSize() > 0) { answer.setBody(new TarInputStreamWrapper(tarInputStream)); } else { // Workaround for the case when the entry is zero bytes big answer.setBody(new ByteArrayInputStream(new byte[0])); } return answer; } else { LOGGER.trace("close tarInputStream"); } } catch (IOException exception) { //Just wrap the IOException as CamelRuntimeException throw new RuntimeCamelException(exception); } } return answer; }
From source file:org.apache.flume.test.util.StagedInstall.java
private void untarTarFile(File tarFile, File destDir) throws Exception { TarArchiveInputStream tarInputStream = null; try {/*w ww.j a va 2 s . com*/ tarInputStream = new TarArchiveInputStream(new FileInputStream(tarFile)); TarArchiveEntry entry = null; while ((entry = tarInputStream.getNextTarEntry()) != null) { String name = entry.getName(); LOGGER.debug("Next file: " + name); File destFile = new File(destDir, entry.getName()); if (entry.isDirectory()) { destFile.mkdirs(); continue; } File destParent = destFile.getParentFile(); destParent.mkdirs(); OutputStream entryOutputStream = null; try { entryOutputStream = new FileOutputStream(destFile); byte[] buffer = new byte[2048]; int length = 0; while ((length = tarInputStream.read(buffer, 0, 2048)) != -1) { entryOutputStream.write(buffer, 0, length); } } catch (Exception ex) { LOGGER.error("Exception while expanding tar file", ex); throw ex; } finally { if (entryOutputStream != null) { try { entryOutputStream.close(); } catch (Exception ex) { LOGGER.warn("Failed to close entry output stream", ex); } } } } } catch (Exception ex) { LOGGER.error("Exception caught while untarring tar file: " + tarFile.getAbsolutePath(), ex); throw ex; } finally { if (tarInputStream != null) { try { tarInputStream.close(); } catch (Exception ex) { LOGGER.warn("Unable to close tar input stream: " + tarFile.getCanonicalPath(), ex); } } } }
From source file:org.apache.gobblin.data.management.copy.writer.TarArchiveInputStreamDataWriter.java
/** * Untars the passed in {@link FileAwareInputStream} to the task's staging directory. Uses the name of the root * {@link TarArchiveEntry} in the stream as the directory name for the untarred file. The method also commits the data * by moving the file from staging to output directory. * * @see org.apache.gobblin.data.management.copy.writer.FileAwareInputStreamDataWriter#write(org.apache.gobblin.data.management.copy.FileAwareInputStream) *///from ww w .ja v a 2s .c o m @Override public void writeImpl(InputStream inputStream, Path writeAt, CopyableFile copyableFile) throws IOException { this.closer.register(inputStream); TarArchiveInputStream tarIn = new TarArchiveInputStream(inputStream); final ReadableByteChannel inputChannel = Channels.newChannel(tarIn); TarArchiveEntry tarEntry; // flush the first entry in the tar, which is just the root directory tarEntry = tarIn.getNextTarEntry(); String tarEntryRootName = StringUtils.remove(tarEntry.getName(), Path.SEPARATOR); log.info("Unarchiving at " + writeAt); try { while ((tarEntry = tarIn.getNextTarEntry()) != null) { // the API tarEntry.getName() is misleading, it is actually the path of the tarEntry in the tar file String newTarEntryPath = tarEntry.getName().replace(tarEntryRootName, writeAt.getName()); Path tarEntryStagingPath = new Path(writeAt.getParent(), newTarEntryPath); if (!FileUtils.isSubPath(writeAt.getParent(), tarEntryStagingPath)) { throw new IOException( String.format("Extracted file: %s is trying to write outside of output directory: %s", tarEntryStagingPath, writeAt.getParent())); } if (tarEntry.isDirectory() && !this.fs.exists(tarEntryStagingPath)) { this.fs.mkdirs(tarEntryStagingPath); } else if (!tarEntry.isDirectory()) { FSDataOutputStream out = this.fs.create(tarEntryStagingPath, true); final WritableByteChannel outputChannel = Channels.newChannel(out); try { StreamCopier copier = new StreamCopier(inputChannel, outputChannel); if (isInstrumentationEnabled()) { copier.withCopySpeedMeter(this.copySpeedMeter); } this.bytesWritten.addAndGet(copier.copy()); if (isInstrumentationEnabled()) { log.info("File {}: copied {} bytes, average rate: {} B/s", copyableFile.getOrigin().getPath(), this.copySpeedMeter.getCount(), this.copySpeedMeter.getMeanRate()); } else { log.info("File {} copied.", copyableFile.getOrigin().getPath()); } } finally { out.close(); outputChannel.close(); } } } } finally { tarIn.close(); inputChannel.close(); inputStream.close(); } }
From source file:org.apache.hadoop.fs.tar.TarFileSystem.java
@Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { Path baseTarPath = getBaseTarPath(f); String inFile = getFileInArchive(f); if (inFile == null) throw new IOException("TAR FileSystem: Can not open the whole TAR"); // adjust for the header long offset = index.getOffset(inFile); long size = index.getSize(inFile); FSDataInputStream in = underlyingFS.open(baseTarPath); in.seek(offset - 512);/* w ww.j av a2 s . c o m*/ TarArchiveEntry entry = readHeaderEntry(in); if (!entry.getName().equals(inFile)) { LOG.fatal("Index file is corrupt." + "Requested filename is present in index " + "but absent in TAR."); throw new IOException("Requested filename does not match "); } return new FSDataInputStream( new BufferedFSInputStream(new SeekableTarInputStream(in, size, offset), bufferSize)); }
From source file:org.apache.hadoop.fs.tar.TarFileSystem.java
@Override public FileStatus[] listStatus(Path f) throws IOException { ArrayList<FileStatus> ret = new ArrayList<FileStatus>(); Path abs = makeAbsolute(f);/*from w ww . jav a2 s. com*/ Path baseTar = getBaseTarPath(abs); String inFile = getFileInArchive(abs); FileStatus underlying = underlyingFS.getFileStatus(baseTar); // if subfile exists in the path, just return the status of that if (inFile != null) { ret.add(getFileStatus(abs)); } else { FSDataInputStream in = underlyingFS.open(baseTar); byte[] buffer = new byte[512]; for (long offset : index.getOffsetList()) { in.seek(offset - 512); // adjust for the header TarArchiveEntry entry = readHeaderEntry(in, buffer); // Construct a FileStatus object FileStatus fstatus = new FileStatus(entry.getSize(), entry.isDirectory(), (int) underlying.getReplication(), underlying.getBlockSize(), entry.getModTime().getTime(), underlying.getAccessTime(), new FsPermission((short) entry.getMode()), entry.getUserName(), entry.getGroupName(), new Path(abs.toUri().toASCIIString() + TAR_INFILESEP + entry.getName())); ret.add(fstatus); } } // copy back FileStatus[] retArray = new FileStatus[ret.size()]; ret.toArray(retArray); return retArray; }
From source file:org.apache.hadoop.fs.tar.TarFileSystem.java
@Override public FileStatus getFileStatus(Path f) throws IOException { FileStatus fstatus = null;/*from w w w .ja v a 2 s . c om*/ Path abs = makeAbsolute(f); Path baseTar = getBaseTarPath(abs); String inFile = getFileInArchive(abs); FileStatus underlying = underlyingFS.getFileStatus(baseTar); if (inFile == null) { // return the status of the tar itself but make it a dir fstatus = new FileStatus(underlying.getLen(), true, underlying.getReplication(), underlying.getBlockSize(), underlying.getModificationTime(), underlying.getAccessTime(), underlying.getPermission(), underlying.getOwner(), underlying.getGroup(), abs); } else { long offset = index.getOffset(inFile); FSDataInputStream in = underlyingFS.open(baseTar); in.seek(offset - 512); TarArchiveEntry entry = readHeaderEntry(in); if (!entry.getName().equals(inFile)) { LOG.fatal("Index file is corrupt." + "Requested filename is present in index " + "but absent in TAR."); throw new IOException("NBU-TAR: FATAL: entry file name " + "does not match requested file name"); } // Construct a FileStatus object fstatus = new FileStatus(entry.getSize(), entry.isDirectory(), (int) underlying.getReplication(), underlying.getBlockSize(), entry.getModTime().getTime(), underlying.getAccessTime(), new FsPermission((short) entry.getMode()), entry.getUserName(), entry.getGroupName(), abs); } return fstatus; }