Search in sources :

Example 66 with TarArchiveInputStream

use of org.apache.commons.compress.archivers.tar.TarArchiveInputStream in project canal by alibaba.

the class BinlogDownloadQueue method saveFile.

private static void saveFile(File parentFile, String fileName, HttpResponse response) throws IOException {
    InputStream is = response.getEntity().getContent();
    long totalSize = Long.parseLong(response.getFirstHeader("Content-Length").getValue());
    if (response.getFirstHeader("Content-Disposition") != null) {
        fileName = response.getFirstHeader("Content-Disposition").getValue();
        fileName = StringUtils.substringAfter(fileName, "filename=");
    }
    boolean isTar = StringUtils.endsWith(fileName, ".tar");
    FileUtils.forceMkdir(parentFile);
    FileOutputStream fos = null;
    try {
        if (isTar) {
            TarArchiveInputStream tais = new TarArchiveInputStream(is);
            TarArchiveEntry tarArchiveEntry = null;
            while ((tarArchiveEntry = tais.getNextTarEntry()) != null) {
                String name = tarArchiveEntry.getName();
                File tarFile = new File(parentFile, name + ".tmp");
                logger.info("start to download file " + tarFile.getName());
                if (tarFile.exists()) {
                    tarFile.delete();
                }
                BufferedOutputStream bos = null;
                try {
                    bos = new BufferedOutputStream(new FileOutputStream(tarFile));
                    int read = -1;
                    byte[] buffer = new byte[1024];
                    while ((read = tais.read(buffer)) != -1) {
                        bos.write(buffer, 0, read);
                    }
                    logger.info("download file " + tarFile.getName() + " end!");
                    tarFile.renameTo(new File(parentFile, name));
                } finally {
                    IOUtils.closeQuietly(bos);
                }
            }
            tais.close();
        } else {
            File file = new File(parentFile, fileName + ".tmp");
            if (file.exists()) {
                file.delete();
            }
            if (!file.isFile()) {
                file.createNewFile();
            }
            try {
                fos = new FileOutputStream(file);
                byte[] buffer = new byte[1024];
                int len;
                long copySize = 0;
                long nextPrintProgress = 0;
                logger.info("start to download file " + file.getName());
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    copySize += len;
                    long progress = copySize * 100 / totalSize;
                    if (progress >= nextPrintProgress) {
                        logger.info("download " + file.getName() + " progress : " + progress + "% , download size : " + copySize + ", total size : " + totalSize);
                        nextPrintProgress += 10;
                    }
                }
                logger.info("download file " + file.getName() + " end!");
                fos.flush();
            } finally {
                IOUtils.closeQuietly(fos);
            }
            file.renameTo(new File(parentFile, fileName));
        }
    } finally {
        IOUtils.closeQuietly(fos);
    }
}
Also used : TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) InputStream(java.io.InputStream) FileOutputStream(java.io.FileOutputStream) BinlogFile(com.alibaba.otter.canal.parse.inbound.mysql.rds.data.BinlogFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry)

Example 67 with TarArchiveInputStream

use of org.apache.commons.compress.archivers.tar.TarArchiveInputStream in project jstorm by alibaba.

the class Utils method unTarUsingJava.

private static void unTarUsingJava(File inFile, File targetDir, boolean gzipped) throws IOException {
    InputStream inputStream = null;
    TarArchiveInputStream tis = null;
    try {
        if (gzipped) {
            inputStream = new BufferedInputStream(new GZIPInputStream(new FileInputStream(inFile)));
        } else {
            inputStream = new BufferedInputStream(new FileInputStream(inFile));
        }
        tis = new TarArchiveInputStream(inputStream);
        for (TarArchiveEntry entry = tis.getNextTarEntry(); entry != null; ) {
            unpackEntries(tis, entry, targetDir);
            entry = tis.getNextTarEntry();
        }
    } finally {
        cleanup(tis, inputStream);
    }
}
Also used : TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) ObjectInputStream(java.io.ObjectInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) FileInputStream(java.io.FileInputStream) ClassLoaderObjectInputStream(org.apache.commons.io.input.ClassLoaderObjectInputStream) InputStream(java.io.InputStream) FileInputStream(java.io.FileInputStream) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry)

Example 68 with TarArchiveInputStream

use of org.apache.commons.compress.archivers.tar.TarArchiveInputStream in project mycore by MyCoRe-Org.

the class MCRUtils method untar.

/**
 * Extracts files in a tar archive. Currently works only on uncompressed tar files.
 *
 * @param source
 *            the uncompressed tar to extract
 * @param expandToDirectory
 *            the directory to extract the tar file to
 * @throws IOException
 *             if the source file does not exists
 */
public static void untar(Path source, Path expandToDirectory) throws IOException {
    try (TarArchiveInputStream tain = new TarArchiveInputStream(Files.newInputStream(source))) {
        TarArchiveEntry tarEntry;
        FileSystem targetFS = expandToDirectory.getFileSystem();
        HashMap<Path, FileTime> directoryTimes = new HashMap<>();
        while ((tarEntry = tain.getNextTarEntry()) != null) {
            Path target = MCRPathUtils.getPath(targetFS, tarEntry.getName());
            Path absoluteTarget = expandToDirectory.resolve(target).normalize().toAbsolutePath();
            if (tarEntry.isDirectory()) {
                Files.createDirectories(expandToDirectory.resolve(absoluteTarget));
                directoryTimes.put(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            } else {
                if (Files.notExists(absoluteTarget.getParent())) {
                    Files.createDirectories(absoluteTarget.getParent());
                }
                Files.copy(tain, absoluteTarget, StandardCopyOption.REPLACE_EXISTING);
                Files.setLastModifiedTime(absoluteTarget, FileTime.fromMillis(tarEntry.getLastModifiedDate().getTime()));
            }
        }
        // restore directory dates
        Files.walkFileTree(expandToDirectory, new SimpleFileVisitor<Path>() {

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                Path absolutePath = dir.normalize().toAbsolutePath();
                Files.setLastModifiedTime(absolutePath, directoryTimes.get(absolutePath));
                return super.postVisitDirectory(dir, exc);
            }
        });
    }
}
Also used : TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) Path(java.nio.file.Path) HashMap(java.util.HashMap) FileSystem(java.nio.file.FileSystem) FileTime(java.nio.file.attribute.FileTime) FileVisitResult(java.nio.file.FileVisitResult) IOException(java.io.IOException) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry)

Example 69 with TarArchiveInputStream

use of org.apache.commons.compress.archivers.tar.TarArchiveInputStream in project gerrit by GerritCodeReview.

the class GetArchiveIT method getTarContent.

private HashMap<String, String> getTarContent(InputStream in) throws Exception {
    HashMap<String, String> archiveEntries = new HashMap<>();
    int bufferSize = 100;
    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(in)) {
        TarArchiveEntry entry;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                archiveEntries.put(entry.getName(), null);
            } else {
                byte[] data = new byte[bufferSize];
                try (ByteArrayOutputStream out = new ByteArrayOutputStream();
                    BufferedOutputStream bufferedOut = new BufferedOutputStream(out, bufferSize)) {
                    int count;
                    while ((count = tarIn.read(data, 0, bufferSize)) != -1) {
                        bufferedOut.write(data, 0, count);
                    }
                    bufferedOut.flush();
                    archiveEntries.put(entry.getName(), out.toString());
                }
            }
        }
    }
    return archiveEntries;
}
Also used : TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) HashMap(java.util.HashMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry)

Example 70 with TarArchiveInputStream

use of org.apache.commons.compress.archivers.tar.TarArchiveInputStream in project ats-framework by Axway.

the class LocalFileSystemOperations method extractTarGZip.

private void extractTarGZip(String tarGzipFilePath, String outputDirPath) {
    TarArchiveEntry entry = null;
    try (TarArchiveInputStream tis = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(tarGzipFilePath)))) {
        while ((entry = (TarArchiveEntry) tis.getNextEntry()) != null) {
            if (log.isDebugEnabled()) {
                log.debug("Extracting " + entry.getName());
            }
            File entryDestination = new File(outputDirPath, entry.getName());
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else {
                entryDestination.getParentFile().mkdirs();
                OutputStream out = new BufferedOutputStream(new FileOutputStream(entryDestination));
                IoUtils.copyStream(tis, out, false, true);
            }
            if (OperatingSystemType.getCurrentOsType() != OperatingSystemType.WINDOWS) {
                // check if the OS is UNIX
                // set file/dir permissions, after it is created
                Files.setPosixFilePermissions(entryDestination.getCanonicalFile().toPath(), getPosixFilePermission(entry.getMode()));
            }
        }
    } catch (Exception e) {
        String errorMsg = null;
        if (entry != null) {
            errorMsg = "Unable to gunzip " + entry.getName() + " from " + tarGzipFilePath + ".Target directory '" + outputDirPath + "' is in inconsistent state.";
        } else {
            errorMsg = "Could not read data from " + tarGzipFilePath;
        }
        throw new FileSystemOperationException(errorMsg, e);
    }
}
Also used : TarArchiveInputStream(org.apache.commons.compress.archivers.tar.TarArchiveInputStream) GzipCompressorInputStream(org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) RandomAccessFile(java.io.RandomAccessFile) ZipFile(org.apache.commons.compress.archivers.zip.ZipFile) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) TarArchiveEntry(org.apache.commons.compress.archivers.tar.TarArchiveEntry) FileInputStream(java.io.FileInputStream) OverlappingFileLockException(java.nio.channels.OverlappingFileLockException) FileSystemOperationException(com.axway.ats.common.filesystem.FileSystemOperationException) AttributeNotSupportedException(com.axway.ats.core.filesystem.exceptions.AttributeNotSupportedException) EOFException(java.io.EOFException) FileNotFoundException(java.io.FileNotFoundException) FileDoesNotExistException(com.axway.ats.core.filesystem.exceptions.FileDoesNotExistException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) SocketTimeoutException(java.net.SocketTimeoutException) IOException(java.io.IOException)

Aggregations

TarArchiveInputStream (org.apache.commons.compress.archivers.tar.TarArchiveInputStream)132 TarArchiveEntry (org.apache.commons.compress.archivers.tar.TarArchiveEntry)99 File (java.io.File)52 IOException (java.io.IOException)50 FileInputStream (java.io.FileInputStream)46 GzipCompressorInputStream (org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream)46 InputStream (java.io.InputStream)35 FileOutputStream (java.io.FileOutputStream)34 BufferedInputStream (java.io.BufferedInputStream)31 ByteArrayInputStream (java.io.ByteArrayInputStream)28 Test (org.junit.Test)23 ArrayList (java.util.ArrayList)20 GZIPInputStream (java.util.zip.GZIPInputStream)20 ByteArrayOutputStream (java.io.ByteArrayOutputStream)19 ArchiveEntry (org.apache.commons.compress.archivers.ArchiveEntry)17 OutputStream (java.io.OutputStream)16 Path (java.nio.file.Path)16 BufferedOutputStream (java.io.BufferedOutputStream)12 ArchiveStreamFactory (org.apache.commons.compress.archivers.ArchiveStreamFactory)12 TarArchiveOutputStream (org.apache.commons.compress.archivers.tar.TarArchiveOutputStream)8