List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry setName
public void setName(String name)
From source file:com.puppetlabs.geppetto.forge.util.TarUtils.java
private static void append(File file, FileFilter filter, int baseNameLen, String addedTopFolder, TarArchiveOutputStream tarOut) throws IOException { String name = file.getAbsolutePath(); if (name.length() <= baseNameLen) name = ""; else// w w w .j a v a 2 s .c om name = name.substring(baseNameLen); if (File.separatorChar == '\\') name = name.replace('\\', '/'); if (addedTopFolder != null) name = addedTopFolder + '/' + name; if (FileUtils.isSymlink(file)) { String linkTarget = FileUtils.readSymbolicLink(file); if (linkTarget != null) { TarArchiveEntry entry = new TarArchiveEntry(name, TarConstants.LF_SYMLINK); entry.setName(name); entry.setLinkName(linkTarget); tarOut.putArchiveEntry(entry); } return; } ArchiveEntry entry = tarOut.createArchiveEntry(file, name); tarOut.putArchiveEntry(entry); File[] children = file.listFiles(filter); if (children != null) { tarOut.closeArchiveEntry(); // This is a directory. Append its children for (File child : children) append(child, filter, baseNameLen, addedTopFolder, tarOut); return; } // Append the content of the file InputStream input = new FileInputStream(file); try { StreamUtil.copy(input, tarOut); tarOut.closeArchiveEntry(); } finally { StreamUtil.close(input); } }
From source file:lucee.commons.io.compress.CompressUtil.java
private static void compressTar(String parent, Resource source, TarArchiveOutputStream tos, int mode) throws IOException { if (source.isFile()) { //TarEntry entry = (source instanceof FileResource)?new TarEntry((FileResource)source):new TarEntry(parent); TarArchiveEntry entry = new TarArchiveEntry(parent); entry.setName(parent); // mode//from w w w . j a va2s.co m //100777 TODO ist das so ok? if (mode > 0) entry.setMode(mode); else if ((mode = source.getMode()) > 0) entry.setMode(mode); entry.setSize(source.length()); entry.setModTime(source.lastModified()); tos.putArchiveEntry(entry); try { IOUtil.copy(source, tos, false); } finally { tos.closeArchiveEntry(); } } else if (source.isDirectory()) { compressTar(parent, source.listResources(), tos, mode); } }
From source file:bb.io.TarUtil.java
/** * Writes path as a new TarArchiveEntry to tarArchiveOutputStream. * If path is a normal file, then next writes path's data to tarArchiveOutputStream. * <p>//from w w w .ja v a2 s .com * If path is a directory, then this method additionally calls itself on the contents * (thus recursing thru the entire directory tree). * <p> * <b>Warning</b>: several popular programs (e.g. winzip) fail to display mere directory entries. * Furthermore, if just a directory entry is present (i.e. it is empty), they also may fail * to create a new empty directoy when extracting the TAR file's contents. * These are bugs in their behavior. * <p> * An optional FileFilter can be supplied to screen out paths that would otherwise be archived. * <p> * <i>This method does not close tarArchiveOutputStream:</i> that is the responsibility of the caller. * <p> * The caller also must take on the responsibility to not do anything stupid, like write * path more than once, or have the path be the same File that tarArchiveOutputStream is writing to. * <p> * @param path the File to archive * @param fileParent the FileParent for path * @param tarArchiveOutputStream the TarArchiveOutputStream that will write the archive data to * @param filter a FileFilter that can use to screen out certain files from being written to the archive; may be null (so everything specified by path gets archived) * @throws Exception if any Throwable is caught; the Throwable is stored as the cause, and the message stores path's information; * here are some of the possible causes: * <ol> * <li>IllegalArgumentException if path fails {@link #isTarable isTarable}</li> * <li>SecurityException if a security manager exists and its SecurityManager.checkRead method denies read access to path</li> * <li>IOException if an I/O problem occurs</li> * </ol> */ private static void archive(File path, FileParent fileParent, TarArchiveOutputStream tarArchiveOutputStream, FileFilter filter) throws Exception { try { if ((filter != null) && !filter.accept(path)) return; if (!isTarable(path)) throw new IllegalArgumentException("path = " + path.getPath() + " failed isTarable"); if (giveUserFeedback) ConsoleUtil.overwriteLine("TarUtil.archive: " + path.getPath()); TarArchiveEntry entry = new TarArchiveEntry(path); entry.setName(fileParent.getRelativePath(path, '/')); // Note: getRelativePath will ensure that '/' is the path separator and that directories end with '/' tarArchiveOutputStream.putNextEntry(entry); if (path.isFile()) readInFile(path, tarArchiveOutputStream); tarArchiveOutputStream.closeEntry(); if (path.isDirectory()) { for (File fileChild : DirUtil.getContents(path, null)) { // supply null, since we test at beginning of this method (supplying filter here will just add a redundant test) archive(fileChild, fileParent, tarArchiveOutputStream, filter); } } } catch (Throwable t) { String preface = "See cause for the underlying Throwable; happened for path = "; if ((t instanceof Exception) && (t.getMessage().startsWith(preface))) throw (Exception) t; // CRITICAL: see if t was actually the wrapping Exception generated by a subsequent recursive call to this method, and if so simply rethrow it unmodified to avoid excessive exception chaining throw new Exception(preface + (path != null ? path.getPath() : "<null>"), t); } }
From source file:com.surevine.gateway.scm.gatewayclient.GatewayPackage.java
void createTar(final Path tarPath, final Path... paths) throws IOException, ArchiveException { ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", Files.newOutputStream(tarPath)); try {/*from w w w .ja va 2 s .co m*/ for (Path path : paths) { TarArchiveEntry entry = new TarArchiveEntry(path.toFile()); entry.setName(path.getFileName().toString()); os.putArchiveEntry(entry); Files.copy(path, os); os.closeArchiveEntry(); } } finally { os.close(); } }
From source file:io.fabric8.docker.client.impl.BuildImage.java
@Override public OutputHandle fromFolder(String path) { try {//from ww w. j a va2s .c o m final Path root = Paths.get(path); final Path dockerIgnore = root.resolve(DOCKER_IGNORE); final List<String> ignorePatterns = new ArrayList<>(); if (dockerIgnore.toFile().exists()) { for (String p : Files.readAllLines(dockerIgnore, UTF_8)) { ignorePatterns.add(path.endsWith(File.separator) ? path + p : path + File.separator + p); } } final DockerIgnorePathMatcher dockerIgnorePathMatcher = new DockerIgnorePathMatcher(ignorePatterns); File tempFile = Files.createTempFile(Paths.get(DEFAULT_TEMP_DIR), DOCKER_PREFIX, BZIP2_SUFFIX).toFile(); try (FileOutputStream fout = new FileOutputStream(tempFile); BufferedOutputStream bout = new BufferedOutputStream(fout); BZip2CompressorOutputStream bzout = new BZip2CompressorOutputStream(bout); final TarArchiveOutputStream tout = new TarArchiveOutputStream(bzout)) { Files.walkFileTree(root, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (dockerIgnorePathMatcher.matches(dir)) { return FileVisitResult.SKIP_SUBTREE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (dockerIgnorePathMatcher.matches(file)) { return FileVisitResult.SKIP_SUBTREE; } final Path relativePath = root.relativize(file); final TarArchiveEntry entry = new TarArchiveEntry(file.toFile()); entry.setName(relativePath.toString()); entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE); entry.setSize(attrs.size()); tout.putArchiveEntry(entry); Files.copy(file, tout); tout.closeArchiveEntry(); return FileVisitResult.CONTINUE; } }); fout.flush(); } return fromTar(tempFile.getAbsolutePath()); } catch (IOException e) { throw DockerClientException.launderThrowable(e); } }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.FilePackager.java
private void copyFileToArchive(final TarArchiveOutputStream out, final String tempFilename, final String filename) throws IOException { if (StringUtils.isEmpty(tempFilename)) { return;// ww w . j a va 2 s.c om } final byte[] buffer = new byte[1024]; final File file = new File(tempFilename); if (!file.exists()) { throw new IOException("File does not exist: " + tempFilename); } final TarArchiveEntry tarAdd = new TarArchiveEntry(file); tarAdd.setModTime(file.lastModified()); tarAdd.setName(filename); out.putArchiveEntry(tarAdd); FileInputStream in = null; try { in = new FileInputStream(file); int nRead = in.read(buffer, 0, buffer.length); while (nRead >= 0) { out.write(buffer, 0, nRead); nRead = in.read(buffer, 0, buffer.length); } } finally { if (in != null) { in.close(); } } out.closeArchiveEntry(); }
From source file:gov.nih.nci.ncicb.tcga.dcc.dam.processors.FilePackager.java
void makeArchive(final String readmeTempFilename) throws IOException { final byte[] buffer = new byte[1024]; File archiveFile = null;//w w w . j av a2 s . c o m TarArchiveOutputStream out = null; //in case we need to write to an external server final String archiveName = prefixPathForExternalServer( filePackagerBean.getArchivePhysicalName() + ".tar.gz"); try { archiveFile = new File(archiveName); out = makeTarGzOutputStream(archiveFile); copyManifestToArchive(out); copyReadmeToArchive(out, readmeTempFilename); int i = 0; for (final DataFile fileInfo : filePackagerBean.getSelectedFiles()) { final File file = new File(fileInfo.getPath()); if (!file.exists()) { throw new IOException("Data file does not exist: " + fileInfo.getPath()); } logger.logToLogger(Level.DEBUG, "tarring file " + (++i) + ":" + fileInfo.getPath() + " into " + archiveName); //"synthetic" file path, as we want it to appear in the tar final String archiveFilePath = constructInternalFilePath(fileInfo); final TarArchiveEntry tarAdd = new TarArchiveEntry(file); tarAdd.setModTime(file.lastModified()); tarAdd.setName(archiveFilePath); out.putArchiveEntry(tarAdd); FileInputStream in = null; try { in = new FileInputStream(file); int nRead = in.read(buffer, 0, buffer.length); while (nRead >= 0) { out.write(buffer, 0, nRead); nRead = in.read(buffer, 0, buffer.length); } } finally { if (in != null) { in.close(); } } out.closeArchiveEntry(); if (fileInfo.getCacheFileToGenerate() != null) { //a special case where there should be a cache file but it doesn't exist - // Send email with error message //filePackagerFactory.getErrorMailSender().send(Messages.CACHE_ERROR, MessageFormat.format(Messages.CACHE_FILE_NOT_FOUND, fileInfo.getCacheFileToGenerate())); } } } catch (IOException ex) { //delete the out file if it exists if (out != null) { out.close(); out = null; } if (archiveFile != null && archiveFile.exists()) { // give OS time to delete file handle try { Thread.sleep(100); } catch (InterruptedException ie) { // it's ok } // keep track of uncompressed size this.actualUncompressedSize = archiveFile.length(); //noinspection ResultOfMethodCallIgnored archiveFile.delete(); } throw ex; } finally { if (out != null) { out.close(); } } logger.logToLogger(Level.DEBUG, "Created tar " + archiveName); }
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 om 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:org.eclipse.orion.server.docker.server.DockerFile.java
/** * Get the tar file containing the Dockerfile that can be sent to the Docker * build API to create an image. /*from w w w . j a va 2 s . com*/ * * @return The tar file. */ public File getTarFile() { try { // get the temporary folder location. String tmpDirName = System.getProperty("java.io.tmpdir"); File tmpDir = new File(tmpDirName); if (!tmpDir.exists() || !tmpDir.isDirectory()) { if (logger.isDebugEnabled()) { logger.error("Cannot find the default temporary-file directory: " + tmpDirName); } return null; } // get a temporary folder name long n = random.nextLong(); n = (n == Long.MIN_VALUE) ? 0 : Math.abs(n); String tmpDirStr = Long.toString(n); tempFolder = new File(tmpDir, tmpDirStr); if (!tempFolder.mkdir()) { if (logger.isDebugEnabled()) { logger.error("Cannot create a temporary directory at " + tempFolder.toString()); } return null; } if (logger.isDebugEnabled()) { logger.debug("Dockerfile: Created a temporary directory at " + tempFolder.toString()); } // create the Dockerfile dockerfile = new File(tempFolder, "Dockerfile"); FileOutputStream fileOutputStream = new FileOutputStream(dockerfile); Charset utf8 = Charset.forName("UTF-8"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, utf8); outputStreamWriter.write(getDockerfileContent()); outputStreamWriter.flush(); outputStreamWriter.close(); fileOutputStream.close(); dockerTarFile = new File(tempFolder, "Dockerfile.tar"); TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream( new FileOutputStream(dockerTarFile)); tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); TarArchiveEntry tarEntry = new TarArchiveEntry(dockerfile); tarEntry.setName(dockerfile.getName()); tarArchiveOutputStream.putArchiveEntry(tarEntry); FileInputStream fileInputStream = new FileInputStream(dockerfile); BufferedInputStream inputStream = new BufferedInputStream(fileInputStream); byte[] buffer = new byte[4096]; int bytes_read; while ((bytes_read = inputStream.read(buffer)) != -1) { tarArchiveOutputStream.write(buffer, 0, bytes_read); } inputStream.close(); tarArchiveOutputStream.closeArchiveEntry(); tarArchiveOutputStream.close(); if (logger.isDebugEnabled()) { logger.debug("Dockerfile: Created a docker tar file at " + dockerTarFile.toString()); } return dockerTarFile; } catch (IOException e) { logger.error(e.getLocalizedMessage(), e); } return null; }
From source file:org.jclouds.docker.compute.features.internal.Archives.java
public static File tar(File baseDir, String archivePath) throws IOException { // Check that the directory is a directory, and get its contents checkArgument(baseDir.isDirectory(), "%s is not a directory", baseDir); File[] files = baseDir.listFiles(); File tarFile = new File(archivePath); String token = getLast(Splitter.on("/").split(archivePath.substring(0, archivePath.lastIndexOf("/")))); byte[] buf = new byte[1024]; int len;//w w w. j a va 2 s.c o m TarArchiveOutputStream tos = new TarArchiveOutputStream(new FileOutputStream(tarFile)); tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (File file : files) { TarArchiveEntry tarEntry = new TarArchiveEntry(file); tarEntry.setName("/" + getLast(Splitter.on(token).split(file.toString()))); tos.putArchiveEntry(tarEntry); if (!file.isDirectory()) { FileInputStream fin = new FileInputStream(file); BufferedInputStream in = new BufferedInputStream(fin); while ((len = in.read(buf)) != -1) { tos.write(buf, 0, len); } in.close(); } tos.closeArchiveEntry(); } tos.close(); return tarFile; }