Example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry TarArchiveEntry

List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry TarArchiveEntry

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry TarArchiveEntry.

Prototype

public TarArchiveEntry(File file, String fileName) 

Source Link

Document

Construct an entry for a file.

Usage

From source file:org.cloudifysource.esc.util.TarGzUtils.java

private static void addFileToTarGz(final TarArchiveOutputStream tOut, final String path, final String base,
        final boolean addRoot) throws IOException {
    File f = new File(path);
    String entryName = base + f.getName();

    if (f.isFile()) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
        tOut.putArchiveEntry(tarEntry);/*from   w  ww. java 2s .  c o  m*/
        IOUtils.copy(new FileInputStream(f), tOut);
        tOut.closeArchiveEntry();
    } else {
        if (addRoot) {
            TarArchiveEntry tarEntry = new TarArchiveEntry(f, entryName);
            tOut.putArchiveEntry(tarEntry);
            tOut.closeArchiveEntry();
        }
        File[] children = f.listFiles();
        if (children != null) {
            for (File child : children) {
                if (addRoot) {
                    addFileToTarGz(tOut, child.getAbsolutePath(), entryName + "/", true);
                } else {
                    addFileToTarGz(tOut, child.getAbsolutePath(), "", true);
                }
            }
        }
    }
}

From source file:org.codehaus.plexus.archiver.tar.TarArchiver.java

/**
 * tar a file/*w ww .jav  a2  s .  c  o  m*/
 *
 * @param entry the file to tar
 * @param tOut  the output stream
 * @param vPath the path name of the file to tar
 * @throws IOException on error
 */
protected void tarFile(ArchiveEntry entry, TarArchiveOutputStream tOut, String vPath)
        throws ArchiverException, IOException {

    // don't add "" to the archive
    if (vPath.length() <= 0) {
        return;
    }

    if (entry.getResource().isDirectory() && !vPath.endsWith("/")) {
        vPath += "/";
    }

    if (vPath.startsWith("/") && !options.getPreserveLeadingSlashes()) {
        int l = vPath.length();
        if (l <= 1) {
            // we would end up adding "" to the archive
            return;
        }
        vPath = vPath.substring(1, l);
    }

    int pathLength = vPath.length();
    InputStream fIn = null;

    try {
        TarArchiveEntry te;
        if (!longFileMode.isGnuMode()
                && pathLength >= org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN) {
            int maxPosixPathLen = org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN
                    + org.apache.commons.compress.archivers.tar.TarConstants.PREFIXLEN;
            if (longFileMode.isPosixMode()) {
            } else if (longFileMode.isPosixWarnMode()) {
                if (pathLength > maxPosixPathLen) {
                    getLogger().warn("Entry: " + vPath + " longer than " + maxPosixPathLen + " characters.");
                    if (!longWarningGiven) {
                        getLogger().warn("Resulting tar file can only be processed "
                                + "successfully by GNU compatible tar commands");
                        longWarningGiven = true;
                    }
                }
            } else if (longFileMode.isOmitMode()) {
                getLogger().info("Omitting: " + vPath);
                return;
            } else if (longFileMode.isWarnMode()) {
                getLogger().warn("Entry: " + vPath + " longer than "
                        + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + " characters.");
                if (!longWarningGiven) {
                    getLogger().warn("Resulting tar file can only be processed "
                            + "successfully by GNU compatible tar commands");
                    longWarningGiven = true;
                }
            } else if (longFileMode.isFailMode()) {
                throw new ArchiverException("Entry: " + vPath + " longer than "
                        + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + " characters.");
            } else {
                throw new IllegalStateException("Non gnu mode should never get here?");
            }
        }

        if (entry.getType() == ArchiveEntry.SYMLINK) {
            final SymlinkDestinationSupplier plexusIoSymlinkResource = (SymlinkDestinationSupplier) entry
                    .getResource();
            te = new TarArchiveEntry(vPath, TarArchiveEntry.LF_SYMLINK);
            te.setLinkName(plexusIoSymlinkResource.getSymlinkDestination());
        } else {
            te = new TarArchiveEntry(vPath);
        }

        long teLastModified = entry.getResource().getLastModified();
        te.setModTime(teLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ? System.currentTimeMillis()
                : teLastModified);

        if (entry.getType() == ArchiveEntry.SYMLINK) {
            te.setSize(0);

        } else if (!entry.getResource().isDirectory()) {
            final long size = entry.getResource().getSize();
            te.setSize(size == PlexusIoResource.UNKNOWN_RESOURCE_SIZE ? 0 : size);
        }
        te.setMode(entry.getMode());

        PlexusIoResourceAttributes attributes = entry.getResourceAttributes();

        te.setUserName((attributes != null && attributes.getUserName() != null) ? attributes.getUserName()
                : options.getUserName());
        te.setGroupName((attributes != null && attributes.getGroupName() != null) ? attributes.getGroupName()
                : options.getGroup());

        final int userId = (attributes != null && attributes.getUserId() != null) ? attributes.getUserId()
                : options.getUid();
        if (userId >= 0) {
            te.setUserId(userId);
        }

        final int groupId = (attributes != null && attributes.getGroupId() != null) ? attributes.getGroupId()
                : options.getGid();
        if (groupId >= 0) {
            te.setGroupId(groupId);
        }

        tOut.putArchiveEntry(te);

        try {
            if (entry.getResource().isFile() && !(entry.getType() == ArchiveEntry.SYMLINK)) {
                fIn = entry.getInputStream();

                Streams.copyFullyDontCloseOutput(fIn, tOut, "xAR");
            }

        } catch (Throwable e) {
            getLogger().warn("When creating tar entry", e);
        } finally {
            tOut.closeArchiveEntry();
        }
    } finally {
        IOUtil.close(fIn);
    }
}

From source file:org.dataconservancy.packaging.tool.impl.generator.BagItPackageAssembler.java

private void addFilesToArchive(ArchiveOutputStream taos, File file) throws IOException {
    // Create an entry for the file
    //taos.putArchiveEntry(new TarArchiveEntry(file, file.getParentFile().toURI().relativize(file.toURI()).toString()));
    switch (archivingFormat) {
    case ArchiveStreamFactory.TAR:
        taos.putArchiveEntry(new TarArchiveEntry(file, FilenameUtils.separatorsToUnix(
                Paths.get(packageLocationDir.getPath()).relativize(Paths.get(file.getPath())).toString())));
        break;/*w w w . j a va2 s.  c  o  m*/
    case ArchiveStreamFactory.ZIP:
        taos.putArchiveEntry(new ZipArchiveEntry(file, FilenameUtils.separatorsToUnix(
                Paths.get(packageLocationDir.getPath()).relativize(Paths.get(file.getPath())).toString())));
        break;
    case ArchiveStreamFactory.JAR:
        taos.putArchiveEntry(new JarArchiveEntry(new ZipArchiveEntry(file, FilenameUtils.separatorsToUnix(
                Paths.get(packageLocationDir.getPath()).relativize(Paths.get(file.getPath())).toString()))));
        break;
    case ArchiveStreamFactory.AR:
        taos.putArchiveEntry(new ArArchiveEntry(file, FilenameUtils.separatorsToUnix(
                Paths.get(packageLocationDir.getPath()).relativize(Paths.get(file.getPath())).toString())));
        break;
    case ArchiveStreamFactory.CPIO:
        taos.putArchiveEntry(new CpioArchiveEntry(file, FilenameUtils.separatorsToUnix(
                Paths.get(packageLocationDir.getPath()).relativize(Paths.get(file.getPath())).toString())));
        break;
    }
    if (file.isFile()) {
        // Add the file to the archive
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(bis, taos);
        taos.closeArchiveEntry();
        bis.close();
    } else if (file.isDirectory()) {
        // close the archive entry
        taos.closeArchiveEntry();
        // go through all the files in the directory and using recursion, add them to the archive
        for (File childFile : file.listFiles()) {
            addFilesToArchive(taos, childFile);
        }
    }
}

From source file:org.eclipse.jgit.archive.TarFormat.java

public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader)
        throws IOException {
    if (mode == FileMode.SYMLINK) {
        final TarArchiveEntry entry = new TarArchiveEntry(path, TarConstants.LF_SYMLINK);
        entry.setLinkName(new String(loader.getCachedBytes(100), "UTF-8")); //$NON-NLS-1$
        out.putArchiveEntry(entry);/*from  w ww .j  ava 2  s  .  c o  m*/
        out.closeArchiveEntry();
        return;
    }

    // TarArchiveEntry detects directories by checking
    // for '/' at the end of the filename.
    if (path.endsWith("/") && mode != FileMode.TREE) //$NON-NLS-1$
        throw new IllegalArgumentException(
                MessageFormat.format(ArchiveText.get().pathDoesNotMatchMode, path, mode));
    if (!path.endsWith("/") && mode == FileMode.TREE) //$NON-NLS-1$
        path = path + "/"; //$NON-NLS-1$

    final TarArchiveEntry entry = new TarArchiveEntry(path);
    if (mode == FileMode.TREE) {
        out.putArchiveEntry(entry);
        out.closeArchiveEntry();
        return;
    }

    if (mode == FileMode.REGULAR_FILE) {
        // ok
    } else if (mode == FileMode.EXECUTABLE_FILE) {
        entry.setMode(mode.getBits());
    } else {
        // Unsupported mode (e.g., GITLINK).
        throw new IllegalArgumentException(MessageFormat.format(ArchiveText.get().unsupportedMode, mode));
    }
    entry.setSize(loader.getSize());
    out.putArchiveEntry(entry);
    loader.copyTo(out);
    out.closeArchiveEntry();
}

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiver.java

private TarArchiveEntry createTarEntry(File tarRootDir, File source) throws IOException {
    String pathInTar = slashify(tarRootDir.toPath().relativize(source.toPath()));
    log.debug("Adding entry " + pathInTar);
    TarArchiveEntry tarEntry;/*from w  w w  .ja v a  2  s  .  c om*/
    if (isSymbolicLink(source) && resolvesBelow(source, tarRootDir)) {
        // only create symlink entry if link target is inside archive
        tarEntry = new TarArchiveEntry(pathInTar, TarArchiveEntry.LF_SYMLINK);
        tarEntry.setLinkName(slashify(getRelativeSymLinkTarget(source, source.getParentFile())));
    } else {
        tarEntry = new TarArchiveEntry(source, pathInTar);
    }
    PosixFileAttributes attrs = getAttributes(source);
    if (attrs != null) {
        tarEntry.setUserName(attrs.owner().getName());
        tarEntry.setGroupName(attrs.group().getName());
        tarEntry.setMode(FilePermissionHelper.toOctalFileMode(attrs.permissions()));
    }
    tarEntry.setModTime(source.lastModified());
    return tarEntry;
}

From source file:org.fabrician.maven.plugins.CompressUtils.java

private static ArchiveEntry createArchiveEntry(File f, String name, OutputStream out, String alternateBaseDir) {
    String substitutedName = substituteAlternateBaseDir(name, f.isDirectory(), alternateBaseDir);
    if (out instanceof TarArchiveOutputStream) {
        return new TarArchiveEntry(f, substitutedName);
    } else {//www .j  a  v a  2s . c  o m
        return new ZipArchiveEntry(f, substitutedName);
    }
}

From source file:org.finra.herd.service.helper.TarHelper.java

/**
 * Adds a TAR archive entry to the specified TAR archive stream. The method calls itself recursively for all directories/files found.
 *
 * @param tarArchiveOutputStream the TAR output stream that writes a UNIX tar archive as an output stream
 * @param path the path relative to the base for a directory or file to be added to the TAR archive stream
 * @param base the base for the directory or file path
 *
 * @throws IOException on error//  w  w  w . j a  va 2s  .  c  om
 */
private void addEntryToTarArchive(TarArchiveOutputStream tarArchiveOutputStream, Path path, Path base)
        throws IOException {
    File file = path.toFile();
    Path entry = Paths.get(base.toString(), file.getName());
    TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(file, entry.toString());
    tarArchiveOutputStream.putArchiveEntry(tarArchiveEntry);

    if (file.isFile()) {
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            // TODO: This method uses a default buffer size of 8K.
            // TODO: Taking a file size in consideration, a bigger buffer size we might increase the performance of the tar.
            IOUtils.copy(fileInputStream, tarArchiveOutputStream);
        } finally {
            tarArchiveOutputStream.closeArchiveEntry();
        }
    } else {
        tarArchiveOutputStream.closeArchiveEntry();
        File[] children = file.listFiles();
        if (children != null) {
            for (File child : children) {
                addEntryToTarArchive(tarArchiveOutputStream, Paths.get(child.getAbsolutePath()), entry);
            }
        }
    }
}

From source file:org.gradle.caching.internal.packaging.impl.TarBuildCacheEntryPacker.java

private static void createTarEntry(String path, long size, int mode, TarArchiveOutputStream tarOutput)
        throws IOException {
    TarArchiveEntry entry = new TarArchiveEntry(path, true);
    entry.setSize(size);/*ww  w .ja  v a  2 s  . c om*/
    entry.setMode(mode);
    tarOutput.putArchiveEntry(entry);
}

From source file:org.hyperledger.fabric.sdk.helper.SDKUtil.java

/**
 * Compress the given directory src to target tar.gz file
 * @param src The source directory/*ww w  .  j a  v a  2 s  . c  o m*/
 * @param target The target tar.gz file
 * @throws IOException
 */
public static void generateTarGz(String src, String target) throws IOException {
    File sourceDirectory = new File(src);
    File destinationArchive = new File(target);

    String sourcePath = sourceDirectory.getAbsolutePath();
    FileOutputStream destinationOutputStream = new FileOutputStream(destinationArchive);

    TarArchiveOutputStream archiveOutputStream = new TarArchiveOutputStream(
            new GzipCompressorOutputStream(new BufferedOutputStream(destinationOutputStream)));
    archiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    try {
        Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true);
        childrenFiles.remove(destinationArchive);

        ArchiveEntry archiveEntry;
        FileInputStream fileInputStream;
        for (File childFile : childrenFiles) {
            String childPath = childFile.getAbsolutePath();
            String relativePath = childPath.substring((sourcePath.length() + 1), childPath.length());

            relativePath = FilenameUtils.separatorsToUnix(relativePath);
            archiveEntry = new TarArchiveEntry(childFile, relativePath);
            fileInputStream = new FileInputStream(childFile);
            archiveOutputStream.putArchiveEntry(archiveEntry);

            try {
                IOUtils.copy(fileInputStream, archiveOutputStream);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
                archiveOutputStream.closeArchiveEntry();
            }
        }
    } finally {
        IOUtils.closeQuietly(archiveOutputStream);
    }
}

From source file:org.hyperledger.fabric.sdk.helper.Utils.java

/**
 * Compress the contents of given directory using Tar and Gzip to an in-memory byte array.
 *
 * @param sourceDirectory  the source directory.
 * @param pathPrefix       a path to be prepended to every file name in the .tar.gz output, or {@code null} if no prefix is required.
 * @param chaincodeMetaInf// w  w w .  ja v  a2 s  .  c  o m
 * @return the compressed directory contents.
 * @throws IOException
 */
public static byte[] generateTarGz(File sourceDirectory, String pathPrefix, File chaincodeMetaInf)
        throws IOException {
    logger.trace(format("generateTarGz: sourceDirectory: %s, pathPrefix: %s, chaincodeMetaInf: %s",
            sourceDirectory == null ? "null" : sourceDirectory.getAbsolutePath(), pathPrefix,
            chaincodeMetaInf == null ? "null" : chaincodeMetaInf.getAbsolutePath()));

    ByteArrayOutputStream bos = new ByteArrayOutputStream(500000);

    String sourcePath = sourceDirectory.getAbsolutePath();

    TarArchiveOutputStream archiveOutputStream = new TarArchiveOutputStream(
            new GzipCompressorOutputStream(bos));
    archiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    try {
        Collection<File> childrenFiles = org.apache.commons.io.FileUtils.listFiles(sourceDirectory, null, true);

        ArchiveEntry archiveEntry;
        FileInputStream fileInputStream;
        for (File childFile : childrenFiles) {
            String childPath = childFile.getAbsolutePath();
            String relativePath = childPath.substring((sourcePath.length() + 1), childPath.length());

            if (pathPrefix != null) {
                relativePath = Utils.combinePaths(pathPrefix, relativePath);
            }

            relativePath = FilenameUtils.separatorsToUnix(relativePath);

            if (TRACE_ENABED) {
                logger.trace(format("generateTarGz: Adding '%s' entry from source '%s' to archive.",
                        relativePath, childFile.getAbsolutePath()));
            }

            archiveEntry = new TarArchiveEntry(childFile, relativePath);
            fileInputStream = new FileInputStream(childFile);
            archiveOutputStream.putArchiveEntry(archiveEntry);

            try {
                IOUtils.copy(fileInputStream, archiveOutputStream);
            } finally {
                IOUtils.closeQuietly(fileInputStream);
                archiveOutputStream.closeArchiveEntry();
            }

        }

        if (null != chaincodeMetaInf) {
            childrenFiles = org.apache.commons.io.FileUtils.listFiles(chaincodeMetaInf, null, true);

            final URI metabase = chaincodeMetaInf.toURI();

            for (File childFile : childrenFiles) {

                final String relativePath = Paths
                        .get("META-INF", metabase.relativize(childFile.toURI()).getPath()).toString();

                if (TRACE_ENABED) {
                    logger.trace(format("generateTarGz: Adding '%s' entry from source '%s' to archive.",
                            relativePath, childFile.getAbsolutePath()));
                }

                archiveEntry = new TarArchiveEntry(childFile, relativePath);
                fileInputStream = new FileInputStream(childFile);
                archiveOutputStream.putArchiveEntry(archiveEntry);

                try {
                    IOUtils.copy(fileInputStream, archiveOutputStream);
                } finally {
                    IOUtils.closeQuietly(fileInputStream);
                    archiveOutputStream.closeArchiveEntry();
                }

            }

        }
    } finally {
        IOUtils.closeQuietly(archiveOutputStream);
    }

    return bos.toByteArray();
}