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: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();
            }/*ww w. j a  v a  2  s . c  o 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.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  a v a 2 s. c  o  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.amaze.filemanager.filesystem.compressed.extractcontents.helpers.GzipExtractor.java

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {

    File outputFile = new File(outputDir, fixEntryName(entry.getName()));
    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect ZipEntry path!");
    }//from w ww. ja  v a2s  .  co m

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:com.playonlinux.core.utils.archive.Tar.java

/**
 * Uncompress a tar//w ww.  j  a v  a  2 s. c  o m
 *
 * @param countingInputStream
 *            to count the number of byte extracted
 * @param outputDir
 *            The directory where files should be extracted
 * @return A list of extracted files
 * @throws ArchiveException
 *             if the process fails
 */
private List<File> uncompress(final InputStream inputStream, CountingInputStream countingInputStream,
        final File outputDir, long finalSize, Consumer<ProgressEntity> stateCallback) {
    final List<File> uncompressedFiles = new LinkedList<>();
    try (ArchiveInputStream debInputStream = new ArchiveStreamFactory().createArchiveInputStream("tar",
            inputStream)) {
        TarArchiveEntry entry;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {
            final File outputFile = new File(outputDir, entry.getName());
            if (entry.isDirectory()) {
                LOGGER.info(String.format("Attempting to write output directory %s.",
                        outputFile.getAbsolutePath()));

                if (!outputFile.exists()) {
                    LOGGER.info(String.format("Attempting to createPrefix output directory %s.",
                            outputFile.getAbsolutePath()));
                    Files.createDirectories(outputFile.toPath());
                }
            } else {
                LOGGER.info(String.format("Creating output file %s (%s).", outputFile.getAbsolutePath(),
                        entry.getMode()));

                if (entry.isSymbolicLink()) {
                    Files.createSymbolicLink(Paths.get(outputFile.getAbsolutePath()),
                            Paths.get(entry.getLinkName()));
                } else {
                    try (final OutputStream outputFileStream = new FileOutputStream(outputFile)) {
                        IOUtils.copy(debInputStream, outputFileStream);

                        Files.setPosixFilePermissions(Paths.get(outputFile.getPath()),
                                com.playonlinux.core.utils.Files.octToPosixFilePermission(entry.getMode()));
                    }
                }

            }
            uncompressedFiles.add(outputFile);

            stateCallback.accept(new ProgressEntity.Builder()
                    .withPercent((double) countingInputStream.getCount() / (double) finalSize * (double) 100)
                    .withProgressText("Extracting " + outputFile.getName()).build());

        }
        return uncompressedFiles;
    } catch (IOException | org.apache.commons.compress.archivers.ArchiveException e) {
        throw new ArchiveException("Unable to extract the file", e);
    }
}

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

private void extractEntry(@NonNull final Context context, TarArchiveInputStream inputStream,
        TarArchiveEntry entry, String outputDir) throws IOException {
    File outputFile = new File(outputDir, fixEntryName(entry.getName()));

    if (!outputFile.getCanonicalPath().startsWith(outputDir)) {
        throw new IOException("Incorrect TarArchiveEntry path!");
    }/*from   w w w .ja  v  a2 s .  c om*/

    if (entry.isDirectory()) {
        FileUtil.mkdir(outputFile, context);
        return;
    }

    if (!outputFile.getParentFile().exists()) {
        FileUtil.mkdir(outputFile.getParentFile(), context);
    }

    BufferedOutputStream outputStream = new BufferedOutputStream(FileUtil.getOutputStream(outputFile, context));
    try {
        int len;
        byte buf[] = new byte[GenericCopyUtil.DEFAULT_BUFFER_SIZE];
        while ((len = inputStream.read(buf)) != -1) {
            if (!listener.isCancelled()) {
                outputStream.write(buf, 0, len);
                ServiceWatcherUtil.position += len;
            } else
                break;
        }
    } finally {
        outputStream.close();
    }
}

From source file:com.baidu.rigel.biplatform.tesseract.util.FileUtils.java

/**
 * Uncompress the incoming file.//from w  ww  .j ava2  s .c  o  m
 * 
 * @param inFileName
 *            Name of the file to be uncompressed
 * @param outFileName
 *            Name of target
 */
public static String doUncompressFile(String inFileName, String outFileName) throws IOException {
    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_BEGIN, "doUncompressFile",
            "[inFileName:" + inFileName + "]"));
    if (StringUtils.isEmpty(inFileName)) {
        throw new IllegalArgumentException();
    }
    String decompressedFileName = outFileName;

    File inFile = new File(inFileName);
    if (StringUtils.isEmpty(decompressedFileName)) {
        // not specified outFileName
        StringBuilder sb = new StringBuilder();
        sb.append(inFile.getParentFile().getAbsolutePath());
        sb.append(File.separator);
        // sb.append(inFile.getName().substring(0,
        // inFile.getName().indexOf(".")));
        // sb.append(File.separator);
        decompressedFileName = sb.toString();
    }
    File outFile = new File(decompressedFileName);
    if (!outFile.exists()) {
        outFile.mkdirs();
    }
    /**
     * create a TarArchiveInputStream object.
     */

    FileInputStream fin = null;
    BufferedInputStream in = null;
    GzipCompressorInputStream gzIn = null;
    TarArchiveInputStream tarIn = null;

    FileOutputStream fos = null;
    BufferedOutputStream dest = null;

    TarArchiveEntry entry = null;

    try {
        fin = new FileInputStream(inFile);
        in = new BufferedInputStream(fin);
        gzIn = new GzipCompressorInputStream(in);
        tarIn = new TarArchiveInputStream(gzIn);

        /**
         * Read the tar entries using the getNextEntry method
         */
        while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) {

            LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_PROCESS,
                    "Extracting File:" + entry.getName()));

            if (entry.isDirectory()) {
                /**
                 * If the entry is a directory, create the directory.
                 */
                File f = new File(decompressedFileName + entry.getName());
                f.mkdirs();
            } else {
                /**
                 * If the entry is a file,write the decompressed file to the
                 * disk and close destination stream.
                 */
                int count;
                byte[] data = new byte[TesseractConstant.FILE_BLOCK_SIZE];
                String fileName = decompressedFileName + entry.getName().substring(
                        entry.getName().indexOf(TesseractConstant.DECOMPRESSION_FILENAME_SPLITTER) + 1);

                fos = new FileOutputStream(new File(fileName));
                dest = new BufferedOutputStream(fos, TesseractConstant.FILE_BLOCK_SIZE);
                while ((count = tarIn.read(data, 0, TesseractConstant.FILE_BLOCK_SIZE)) != -1) {
                    dest.write(data, 0, count);

                }

                dest.close();

            }

        }

        /**
         * Close the input stream
         */

        tarIn.close();
    } catch (IOException e) {
        LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_ERROR, "IOException"));
        LOGGER.error(e.getMessage(), e);
        throw e;
    } finally {

        try {
            fin.close();
            in.close();
            gzIn.close();
            tarIn.close();
            fos.close();
            dest.close();
        } catch (IOException e) {
            LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_DECOMPRESS_ERROR,
                    "IOException occur when closing fd"));
            LOGGER.error(e.getMessage(), e);
            throw e;
        }

    }

    LOGGER.info(String.format(LogInfoConstants.INFO_PATTERN_FUNCTION_END, "doUncompressFile",
            "[inFileName:" + inFileName + "]"));
    return decompressedFileName;
}

From source file:com.vmware.photon.controller.model.adapters.vsphere.ovf.OvfRetriever.java

private void extractEntry(TarArchiveInputStream tar, File destination, TarArchiveEntry entry)
        throws IOException {
    File file = new File(destination, entry.getName());
    if (entry.isDirectory()) {
        file.mkdirs();//from   w  w  w.j ava  2  s .c  o m
    } else {
        try (FileOutputStream fos = new FileOutputStream(file)) {
            logger.debug("Extracting {} to {}", entry.getName(), file.getAbsoluteFile());
            IOUtils.copy(tar, fos);
        }
    }
}

From source file:CASUAL.communicationstools.heimdall.odin.OdinFile.java

/**
 * Extracts Odin contents to outputDir//from ww w.  j  a va  2 s . c  om
 *
 * @param outputDir temp folder
 * @return an array of files extracted from Odin Package
 * @throws IOException {@inheritDoc}
 * @throws ArchiveException {@inheritDoc}
 * @throws NoSuchAlgorithmException {@inheritDoc}
 */
public File[] extractOdinContents(String outputDir)
        throws IOException, ArchiveException, NoSuchAlgorithmException {
    if (files != null) {
        //for sucessive calls
        return files.toArray(new File[files.size()]);
    }
    files = new ArrayList<File>();
    TarArchiveEntry entry;
    //parse the entries
    while ((entry = (TarArchiveEntry) tarStream.getNextEntry()) != null) {
        final File outputFile = new File(outputDir, entry.getName());
        //make folders
        if (entry.isDirectory()) {
            if (!outputFile.exists()) {
                System.out.println("creating dir:" + outputFile.getCanonicalFile());
                if (!outputFile.mkdirs()) {
                    throw new IllegalStateException();
                }
            }
            //create files
        } else {
            final OutputStream outputFileStream = new FileOutputStream(outputFile);
            System.out.println("decompressing file:" + outputFile.getCanonicalFile());
            byte[] buffer = new byte[1024 * 1024];
            int len;
            while ((len = tarStream.read(buffer)) >= 0) {
                outputFileStream.write(buffer, 0, len);
            }
            outputFileStream.close();
        }
        //add files to output array
        files.add(outputFile);
    }
    return files.toArray(new File[files.size()]);
}

From source file:de.uzk.hki.da.pkg.ArchiveBuilder.java

/**
 * Unpacks the contents of the given archive into the given folder
 * //from w  ww.  j  ava 2  s.c om
 * @param srcFile The archive container file
 * @param destFolder The destination folder
 * @param uncompress Indicates if the archive file is compressed (tgz file) or not (tar file)
 * @throws Exception
 */
public void unarchiveFolder(File srcFile, File destFolder, boolean uncompress) throws Exception {

    FileInputStream fIn = new FileInputStream(srcFile);
    BufferedInputStream in = new BufferedInputStream(fIn);

    TarArchiveInputStream tIn = null;
    GzipCompressorInputStream gzIn = null;

    if (uncompress) {
        gzIn = new GzipCompressorInputStream(in);
        tIn = new TarArchiveInputStream(gzIn);
    } else
        tIn = new TarArchiveInputStream(fIn);

    TarArchiveEntry entry;
    do {
        entry = tIn.getNextTarEntry();

        if (entry == null)
            break;

        File entryFile = new File(destFolder.getAbsolutePath() + "/" + entry.getName());

        if (entry.isDirectory())
            entryFile.mkdirs();
        else {
            new File(entryFile.getAbsolutePath().substring(0, entryFile.getAbsolutePath().lastIndexOf('/')))
                    .mkdirs();

            FileOutputStream out = new FileOutputStream(entryFile);
            IOUtils.copy(tIn, out);
            out.close();
        }
    } while (true);

    tIn.close();
    if (gzIn != null)
        gzIn.close();
    in.close();
    fIn.close();
}

From source file:drawnzer.anurag.tarHelper.TarManager.java

/**
 * /*from   w  w  w  .  j a v  a2  s  .c o m*/
 * THE DIRECTORY ENTRIES CANNOT BE SKIPPED LIKE WE SKIPPED IN
 * RAR OR ZIP MANAGER....
 * 
 * @return
 * @throws IOException
 */
public ArrayList<TarObj> generateList() throws IOException {
    list = new ArrayList<TarObj>();
    TarArchiveEntry entry;
    while ((entry = tar.getNextTarEntry()) != null) {

        boolean added = false;
        int len = list.size();
        String name = entry.getName();
        if (name.startsWith("/"))
            name = name.substring(1, name.length());
        if (entry.isDirectory())
            name = name.substring(0, name.length() - 1);

        if (path.equalsIgnoreCase("/")) {
            while (name.contains("/"))
                name = name.substring(0, name.lastIndexOf("/"));

            for (int i = 0; i < len; ++i) {
                if (list.get(i).getName().equalsIgnoreCase(name)) {
                    added = true;
                    break;
                }
            }
            if (!added && !name.equalsIgnoreCase(""))
                list.add(new TarObj(entry, name, ""));
        } else {
            try {
                name = name.substring(path.length() + 1, name.length());
                while (name.contains("/"))
                    name = name.substring(0, name.lastIndexOf("/"));

                if (len > 0) {
                    for (int i = 0; i < len; ++i)
                        if (list.get(i).getName().equalsIgnoreCase(name)) {
                            added = true;
                            break;
                        }
                    if (!added && entry.getName().startsWith(path))
                        list.add(new TarObj(entry, name, path));
                } else if (entry.getName().startsWith(path))
                    list.add(new TarObj(entry, name, path));
            } catch (Exception e) {

            }
        }
    }
    tar.close();
    sort();
    return list;
}