Example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry setSize

List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveEntry setSize

Introduction

In this page you can find the example usage for org.apache.commons.compress.archivers.tar TarArchiveEntry setSize.

Prototype

public void setSize(long size) 

Source Link

Document

Set this entry's file size.

Usage

From source file:org.apache.openaz.xacml.admin.components.PolicyWorkspace.java

@Override
public InputStream getStream() {
    ///*ww  w  . java  2 s . c o  m*/
    // Grab our working repository
    //
    final Path repoPath = ((XacmlAdminUI) getUI()).getUserGitPath();
    Path workspacePath = ((XacmlAdminUI) getUI()).getUserWorkspace();
    final Path tarFile = Paths.get(workspacePath.toString(), "Repository.tgz");

    try (OutputStream os = Files.newOutputStream(tarFile)) {
        try (GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(os)) {
            try (TarArchiveOutputStream tarOut = new TarArchiveOutputStream(gzOut)) {

                tarOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

                Files.walkFileTree(repoPath, new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        if (dir.getFileName().toString().startsWith(".git")) {
                            return FileVisitResult.SKIP_SUBTREE;
                        }
                        Path relative = repoPath.relativize(dir);
                        if (relative.toString().isEmpty()) {
                            return super.preVisitDirectory(dir, attrs);
                        }
                        TarArchiveEntry entry = new TarArchiveEntry(relative.toFile());
                        tarOut.putArchiveEntry(entry);
                        tarOut.closeArchiveEntry();
                        return super.preVisitDirectory(dir, attrs);
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (file.getFileName().toString().endsWith(".xml") == false) {
                            return super.visitFile(file, attrs);
                        }
                        Path relative = repoPath.relativize(file);
                        TarArchiveEntry entry = new TarArchiveEntry(relative.toFile());
                        entry.setSize(Files.size(file));
                        tarOut.putArchiveEntry(entry);
                        try {
                            IOUtils.copy(Files.newInputStream(file), tarOut);
                        } catch (IOException e) {
                            logger.error(e);
                        }
                        tarOut.closeArchiveEntry();
                        return super.visitFile(file, attrs);
                    }

                });
                tarOut.finish();
            }
        }
    } catch (IOException e) {
        logger.error(e);
    }
    try {
        return Files.newInputStream(tarFile);
    } catch (IOException e) {
        logger.error(e);
    }
    return null;
}

From source file:org.apache.tika.server.TarWriter.java

private static void tarStoreBuffer(TarArchiveOutputStream zip, String name, byte[] dataBuffer)
        throws IOException {
    TarArchiveEntry entry = new TarArchiveEntry(name);

    entry.setSize(dataBuffer.length);

    zip.putArchiveEntry(entry);//from w w w .  j av  a2 s  . c om

    zip.write(dataBuffer);

    zip.closeArchiveEntry();
}

From source file:org.artifactory.util.ArchiveUtils.java

/**
 * Use for writing streams - must specify file size in advance as well
 *///from   w  w  w  .  j  a v  a2 s .c  o  m
public static ArchiveEntry createArchiveEntry(String relativePath, ArchiveType archiveType, long size) {
    switch (archiveType) {
    case ZIP:
        ZipArchiveEntry zipEntry = new ZipArchiveEntry(relativePath);
        zipEntry.setSize(size);
        return zipEntry;
    case TAR:
    case TARGZ:
    case TGZ:
        TarArchiveEntry tarEntry = new TarArchiveEntry(relativePath);
        tarEntry.setSize(size);
        return tarEntry;
    }
    throw new IllegalArgumentException("Unsupported archive type: '" + archiveType + "'");
}

From source file:org.codehaus.plexus.archiver.tar.TarArchiver.java

/**
 * tar a file//from  ww  w .j  ava  2 s  .  c  o m
 *
 * @param entry the file to tar
 * @param tOut  the output stream
 * @param vPath the path name of the file to tar
 * @throws IOException on error
 */
protected void tarFile(ArchiveEntry entry, TarArchiveOutputStream tOut, String vPath)
        throws ArchiverException, IOException {

    // don't add "" to the archive
    if (vPath.length() <= 0) {
        return;
    }

    if (entry.getResource().isDirectory() && !vPath.endsWith("/")) {
        vPath += "/";
    }

    if (vPath.startsWith("/") && !options.getPreserveLeadingSlashes()) {
        int l = vPath.length();
        if (l <= 1) {
            // we would end up adding "" to the archive
            return;
        }
        vPath = vPath.substring(1, l);
    }

    int pathLength = vPath.length();
    InputStream fIn = null;

    try {
        TarArchiveEntry te;
        if (!longFileMode.isGnuMode()
                && pathLength >= org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN) {
            int maxPosixPathLen = org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN
                    + org.apache.commons.compress.archivers.tar.TarConstants.PREFIXLEN;
            if (longFileMode.isPosixMode()) {
            } else if (longFileMode.isPosixWarnMode()) {
                if (pathLength > maxPosixPathLen) {
                    getLogger().warn("Entry: " + vPath + " longer than " + maxPosixPathLen + " characters.");
                    if (!longWarningGiven) {
                        getLogger().warn("Resulting tar file can only be processed "
                                + "successfully by GNU compatible tar commands");
                        longWarningGiven = true;
                    }
                }
            } else if (longFileMode.isOmitMode()) {
                getLogger().info("Omitting: " + vPath);
                return;
            } else if (longFileMode.isWarnMode()) {
                getLogger().warn("Entry: " + vPath + " longer than "
                        + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + " characters.");
                if (!longWarningGiven) {
                    getLogger().warn("Resulting tar file can only be processed "
                            + "successfully by GNU compatible tar commands");
                    longWarningGiven = true;
                }
            } else if (longFileMode.isFailMode()) {
                throw new ArchiverException("Entry: " + vPath + " longer than "
                        + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + " characters.");
            } else {
                throw new IllegalStateException("Non gnu mode should never get here?");
            }
        }

        if (entry.getType() == ArchiveEntry.SYMLINK) {
            final SymlinkDestinationSupplier plexusIoSymlinkResource = (SymlinkDestinationSupplier) entry
                    .getResource();
            te = new TarArchiveEntry(vPath, TarArchiveEntry.LF_SYMLINK);
            te.setLinkName(plexusIoSymlinkResource.getSymlinkDestination());
        } else {
            te = new TarArchiveEntry(vPath);
        }

        long teLastModified = entry.getResource().getLastModified();
        te.setModTime(teLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ? System.currentTimeMillis()
                : teLastModified);

        if (entry.getType() == ArchiveEntry.SYMLINK) {
            te.setSize(0);

        } else if (!entry.getResource().isDirectory()) {
            final long size = entry.getResource().getSize();
            te.setSize(size == PlexusIoResource.UNKNOWN_RESOURCE_SIZE ? 0 : size);
        }
        te.setMode(entry.getMode());

        PlexusIoResourceAttributes attributes = entry.getResourceAttributes();

        te.setUserName((attributes != null && attributes.getUserName() != null) ? attributes.getUserName()
                : options.getUserName());
        te.setGroupName((attributes != null && attributes.getGroupName() != null) ? attributes.getGroupName()
                : options.getGroup());

        final int userId = (attributes != null && attributes.getUserId() != null) ? attributes.getUserId()
                : options.getUid();
        if (userId >= 0) {
            te.setUserId(userId);
        }

        final int groupId = (attributes != null && attributes.getGroupId() != null) ? attributes.getGroupId()
                : options.getGid();
        if (groupId >= 0) {
            te.setGroupId(groupId);
        }

        tOut.putArchiveEntry(te);

        try {
            if (entry.getResource().isFile() && !(entry.getType() == ArchiveEntry.SYMLINK)) {
                fIn = entry.getInputStream();

                Streams.copyFullyDontCloseOutput(fIn, tOut, "xAR");
            }

        } catch (Throwable e) {
            getLogger().warn("When creating tar entry", e);
        } finally {
            tOut.closeArchiveEntry();
        }
    } finally {
        IOUtil.close(fIn);
    }
}

From source file:org.dcm4chee.storage.tar.TarContainerProvider.java

@Override
public void writeEntriesTo(StorageContext context, List<ContainerEntry> entries, OutputStream out)
        throws IOException {
    TarArchiveOutputStream tar = new TarArchiveOutputStream(out);
    String checksumEntry = container.getChecksumEntry();
    if (checksumEntry != null) {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ContainerEntry.writeChecksumsTo(entries, bout);
        TarArchiveEntry tarEntry = new TarArchiveEntry(checksumEntry);
        tarEntry.setSize(bout.size());
        tar.putArchiveEntry(tarEntry);//from ww  w .  j av  a 2s.  co m
        tar.write(bout.toByteArray());
        tar.closeArchiveEntry();
    }
    for (ContainerEntry entry : entries) {
        Path path = entry.getSourcePath();
        TarArchiveEntry tarEntry = new TarArchiveEntry(entry.getName());
        tarEntry.setModTime(Files.getLastModifiedTime(path).toMillis());
        tarEntry.setSize(Files.size(path));
        tar.putArchiveEntry(tarEntry);
        Files.copy(path, tar);
        tar.closeArchiveEntry();
    }
    tar.finish();
}

From source file:org.dspace.pack.bagit.Bag.java

private void fillArchive(File dirFile, String relBase, ArchiveOutputStream out) throws IOException {
    for (File file : dirFile.listFiles()) {
        String relPath = relBase + File.separator + file.getName();
        if (file.isDirectory()) {
            fillArchive(file, relPath, out);
        } else {// w  w  w.  j a  v a  2  s.  c o m
            TarArchiveEntry entry = new TarArchiveEntry(relPath);
            entry.setSize(file.length());
            entry.setModTime(0L);
            out.putArchiveEntry(entry);
            FileInputStream fin = new FileInputStream(file);
            Utils.copy(fin, out);
            out.closeArchiveEntry();
            fin.close();
        }
    }
}

From source file:org.eclipse.che.api.vfs.TarArchiver.java

private void addTarEntry(VirtualFile virtualFile, TarArchiveOutputStream tarOutputStream)
        throws ServerException {
    try {/*from w  w w .j  av  a 2s  .  com*/
        TarArchiveEntry tarEntry = new TarArchiveEntry(getTarEntryName(virtualFile));
        if (virtualFile.isFolder()) {
            tarEntry.setModTime(0);
            tarOutputStream.putArchiveEntry(tarEntry);
        } else {
            tarEntry.setSize(virtualFile.getLength());
            tarEntry.setModTime(virtualFile.getLastModificationDate());
            tarOutputStream.putArchiveEntry(tarEntry);
            try (InputStream content = virtualFile.getContent()) {
                ByteStreams.copy(content, tarOutputStream);
            }
        }
        tarOutputStream.closeArchiveEntry();
    } catch (ForbiddenException e) {
        throw new ServerException(e.getServiceError());
    } catch (IOException e) {
        throw new ServerException(e.getMessage(), e);
    }
}

From source file:org.eclipse.che.api.vfs.TarArchiverTest.java

private void addFileEntry(TarArchiveOutputStream tarOut, String name) throws IOException {
    TarArchiveEntry entryA = new TarArchiveEntry(name);
    entryA.setSize(TEST_CONTENT_BYTES.length);
    tarOut.putArchiveEntry(entryA);/*w w w . j  a  v a 2  s  . co  m*/
    tarOut.write(TEST_CONTENT_BYTES);
    tarOut.closeArchiveEntry();
}

From source file:org.eclipse.jgit.archive.TarFormat.java

public void putEntry(ArchiveOutputStream out, String path, FileMode mode, ObjectLoader loader)
        throws IOException {
    if (mode == FileMode.SYMLINK) {
        final TarArchiveEntry entry = new TarArchiveEntry(path, TarConstants.LF_SYMLINK);
        entry.setLinkName(new String(loader.getCachedBytes(100), "UTF-8")); //$NON-NLS-1$
        out.putArchiveEntry(entry);//from ww  w .j  a v  a 2 s  . c  o  m
        out.closeArchiveEntry();
        return;
    }

    // TarArchiveEntry detects directories by checking
    // for '/' at the end of the filename.
    if (path.endsWith("/") && mode != FileMode.TREE) //$NON-NLS-1$
        throw new IllegalArgumentException(
                MessageFormat.format(ArchiveText.get().pathDoesNotMatchMode, path, mode));
    if (!path.endsWith("/") && mode == FileMode.TREE) //$NON-NLS-1$
        path = path + "/"; //$NON-NLS-1$

    final TarArchiveEntry entry = new TarArchiveEntry(path);
    if (mode == FileMode.TREE) {
        out.putArchiveEntry(entry);
        out.closeArchiveEntry();
        return;
    }

    if (mode == FileMode.REGULAR_FILE) {
        // ok
    } else if (mode == FileMode.EXECUTABLE_FILE) {
        entry.setMode(mode.getBits());
    } else {
        // Unsupported mode (e.g., GITLINK).
        throw new IllegalArgumentException(MessageFormat.format(ArchiveText.get().unsupportedMode, mode));
    }
    entry.setSize(loader.getSize());
    out.putArchiveEntry(entry);
    loader.copyTo(out);
    out.closeArchiveEntry();
}

From source file:org.eclipse.packagedrone.utils.deb.build.DebianPackageWriter.java

@Override
public void addFile(final ContentProvider contentProvider, String fileName, EntryInformation entryInformation)
        throws IOException {
    if (entryInformation == null) {
        entryInformation = EntryInformation.DEFAULT_FILE;
    }/* w w w . ja  v  a2s.  c  om*/

    try {
        fileName = cleanupPath(fileName);

        if (entryInformation.isConfigurationFile()) {
            this.confFiles.add(fileName.substring(1)); // without the leading dot
        }

        final TarArchiveEntry entry = new TarArchiveEntry(fileName);
        entry.setSize(contentProvider.getSize());
        applyInfo(entry, entryInformation);

        checkCreateParents(fileName);

        this.dataStream.putArchiveEntry(entry);

        final Map<String, byte[]> results = new HashMap<>();
        try (final ChecksumInputStream in = new ChecksumInputStream(contentProvider.createInputStream(),
                results, MessageDigest.getInstance("MD5"))) {
            this.installedSize += IOUtils.copyLarge(in, this.dataStream);
        }

        this.dataStream.closeArchiveEntry();

        // record the checksum
        recordChecksum(fileName, results.get("MD5"));
    } catch (final Exception e) {
        throw new IOException(e);
    }
}