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

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

Introduction

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

Prototype

public TarArchiveInputStream(InputStream is) 

Source Link

Document

Constructor for TarInputStream.

Usage

From source file:io.sloeber.core.managers.InternalPackageManager.java

private static IStatus processArchive(String pArchiveFileName, IPath pInstallPath, boolean pForceDownload,
        String pArchiveFullFileName, IProgressMonitor pMonitor) {
    // Create an ArchiveInputStream with the correct archiving algorithm
    String faileToExtractMessage = Messages.Manager_Failed_to_extract.replace(FILE, pArchiveFullFileName);
    if (pArchiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
        try (ArchiveInputStream inStream = new TarArchiveInputStream(
                new BZip2CompressorInputStream(new FileInputStream(pArchiveFullFileName)))) {
            return extract(inStream, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }/*from  w  w w.ja  v  a 2  s .co m*/
    } else if (pArchiveFileName.endsWith("zip")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(pArchiveFullFileName))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else if (pArchiveFileName.endsWith("tar.gz")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new TarArchiveInputStream(
                new GzipCompressorInputStream(new FileInputStream(pArchiveFullFileName)))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else if (pArchiveFileName.endsWith("tar")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new TarArchiveInputStream(new FileInputStream(pArchiveFullFileName))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else {
        return new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Format_not_supported);
    }
}

From source file:de.dentrassi.build.apt.repo.AptWriter.java

private BinaryPackagePackagesFile readArtifact(final File packageFile) throws Exception {
    try (final ArArchiveInputStream in = new ArArchiveInputStream(new FileInputStream(packageFile))) {
        ArchiveEntry ar;// w w  w .j  a v a2  s.co  m
        while ((ar = in.getNextEntry()) != null) {
            if (!ar.getName().equals("control.tar.gz")) {
                continue;
            }

            try (final TarArchiveInputStream inputStream = new TarArchiveInputStream(new GZIPInputStream(in))) {

                TarArchiveEntry te;
                while ((te = inputStream.getNextTarEntry()) != null) {
                    if (!te.getName().equals("./control")) {
                        continue;
                    }
                    return convert(new BinaryPackageControlFile(inputStream), packageFile);
                }

            }
        }
    }
    return null;
}

From source file:backup.integration.MiniClusterTestBase.java

private static File extract(File output, File parcelLocation) throws Exception {
    try (TarArchiveInputStream tarInput = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(parcelLocation)))) {
        ArchiveEntry entry;/*from   ww w . j  av  a  2 s .c  o  m*/
        while ((entry = (ArchiveEntry) tarInput.getNextEntry()) != null) {
            LOG.info("Extracting: {}", entry.getName());
            File f = new File(output, entry.getName());
            if (entry.isDirectory()) {
                f.mkdirs();
            } else {
                f.getParentFile().mkdirs();
                try (OutputStream out = new BufferedOutputStream(new FileOutputStream(f))) {
                    IOUtils.copy(tarInput, out);
                }
            }
        }
    }
    return output;
}

From source file:ezbake.deployer.publishers.openShift.RhcApplication.java

private void writeTarFileToProjectDirectory(byte[] artifact) throws DeploymentException {
    final File gitDbPath = gitRepo.getRepository().getDirectory();
    final File projectDir = gitDbPath.getParentFile();
    try {/* w w  w .  j  a  v  a  2 s  . c  o m*/
        CompressorInputStream uncompressedInput = new GzipCompressorInputStream(
                new ByteArrayInputStream(artifact));
        TarArchiveInputStream inputStream = new TarArchiveInputStream(uncompressedInput);

        // copy the existing entries
        TarArchiveEntry nextEntry;
        while ((nextEntry = (TarArchiveEntry) inputStream.getNextEntry()) != null) {
            File fileToWrite = new File(projectDir, nextEntry.getName());
            if (nextEntry.isDirectory()) {
                fileToWrite.mkdirs();
            } else {
                File house = fileToWrite.getParentFile();
                if (!house.exists()) {
                    house.mkdirs();
                }
                copyInputStreamToFile(inputStream, fileToWrite);
                Files.setPosixFilePermissions(fileToWrite, nextEntry.getMode());
            }
        }
    } catch (IOException e) {
        log.error("[" + getApplicationName() + "]" + e.getMessage(), e);
        throw new DeploymentException(e.getMessage());
    }
}

From source file:com.sshtools.common.vomanagementtool.common.VOHelper.java

private static void untar(InputStream in, String untarDir) throws IOException {

    TarArchiveInputStream tin = new TarArchiveInputStream(in);
    TarArchiveEntry entry = tin.getNextTarEntry();

    //TarInputStream tin = new TarInputStream(in);
    //TarEntry tarEntry = tin.getNextEntry();
    if (new File(untarDir).exists()) {
        //To handle the normal files (not symbolic files)
        while (entry != null) {
            if (!entry.isSymbolicLink()) {
                String filename = untarDir + File.separatorChar + entry.getName();
                File destPath = new File(filename);

                if (!entry.isDirectory()) {
                    FileOutputStream fout = new FileOutputStream(destPath);
                    IOUtils.copy(tin, fout);
                    //tin.copyEntryContents(fout);
                    fout.close();//from ww w  .j a v a  2  s  .c  om
                } else {
                    if (!destPath.exists()) {
                        boolean success = destPath.mkdir();
                        if (!success) {
                            throw new IOException("Couldn't create directory for VOMS support: "
                                    + destPath.getAbsolutePath());
                        }
                    }
                }
            }
            entry = tin.getNextTarEntry();
            //tarEntry = tin.getNextEntry();
        }
        //tin.close();

        //To handle the symbolic link files
        tin = new TarArchiveInputStream(in);
        entry = tin.getNextTarEntry();
        while (entry != null) {

            if (entry.isSymbolicLink()) {
                File srcPath = new File(untarDir + File.separatorChar + entry.getLinkName());
                File destPath = new File(untarDir + File.separatorChar + entry.getName());
                copyFile(srcPath, destPath);

                //tarEntry = tin.getNextEntry();
            }
            entry = tin.getNextTarEntry();
        }
        tin.close();
    } else {
        throw new IOException("Couldn't find directory: " + untarDir);
    }

}

From source file:freenet.client.ArchiveManager.java

private void handleTARArchive(ArchiveStoreContext ctx, FreenetURI key, InputStream data, String element,
        ArchiveExtractCallback callback, MutableBoolean gotElement, boolean throwAtExit, ClientContext context)
        throws ArchiveFailureException, ArchiveRestartException {
    if (logMINOR)
        Logger.minor(this, "Handling a TAR Archive");
    TarArchiveInputStream tarIS = null;/*from   w w w .  j a  v a 2 s .co  m*/
    try {
        tarIS = new TarArchiveInputStream(data);

        // MINOR: Assumes the first entry in the tarball is a directory.
        ArchiveEntry entry;

        byte[] buf = new byte[32768];
        HashSet<String> names = new HashSet<String>();
        boolean gotMetadata = false;

        outerTAR: while (true) {
            try {
                entry = tarIS.getNextEntry();
            } catch (IllegalArgumentException e) {
                // Annoyingly, it can throw this on some corruptions...
                throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e);
            }
            if (entry == null)
                break;
            if (entry.isDirectory())
                continue;
            String name = stripLeadingSlashes(entry.getName());
            if (names.contains(name)) {
                Logger.error(this, "Duplicate key " + name + " in archive " + key);
                continue;
            }
            long size = entry.getSize();
            if (name.equals(".metadata"))
                gotMetadata = true;
            if (size > maxArchivedFileSize && !name.equals(element)) {
                addErrorElement(
                        ctx, key, name, "File too big: " + size
                                + " greater than current archived file size limit " + maxArchivedFileSize,
                        true);
            } else {
                // Read the element
                long realLen = 0;
                Bucket output = tempBucketFactory.makeBucket(size);
                OutputStream out = output.getOutputStream();

                try {
                    int readBytes;
                    while ((readBytes = tarIS.read(buf)) > 0) {
                        out.write(buf, 0, readBytes);
                        readBytes += realLen;
                        if (readBytes > maxArchivedFileSize) {
                            addErrorElement(ctx, key, name, "File too big: " + maxArchivedFileSize
                                    + " greater than current archived file size limit " + maxArchivedFileSize,
                                    true);
                            out.close();
                            out = null;
                            output.free();
                            continue outerTAR;
                        }
                    }

                } finally {
                    if (out != null)
                        out.close();
                }
                if (size <= maxArchivedFileSize) {
                    addStoreElement(ctx, key, name, output, gotElement, element, callback, context);
                    names.add(name);
                    trimStoredData();
                } else {
                    // We are here because they asked for this file.
                    callback.gotBucket(output, context);
                    gotElement.value = true;
                    addErrorElement(
                            ctx, key, name, "File too big: " + size
                                    + " greater than current archived file size limit " + maxArchivedFileSize,
                            true);
                }
            }
        }

        // If no metadata, generate some
        if (!gotMetadata) {
            generateMetadata(ctx, key, names, gotElement, element, callback, context);
            trimStoredData();
        }
        if (throwAtExit)
            throw new ArchiveRestartException("Archive changed on re-fetch");

        if ((!gotElement.value) && element != null)
            callback.notInArchive(context);

    } catch (IOException e) {
        throw new ArchiveFailureException("Error reading archive: " + e.getMessage(), e);
    } finally {
        Closer.close(tarIS);
    }
}

From source file:io.sloeber.core.managers.Manager.java

private static IStatus processArchive(String pArchiveFileName, Path pInstallPath, boolean pForceDownload,
        String pArchiveFullFileName, IProgressMonitor pMonitor) {
    // Create an ArchiveInputStream with the correct archiving algorithm
    String faileToExtractMessage = Messages.Manager_Failed_to_extract + pArchiveFullFileName;
    if (pArchiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
        try (ArchiveInputStream inStream = new TarArchiveInputStream(
                new BZip2CompressorInputStream(new FileInputStream(pArchiveFullFileName)))) {
            return extract(inStream, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }/*w  w w  . j  a  v a2 s  .c o  m*/
    } else if (pArchiveFileName.endsWith("zip")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new ZipArchiveInputStream(new FileInputStream(pArchiveFullFileName))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else if (pArchiveFileName.endsWith("tar.gz")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new TarArchiveInputStream(
                new GzipCompressorInputStream(new FileInputStream(pArchiveFullFileName)))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else if (pArchiveFileName.endsWith("tar")) { //$NON-NLS-1$
        try (ArchiveInputStream in = new TarArchiveInputStream(new FileInputStream(pArchiveFullFileName))) {
            return extract(in, pInstallPath.toFile(), 1, pForceDownload, pMonitor);
        } catch (IOException | InterruptedException e) {
            return new Status(IStatus.ERROR, Activator.getId(), faileToExtractMessage, e);
        }
    } else {
        return new Status(IStatus.ERROR, Activator.getId(), Messages.Manager_Format_not_supported);
    }
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * TODO recopy file permissions/*w  ww.j a v a  2  s  .com*/
 * <p/>
 * Uncompress the specified tgz file to the specified destination directory.
 * Replaces any files in the destination, if they already exist.
 *
 * @param tgzFile the name of the zip file to extract
 * @param destDir the directory to unzip to
 * @throws RuntimeIOException
 */
public static void untgz(@Nonnull Path tgzFile, @Nonnull Path destDir) throws RuntimeIOException {
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        TarArchiveInputStream in = new TarArchiveInputStream(
                new GzipCompressorInputStream(Files.newInputStream(tgzFile)));

        TarArchiveEntry entry;
        while ((entry = in.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                Path dir = destDir.resolve(entry.getName());
                logger.trace("Create dir {}", dir);
                Files.createDirectories(dir);
            } else {
                Path file = destDir.resolve(entry.getName());
                logger.trace("Create file {}: {} bytes", file, entry.getSize());
                OutputStream out = Files.newOutputStream(file);
                IOUtils.copy(in, out);
                out.close();
            }
        }

        in.close();
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + tgzFile + " to " + destDir, e);
    }
}

From source file:io.syndesis.project.converter.DefaultProjectGeneratorTest.java

private Path generate(GenerateProjectRequest request, ProjectGeneratorProperties generatorProperties)
        throws IOException {
    try (InputStream is = new DefaultProjectGenerator(new ConnectorCatalog(CATALOG_PROPERTIES),
            generatorProperties, registry).generate(request)) {
        Path ret = Files.createTempDirectory("integration-runtime");
        try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) {

            TarArchiveEntry tarEntry = tis.getNextTarEntry();
            // tarIn is a TarArchiveInputStream
            while (tarEntry != null) {// create a file with the same name as the tarEntry
                File destPath = new File(ret.toFile(), tarEntry.getName());
                if (tarEntry.isDirectory()) {
                    destPath.mkdirs();//from w ww  .j av  a2s . c o m
                } else {
                    destPath.getParentFile().mkdirs();
                    destPath.createNewFile();
                    byte[] btoRead = new byte[8129];
                    BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(destPath));
                    int len = tis.read(btoRead);
                    while (len != -1) {
                        bout.write(btoRead, 0, len);
                        len = tis.read(btoRead);
                    }
                    bout.close();
                }
                tarEntry = tis.getNextTarEntry();
            }
        }
        return ret;
    }
}

From source file:it.evilsocket.dsploit.core.UpdateService.java

/**
 * open an Archive InputStream//from w ww . ja  v a  2 s  . c  om
 * @param in the InputStream to the archive
 * @return the ArchiveInputStream to read from
 * @throws IOException if an I/O error occurs
 * @throws java.lang.IllegalStateException if no archive method has been choose
 */
private ArchiveInputStream openArchiveStream(InputStream in) throws IOException, IllegalStateException {
    switch (mCurrentTask.archiver) {
    case tar:
        return new TarArchiveInputStream(new BufferedInputStream(openCompressedStream(in)));
    case zip:
        return new ZipArchiveInputStream(new BufferedInputStream(openCompressedStream(in)));
    default:
        throw new IllegalStateException("trying to open an archive, but no archive algorithm selected.");
    }
}