List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveInputStream getNextEntry
public ArchiveEntry getNextEntry() throws IOException
From source file:ezbake.deployer.publishers.openShift.RhcApplication.java
private void writeTarFileToProjectDirectory(byte[] artifact) throws DeploymentException { final File gitDbPath = gitRepo.getRepository().getDirectory(); final File projectDir = gitDbPath.getParentFile(); try {//from w w w. j a v a 2 s.co m CompressorInputStream uncompressedInput = new GzipCompressorInputStream( new ByteArrayInputStream(artifact)); TarArchiveInputStream inputStream = new TarArchiveInputStream(uncompressedInput); // copy the existing entries TarArchiveEntry nextEntry; while ((nextEntry = (TarArchiveEntry) inputStream.getNextEntry()) != null) { File fileToWrite = new File(projectDir, nextEntry.getName()); if (nextEntry.isDirectory()) { fileToWrite.mkdirs(); } else { File house = fileToWrite.getParentFile(); if (!house.exists()) { house.mkdirs(); } copyInputStreamToFile(inputStream, fileToWrite); Files.setPosixFilePermissions(fileToWrite, nextEntry.getMode()); } } } catch (IOException e) { log.error("[" + getApplicationName() + "]" + e.getMessage(), e); throw new DeploymentException(e.getMessage()); } }
From source file:com.netflix.spinnaker.halyard.backup.services.v1.BackupService.java
private void untarHalconfig(String halconfigDir, String halconfigTar) { FileInputStream tarInput = null; TarArchiveInputStream tarArchiveInputStream = null; try {/*from w w w . j a v a 2s . c o m*/ tarInput = new FileInputStream(new File(halconfigTar)); tarArchiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream("tar", tarInput); } catch (IOException | ArchiveException e) { throw new HalException(Problem.Severity.FATAL, "Failed to open backup: " + e.getMessage(), e); } try { ArchiveEntry archiveEntry = tarArchiveInputStream.getNextEntry(); while (archiveEntry != null) { String entryName = archiveEntry.getName(); Path outputPath = Paths.get(halconfigDir, entryName); File outputFile = outputPath.toFile(); if (!outputFile.getParentFile().exists()) { outputFile.getParentFile().mkdirs(); } if (archiveEntry.isDirectory()) { outputFile.mkdir(); } else { Files.copy(tarArchiveInputStream, outputPath, REPLACE_EXISTING); } archiveEntry = tarArchiveInputStream.getNextEntry(); } } catch (IOException e) { throw new HalException(Problem.Severity.FATAL, "Failed to read archive entry: " + e.getMessage(), e); } }
From source file:autoupdater.FileDAO.java
/** * Untars a .tar.//from w w w. j a v a2 s . c o m * * @param fileToUntar * @return true if successful * @throws FileNotFoundException * @throws IOException */ private boolean untar(File fileToUntar) throws FileNotFoundException, IOException { boolean fileUntarred = false; String untarLocation = fileToUntar.getParentFile().getAbsolutePath(); TarArchiveInputStream tarStream = null; try { tarStream = new TarArchiveInputStream(new FileInputStream(fileToUntar)); BufferedReader bufferedTarReader = null; try { bufferedTarReader = new BufferedReader(new InputStreamReader(tarStream)); ArchiveEntry entry; while ((entry = tarStream.getNextEntry()) != null) { byte[] buffer = new byte[8 * 1024]; File tempFile = new File(String.format("%s/%s", untarLocation, entry.getName())); if (entry.isDirectory()) { if (!tempFile.exists()) { tempFile.mkdir(); } } else { OutputStream output = new FileOutputStream(tempFile); try { int bytesRead; while ((bytesRead = tarStream.read(buffer)) != -1) { output.write(buffer, 0, bytesRead); } } finally { output.close(); } tempFile.setExecutable(true); // make sure the binary files can be executed } } } finally { if (bufferedTarReader != null) { bufferedTarReader.close(); } } } finally { if (tarStream != null) { tarStream.close(); } } return fileUntarred; }
From source file:com.mobilesorcery.sdk.builder.linux.PackageParser.java
/** * Extracts a package template and parses and replaces variables * in filenames and files./* w w w .ja v a 2 s . co m*/ * * @param o Output directory * @param i Input file * * @throws Exception If recursion is too deep, a variable isn't defined or * malformed meta data * @throws IOException Error reading inputstream * @throws ParseException Malformed JSON * @throws FileNotFoundException Could not open input file */ public void doProcessTarGZip(File o, File i) throws Exception, IOException, ParseException, FileNotFoundException { FileInputStream fis = new FileInputStream(i); GZIPInputStream gis = new GZIPInputStream(fis); TarArchiveInputStream tis = new TarArchiveInputStream(gis); // Remove any old data if any if (o.exists() == true) o.delete(); // Find and parse meta data, this should always be the // first file, but it can' be assumed while (true) { ArchiveEntry e = tis.getNextEntry(); if (e == null) break; if (e.getName().equals(".meta/.meta") == false) continue; doParseMeta(tis); break; } // Reset input tis.close(); gis.close(); fis.close(); fis = new FileInputStream(i); gis = new GZIPInputStream(fis); tis = new TarArchiveInputStream(gis); // Process and extract files while (true) { File f; ArchiveEntry e = tis.getNextEntry(); if (e == null) break; // Check if it's a script that we need to load and parse if (e.getName().contains(".meta") == true) { if (m_scriptMap.containsKey(e.getName()) == true) { String name = m_scriptMap.get(e.getName()); String script = m_varResolver.doParseStream(tis); m_scriptMap.put(name, script); m_scriptMap.remove(e.getName()); } continue; } // Store its permissions String n = m_varResolver.doResolveString(e.getName()); m_filemodeMap.put(n, ((TarArchiveEntry) e).getMode()); // Directory ? f = new File(o, n); if (e.isDirectory() == true) { if (f.exists() == false) f.mkdirs(); continue; } // It's a file if (m_parseSet.contains(e.getName()) == true) m_varResolver.doParseCopyStream(f, tis); else BuilderUtil.getInstance().copyInputStreamToFile(f, tis, e.getSize()); } }
From source file:net.sf.sveditor.core.tests.utils.BundleUtils.java
public void unpackBundleTarToFS(String bundle_path, File fs_path) { URL url = fBundle.getEntry(bundle_path); TestCase.assertNotNull(url);/*from w w w. j a v a2s . com*/ if (!fs_path.isDirectory()) { TestCase.assertTrue(fs_path.mkdirs()); } InputStream in = null; TarArchiveInputStream tar_stream = null; try { in = url.openStream(); } catch (IOException e) { TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage()); } tar_stream = new TarArchiveInputStream(in); try { byte tmp[] = new byte[4 * 1024]; int cnt; ArchiveEntry te; while ((te = tar_stream.getNextEntry()) != null) { // System.out.println("Entry: \"" + ze.getName() + "\""); File entry_f = new File(fs_path, te.getName()); if (te.getName().endsWith("/")) { // Directory continue; } if (!entry_f.getParentFile().exists()) { TestCase.assertTrue(entry_f.getParentFile().mkdirs()); } FileOutputStream fos = new FileOutputStream(entry_f); BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length); while ((cnt = tar_stream.read(tmp, 0, tmp.length)) > 0) { bos.write(tmp, 0, cnt); } bos.flush(); bos.close(); fos.close(); // tar_stream.closeEntry(); } tar_stream.close(); } catch (IOException e) { e.printStackTrace(); TestCase.fail("Failed to unpack tar file: " + e.getMessage()); } }
From source file:com.platform.APIClient.java
public boolean tryExtractTar(File inputFile) { String extractFolderName = MainActivity.app.getFilesDir().getAbsolutePath() + bundlesFileName + "/" + extractedFolder;// w w w. j ava 2 s.com 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:net.sf.sveditor.core.tests.utils.BundleUtils.java
public void unpackBundleTgzToFS(String bundle_path, File fs_path) { URL url = fBundle.getEntry(bundle_path); TestCase.assertNotNull(url);//from w ww .j a va2s . co m if (!fs_path.isDirectory()) { TestCase.assertTrue(fs_path.mkdirs()); } InputStream in = null; GzipCompressorInputStream gz_stream = null; TarArchiveInputStream tar_stream = null; try { in = url.openStream(); } catch (IOException e) { TestCase.fail("Failed to open data file " + bundle_path + " : " + e.getMessage()); } try { gz_stream = new GzipCompressorInputStream(in); } catch (IOException e) { TestCase.fail("Failed to uncompress data file " + bundle_path + " : " + e.getMessage()); } tar_stream = new TarArchiveInputStream(gz_stream); try { byte tmp[] = new byte[4 * 1024]; int cnt; ArchiveEntry te; while ((te = tar_stream.getNextEntry()) != null) { // System.out.println("Entry: \"" + ze.getName() + "\""); File entry_f = new File(fs_path, te.getName()); if (te.getName().endsWith("/")) { // Directory continue; } if (!entry_f.getParentFile().exists()) { TestCase.assertTrue(entry_f.getParentFile().mkdirs()); } FileOutputStream fos = new FileOutputStream(entry_f); BufferedOutputStream bos = new BufferedOutputStream(fos, tmp.length); while ((cnt = tar_stream.read(tmp, 0, tmp.length)) > 0) { bos.write(tmp, 0, cnt); } bos.flush(); bos.close(); fos.close(); // tar_stream.closeEntry(); } tar_stream.close(); } catch (IOException e) { e.printStackTrace(); TestCase.fail("Failed to unpack tar file: " + e.getMessage()); } }
From source file:freenet.client.ArchiveManager.java
private void handleTARArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element, ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context) throws ArchiveFailureException, ArchiveRestartException { if (logMINOR) Logger.minor(this, "Handling a TAR Archive"); TarArchiveInputStream tarIS = null; try {/* w w w.ja va 2 s. c om*/ tarIS = new TarArchiveInputStream(data); // MINOR: Assumes the first entry in the tarball is a directory. ArchiveEntry entry; byte[] buf = new byte[32768]; HashSet<String> names = new HashSet<String>(); boolean gotMetadata = false; outerTAR: while (true) { try { entry = tarIS.getNextEntry(); } catch (IllegalArgumentException e) { // Annoyingly, it can throw this on some corruptions... throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e); } if (entry == null) break; if (entry.isDirectory()) continue; String name = stripLeadingSlashes(entry.getName()); if (names.contains(name)) { Logger.error(this, "Duplicate key " + name + " in archive " + key); continue; } long size = entry.getSize(); if (name.equals(".metadata")) gotMetadata = true; if (size > maxArchivedFileSize && !name.equals(element)) { addErrorElement( ctx, key, name, "File too big: " + size + " greater than current archived file size limit " + maxArchivedFileSize, true); } else { // Read the element long realLen = 0; Bucket output = tempBucketFactory.makeBucket(size); OutputStream out = output.getOutputStream(); try { int readBytes; while ((readBytes = tarIS.read(buf)) > 0) { out.write(buf, 0, readBytes); readBytes += realLen; if (readBytes > maxArchivedFileSize) { addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize + " greater than current archived file size limit " + maxArchivedFileSize, true); out.close(); out = null; output.free(); continue outerTAR; } } } finally { if (out != null) out.close(); } if (size <= maxArchivedFileSize) { addStoreElement(ctx, key, name, output, gotElement, element, callback, context); names.add(name); trimStoredData(); } else { // We are here because they asked for this file. callback.gotBucket(output, context); gotElement.value = true; addErrorElement( ctx, key, name, "File too big: " + size + " greater than current archived file size limit " + maxArchivedFileSize, true); } } } // If no metadata, generate some if (!gotMetadata) { generateMetadata(ctx, key, names, gotElement, element, callback, context); trimStoredData(); } if (throwAtExit) throw new ArchiveRestartException("Archive changed on re-fetch"); if ((!gotElement.value) && element != null) callback.notInArchive(context); } catch (IOException e) { throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e); } finally { Closer.close(tarIS); } }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
/** * Untar an input file into an output file. * * The output file is created in the output folder, having the same name as * the input file, minus the '.tar' extension. * * @param is the input .tar stream./*from w ww.j a v a2 s . c om*/ * @param outputDir the output directory file. * @throws IOException * @throws FileNotFoundException * * @return The {@link List} of {@link File}s with the untared content. * @throws ArchiveException */ @SuppressWarnings("ConvertToTryWithResources") private ArrayList<String> unTar(final InputStream is, final File outputDir) throws FileNotFoundException, IOException, ArchiveException { final ArrayList<String> untaredFiles = new ArrayList<>(); final TarArchiveInputStream archiveStream = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream("tar", is); TarArchiveEntry entry; int bytesRead = 0; /*int x = 0;*/ byte[] buf = new byte[16384]; /*log.println("|---+----+----+----+----+----+----+----+----+----|"); log.print("/");*/ while ((entry = (TarArchiveEntry) archiveStream.getNextEntry()) != null) { final File outputFile = new File(outputDir, entry.getName()); if (entry.isDirectory()) { if (!outputFile.exists()) { if (!outputFile.mkdirs()) { throw new IllegalStateException( String.format("Couldn't create directory %s.", outputFile.getAbsolutePath())); } } } else { final FileOutputStream outputFileStream = new FileOutputStream(outputFile); /*int incr = Math.floorDiv(downloadSize, 50);*/ for (int n = archiveStream.read(buf); n > 0; n = archiveStream.read(buf)) { outputFileStream.write(buf, 0, n); log.advance(n); /*bytesRead += n; x++;*/ /*if (bytesRead >= incr) { log.backspace(); log.print("#"); switch (Math.floorDiv(x, 100)) { case 0: log.print("/"); break; case 1: log.print("-"); break; case 2: log.print("\\"); break; case 3: log.print("|"); break; } bytesRead -= incr; } if (x % 100 == 0) { log.backspace(); switch (Math.floorDiv(x, 100)) { case 0: case 4: log.print("/"); x = 0; break; case 1: log.print("-"); break; case 2: log.print("\\"); break; case 3: log.print("|"); break; } }*/ } outputFileStream.close(); } untaredFiles.add(entry.getName()); } archiveStream.close(); /*log.backspace(); log.println("#");*/ return untaredFiles; }
From source file:org.apache.camel.processor.aggregate.tarfile.TarAggregationStrategy.java
private static void addFileToTar(File source, File file, String fileName) throws IOException, ArchiveException { File tmpTar = File.createTempFile(source.getName(), null); tmpTar.delete();//from w w w . ja va 2 s .c o m if (!source.renameTo(tmpTar)) { throw new IOException("Could not make temp file (" + source.getName() + ")"); } TarArchiveInputStream tin = (TarArchiveInputStream) new ArchiveStreamFactory() .createArchiveInputStream(ArchiveStreamFactory.TAR, new FileInputStream(tmpTar)); TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(source)); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); InputStream in = new FileInputStream(file); // copy the existing entries ArchiveEntry nextEntry; while ((nextEntry = tin.getNextEntry()) != null) { tos.putArchiveEntry(nextEntry); IOUtils.copy(tin, tos); tos.closeArchiveEntry(); } // Add the new entry TarArchiveEntry entry = new TarArchiveEntry(fileName == null ? file.getName() : fileName); entry.setSize(file.length()); tos.putArchiveEntry(entry); IOUtils.copy(in, tos); tos.closeArchiveEntry(); IOHelper.close(in); IOHelper.close(tin); IOHelper.close(tos); }