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

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

Introduction

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

Prototype

public Date getLastModifiedDate();

Source Link

Document

The last modified date of the entry.

Usage

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

public static IStatus extract(ArchiveInputStream in, File destFolder, int stripPath, boolean overwrite,
        IProgressMonitor pMonitor) 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<>();

    String pathPrefix = new String();

    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;
        }/*from  w  ww. j av  a  2s.  com*/

        // 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 = new Long(entry.getLastModifiedDate().getTime());

        pMonitor.subTask("Processing " + name); //$NON-NLS-1$

        {
            // 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("._")) { //$NON-NLS-1$
                    continue;
                }
            } else {
                if (name.substring(slash + 1).startsWith("._")) { //$NON-NLS-1$
                    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")) { //$NON-NLS-1$
            continue;
        }

        if (entry instanceof TarArchiveEntry) {
            TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
            mode = new Integer(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
        int localstripPath = stripPath;
        if (localstripPath > 0 && pathPrefix.isEmpty()) {
            int slash = 0;
            while (localstripPath > 0) {
                slash = name.indexOf("/", slash); //$NON-NLS-1$
                if (slash == -1) {
                    throw new IOException(Messages.Manager_archiver_eror_single_root_folder_required);
                }
                slash++;
                localstripPath--;
            }
            pathPrefix = name.substring(0, slash);
        }

        // Strip the common path prefix when requested
        if (!name.startsWith(pathPrefix)) {
            throw new IOException(Messages.Manager_archive_error_root_folder_name_mismatch.replace(FILE, name)
                    .replace(FOLDER, pathPrefix));

        }
        name = name.substring(pathPrefix.length());
        if (name.isEmpty()) {
            continue;
        }
        File outputFile = new File(destFolder, name);

        File outputLinkedFile = null;
        if (isLink && linkName != null) {
            if (!linkName.startsWith(pathPrefix)) {
                throw new IOException(Messages.Manager_archive_error_root_folder_name_mismatch
                        .replace(FILE, name).replace(FOLDER, 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(Messages.Manager_archive_error_symbolic_link_to_absolute_path
                        .replace(FILE, outputFile.toString()).replace(FOLDER, outputLinkedFile.toString()));
                System.err.println();
            }
        }

        // Safety check
        if (isDirectory) {
            if (outputFile.isFile() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_create_folder_exists.replace(FILE, outputFile.getPath()));
            }
        } else {
            // - isLink
            // - isSymLink
            // - anything else
            if (outputFile.exists() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_extract_file_exist.replace(FILE, outputFile.getPath()));
            }
        }

        // Extract the entry
        if (isDirectory) {
            if (!outputFile.exists() && !outputFile.mkdirs()) {
                throw new IOException(Messages.Manager_Cant_create_folder.replace(FILE, outputFile.getPath()));
            }
            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.longValue());
        }

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

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

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

        symlink(entry.getValue(), entry.getKey());
        entry.getKey().setLastModified(symLinksModifiedTimes.get(entry.getKey()).longValue());
    }

    // Set folders timestamps
    for (Map.Entry<File, Long> entry : foldersTimestamps.entrySet()) {
        entry.getKey().setLastModified(entry.getValue().longValue());
    }

    return Status.OK_STATUS;

}

From source file:de.dentrassi.eclipse.rpm.editor.EditorImpl.java

private RpmInformation load(final InputStream stream) {
    try (RpmInputStream in = new RpmInputStream(stream)) {
        final RpmLead lead = in.getLead();

        final InputHeader<RpmTag> header = in.getPayloadHeader();
        final InputHeader<RpmSignatureTag> sigHeader = in.getSignatureHeader();

        final CpioArchiveInputStream cpio = in.getCpioStream();

        ArchiveEntry entry;

        final List<FileEntry> files = new ArrayList<>();
        while ((entry = cpio.getNextEntry()) != null) {
            final FileEntry fe = new FileEntry(entry.getName(), entry.getSize(),
                    entry.getLastModifiedDate().toInstant());
            files.add(fe);//from   w  ww  .java 2  s  .  c  om
        }

        return new RpmInformation(lead, header, sigHeader, files);
    } catch (final IOException e) {
        return null;
    }
}

From source file:com.github.n_i_e.dirtreedb.ApacheCompressArchiveLister.java

@Override
protected PathEntry getNext() throws IOException {
    ArchiveEntry z = instream.getNextEntry();
    if (z == null) {
        return null;
    }/*from   w w w  .ja  v a2s. c  om*/
    int newtype = z.isDirectory() ? PathEntry.COMPRESSEDFOLDER : PathEntry.COMPRESSEDFILE;
    String s = z.getName();
    s = s.replace("\\", "/");
    PathEntry next_entry = new PathEntry(getBasePath().getPath() + "/" + s, newtype);
    next_entry.setDateLastModified(z.getLastModifiedDate().getTime());
    next_entry.setStatus(PathEntry.DIRTY);
    next_entry.setSize(z.getSize());
    next_entry.setCompressedSize(z.getSize());
    if (isCsumRequested() && newtype == PathEntry.COMPRESSEDFILE) {
        next_entry.setCsum(instream);
    }
    if (next_entry.getSize() < 0) {
        next_entry.setSize(0);
    }
    if (next_entry.getCompressedSize() < 0) {
        next_entry.setCompressedSize(next_entry.getSize());
    }
    return next_entry;
}

From source file:com.github.n_i_e.dirtreedb.ApacheCompressCompressingArchiveLister.java

@Override
protected PathEntry getNext() throws IOException {
    ArchiveEntry z = instream.getNextEntry();
    if (z == null) {
        close();//  ww  w. j  a  v  a  2 s . co m
        return null;
    }
    int newtype = z.isDirectory() ? PathEntry.COMPRESSEDFOLDER : PathEntry.COMPRESSEDFILE;
    String s = z.getName();
    s = s.replace("\\", "/");
    PathEntry next_entry = new PathEntry(getBasePath().getPath() + "/" + s, newtype);
    next_entry.setDateLastModified(z.getLastModifiedDate().getTime());
    next_entry.setStatus(PathEntry.DIRTY);
    next_entry.setSize(z.getSize());
    next_entry.setCompressedSize(z.getSize());
    if (isCsumRequested() && newtype == PathEntry.COMPRESSEDFILE) {
        next_entry.setCsum(instream);
    }
    if (next_entry.getSize() < 0) {
        next_entry.setSize(0);
    }
    if (next_entry.getCompressedSize() < 0) {
        next_entry.setCompressedSize(next_entry.getSize());
    }
    return next_entry;
}

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

public static IStatus extract(ArchiveInputStream in, File destFolder, int stripPath, boolean overwrite,
        IProgressMonitor pMonitor) 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<>();

    String pathPrefix = ""; //$NON-NLS-1$

    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;
        }/*from ww w .  j  ava 2s . co m*/

        // 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 = new Long(entry.getLastModifiedDate().getTime());

        pMonitor.subTask("Processing " + name); //$NON-NLS-1$

        {
            // 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("._")) { //$NON-NLS-1$
                    continue;
                }
            } else {
                if (name.substring(slash + 1).startsWith("._")) { //$NON-NLS-1$
                    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")) { //$NON-NLS-1$
            continue;
        }

        if (entry instanceof TarArchiveEntry) {
            TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
            mode = new Integer(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
        int localstripPath = stripPath;
        if (localstripPath > 0 && pathPrefix.isEmpty()) {
            int slash = 0;
            while (localstripPath > 0) {
                slash = name.indexOf("/", slash); //$NON-NLS-1$
                if (slash == -1) {
                    throw new IOException(Messages.Manager_no_single_root_folder);
                }
                slash++;
                localstripPath--;
            }
            pathPrefix = name.substring(0, slash);
        }

        // Strip the common path prefix when requested
        if (!name.startsWith(pathPrefix)) {
            throw new IOException(Messages.Manager_no_single_root_folder_while_file + name
                    + Messages.Manager_is_outside + pathPrefix);
        }
        name = name.substring(pathPrefix.length());
        if (name.isEmpty()) {
            continue;
        }
        File outputFile = new File(destFolder, name);

        File outputLinkedFile = null;
        if (isLink && linkName != null) {
            if (!linkName.startsWith(pathPrefix)) {
                throw new IOException(Messages.Manager_no_single_root_folder_while_file + linkName
                        + Messages.Manager_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(Messages.Manager_Warning_file + outputFile
                        + Messages.Manager_links_to_absolute_path + outputLinkedFile);
                System.err.println();
            }
        }

        // Safety check
        if (isDirectory) {
            if (outputFile.isFile() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_create_folder + outputFile + Messages.Manager_File_exists);
            }
        } else {
            // - isLink
            // - isSymLink
            // - anything else
            if (outputFile.exists() && !overwrite) {
                throw new IOException(
                        Messages.Manager_Cant_extract_file + outputFile + Messages.Manager_File_already_exists);
            }
        }

        // Extract the entry
        if (isDirectory) {
            if (!outputFile.exists() && !outputFile.mkdirs()) {
                throw new IOException(Messages.Manager_Cant_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.longValue());
        }

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

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

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

    // Set folders timestamps
    for (Map.Entry<File, Long> entry : foldersTimestamps.entrySet()) {
        entry.getKey().setLastModified(entry.getValue().longValue());
    }

    return Status.OK_STATUS;

}

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;//from   w w  w.  j a va2s  .  c  o m
    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:consulo.cold.runner.execute.target.artifacts.Generator.java

public void buildDistributionInArchive(String distZip, @Nullable String jdkArchivePath, String path,
        String archiveOutType) throws Exception {
    myListener.info("Build: " + path);

    ArchiveStreamFactory factory = new ArchiveStreamFactory();

    final File fileZip = new File(myDistPath, distZip);

    final List<String> executables = Arrays.asList(ourExecutable);

    try (OutputStream pathStream = createOutputStream(archiveOutType, path)) {
        ArchiveOutputStream archiveOutputStream = factory.createArchiveOutputStream(archiveOutType, pathStream);
        if (archiveOutputStream instanceof TarArchiveOutputStream) {
            ((TarArchiveOutputStream) archiveOutputStream).setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        }/*from   w  ww  . jav a2 s.c om*/

        // move Consulo to archive, and change permissions
        try (InputStream is = new FileInputStream(fileZip)) {
            try (ArchiveInputStream ais = factory.createArchiveInputStream(ArchiveStreamFactory.ZIP, is)) {
                ArchiveEntry tempEntry = ais.getNextEntry();
                while (tempEntry != null) {
                    final ArchiveEntryWrapper newEntry = createEntry(archiveOutType, tempEntry.getName(),
                            tempEntry);

                    newEntry.setMode(extractMode(tempEntry));
                    newEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                    if (executables.contains(tempEntry.getName())) {
                        newEntry.setMode(0b111_101_101);
                    }

                    copyEntry(archiveOutputStream, ais, tempEntry, newEntry);

                    tempEntry = ais.getNextEntry();
                }
            }
        }

        boolean mac = distZip.contains("mac");

        // jdk check
        if (jdkArchivePath != null) {
            try (InputStream is = new FileInputStream(jdkArchivePath)) {
                try (GzipCompressorInputStream gz = new GzipCompressorInputStream(is)) {
                    try (ArchiveInputStream ais = factory.createArchiveInputStream(ArchiveStreamFactory.TAR,
                            gz)) {
                        ArchiveEntry tempEntry = ais.getNextEntry();
                        while (tempEntry != null) {
                            final String name = tempEntry.getName();

                            // is our path
                            if (!mac && name.startsWith("jre/")) {
                                final ArchiveEntryWrapper jdkEntry = createEntry(archiveOutType,
                                        "Consulo/platform/buildSNAPSHOT/" + name, tempEntry);
                                jdkEntry.setMode(extractMode(tempEntry));
                                jdkEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                                copyEntry(archiveOutputStream, ais, tempEntry, jdkEntry);
                            } else if (mac && name.startsWith("jdk")) {
                                boolean needAddToArchive = true;
                                for (String prefix : ourMacSkipJdkList) {
                                    if (name.startsWith(prefix)) {
                                        needAddToArchive = false;
                                    }
                                }

                                if (needAddToArchive) {
                                    final ArchiveEntryWrapper jdkEntry = createEntry(archiveOutType,
                                            "Consulo.app/Contents/platform/buildSNAPSHOT/jre/" + name,
                                            tempEntry);
                                    jdkEntry.setMode(extractMode(tempEntry));
                                    jdkEntry.setTime(tempEntry.getLastModifiedDate().getTime());

                                    copyEntry(archiveOutputStream, ais, tempEntry, jdkEntry);
                                }
                            }

                            tempEntry = ais.getNextEntry();
                        }
                    }
                }
            }
        }

        archiveOutputStream.finish();
    }
}

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;//from   w w w .  j  a  va  2  s  .c  om
    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.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }//from   w ww  . j a  va  2  s .  co  m
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}

From source file:org.apache.ant.compress.resources.CommonsCompressArchiveResource.java

protected void setEntry(ArchiveEntry e) {
    if (e == null) {
        setExists(false);//from   w w w  .j  a v  a2 s .  c  o  m
        return;
    }
    setName(e.getName());
    setExists(true);
    setLastModified(e.getLastModifiedDate().getTime());
    setDirectory(e.isDirectory());
    setSize(e.getSize());
    setMode(EntryHelper.getMode(e));
    uid = EntryHelper.getUserId(e);
    gid = EntryHelper.getGroupId(e);
}