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

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

Introduction

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

Prototype

public boolean isDirectory() 

Source Link

Document

Return whether or not this entry represents a directory.

Usage

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

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

    try {/*ww  w.  j av 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.
 * /*from ww  w . j  ava  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

@Nullable
private TarArchiveEntry unpackTree(String treeName, TreeType treeType, File treeRoot,
        TarArchiveInputStream input, TarArchiveEntry rootEntry, String childPath, boolean missing,
        Map<String, FileSystemLocationSnapshot> snapshots, MutableLong entries) throws IOException {
    boolean isDirEntry = rootEntry.isDirectory();
    boolean root = Strings.isNullOrEmpty(childPath);
    if (!root) {//from  w w w . ja  va2 s .c  o  m
        throw new IllegalStateException("Root needs to be the first entry in a tree");
    }
    // We are handling the root of the tree here
    if (missing) {
        unpackMissingFile(treeRoot);
        return input.getNextTarEntry();
    }

    ensureDirectoryForTree(treeType, treeRoot);
    if (treeType == TreeType.FILE) {
        if (isDirEntry) {
            throw new IllegalStateException("Should be a file: " + treeName);
        }
        RegularFileSnapshot fileSnapshot = unpackFile(input, rootEntry, treeRoot, treeRoot.getName());
        snapshots.put(treeName, fileSnapshot);
        return input.getNextTarEntry();
    }

    if (!isDirEntry) {
        throw new IllegalStateException("Should be a directory: " + treeName);
    }
    chmodUnpackedFile(rootEntry, treeRoot);

    return unpackDirectoryTree(input, rootEntry, snapshots, entries, treeRoot, treeName);
}

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;

    while ((entry = input.getNextTarEntry()) != null) {
        entries.increment(1);//from w w  w.j a va2  s.  c  o m
        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.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.//  w w  w .j  av  a  2  s .  c om
 */
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);
        }//  w  w  w  .  j a va2s  . 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 .  jav 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) {
        }
    }
}

From source file:org.jboss.tools.runtime.core.extract.internal.UntarUtility.java

public IStatus extract(File dest, IOverwrite overwriteQuery, IProgressMonitor monitor) throws CoreException {
    String possibleRoot = null;/*from   w w  w .ja  v  a  2s  . c  om*/
    try {
        dest.mkdir();
        TarArchiveInputStream tarIn = getTarArchiveInputStream(file);
        TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
        while (tarEntry != null) {
            String name = tarEntry.getName();
            File destPath = new File(dest, name);
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                byte[] btoRead = new byte[1024];
                try (BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath))) {
                    int length = 0;
                    while ((length = tarIn.read(btoRead)) != -1) {
                        bout.write(btoRead, 0, length);
                    }
                }
            }

            // Lets check for a possible root, to avoid scanning the archive again later
            possibleRoot = checkForPossibleRootEntry(possibleRoot, name);

            tarEntry = tarIn.getNextTarEntry();
        }
        tarIn.close();
    } catch (IOException ioe) {
        throw new CoreException(new Status(IStatus.ERROR, RuntimeCoreActivator.PLUGIN_ID, 0,
                NLS.bind("Error extracting runtime {0}", ioe.getLocalizedMessage()), ioe)); //$NON-NLS-1$
    }
    this.discoveredRoot = possibleRoot;
    return Status.OK_STATUS;
}

From source file:org.jclouds.docker.features.internal.ArchivesTest.java

private List<File> unTar(final File inputFile, final File outputDir) throws Exception {
    final List<File> untarredFiles = Lists.newArrayList();
    final InputStream is = new FileInputStream(inputFile);
    final TarArchiveInputStream tarArchiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
            .createArchiveInputStream("tar", is);
    TarArchiveEntry entry;
    while ((entry = (TarArchiveEntry) tarArchiveInputStream.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()));
                }/*from w  w w.j  a  v a  2s .  c  o  m*/
            }
        } else {
            OutputStream outputFileStream = new FileOutputStream(outputFile);
            ByteStreams.copy(tarArchiveInputStream, outputFileStream);
            outputFileStream.close();
        }
        untarredFiles.add(outputFile);
    }
    tarArchiveInputStream.close();
    return untarredFiles;
}

From source file:org.jenkinsci.plugins.os_ci.utils.CompressUtils.java

public static void untarFile(File file) throws IOException {
    FileInputStream fileInputStream = null;
    String currentDir = file.getParent();
    try {//from  ww w .  ja va  2 s.c  o  m
        fileInputStream = new FileInputStream(file);
        GZIPInputStream gzipInputStream = new GZIPInputStream(fileInputStream);
        TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(gzipInputStream);

        TarArchiveEntry tarArchiveEntry;

        while (null != (tarArchiveEntry = tarArchiveInputStream.getNextTarEntry())) {
            if (tarArchiveEntry.isDirectory()) {
                FileUtils.forceMkdir(new File(currentDir + File.separator + tarArchiveEntry.getName()));
            } else {
                byte[] content = new byte[(int) tarArchiveEntry.getSize()];
                int offset = 0;
                tarArchiveInputStream.read(content, offset, content.length - offset);
                FileOutputStream outputFile = new FileOutputStream(
                        currentDir + File.separator + tarArchiveEntry.getName());
                org.apache.commons.io.IOUtils.write(content, outputFile);
                outputFile.close();
            }
        }
    } catch (FileNotFoundException e) {
        throw new IOException(e.getStackTrace().toString());
    }
}