Example usage for org.apache.commons.compress.archivers.tar TarArchiveInputStream getNextTarEntry

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

Introduction

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

Prototype

public TarArchiveEntry getNextTarEntry() throws IOException 

Source Link

Document

Get the next entry in this tar archive.

Usage

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

private static boolean hasPropertyIndexInTarStream(TarArchiveInputStream tis) {
    try {/* w  w  w .j av  a2s.co  m*/
        TarArchiveEntry entry = null;
        String entryName$;
        while ((entry = tis.getNextTarEntry()) != null) {
            entryName$ = entry.getName();
            if (entryName$.equals(Entigrator.PROPERTY_INDEX)) {
                tis.close();
                return true;
            }
        }
        tis.close();
        return false;
    } catch (Exception e) {
        Logger.getLogger(ArchiveHandler.class.getName()).severe(e.toString());
        return false;
    }
}

From source file:de.flapdoodle.embedmongo.extract.TgzExtractor.java

@Override
public void extract(RuntimeConfig runtime, File source, File destination, Pattern file) throws IOException {

    IProgressListener progressListener = runtime.getProgressListener();
    String progressLabel = "Extract " + source;
    progressListener.start(progressLabel);

    FileInputStream fin = new FileInputStream(source);
    BufferedInputStream in = new BufferedInputStream(fin);
    GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);

    TarArchiveInputStream tarIn = new TarArchiveInputStream(gzIn);
    try {/*from w ww.ja  v a 2s  . c  o m*/
        TarArchiveEntry entry;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            if (file.matcher(entry.getName()).matches()) {
                //               System.out.println("File: " + entry.getName());
                if (tarIn.canReadEntryData(entry)) {
                    //                  System.out.println("Can Read: " + entry.getName());
                    long size = entry.getSize();
                    Files.write(tarIn, size, destination);
                    destination.setExecutable(true);
                    //                  System.out.println("DONE");
                    progressListener.done(progressLabel);
                }
                break;

            } else {
                //               System.out.println("SKIP File: " + entry.getName());
            }
        }

    } finally {
        tarIn.close();
        gzIn.close();
    }
}

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

/**
 * Unarchives the arvive into the pBaseDir
 * @param baseDir/*from   w ww  .j  a  v a 2s.co  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:ezbake.deployer.publishers.SecurityServiceClient.java

/**
 * The applicationId is part of the REST call to the Security Service.
 * Returns an empty list if no certificates were found or throws exception if
 * something went wrong with Security Service communication.
 *//*w  w  w . j a v  a 2 s .c om*/
@Override
public List<ArtifactDataEntry> get(String applicationId, String securityId) throws DeploymentException {
    try {
        ArrayList<ArtifactDataEntry> certList = new ArrayList<ArtifactDataEntry>();
        String endpoint = config.getSecurityServiceBasePath() + "/registrations/" + securityId + "/download";
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = openUrlConnection(url);
        urlConn.connect();

        // Read in tar file of certificates into byte array
        BufferedInputStream in = new BufferedInputStream(urlConn.getInputStream());
        // Create CertDataEntry list from tarFile byte array
        TarArchiveInputStream tarIn = new TarArchiveInputStream(in);
        TarArchiveEntry entry = tarIn.getNextTarEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                IOUtils.copy(tarIn, bout);
                byte[] certData = bout.toByteArray();
                String certFileName = entry.getName().substring(entry.getName().lastIndexOf("/") + 1,
                        entry.getName().length());
                TarArchiveEntry tae = new TarArchiveEntry(
                        Files.get(SSL_CONFIG_DIRECTORY, securityId, certFileName));
                ArtifactDataEntry cde = new ArtifactDataEntry(tae, certData);
                certList.add(cde);
                bout.close();
            }

            entry = tarIn.getNextTarEntry();
        }
        tarIn.close();

        return certList;
    } catch (Exception e) {
        log.error("Unable to download certificates from security service.", e);
        throw new DeploymentException(
                "Unable to download certificates from security service. " + e.getMessage());
    }
}

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

@Nullable
@Override/*w  ww . ja v a 2 s .c  o m*/
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.renard.ocr.help.OCRLanguageInstallService.java

@Override
protected void onHandleIntent(Intent intent) {
    if (!intent.hasExtra(DownloadManager.EXTRA_DOWNLOAD_ID)) {
        return;/*www.j a va 2 s . c o m*/
    }
    final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
    if (downloadId != 0) {

        DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
        ParcelFileDescriptor file;
        try {
            file = dm.openDownloadedFile(downloadId);
            FileInputStream fin = new FileInputStream(file.getFileDescriptor());
            BufferedInputStream in = new BufferedInputStream(fin);
            FileOutputStream out = openFileOutput("tess-lang.tmp", Context.MODE_PRIVATE);
            GzipCompressorInputStream gzIn = new GzipCompressorInputStream(in);
            final byte[] buffer = new byte[2048 * 2];
            int n = 0;
            while (-1 != (n = gzIn.read(buffer))) {
                out.write(buffer, 0, n);
            }
            out.close();
            gzIn.close();
            FileInputStream fileIn = openFileInput("tess-lang.tmp");
            TarArchiveInputStream tarIn = new TarArchiveInputStream(fileIn);

            TarArchiveEntry entry = tarIn.getNextTarEntry();

            while (entry != null && !(entry.getName().endsWith(".traineddata")
                    && !entry.getName().endsWith("_old.traineddata"))) {
                entry = tarIn.getNextTarEntry();
            }
            if (entry != null) {
                File tessDir = Util.getTrainingDataDir(this);
                final String langName = entry.getName().substring("tesseract-ocr/tessdata/".length());
                File trainedData = new File(tessDir, langName);
                FileOutputStream fout = new FileOutputStream(trainedData);
                int len;
                while ((len = tarIn.read(buffer)) != -1) {
                    fout.write(buffer, 0, len);
                }
                fout.close();
                String lang = langName.substring(0, langName.length() - ".traineddata".length());
                notifyReceivers(lang);
            }
            tarIn.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            String tessDir = Util.getTessDir(this);
            File targetFile = new File(tessDir, OCRLanguageActivity.DOWNLOADED_TRAINING_DATA);
            if (targetFile.exists()) {
                targetFile.delete();
            }
        }

    }
}

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;/*from   w  w  w .j a va  2  s .  co  m*/
        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() || 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.wenzani.maven.mongodb.TarUtils.java

public String untargz(File archive, File outputDir) {
    String absolutePath = archive.getAbsolutePath();
    String root = null;//from   w ww .j  a  v  a 2  s .  c o m
    boolean first = true;

    while (absolutePath.contains("tar") || absolutePath.contains("gz") || absolutePath.contains("tgz")) {
        absolutePath = absolutePath.substring(0, absolutePath.lastIndexOf("."));
    }

    absolutePath = absolutePath + ".tar";

    try {
        GZIPInputStream input = new GZIPInputStream(new FileInputStream(archive));
        FileOutputStream fos = new FileOutputStream(new File(absolutePath));

        IOUtils.copy(input, fos);
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(fos);

        TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(
                new FileInputStream(absolutePath));

        for (TarArchiveEntry entry = tarArchiveInputStream.getNextTarEntry(); entry != null;) {
            unpackEntries(tarArchiveInputStream, entry, outputDir);

            if (first && entry.isDirectory()) {
                root = outputDir + File.separator + entry.getName();
            }

            entry = tarArchiveInputStream.getNextTarEntry();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return root;
}

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 .j a v a 2  s. c o  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());
    }
}

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   w w w .j  a v a2s. co m
 * @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;
}