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

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Get this entry's name.

Usage

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

public static boolean entryExistsInTargz(File targz, String entryName) throws IOException {
    FileInputStream fin = null;//from w w  w.j  a  v  a  2s  .  com
    CompressorInputStream zipIn = null;
    TarArchiveInputStream tarIn = null;
    boolean exists = false;
    try {
        fin = new FileInputStream(targz);
        zipIn = new CompressorStreamFactory().createCompressorInputStream(CompressorStreamFactory.GZIP, fin);
        tarIn = new TarArchiveInputStream(zipIn);

        TarArchiveEntry entry = tarIn.getNextTarEntry();
        while (entry != null) {
            if (entry.getName().equals(entryName)) {
                exists = true;
                break;
            }
            entry = tarIn.getNextTarEntry();
        }
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        close(zipIn);
        close(tarIn);
        close(fin);
    }
    return exists;
}

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

/**
 * Logs contents of a TAR file./*  w  w  w .ja  va  2 s  .c o m*/
 *
 * @param tarFile the TAR file
 *
 * @throws IOException on error
 */
public void logTarFileContents(File tarFile) throws IOException {
    TarArchiveInputStream tarArchiveInputStream = null;

    try {
        tarArchiveInputStream = new TarArchiveInputStream(new FileInputStream(tarFile));
        TarArchiveEntry entry;

        LOGGER.info(String.format("Listing the contents of \"%s\" TAR archive file:", tarFile.getPath()));

        while (null != (entry = tarArchiveInputStream.getNextTarEntry())) {
            LOGGER.info(String.format("    %s", entry.getName()));
        }
    } finally {
        if (tarArchiveInputStream != null) {
            tarArchiveInputStream.close();
        }
    }
}

From source file:org.fuin.esmp.EventStoreDownloadMojo.java

private void unTarGz(final File archive, final File destDir) throws MojoExecutionException {

    try {/*from   w w w  . ja v a2  s . c  o  m*/
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(archive))));
        try {
            TarArchiveEntry entry;
            while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
                LOG.info("Extracting: " + entry.getName());
                final File file = new File(destDir, entry.getName());
                if (entry.isDirectory()) {
                    createIfNecessary(file);
                } else {
                    int count;
                    final byte[] data = new byte[MB];
                    final FileOutputStream fos = new FileOutputStream(file);
                    final BufferedOutputStream dest = new BufferedOutputStream(fos, MB);
                    try {
                        while ((count = tarIn.read(data, 0, MB)) != -1) {
                            dest.write(data, 0, count);
                        }
                    } finally {
                        dest.close();
                    }
                    entry.getMode();
                }
                applyFileMode(file, new FileMode(entry.getMode()));
            }
        } finally {
            tarIn.close();
        }
    } catch (final IOException ex) {
        throw new MojoExecutionException("Error uncompressing event store archive: " + archive, ex);
    }
}

From source file:org.fuin.owndeb.commons.DebUtils.java

/**
 * Reads the first folder found from TAR.GZ file.
 * // www  .jav  a  2  s.co m
 * @param tarGzFile
 *            Archive file to peek the first folder from.
 * 
 * @return The first directory name or <code>null</code> if the archive only
 *         contains files (no folders).
 */
@Nullable
public static String peekFirstTarGzFolderName(@NotNull final File tarGzFile) {
    Contract.requireArgNotNull("tarGzFile", tarGzFile);

    try {
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(
                new GzipCompressorInputStream(new BufferedInputStream(new FileInputStream(tarGzFile))));
        try {
            TarArchiveEntry entry;
            while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {
                if (entry.isDirectory()) {
                    return entry.getName();
                }
            }
        } finally {
            tarIn.close();
        }
        return null;
    } catch (final IOException ex) {
        throw new RuntimeException("Error uncompressing archive: " + tarGzFile, ex);
    }
}

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

private UnpackResult unpack(CacheableEntity entity, TarArchiveInputStream tarInput,
        OriginReader readOriginAction) throws IOException {
    ImmutableMap.Builder<String, CacheableTree> treesBuilder = ImmutableMap.builder();
    entity.visitTrees((name, type, root) -> {
        if (root != null) {
            treesBuilder.put(name, new CacheableTree(type, root));
        }//ww  w. j  ava 2s.c  o  m
    });
    ImmutableMap<String, CacheableTree> treesByName = treesBuilder.build();

    TarArchiveEntry tarEntry;
    OriginMetadata originMetadata = null;
    Map<String, FileSystemLocationSnapshot> snapshots = new HashMap<String, FileSystemLocationSnapshot>();

    tarEntry = tarInput.getNextTarEntry();
    MutableLong entries = new MutableLong();
    while (tarEntry != null) {
        entries.increment(1);
        String path = tarEntry.getName();

        if (path.equals(METADATA_PATH)) {
            // handle origin metadata
            originMetadata = readOriginAction.execute(new CloseShieldInputStream(tarInput));
            tarEntry = tarInput.getNextTarEntry();
        } else {
            // handle tree
            Matcher matcher = TREE_PATH.matcher(path);
            if (!matcher.matches()) {
                throw new IllegalStateException("Cached entry format error, invalid contents: " + path);
            }

            String treeName = unescape(matcher.group(2));
            CacheableTree tree = treesByName.get(treeName);
            if (tree == null) {
                throw new IllegalStateException(String.format("No tree '%s' registered", treeName));
            }

            boolean missing = matcher.group(1) != null;
            String childPath = matcher.group(3);
            tarEntry = unpackTree(treeName, tree.getType(), tree.getRoot(), tarInput, tarEntry, childPath,
                    missing, snapshots, entries);
        }
    }
    if (originMetadata == null) {
        throw new IllegalStateException("Cached result format error, no origin metadata was found.");
    }

    return new UnpackResult(originMetadata, entries.get(), snapshots);
}

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

@Nullable
private TarArchiveEntry unpackDirectoryTree(TarArchiveInputStream input, TarArchiveEntry rootEntry,
        Map<String, FileSystemLocationSnapshot> snapshots, MutableLong entries, File treeRoot, String treeName)
        throws IOException {
    RelativePathParser parser = new RelativePathParser();
    parser.rootPath(rootEntry.getName());

    MerkleDirectorySnapshotBuilder builder = MerkleDirectorySnapshotBuilder.noSortingRequired();
    String rootPath = stringInterner.intern(treeRoot.getAbsolutePath());
    String rootDirName = stringInterner.intern(treeRoot.getName());
    builder.preVisitDirectory(rootPath, rootDirName);

    TarArchiveEntry entry;/*  ww w  . ja va2  s  .c o  m*/

    while ((entry = input.getNextTarEntry()) != null) {
        entries.increment(1);
        boolean isDir = entry.isDirectory();
        int directoriesLeft = parser.nextPath(entry.getName(), isDir);
        for (int i = 0; i < directoriesLeft; i++) {
            builder.postVisitDirectory();
        }
        if (parser.getDepth() == 0) {
            break;
        }

        File file = new File(treeRoot, parser.getRelativePath());
        if (isDir) {
            FileUtils.forceMkdir(file);
            chmodUnpackedFile(entry, file);
            String internedAbsolutePath = stringInterner.intern(file.getAbsolutePath());
            String indernedDirName = stringInterner.intern(parser.getName());
            builder.preVisitDirectory(internedAbsolutePath, indernedDirName);
        } else {
            RegularFileSnapshot fileSnapshot = unpackFile(input, entry, file, parser.getName());
            builder.visit(fileSnapshot);
        }
    }

    for (int i = 0; i < parser.getDepth(); i++) {
        builder.postVisitDirectory();
    }

    snapshots.put(treeName, builder.getResult());
    return entry;
}

From source file:org.gradle.caching.internal.tasks.CommonsTarPacker.java

@Override
public void unpack(DataSource input, DataTargetFactory targetFactory) throws IOException {
    TarArchiveInputStream tarInput = new TarArchiveInputStream(input.openInput());
    while (true) {
        TarArchiveEntry entry = tarInput.getNextTarEntry();
        if (entry == null) {
            break;
        }//ww  w  . ja  v a  2s.  c o  m
        PackerUtils.unpackEntry(entry.getName(), tarInput, buffer, targetFactory);
    }
    tarInput.close();
}

From source file:org.gridgain.testsuites.bamboo.GridHadoopTestSuite.java

/**
 *  Downloads and extracts an Apache product.
 *
 * @param appName Name of application for log messages.
 * @param homeVariable Pointer to home directory of the component.
 * @param downloadPath Relative download path of tar package.
 * @param destName Local directory name to install component.
 * @throws Exception If failed./*from  w  w w. j a  v  a2s .co  m*/
 */
private static void download(String appName, String homeVariable, String downloadPath, String destName)
        throws Exception {
    String homeVal = GridSystemProperties.getString(homeVariable);

    if (!F.isEmpty(homeVal) && new File(homeVal).isDirectory()) {
        X.println(homeVariable + " is set to: " + homeVal);

        return;
    }

    List<String> urls = F.asList("http://apache-mirror.rbc.ru/pub/apache/", "http://www.eu.apache.org/dist/",
            "http://www.us.apache.org/dist/");

    String tmpPath = System.getProperty("java.io.tmpdir");

    X.println("tmp: " + tmpPath);

    File install = new File(tmpPath + File.separatorChar + "__hadoop");

    File home = new File(install, destName);

    X.println("Setting " + homeVariable + " to " + home.getAbsolutePath());

    System.setProperty(homeVariable, home.getAbsolutePath());

    File successFile = new File(home, "__success");

    if (home.exists()) {
        if (successFile.exists()) {
            X.println(appName + " distribution already exists.");

            return;
        }

        X.println(appName + " distribution is invalid and it will be deleted.");

        if (!U.delete(home))
            throw new IOException("Failed to delete directory: " + install.getAbsolutePath());
    }

    for (String url : urls) {
        if (!(install.exists() || install.mkdirs()))
            throw new IOException("Failed to create directory: " + install.getAbsolutePath());

        URL u = new URL(url + downloadPath);

        X.println("Attempting to download from: " + u);

        try {
            URLConnection c = u.openConnection();

            c.connect();

            try (TarArchiveInputStream in = new TarArchiveInputStream(
                    new GzipCompressorInputStream(new BufferedInputStream(c.getInputStream(), 32 * 1024)))) {

                TarArchiveEntry entry;

                while ((entry = in.getNextTarEntry()) != null) {
                    File dest = new File(install, entry.getName());

                    if (entry.isDirectory()) {
                        if (!dest.mkdirs())
                            throw new IllegalStateException();
                    } else {
                        File parent = dest.getParentFile();

                        if (!(parent.exists() || parent.mkdirs()))
                            throw new IllegalStateException();

                        X.print(" [" + dest);

                        try (BufferedOutputStream out = new BufferedOutputStream(
                                new FileOutputStream(dest, false), 128 * 1024)) {
                            U.copy(in, out);

                            out.flush();
                        }

                        Files.setPosixFilePermissions(dest.toPath(), modeToPermissionSet(entry.getMode()));

                        X.println("]");
                    }
                }
            }

            if (successFile.createNewFile())
                return;
        } catch (Exception e) {
            e.printStackTrace();

            U.delete(install);
        }
    }

    throw new IllegalStateException("Failed to install " + appName + ".");
}

From source file:org.jboss.qa.jenkins.test.executor.utils.unpack.GUnZipper.java

@Override
public void unpack(File archive, File destination) throws IOException {
    try (FileInputStream in = new FileInputStream(archive);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn)) {
        final Set<TarArchiveEntry> entries = getEntries(tarIn);

        if (ignoreRootFolders) {
            pathSegmentsToTrim = countRootFolders(entries);
        }//from   w ww.ja va  2 s  . c  om

        for (TarArchiveEntry entry : entries) {
            if (entry.isDirectory()) {
                continue;
            }

            final File file = new File(destination, trimPathSegments(entry.getName(), pathSegmentsToTrim));
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            try (FileOutputStream fos = new FileOutputStream(file)) {
                IOUtils.copy(tarIn, fos);

                // check for user-executable bit on entry and apply to file
                if ((entry.getMode() & 0100) != 0) {
                    file.setExecutable(true);
                }
            }
        }
    }
}

From source file:org.jboss.tools.openshift.reddeer.utils.FileHelper.java

public static void extractTarGz(File archive, File outputDirectory) {
    InputStream inputStream = null;
    try {/*from   ww  w  .  ja  v a  2  s.  c  o m*/
        logger.info("Opening stream to gzip archive");
        inputStream = new GzipCompressorInputStream(new FileInputStream(archive));
    } catch (IOException ex) {
        throw new OpenShiftToolsException(
                "Exception occured while processing tar.gz file.\n" + ex.getMessage());
    }

    logger.info("Opening stream to tar archive");
    BufferedOutputStream outputStream = null;
    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(inputStream);
    TarArchiveEntry currentEntry = null;
    try {
        while ((currentEntry = tarArchiveInputStream.getNextTarEntry()) != null) {
            if (currentEntry.isDirectory()) {
                logger.info("Creating directory: " + currentEntry.getName());
                createDirectory(new File(outputDirectory, currentEntry.getName()));
            } else {
                File outputFile = new File(outputDirectory, currentEntry.getName());
                if (!outputFile.getParentFile().exists()) {
                    logger.info("Creating directory: " + outputFile.getParentFile());
                    createDirectory(outputFile.getParentFile());
                }

                outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

                logger.info("Extracting file: " + currentEntry.getName());
                copy(tarArchiveInputStream, outputStream, (int) currentEntry.getSize());
                outputStream.close();

                outputFile.setExecutable(true);
                outputFile.setReadable(true);
                outputFile.setWritable(true);
            }
        }
    } catch (IOException e) {
        throw new OpenShiftToolsException("Exception occured while processing tar.gz file.\n" + e.getMessage());
    } finally {
        try {
            tarArchiveInputStream.close();
        } catch (Exception ex) {
        }
        try {
            outputStream.close();
        } catch (Exception ex) {
        }
    }
}