Example usage for org.apache.commons.compress.archivers ArchiveEntry isDirectory

List of usage examples for org.apache.commons.compress.archivers ArchiveEntry isDirectory

Introduction

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

Prototype

public boolean isDirectory();

Source Link

Document

True if the entry refers to a directory

Usage

From source file:com.github.nethad.clustermeister.integration.JPPFTestNode.java

private void untar(File tarFile) throws IOException {
    logger.info("Untar {}.", tarFile.getAbsolutePath());
    TarArchiveInputStream tarArchiveInputStream = new TarArchiveInputStream(new FileInputStream(tarFile));
    try {/*from w  ww.  j a  v a 2  s  . co  m*/
        ArchiveEntry tarEntry = tarArchiveInputStream.getNextEntry();
        while (tarEntry != null) {
            File destPath = new File(libDir, tarEntry.getName());
            logger.info("Unpacking {}.", destPath.getAbsoluteFile());
            if (!tarEntry.isDirectory()) {
                FileOutputStream fout = new FileOutputStream(destPath);
                final byte[] buffer = new byte[8192];
                int n = 0;
                while (-1 != (n = tarArchiveInputStream.read(buffer))) {
                    fout.write(buffer, 0, n);
                }
                fout.close();

            } else {
                destPath.mkdir();
            }
            tarEntry = tarArchiveInputStream.getNextEntry();
        }
    } finally {
        tarArchiveInputStream.close();
    }
}

From source file:com.qwazr.tools.ArchiverTool.java

public void extract(File sourceFile, File destDir) throws IOException, ArchiveException {
    final InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
    try {/*from  w w  w . j  a v  a 2 s  .c  o m*/
        ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is);
        try {
            ArchiveEntry entry;
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    new File(destDir, entry.getName()).mkdir();
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                File destFile = new File(destDir, entry.getName());
                File parentDir = destFile.getParentFile();
                if (!parentDir.exists())
                    parentDir.mkdirs();
                IOUtils.copy(in, destFile);
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.getPath(), e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.getPath(), e);
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.fizzed.stork.deploy.Archive.java

public Path unpack(Path unpackDir) throws IOException {
    Files.createDirectories(unpackDir);

    log.info("Unpacking {} to {}", file, unpackDir);

    // we need to know the top-level dir(s) created by unpack
    final Set<Path> firstLevelPaths = new LinkedHashSet<>();
    final AtomicInteger count = new AtomicInteger();

    try (ArchiveInputStream ais = newArchiveInputStream(file)) {
        ArchiveEntry entry;
        while ((entry = ais.getNextEntry()) != null) {
            try {
                Path entryFile = Paths.get(entry.getName());
                Path resolvedFile = unpackDir.resolve(entryFile);

                firstLevelPaths.add(entryFile.getName(0));

                log.debug("{}", resolvedFile);

                if (entry.isDirectory()) {
                    Files.createDirectories(resolvedFile);
                } else {
                    unpackEntry(ais, resolvedFile);
                    count.incrementAndGet();
                }/*from  ww  w  . j a va 2  s. c  om*/
            } catch (IOException | IllegalStateException | IllegalArgumentException e) {
                log.error("", e);
                throw new RuntimeException(e);
            }
        }
    }

    if (firstLevelPaths.size() != 1) {
        throw new IOException("Only archives with a single top-level directory are supported!");
    }

    Path assemblyDir = unpackDir.resolve(firstLevelPaths.iterator().next());

    log.info("Unpacked {} files to {}", count, assemblyDir);

    return assemblyDir;
}

From source file:autoupdater.FileDAO.java

/**
 * Untars a .tar.//from w ww.j  av  a2 s  . com
 *
 * @param fileToUntar
 * @return true if successful
 * @throws FileNotFoundException
 * @throws IOException
 */
private boolean untar(File fileToUntar) throws FileNotFoundException, IOException {
    boolean fileUntarred = false;
    String untarLocation = fileToUntar.getParentFile().getAbsolutePath();
    TarArchiveInputStream tarStream = null;
    try {
        tarStream = new TarArchiveInputStream(new FileInputStream(fileToUntar));
        BufferedReader bufferedTarReader = null;
        try {
            bufferedTarReader = new BufferedReader(new InputStreamReader(tarStream));
            ArchiveEntry entry;
            while ((entry = tarStream.getNextEntry()) != null) {
                byte[] buffer = new byte[8 * 1024];
                File tempFile = new File(String.format("%s/%s", untarLocation, entry.getName()));
                if (entry.isDirectory()) {
                    if (!tempFile.exists()) {
                        tempFile.mkdir();
                    }
                } else {
                    OutputStream output = new FileOutputStream(tempFile);
                    try {
                        int bytesRead;
                        while ((bytesRead = tarStream.read(buffer)) != -1) {
                            output.write(buffer, 0, bytesRead);
                        }
                    } finally {
                        output.close();
                    }
                    tempFile.setExecutable(true); // make sure the binary files can be executed
                }
            }
        } finally {
            if (bufferedTarReader != null) {
                bufferedTarReader.close();
            }
        }
    } finally {
        if (tarStream != null) {
            tarStream.close();
        }
    }
    return fileUntarred;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetLoader.java

private void extract(File aArchive, ArchiveInputStream aArchiveStream, File aTarget) throws IOException {
    ArchiveEntry entry = null;
    while ((entry = aArchiveStream.getNextEntry()) != null) {
        String name = entry.getName();

        // Ensure that the filename will not break the manifest
        if (name.contains("\n")) {
            throw new IllegalStateException("Filename must not contain line break");
        }// www  .  j a v  a 2  s  . co m

        File out = new File(aTarget, name);
        if (entry.isDirectory()) {
            FileUtils.forceMkdir(out);
        } else {
            FileUtils.copyInputStreamToFile(new CloseShieldInputStream(aArchiveStream), out);
        }
    }
}

From source file:com.netflix.spinnaker.halyard.backup.services.v1.BackupService.java

private void untarHalconfig(String halconfigDir, String halconfigTar) {
    FileInputStream tarInput = null;
    TarArchiveInputStream tarArchiveInputStream = null;

    try {//from   ww w  . j  ava 2  s . c  om
        tarInput = new FileInputStream(new File(halconfigTar));
        tarArchiveInputStream = (TarArchiveInputStream) new ArchiveStreamFactory()
                .createArchiveInputStream("tar", tarInput);

    } catch (IOException | ArchiveException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to open backup: " + e.getMessage(), e);
    }

    try {
        ArchiveEntry archiveEntry = tarArchiveInputStream.getNextEntry();
        while (archiveEntry != null) {
            String entryName = archiveEntry.getName();
            Path outputPath = Paths.get(halconfigDir, entryName);
            File outputFile = outputPath.toFile();
            if (!outputFile.getParentFile().exists()) {
                outputFile.getParentFile().mkdirs();
            }

            if (archiveEntry.isDirectory()) {
                outputFile.mkdir();
            } else {
                Files.copy(tarArchiveInputStream, outputPath, REPLACE_EXISTING);
            }

            archiveEntry = tarArchiveInputStream.getNextEntry();
        }
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL, "Failed to read archive entry: " + e.getMessage(), e);
    }
}

From source file:at.beris.virtualfile.provider.LocalArchivedFileOperationProvider.java

@Override
public Boolean exists(FileModel model) throws IOException {
    String archivePath = getArchivePath(model);
    String targetArchiveEntryPath = model.getUrl().getPath().substring(archivePath.length() + 1);

    ArchiveInputStream ais = null;/*ww w . j  a v  a 2 s.  com*/
    InputStream fis = null;

    try {
        ArchiveStreamFactory factory = new ArchiveStreamFactory();
        fis = new BufferedInputStream(new FileInputStream(new java.io.File(archivePath)));
        ais = factory.createArchiveInputStream(fis);
        ArchiveEntry archiveEntry;

        while ((archiveEntry = ais.getNextEntry()) != null) {
            String archiveEntryPath = archiveEntry.getName();

            if (archiveEntryPath.equals(targetArchiveEntryPath)) {
                model.setSize(archiveEntry.getSize());
                model.setLastModifiedTime(FileTime.fromMillis(archiveEntry.getLastModifiedDate().getTime()));

                if (model.getUrl().toString().endsWith("/") && (!archiveEntry.isDirectory())) {
                    String urlString = model.getUrl().toString();
                    model.setUrl(UrlUtils.newUrl(urlString.substring(0, urlString.length() - 1)));
                } else if (!model.getUrl().toString().endsWith("/") && (archiveEntry.isDirectory())) {
                    String urlString = model.getUrl().toString() + "/";
                    model.setUrl(UrlUtils.newUrl(urlString));
                }
                break;
            }
        }
    } catch (ArchiveException e) {
        throw new IOException(e);
    } finally {
        if (ais != null)
            ais.close();
        if (fis != null)
            fis.close();
    }
    return false;
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extract(ActionDescription aAction, Path aArchive, ArchiveInputStream aAStream, Path aTarget)
        throws IOException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aArchive.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    ArchiveEntry entry = null;
    while ((entry = aAStream.getNextEntry()) != null) {
        String name = stripLeadingFolders(entry.getName(), strip);

        if (name == null) {
            // Stripped to null - nothing left to extract - continue;
            continue;
        }/*from  w  w w  . ja  va2 s . co  m*/

        if (filter.accept(name)) {
            Path out = aTarget.resolve(base).resolve(name);
            if (entry.isDirectory()) {
                Files.createDirectories(out);
            } else {
                Files.createDirectories(out.getParent());
                Files.copy(aAStream, out);
            }
        }
    }
}

From source file:cc.arduino.utils.ArchiveExtractor.java

public void extract(File archiveFile, File destFolder, int stripPath, boolean overwrite)
        throws IOException, InterruptedException {

    // Folders timestamps must be set at the end of archive extraction
    // (because creating a file in a folder alters the folder's timestamp)
    Map<File, Long> foldersTimestamps = new HashMap<>();

    ArchiveInputStream in = null;//  w  ww.jav  a  2  s. c  o m
    try {

        // Create an ArchiveInputStream with the correct archiving algorithm
        if (archiveFile.getName().endsWith("tar.bz2")) {
            in = new TarArchiveInputStream(new BZip2CompressorInputStream(new FileInputStream(archiveFile)));
        } else if (archiveFile.getName().endsWith("zip")) {
            in = new ZipArchiveInputStream(new FileInputStream(archiveFile));
        } else if (archiveFile.getName().endsWith("tar.gz")) {
            in = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(archiveFile)));
        } else if (archiveFile.getName().endsWith("tar")) {
            in = new TarArchiveInputStream(new FileInputStream(archiveFile));
        } else {
            throw new IOException("Archive format not supported.");
        }

        String pathPrefix = "";

        Map<File, File> hardLinks = new HashMap<>();
        Map<File, Integer> hardLinksMode = new HashMap<>();
        Map<File, String> symLinks = new HashMap<>();
        Map<File, Long> symLinksModifiedTimes = new HashMap<>();

        // Cycle through all the archive entries
        while (true) {
            ArchiveEntry entry = in.getNextEntry();
            if (entry == null) {
                break;
            }

            // Extract entry info
            long size = entry.getSize();
            String name = entry.getName();
            boolean isDirectory = entry.isDirectory();
            boolean isLink = false;
            boolean isSymLink = false;
            String linkName = null;
            Integer mode = null;
            long modifiedTime = entry.getLastModifiedDate().getTime();

            {
                // Skip MacOSX metadata
                // http://superuser.com/questions/61185/why-do-i-get-files-like-foo-in-my-tarball-on-os-x
                int slash = name.lastIndexOf('/');
                if (slash == -1) {
                    if (name.startsWith("._")) {
                        continue;
                    }
                } else {
                    if (name.substring(slash + 1).startsWith("._")) {
                        continue;
                    }
                }
            }

            // Skip git metadata
            // http://www.unix.com/unix-for-dummies-questions-and-answers/124958-file-pax_global_header-means-what.html
            if (name.contains("pax_global_header")) {
                continue;
            }

            if (entry instanceof TarArchiveEntry) {
                TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                mode = tarEntry.getMode();
                isLink = tarEntry.isLink();
                isSymLink = tarEntry.isSymbolicLink();
                linkName = tarEntry.getLinkName();
            }

            // On the first archive entry, if requested, detect the common path
            // prefix to be stripped from filenames
            if (stripPath > 0 && pathPrefix.isEmpty()) {
                int slash = 0;
                while (stripPath > 0) {
                    slash = name.indexOf("/", slash);
                    if (slash == -1) {
                        throw new IOException("Invalid archive: it must contain a single root folder");
                    }
                    slash++;
                    stripPath--;
                }
                pathPrefix = name.substring(0, slash);
            }

            // Strip the common path prefix when requested
            if (!name.startsWith(pathPrefix)) {
                throw new IOException("Invalid archive: it must contain a single root folder while file " + name
                        + " is outside " + pathPrefix);
            }
            name = name.substring(pathPrefix.length());
            if (name.isEmpty()) {
                continue;
            }
            File outputFile = new File(destFolder, name);

            File outputLinkedFile = null;
            if (isLink) {
                if (!linkName.startsWith(pathPrefix)) {
                    throw new IOException("Invalid archive: it must contain a single root folder while file "
                            + linkName + " is outside " + pathPrefix);
                }
                linkName = linkName.substring(pathPrefix.length());
                outputLinkedFile = new File(destFolder, linkName);
            }
            if (isSymLink) {
                // Symbolic links are referenced with relative paths
                outputLinkedFile = new File(linkName);
                if (outputLinkedFile.isAbsolute()) {
                    System.err.println(I18n.format(tr("Warning: file {0} links to an absolute path {1}"),
                            outputFile, outputLinkedFile));
                    System.err.println();
                }
            }

            // Safety check
            if (isDirectory) {
                if (outputFile.isFile() && !overwrite) {
                    throw new IOException(
                            "Can't create folder " + outputFile + ", a file with the same name exists!");
                }
            } else {
                // - isLink
                // - isSymLink
                // - anything else
                if (outputFile.exists() && !overwrite) {
                    throw new IOException("Can't extract file " + outputFile + ", file already exists!");
                }
            }

            // Extract the entry
            if (isDirectory) {
                if (!outputFile.exists() && !outputFile.mkdirs()) {
                    throw new IOException("Could not create folder: " + outputFile);
                }
                foldersTimestamps.put(outputFile, modifiedTime);
            } else if (isLink) {
                hardLinks.put(outputFile, outputLinkedFile);
                hardLinksMode.put(outputFile, mode);
            } else if (isSymLink) {
                symLinks.put(outputFile, linkName);
                symLinksModifiedTimes.put(outputFile, modifiedTime);
            } else {
                // Create the containing folder if not exists
                if (!outputFile.getParentFile().isDirectory()) {
                    outputFile.getParentFile().mkdirs();
                }
                copyStreamToFile(in, size, outputFile);
                outputFile.setLastModified(modifiedTime);
            }

            // Set file/folder permission
            if (mode != null && !isSymLink && outputFile.exists()) {
                platform.chmod(outputFile, mode);
            }
        }

        for (Map.Entry<File, File> entry : hardLinks.entrySet()) {
            if (entry.getKey().exists() && overwrite) {
                entry.getKey().delete();
            }
            platform.link(entry.getValue(), entry.getKey());
            Integer mode = hardLinksMode.get(entry.getKey());
            if (mode != null) {
                platform.chmod(entry.getKey(), mode);
            }
        }

        for (Map.Entry<File, String> entry : symLinks.entrySet()) {
            if (entry.getKey().exists() && overwrite) {
                entry.getKey().delete();
            }
            platform.symlink(entry.getValue(), entry.getKey());
            entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()));
        }

    } finally {
        IOUtils.closeQuietly(in);
    }

    // Set folders timestamps
    for (File folder : foldersTimestamps.keySet()) {
        folder.setLastModified(foldersTimestamps.get(folder));
    }
}

From source file:com.nike.cerberus.operation.dashboard.PublishDashboardOperation.java

private File extractArtifact(final URL artifactUrl) {
    final File extractionDirectory = Files.createTempDir();
    logger.debug("Extracting artifact contents to {}", extractionDirectory.getAbsolutePath());

    ArchiveEntry entry;
    TarArchiveInputStream tarArchiveInputStream = null;
    try {/*from w ww .j  a v  a 2  s. c  o  m*/
        tarArchiveInputStream = new TarArchiveInputStream(
                new GzipCompressorInputStream(artifactUrl.openStream()));
        entry = tarArchiveInputStream.getNextEntry();
        while (entry != null) {
            String entryName = entry.getName();
            if (entry.getName().startsWith("./")) {
                entryName = entry.getName().substring(1);
            }
            final File destPath = new File(extractionDirectory, entryName);
            if (!entry.isDirectory()) {
                final File fileParentDir = new File(destPath.getParent());
                if (!fileParentDir.exists()) {
                    FileUtils.forceMkdir(fileParentDir);
                }
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(destPath);
                    IOUtils.copy(tarArchiveInputStream, fileOutputStream);
                } finally {
                    IOUtils.closeQuietly(fileOutputStream);
                }
            }
            entry = tarArchiveInputStream.getNextEntry();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(tarArchiveInputStream);
    }

    return extractionDirectory;
}