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: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.
 *///  ww  w.j  a  v a2 s.  c  o  m
@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.datos.vfs.provider.tar.TarFileObject.java

/**
 * Sets the details for this file object.
 * //w  ww .j  a v a  2  s  .  co  m
 * Consider this method package private. TODO Might be made package private in the next major version. 
 */
protected void setTarEntry(final TarArchiveEntry entry) {
    if (this.entry != null) {
        return;
    }

    if (entry == null || entry.isDirectory()) {
        type = FileType.FOLDER;
    } else {
        type = FileType.FILE;
    }

    this.entry = entry;
}

From source file:com.buaa.cfs.utils.FileUtil.java

private static void unpackEntries(TarArchiveInputStream tis, TarArchiveEntry entry, File outputDir)
        throws IOException {
    if (entry.isDirectory()) {
        File subDir = new File(outputDir, entry.getName());
        if (!subDir.mkdirs() && !subDir.isDirectory()) {
            throw new IOException("Mkdirs failed to create tar internal dir " + outputDir);
        }//from w w  w .jav  a2s  .co m

        for (TarArchiveEntry e : entry.getDirectoryEntries()) {
            unpackEntries(tis, e, subDir);
        }

        return;
    }

    File outputFile = new File(outputDir, entry.getName());
    if (!outputFile.getParentFile().exists()) {
        if (!outputFile.getParentFile().mkdirs()) {
            throw new IOException("Mkdirs failed to create tar internal dir " + outputDir);
        }
    }

    int count;
    byte data[] = new byte[2048];
    BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outputFile));

    while ((count = tis.read(data)) != -1) {
        outputStream.write(data, 0, count);
    }

    outputStream.flush();
    outputStream.close();
}

From source file:adams.core.io.TarUtils.java

/**
 * Decompresses the specified file from a tar file.
 *
 * @param input   the tar file to decompress
 * @param archiveFile   the file from the archive to extract
 * @param output   the name of the output file
 * @param createDirs   whether to create the directory structure represented
 *          by output file/*w w  w  . j a v a  2s.  c  o  m*/
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      whether file was successfully extracted
 */
public static boolean decompress(File input, String archiveFile, File output, boolean createDirs,
        int bufferSize, StringBuilder errors) {
    boolean result;
    FileInputStream fis;
    TarArchiveInputStream archive;
    TarArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    FileOutputStream fos;
    BufferedOutputStream out;
    int len;
    String error;
    long size;
    long read;

    result = false;
    archive = null;
    fis = null;
    fos = null;
    try {
        // decompress archive
        buffer = new byte[bufferSize];
        fis = new FileInputStream(input.getAbsoluteFile());
        archive = openArchiveForReading(input, fis);
        while ((entry = archive.getNextTarEntry()) != null) {
            if (entry.isDirectory())
                continue;
            if (!entry.getName().equals(archiveFile))
                continue;

            out = null;
            outName = null;
            try {
                // output name
                outName = output.getAbsolutePath();

                // create directory, if necessary
                outFile = new File(outName).getParentFile();
                if (!outFile.exists()) {
                    if (!createDirs) {
                        error = "Output directory '" + outFile.getAbsolutePath() + " does not exist', "
                                + "skipping extraction of '" + outName + "'!";
                        System.err.println(error);
                        errors.append(error + "\n");
                        break;
                    } else {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            break;
                        }
                    }
                }

                // extract data
                fos = new FileOutputStream(outName);
                out = new BufferedOutputStream(fos, bufferSize);
                size = entry.getSize();
                read = 0;
                while (read < size) {
                    len = archive.read(buffer);
                    read += len;
                    out.write(buffer, 0, len);
                }

                result = true;
                break;
            } catch (Exception e) {
                result = false;
                error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                System.err.println(error);
                errors.append(error + "\n");
            } finally {
                FileUtils.closeQuietly(out);
                FileUtils.closeQuietly(fos);
            }
        }
    } catch (Exception e) {
        result = false;
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        FileUtils.closeQuietly(fis);
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

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  . ja va 2 s.  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;
}

From source file:adams.core.io.TarUtils.java

/**
 * Decompresses the files in a tar file. Files can be filtered based on their
 * filename, using a regular expression (the matching sense can be inverted).
 *
 * @param input   the tar file to decompress
 * @param outputDir   the directory where to store the extracted files
 * @param createDirs   whether to re-create the directory structure from the
 *          tar file//from w w w  .ja  v  a  2  s . c om
 * @param match   the regular expression that the files are matched against
 * @param invertMatch   whether to invert the matching sense
 * @param bufferSize   the buffer size to use
 * @param errors   for storing potential errors
 * @return      the successfully extracted files
 */
public static List<File> decompress(File input, File outputDir, boolean createDirs, BaseRegExp match,
        boolean invertMatch, int bufferSize, StringBuilder errors) {
    List<File> result;
    FileInputStream fis;
    TarArchiveInputStream archive;
    TarArchiveEntry entry;
    File outFile;
    String outName;
    byte[] buffer;
    BufferedOutputStream out;
    FileOutputStream fos;
    int len;
    String error;
    long size;
    long read;

    result = new ArrayList<>();
    archive = null;
    fis = null;
    fos = null;
    try {
        // decompress archive
        buffer = new byte[bufferSize];
        fis = new FileInputStream(input.getAbsoluteFile());
        archive = openArchiveForReading(input, fis);
        while ((entry = archive.getNextTarEntry()) != null) {
            if (entry.isDirectory() && !createDirs)
                continue;

            // does name match?
            if (!match.isMatchAll() && !match.isEmpty()) {
                if (invertMatch && match.isMatch(entry.getName()))
                    continue;
                else if (!invertMatch && !match.isMatch(entry.getName()))
                    continue;
            }

            // extract
            if (entry.isDirectory() && createDirs) {
                outFile = new File(outputDir.getAbsolutePath() + File.separator + entry.getName());
                if (!outFile.mkdirs()) {
                    error = "Failed to create directory '" + outFile.getAbsolutePath() + "'!";
                    System.err.println(error);
                    errors.append(error + "\n");
                }
            } else {
                out = null;
                outName = null;
                try {
                    // assemble output name
                    outName = outputDir.getAbsolutePath() + File.separator;
                    if (createDirs)
                        outName += entry.getName();
                    else
                        outName += new File(entry.getName()).getName();

                    // create directory, if necessary
                    outFile = new File(outName).getParentFile();
                    if (!outFile.exists()) {
                        if (!outFile.mkdirs()) {
                            error = "Failed to create directory '" + outFile.getAbsolutePath() + "', "
                                    + "skipping extraction of '" + outName + "'!";
                            System.err.println(error);
                            errors.append(error + "\n");
                            continue;
                        }
                    }

                    // extract data
                    fos = new FileOutputStream(outName);
                    out = new BufferedOutputStream(fos, bufferSize);
                    size = entry.getSize();
                    read = 0;
                    while (read < size) {
                        len = archive.read(buffer);
                        read += len;
                        out.write(buffer, 0, len);
                    }
                    result.add(new File(outName));
                } catch (Exception e) {
                    error = "Error extracting '" + entry.getName() + "' to '" + outName + "': " + e;
                    System.err.println(error);
                    errors.append(error + "\n");
                } finally {
                    FileUtils.closeQuietly(out);
                    FileUtils.closeQuietly(fos);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        errors.append("Error occurred: " + e + "\n");
    } finally {
        FileUtils.closeQuietly(fis);
        if (archive != null) {
            try {
                archive.close();
            } catch (Exception e) {
                // ignored
            }
        }
    }

    return result;
}

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

/**
 * Unarchives the arvive into the pBaseDir
 * @param baseDir//from   w  ww.j  av 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:com.foreignreader.util.WordNetExtractor.java

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

    try {/* ww  w .  j a v a  2s.c o 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: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 w w .  j ava  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.dtstack.jlogstash.inputs.ReadTarFile.java

public BufferedReader getNextBuffer() {

    if (currBuff != null) {
        //?currBuffer??inputstream
        currBuff = null;//  w  ww  .j  a  v  a2 s.  c o m
    }

    TarArchiveEntry entry = null;

    try {
        while ((entry = tarAchive.getNextTarEntry()) != null) {
            if (entry.isDirectory()) {
                continue;
            }

            currFileName = entry.getName();
            currFileSize = (int) entry.getSize();
            String identify = getIdentify(currFileName);
            long skipNum = getSkipNum(identify);
            if (skipNum >= entry.getSize()) {
                continue;
            }

            tarAchive.skip(skipNum);
            currBuff = new BufferedReader(new InputStreamReader(tarAchive, encoding));
            break;
        }

    } catch (Exception e) {
        logger.error("", e);
    }

    if (currBuff == null) {
        try {
            doAfterReaderOver();
        } catch (IOException e) {
            logger.error("", e);
        }
    }

    return currBuff;
}