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:co.cask.tigon.sql.internal.StreamBinaryGenerator.java

private void unzipFile(File libZip) throws IOException, ArchiveException {
    String path = libZip.toURI().getPath();
    String outDir = libZip.getParentFile().getPath();
    TarArchiveInputStream archiveInputStream = new TarArchiveInputStream(
            new GZIPInputStream(new FileInputStream(path)));
    try {//w  ww. ja va  2  s .c om
        TarArchiveEntry entry = archiveInputStream.getNextTarEntry();
        while (entry != null) {
            File destFile = new File(outDir, entry.getName());
            destFile.getParentFile().mkdirs();
            if (!entry.isDirectory()) {
                ByteStreams.copy(archiveInputStream, Files.newOutputStreamSupplier(destFile));
                //TODO: Set executable permission based on entry.getMode()
                destFile.setExecutable(true, false);
            }
            entry = archiveInputStream.getNextTarEntry();
        }
    } finally {
        archiveInputStream.close();
    }
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.TarExtractor.java

@Override
protected void extractWithFilter(@NonNull Filter filter) throws IOException {
    long totalBytes = 0;
    List<TarArchiveEntry> archiveEntries = new ArrayList<>();
    TarArchiveInputStream inputStream = new TarArchiveInputStream(new FileInputStream(filePath));

    TarArchiveEntry tarArchiveEntry;

    while ((tarArchiveEntry = inputStream.getNextTarEntry()) != null) {
        if (CompressedHelper.isEntryPathValid(tarArchiveEntry.getName())) {
            if (filter.shouldExtract(tarArchiveEntry.getName(), tarArchiveEntry.isDirectory())) {
                archiveEntries.add(tarArchiveEntry);
                totalBytes += tarArchiveEntry.getSize();
            }/* w  ww .j  ava  2s.co m*/
        } else {
            invalidArchiveEntries.add(tarArchiveEntry.getName());
        }
    }

    listener.onStart(totalBytes, archiveEntries.get(0).getName());

    inputStream.close();
    inputStream = new TarArchiveInputStream(new FileInputStream(filePath));

    for (TarArchiveEntry entry : archiveEntries) {
        if (!listener.isCancelled()) {
            listener.onUpdate(entry.getName());
            //TAR is sequential, you need to walk all the way to the file you want
            while (entry.hashCode() != inputStream.getNextTarEntry().hashCode())
                ;
            extractEntry(context, inputStream, entry, outputPath);
        }
    }
    inputStream.close();

    listener.onFinish();
}

From source file:com.google.devtools.build.lib.bazel.repository.TarGzFunction.java

@Nullable
@Override//w  ww . j  a v  a  2 s.  c  om
public SkyValue compute(SkyKey skyKey, Environment env) throws RepositoryFunctionException {
    DecompressorDescriptor descriptor = (DecompressorDescriptor) skyKey.argument();
    Optional<String> prefix = descriptor.prefix();
    boolean foundPrefix = false;

    try (GZIPInputStream gzipStream = new GZIPInputStream(
            new FileInputStream(descriptor.archivePath().getPathFile()))) {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(gzipStream);
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix);
            foundPrefix = foundPrefix || entryPath.foundPrefix();
            if (entryPath.skip()) {
                continue;
            }

            Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment());
            FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory());
            if (entry.isDirectory()) {
                FileSystemUtils.createDirectoryAndParents(filename);
            } else {
                if (entry.isSymbolicLink()) {
                    PathFragment linkName = new PathFragment(entry.getLinkName());
                    if (linkName.isAbsolute()) {
                        linkName = linkName.relativeTo(PathFragment.ROOT_DIR);
                        linkName = descriptor.repositoryPath().getRelative(linkName).asFragment();
                    }
                    FileSystemUtils.ensureSymbolicLink(filename, linkName);
                } else {
                    Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                    filename.chmod(entry.getMode());
                }
            }
        }
    } catch (IOException e) {
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    if (prefix.isPresent() && !foundPrefix) {
        throw new RepositoryFunctionException(
                new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"),
                Transience.PERSISTENT);
    }

    return new DecompressorValue(descriptor.repositoryPath());
}

From source file:com.arturmkrtchyan.kafka.util.TarUnpacker.java

/**
 * Unpack data from the stream to specified directory.
 *
 * @param in        stream with tar data
 * @param outputPath destination path//from  www. j  ava 2s  . c om
 * @return true in case of success, otherwise - false
 */
protected boolean unpack(final TarArchiveInputStream in, final Path outputPath) throws IOException {
    TarArchiveEntry entry;
    while ((entry = in.getNextTarEntry()) != null) {
        final Path entryPath = outputPath.resolve(entry.getName());
        if (entry.isDirectory()) {
            if (!Files.exists(entryPath)) {
                Files.createDirectories(entryPath);
            }
        } else if (entry.isFile()) {
            try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryPath))) {
                IOUtils.copy(in, out);
                setPermissions(entry.getMode(), entryPath);
            }
        }
    }
    return true;
}

From source file:com.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor.java

@Override
protected void extractWithFilter(@NonNull Filter filter) throws IOException {
    long totalBytes = 0;
    ArrayList<TarArchiveEntry> archiveEntries = new ArrayList<>();
    TarArchiveInputStream inputStream = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(filePath)));

    TarArchiveEntry tarArchiveEntry;

    while ((tarArchiveEntry = inputStream.getNextTarEntry()) != null) {
        if (CompressedHelper.isEntryPathValid(tarArchiveEntry.getName())) {
            if (filter.shouldExtract(tarArchiveEntry.getName(), tarArchiveEntry.isDirectory())) {
                archiveEntries.add(tarArchiveEntry);
                totalBytes += tarArchiveEntry.getSize();
            }//from  w  ww.  j av a 2s .co  m
        } else {
            invalidArchiveEntries.add(tarArchiveEntry.getName());
        }
    }

    listener.onStart(totalBytes, archiveEntries.get(0).getName());

    inputStream.close();
    inputStream = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(filePath)));

    for (TarArchiveEntry entry : archiveEntries) {
        if (!listener.isCancelled()) {
            listener.onUpdate(entry.getName());
            //TAR is sequential, you need to walk all the way to the file you want
            while (entry.hashCode() != inputStream.getNextTarEntry().hashCode())
                ;
            extractEntry(context, inputStream, entry, outputPath);
        }
    }
    inputStream.close();

    listener.onFinish();
}

From source file:com.google.devtools.build.lib.bazel.repository.CompressedTarFunction.java

@Override
public Path decompress(DecompressorDescriptor descriptor) throws RepositoryFunctionException {
    Optional<String> prefix = descriptor.prefix();
    boolean foundPrefix = false;

    try (InputStream decompressorStream = getDecompressorStream(descriptor)) {
        TarArchiveInputStream tarStream = new TarArchiveInputStream(decompressorStream);
        TarArchiveEntry entry;
        while ((entry = tarStream.getNextTarEntry()) != null) {
            StripPrefixedPath entryPath = StripPrefixedPath.maybeDeprefix(entry.getName(), prefix);
            foundPrefix = foundPrefix || entryPath.foundPrefix();
            if (entryPath.skip()) {
                continue;
            }//from w w  w.  ja va2  s  . c o m

            Path filename = descriptor.repositoryPath().getRelative(entryPath.getPathFragment());
            FileSystemUtils.createDirectoryAndParents(filename.getParentDirectory());
            if (entry.isDirectory()) {
                FileSystemUtils.createDirectoryAndParents(filename);
            } else {
                if (entry.isSymbolicLink() || entry.isLink()) {
                    PathFragment linkName = new PathFragment(entry.getLinkName());
                    boolean wasAbsolute = linkName.isAbsolute();
                    // Strip the prefix from the link path if set.
                    linkName = StripPrefixedPath.maybeDeprefix(linkName.getPathString(), prefix)
                            .getPathFragment();
                    if (wasAbsolute) {
                        // Recover the path to an absolute path as maybeDeprefix() relativize the path
                        // even if the prefix is not set
                        linkName = descriptor.repositoryPath().getRelative(linkName).asFragment();
                    }
                    if (entry.isSymbolicLink()) {
                        FileSystemUtils.ensureSymbolicLink(filename, linkName);
                    } else {
                        FileSystemUtils.createHardLink(filename,
                                descriptor.repositoryPath().getRelative(linkName));
                    }
                } else {
                    Files.copy(tarStream, filename.getPathFile().toPath(), StandardCopyOption.REPLACE_EXISTING);
                    filename.chmod(entry.getMode());

                    // This can only be done on real files, not links, or it will skip the reader to
                    // the next "real" file to try to find the mod time info.
                    Date lastModified = entry.getLastModifiedDate();
                    filename.setLastModifiedTime(lastModified.getTime());
                }
            }
        }
    } catch (IOException e) {
        throw new RepositoryFunctionException(e, Transience.TRANSIENT);
    }

    if (prefix.isPresent() && !foundPrefix) {
        throw new RepositoryFunctionException(
                new IOException("Prefix " + prefix.get() + " was given, but not found in the archive"),
                Transience.PERSISTENT);
    }

    return descriptor.repositoryPath();
}

From source file:com.vmware.content.samples.ImportOva.java

private void uploadOva(String ovaPath, String sessionId) throws Exception {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    IOUtil.print("Streaming OVF to update session " + sessionId);
    try (TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(ovaPath))) {
        TarArchiveEntry entry;
        while ((entry = tar.getNextTarEntry()) != null) {
            long bytes = entry.getSize();
            IOUtil.print("Uploading " + entry.getName() + " (" + entry.getSize() + " bytes)");
            URI uploadUri = generateUploadUri(sessionId, entry.getName());
            HttpPut request = new HttpPut(uploadUri);
            HttpEntity content = new TarBasedInputStreamEntity(tar, bytes);
            request.setEntity(content);//from  w w  w .  j  av a  2  s  .co  m
            HttpResponse response = httpclient.execute(request);
            EntityUtils.consumeQuietly(response.getEntity());
        }
    }
}

From source file:io.wcm.maven.plugins.nodejs.installation.TarUnArchiver.java

/**
 * Unarchives the arvive into the pBaseDir
 * @param baseDir// w  ww. j  a  v a 2s .  c  o m
 * @throws MojoExecutionException
 */
public void unarchive(String baseDir) throws MojoExecutionException {
    try {
        FileInputStream fis = new FileInputStream(archive);

        // TarArchiveInputStream can be constructed with a normal FileInputStream if
        // we ever need to extract regular '.tar' files.
        final TarArchiveInputStream tarIn = new TarArchiveInputStream(new GzipCompressorInputStream(fis));

        TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
        while (tarEntry != null) {
            // Create a file for this tarEntry
            final File destPath = new File(baseDir + File.separator + tarEntry.getName());
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                destPath.setExecutable(true);
                //byte [] btoRead = new byte[(int)tarEntry.getSize()];
                byte[] btoRead = new byte[8024];
                final BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                int len = 0;

                while ((len = tarIn.read(btoRead)) != -1) {
                    bout.write(btoRead, 0, len);
                }

                bout.close();
            }
            tarEntry = tarIn.getNextTarEntry();
        }
        tarIn.close();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not extract archive: '" + archive.getAbsolutePath() + "'", e);
    }

}

From source file:com.foreignreader.util.WordNetExtractor.java

@Override
protected Void doInBackground(InputStream... streams) {
    assert streams.length == 1;

    try {//w ww.  j a v a 2  s.co  m

        BufferedInputStream in = new BufferedInputStream(streams[0]);
        GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);

        TarArchiveInputStream tar = new TarArchiveInputStream(gzIn);

        TarArchiveEntry tarEntry;

        File dest = LongTranslationHelper.getWordNetDict().getParentFile();

        while ((tarEntry = tar.getNextTarEntry()) != null) {
            File destPath = new File(dest, tarEntry.getName());
            if (tarEntry.isDirectory()) {
                destPath.mkdirs();
            } else {
                destPath.createNewFile();
                byte[] btoRead = new byte[1024 * 10];

                BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                int len = 0;

                while ((len = tar.read(btoRead)) != -1) {
                    bout.write(btoRead, 0, len);
                }

                bout.close();

            }
        }

        tar.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:gdt.data.entity.ArchiveHandler.java

/**
 * Extract tar archive stream into the target directory
 * @param targetDirectory$ the path of the target directory
 * @param tis the tar archive input stream.
 *///from  w w w.  ja  v  a  2  s .  co m
public static void extractEntitiesFromTar(String targetDirectory$, TarArchiveInputStream tis) {
    try {

        TarArchiveEntry entry = null;
        File outputFile;
        File outputDir;
        FileOutputStream outputStream;
        while ((entry = tis.getNextTarEntry()) != null) {

            outputFile = new File(targetDirectory$ + "/" + entry.getName());
            outputDir = outputFile.getParentFile();
            if (!outputDir.exists())
                outputDir.mkdirs();
            if (entry.isDirectory()) {
                outputFile.mkdir();

            } else {
                outputStream = new FileOutputStream(outputFile);
                IOUtils.copy(tis, outputStream);
                outputStream.close();
            }
        }
        tis.close();
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
    }
}