List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry getName
public String getName()
From source file:org.vafer.jdeb.signing.DebMakerTestCase.java
public void testCreation() throws Exception { File control = new File(getClass().getResource("../deb/control/control").toURI()); File archive1 = new File(getClass().getResource("../deb/data.tgz").toURI()); File archive2 = new File(getClass().getResource("../deb/data.tar.bz2").toURI()); File archive3 = new File(getClass().getResource("../deb/data.zip").toURI()); File directory = new File(getClass().getResource("../deb/data").toURI()); final InputStream ring = getClass().getClassLoader().getResourceAsStream("org/vafer/gpg/secring.gpg"); DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null), new DataProducerArchive(archive2, null, null, null), new DataProducerArchive(archive3, null, null, null), new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null), new DataProducerLink("/link/path-element.ext", "/link/target-element.ext", true, null, null, null) };/*from w w w . ja v a 2 s .c o m*/ int digest = PGPUtil.SHA1; PGPSigner signer = new PGPSigner(ring, "2E074D8F", "test"); PGPSignatureGenerator signatureGenerator = new PGPSignatureGenerator( new BcPGPContentSignerBuilder(signer.getSecretKey().getPublicKey().getAlgorithm(), digest)); signatureGenerator.init(PGPSignature.BINARY_DOCUMENT, signer.getPrivateKey()); for (int i = 0; i <= 1; i++) { File deb = File.createTempFile("jdeb", ".deb"); DebMaker maker = new DebMaker(new NullConsole(), Arrays.asList(data), null); maker.setControl(new File(getClass().getResource("../deb/control").toURI())); maker.setDeb(deb); if (i == 0) maker.setSignMethod("debsig-verify"); else maker.setSignMethod("dpkg-sig"); BinaryPackageControlFile packageControlFile = maker.createSignedDeb(Compression.GZIP, signatureGenerator, signer); assertTrue(packageControlFile.isValid()); final Map<String, TarArchiveEntry> filesInDeb = new HashMap<String, TarArchiveEntry>(); ArchiveWalker.walkData(deb, new ArchiveVisitor<TarArchiveEntry>() { public void visit(TarArchiveEntry entry, byte[] content) throws IOException { filesInDeb.put(entry.getName(), entry); } }, Compression.GZIP); assertTrue("_gpgorigin wasn't found in the package", ArchiveWalker.arArchiveContains(deb, "_gpgorigin")); assertTrue("debian-binary wasn't found in the package", ArchiveWalker.arArchiveContains(deb, "debian-binary")); assertTrue("control.tar.gz wasn't found in the package", ArchiveWalker.arArchiveContains(deb, "control.tar.gz")); assertTrue("testfile wasn't found in the package", filesInDeb.containsKey("./test/testfile")); assertTrue("testfile2 wasn't found in the package", filesInDeb.containsKey("./test/testfile2")); assertTrue("testfile3 wasn't found in the package", filesInDeb.containsKey("./test/testfile3")); assertTrue("testfile4 wasn't found in the package", filesInDeb.containsKey("./test/testfile4")); assertTrue("/link/path-element.ext wasn't found in the package", filesInDeb.containsKey("./link/path-element.ext")); assertEquals("/link/path-element.ext has wrong link target", "/link/target-element.ext", filesInDeb.get("./link/path-element.ext").getLinkName()); if (i == 0) { FileUtils.copyFile(deb, new File("./target/test_debsig-verify.deb")); } else { FileUtils.copyFile(deb, new File("./target/test_dpkg-sig.deb")); } assertTrue("Cannot delete the file " + deb, deb.delete()); } }
From source file:org.waarp.common.tar.TarUtility.java
/** * Extract all files from Tar into the specified directory * /*from ww w. j a v a2 s .c o m*/ * @param tarFile * @param directory * @return the list of extracted filenames * @throws IOException */ public static List<String> unTar(File tarFile, File directory) throws IOException { List<String> result = new ArrayList<String>(); InputStream inputStream = new FileInputStream(tarFile); TarArchiveInputStream in = new TarArchiveInputStream(inputStream); TarArchiveEntry entry = in.getNextTarEntry(); while (entry != null) { if (entry.isDirectory()) { entry = in.getNextTarEntry(); 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.getNextTarEntry(); } in.close(); return result; }
From source file:org.xenmaster.setup.debian.Bootstrapper.java
protected boolean downloadNetbootFiles() { if (System.currentTimeMillis() - lastChecked < 50 * 60 * 1000) { return false; }// w ww .ja v a 2 s . c o m File localVersionFile = new File(Settings.getInstance().getString("StorePath") + "/netboot/version"); int localVersion = -1; try (FileInputStream fis = new FileInputStream(localVersionFile)) { localVersion = Integer.parseInt(IOUtils.toString(fis)); } catch (IOException | NumberFormatException ex) { Logger.getLogger(getClass()).error("Failed to retrieve local version file", ex); } int remoteVersion = -1; try { remoteVersion = Integer.parseInt(IOUtils.toString(XenMasterSite.getFileAsStream("/netboot/version"))); } catch (IOException | NumberFormatException ex) { Logger.getLogger(getClass()).error("Failed to retrieve remote version file", ex); } lastChecked = System.currentTimeMillis(); if (localVersion < remoteVersion) { Logger.getLogger(getClass()) .info("New version " + remoteVersion + " found. Please hold while downloading netboot data"); try { TarArchiveInputStream tais = new TarArchiveInputStream( new GZIPInputStream(XenMasterSite.getFileAsStream("/netboot/netboot.tar.gz"))); TarArchiveEntry tae = null; FileOutputStream fos = null; while ((tae = tais.getNextTarEntry()) != null) { if (tais.canReadEntryData(tae)) { String target = Settings.getInstance().getString("StorePath") + "/" + tae.getName(); if (tae.isSymbolicLink()) { Path targetFile = FileSystems.getDefault().getPath(tae.getLinkName()); Path linkName = FileSystems.getDefault().getPath(target); // Link might already have been written as null file if (targetFile.toFile().exists()) { targetFile.toFile().delete(); } Files.createSymbolicLink(linkName, targetFile); Logger.getLogger(getClass()).info( "Created sym link " + linkName.toString() + " -> " + targetFile.toString()); } else if (tae.isDirectory()) { new File(target).mkdir(); Logger.getLogger(getClass()).info("Created dir " + target); } else if (tae.isFile()) { fos = new FileOutputStream(target); byte[] b = new byte[1024]; int curPos = 0; while (tais.available() > 0) { tais.read(b, curPos, 1024); fos.write(b, curPos, 1024); } fos.flush(); fos.close(); Logger.getLogger(getClass()).info("Wrote file " + target); } } } tais.close(); // Write local version IOUtils.write("" + remoteVersion, new FileOutputStream(localVersionFile)); } catch (IOException ex) { Logger.getLogger(getClass()).error("Failed to download netboot files", ex); } } else { return false; } return true; }
From source file:plptool.gui.ProjectDriver.java
/** * Open plp file specified by path./* w ww . j a va 2s . c om*/ * * @param path Path to project file to load. * @param assemble Attempt to assemble after opening (if dirty is not set) * @return PLP_OK on successful operation, error code otherwise */ public int open(String path, boolean assemble) { File plpFile = new File(path); CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN, plpFile); if (!plpFile.exists()) return Msg.E("open(" + path + "): File not found.", Constants.PLP_BACKEND_PLP_OPEN_ERROR, null); boolean metafileFound = false; dirty = true; Msg.I("Opening " + path, null); if (arch != null) { arch.cleanup(); arch = null; } asm = null; asms = new ArrayList<PLPAsmSource>(); smods = null; watcher = null; pAttrSet = new HashMap<String, Object>(); HashMap<String, Integer> asmFileOrder = new HashMap<String, Integer>(); try { TarArchiveInputStream tIn = new TarArchiveInputStream(new FileInputStream(plpFile)); TarArchiveEntry entry; byte[] image; String metaStr; // Find meta file first while ((entry = tIn.getNextTarEntry()) != null) { if (entry.getName().equals("plp.metafile")) { image = new byte[(int) entry.getSize()]; tIn.read(image, 0, (int) entry.getSize()); metaStr = new String(image); metafileFound = true; meta = metaStr; Scanner metaScanner; String lines[] = meta.split("\\r?\\n"); if (lines[0].equals(Text.projectFileVersionString)) { } else { Msg.W("This is not a " + Text.projectFileVersionString + " project file. Opening anyways.", this); } metaScanner = new Scanner(meta); metaScanner.findWithinHorizon("DIRTY=", 0); if (metaScanner.nextInt() == 0) dirty = false; if (metaScanner.findWithinHorizon("ARCH=", 0) != null) { String temp = metaScanner.nextLine(); if (Config.cfgOverrideISA >= 0) { // ISA ID override, ignore the metafile arch = ArchRegistry.getArchitecture(this, Config.cfgOverrideISA); arch.init(); } else if (temp.equals("plpmips")) { Msg.W("This project file was created by PLPTool version 3 or earlier. " + "Meta data for this project will be updated " + "with the default ISA (plpmips) when the project " + "file is saved.", this); arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS); arch.init(); } else { arch = ArchRegistry.getArchitecture(this, Integer.parseInt(temp)); if (arch == null) { Msg.W("Invalid ISA ID is specified in the project file: '" + temp + "'. Assuming PLPCPU.", this); arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS); } arch.init(); } arch.hook(this); } // get asm files order int asmOrder = 0; while (metaScanner.hasNext()) { String asmName = metaScanner.nextLine(); if (asmName.endsWith(".asm")) { asmFileOrder.put(asmName, new Integer(asmOrder)); asmOrder++; asms.add(null); } } } } if (!metafileFound) return Msg.E("No PLP metadata found.", Constants.PLP_BACKEND_INVALID_PLP_FILE, this); // reset the tar input stream tIn = new TarArchiveInputStream(new FileInputStream(plpFile)); while ((entry = tIn.getNextTarEntry()) != null) { boolean handled = false; image = new byte[(int) entry.getSize()]; tIn.read(image, 0, (int) entry.getSize()); metaStr = new String(image); // Hook for project open for each entry Object[] eParams = { entry.getName(), image, plpFile }; handled = CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_ENTRY, eParams) || handled; if (entry.getName().endsWith("asm") && !entry.getName().startsWith("plp.")) { Integer order = (Integer) asmFileOrder.get(entry.getName()); if (order == null) Msg.W("The file '" + entry.getName() + "' is not listed in " + "the meta file. This file will be removed when the project " + "is saved.", this); else { asms.set(order, new PLPAsmSource(metaStr, entry.getName(), order)); } } else if (entry.getName().equals("plp.metafile")) { // we've done reading the metafile } else if (entry.getName().equals("plp.image")) { binimage = new byte[(int) entry.getSize()]; binimage = image; } else if (entry.getName().equals("plp.hex")) { hexstring = new String(image); // Restore bus modules states } else if (entry.getName().equals("plp.simconfig")) { Msg.D("simconfig:\n" + metaStr + "\n", 4, this); String lines[] = metaStr.split("\\r?\\n"); int i; for (i = 0; i < lines.length; i++) { String tokens[] = lines[i].split("::"); if (lines[i].startsWith("simRunnerDelay")) { Config.simRunnerDelay = Integer.parseInt(tokens[1]); } if (lines[i].equals("MODS")) { i++; this.smods = new Preset(); while (i < lines.length && !lines[i].equals("END")) { tokens = lines[i].split("::"); if (tokens.length > 4 && tokens[4].equals("noframe")) smods.addModuleDefinition(Integer.parseInt(tokens[0]), Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), false, false); else if (tokens.length > 4) smods.addModuleDefinition(Integer.parseInt(tokens[0]), Long.parseLong(tokens[2]), Long.parseLong(tokens[3]), true, Boolean.parseBoolean(tokens[5])); i++; } } if (lines[i].equals("WATCHER")) { i++; this.watcher = Watcher.getTableInitialModel(); while (i < lines.length && !lines[i].equals("END")) { tokens = lines[i].split("::"); Object row[] = { tokens[0], tokens[1], null, null }; watcher.addRow(row); i++; } } if (lines[i].equals("ISASPECIFIC")) { i++; while (i < lines.length && !lines[i].equals("END")) { tokens = lines[i].split("::"); arch.restoreArchSpecificSimStates(tokens); i++; } } } } else if (handled) { } else { Msg.W("open(" + path + "): unable to process entry: " + entry.getName() + ". This file will be removed when" + " you save the project.", this); } } tIn.close(); if (asmFileOrder.isEmpty()) { return Msg.E("open(" + path + "): no .asm files found.", Constants.PLP_BACKEND_INVALID_PLP_FILE, null); } } catch (Exception e) { Msg.trace(e); return Msg.E("open(" + path + "): Invalid PLP archive.", Constants.PLP_BACKEND_INVALID_PLP_FILE, null); } if (arch == null) { Msg.W("No ISA information specified in the archive, assuming plpmips", this); arch = ArchRegistry.getArchitecture(this, ArchRegistry.ISA_PLPMIPS); arch.init(); } plpfile = new File(path); modified = false; open_asm = 0; for (int i = 0; i < asms.size(); i++) Msg.I(i + ": " + asms.get(i).getAsmFilePath(), null); if (g) refreshProjectView(false); if (!dirty && assemble) { assemble(); asm_req = false; } else asm_req = true; if (g) { g_opts.restoreSavedOpts(); desimulate(); if (asm != null && asm.isAssembled()) g_dev.enableSimControls(); else g_dev.disableSimControls(); this.setUnModified(); updateWindowTitle(); g_dev.updateDevelopRecentProjectList(plpFile.getAbsolutePath()); if (g_asmview != null) g_asmview.dispose(); } CallbackRegistry.callback(CallbackRegistry.PROJECT_OPEN_SUCCESSFUL, plpFile); return Constants.PLP_OK; }
From source file:rv.comm.rcssserver.TarBz2ZipUtil.java
public static Reader getTarBZ2InputStream(File file) { try {//w ww . ja v a 2 s. c om // only works for the current layout of tar.bz2 files InputStream zStream = new BufferedInputStream(new FileInputStream(file)); CompressorInputStream bz2InputStream = new CompressorStreamFactory() .createCompressorInputStream(CompressorStreamFactory.BZIP2, zStream); TarArchiveInputStream tarStream = new TarArchiveInputStream(bz2InputStream); TarArchiveEntry entry = tarStream.getNextTarEntry(); // step into deepest directory while (entry != null && entry.isDirectory()) { TarArchiveEntry[] entries = entry.getDirectoryEntries(); if (entries.length > 0) { entry = entries[0]; } else { // empty directory entry = tarStream.getNextTarEntry(); } } if (entry == null) { System.out.println("tar file does not contain logfile"); return null; } // search for proper file while (entry != null && !entry.getName().endsWith("sparkmonitor.log")) { entry = tarStream.getNextTarEntry(); } if (entry == null) { System.out.println("tar file does not contain logfile"); return null; } // we have reached the proper position return new InputStreamReader(tarStream); } catch (IOException e) { // not a bz2 file System.out.println("File has bz2 ending, but seems to be not bz2"); e.printStackTrace(); } catch (CompressorException e) { e.printStackTrace(); } return null; }
From source file:taller.mundo.BogotaMap.java
/** * Rutina que permite realizar la descompresin de un contenedor tar.bz2. Durante el * proceso de descompresin, la rutina informa al usuario en consola, adems * del nombre del archivo actual, el progreso de la operacin. La rutina de- * tiene la ejecucin del programa si ocurre algn error. * @param path La ubicacin del archivo tar.bz2 a ser descomprimido. **//* www . ja v a2s . c o m*/ private void uncompressTarBzip(String path) { String anim = "|/-\\"; int buffersize = 1024; try (TarArchiveInputStream is = new TarArchiveInputStream( new BZip2CompressorInputStream(new FileInputStream(path)))) { TarArchiveEntry entry; while ((entry = is.getNextTarEntry()) != null) { int offset = 0; final byte[] buffer = new byte[buffersize]; FileOutputStream fout = new FileOutputStream("./data/" + entry.getName()); System.out.println(entry.getName()); int size = 0; int n = 0; long total = entry.getSize(); while (-1 != (n = is.read(buffer))) { double x = ((size * 1.0) / total) * 100.0; String progress = "\r" + anim.charAt(((int) Math.round(x)) % anim.length()) + " " + Math.round(x) + "% " + String.format("(%d / %d)", size, total); System.out.write(progress.getBytes()); size += n; fout.write(buffer, 0, n); } System.out.println(); fout.close(); } } catch (Exception e) { e.printStackTrace(); } }
From source file:uk.ac.man.cs.mdsd.webgen.ui.wizards.NewWebgenProjectOperation.java
@SuppressWarnings("unused") private void extractTGZ(final URL sourceURL, final IPath rootPath, final int removeSegemntsCount, final IPath[] ignoreFilter, final Map<IPath, IPath> renames) { try {/* w w w .j a va 2s . c o m*/ final File tgzPath = new File(FileLocator.resolve(sourceURL).toURI()); final TarArchiveInputStream tarIn = new TarArchiveInputStream( new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tgzPath)))); TarArchiveEntry entry = (TarArchiveEntry) tarIn.getNextEntry(); while (entry != null) { IPath path = new Path(entry.getName()).removeFirstSegments(removeSegemntsCount); if (renames.containsKey(path)) { path = renames.get(path); } if (rootPath != null) { path = new Path(rootPath.toString() + path.toString()); } if (!path.isEmpty() && !ignoreEntry(path, ignoreFilter)) { if (entry.isDirectory()) { final IFolder folder = projectHandle.getFolder(path); if (!folder.exists()) { folder.create(false, true, null); } } else { byte[] contents = new byte[(int) entry.getSize()]; tarIn.read(contents); final IFile file = projectHandle.getFile(path); file.create(new ByteArrayInputStream(contents), false, null); } } entry = (TarArchiveEntry) tarIn.getNextEntry(); } tarIn.close(); } catch (URISyntaxException | IOException | CoreException e) { WebgenUiPlugin.log(e); } }
From source file:uk.co.saiman.webmodule.commonjs.repository.CommonJsBundleVersion.java
private void extractTarballPackageDist(Resource archive, CacheEntry entry) { try (TarGzInputStream input = new TarGzInputStream(archive.getUrl().openStream(), getSha1().orElse(null))) { TarArchiveEntry tarEntry = input.getNextTarEntry(); while (tarEntry != null) { if (tarEntry.isFile()) { entry.writeBytes(tarEntry.getName(), getBytes(input)); }// w ww . j a v a 2 s . c o m tarEntry = input.getNextTarEntry(); } } catch (IOException e) { throw new RegistryResolutionException("Failed to extract archive from URL " + archive.getUrl(), e); } }
From source file:uk.co.saiman.webmodule.commonjs.repository.TarGzInputStream.java
public TarArchiveEntry findEntry(String name) { name = name.toLowerCase();/*from ww w .jav a 2s . c om*/ TarArchiveEntry tarEntry; try { do { tarEntry = getNextTarEntry(); } while (tarEntry != null && !tarEntry.getName().toLowerCase().equals(name)); } catch (IOException e) { throw new RegistryResolutionException("Failed to open " + name); } if (tarEntry == null) { throw new RegistryResolutionException("Failed to locate " + name); } return tarEntry; }
From source file:uni.bielefeld.cmg.sparkhit.io.TextFileBufferInput.java
/** * *//*from w w w. ja v a 2 s . c om*/ private void setInputStreamReader() { if (fileFormatIntMark == 0) { this.inputStreamReader = new InputStreamReader(inputFileStream); } else if (fileFormatIntMark == 1) { setGzipCompressorInputStream(); this.inputStreamReader = new InputStreamReader(inputGzipStream); } else if (fileFormatIntMark == 2) { setBZip2CompressorInputStream(); this.inputStreamReader = new InputStreamReader(inputBZip2Stream); } else if (fileFormatIntMark == 3) { setGzipCompressorInputStream(); setTarArchiveInputStreamFromGzipStream(); try { TarArchiveEntry currentEntry = inputTarArchiveStream.getNextTarEntry(); info.readMessage("Reading the first TarArchive Entry : " + currentEntry.getName()); info.screenDump(); } catch (IOException e) { e.printStackTrace(); } this.inputStreamReader = new InputStreamReader(inputTarArchiveStream); } else if (fileFormatIntMark == 4) { setBZip2CompressorInputStream(); setTarArchiveInputStreamFromBZipStream(); try { TarArchiveEntry currentEntry = inputTarArchiveStream.getNextTarEntry(); info.readMessage("Reading the first TarArchive Entry : " + currentEntry.getName()); info.screenDump(); } catch (IOException e) { e.printStackTrace(); } this.inputStreamReader = new InputStreamReader(inputTarArchiveStream); } else { info.readMessage( "fileFormatIntMark should be 0-4: 0 for uncompressed file; 1 for .gz file; 2 for .bz2 file; 3 for .tar.gz file; 4 for .tar.bz2 file."); info.screenDump(); } }