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:com.st.maven.debian.DebianPackageMojo.java

private void addRecursively(Config config, TarArchiveOutputStream tar, Fileset fileset)
        throws MojoExecutionException {
    File sourceFile = new File(fileset.getSource());
    String targetFilename = fileset.getTarget();
    // skip well-known ignore directories
    if (ignore.contains(sourceFile.getName()) || sourceFile.getName().endsWith(".rrd")
            || sourceFile.getName().endsWith(".log")) {
        return;/* www  .  j  av a  2 s  .  c  o m*/
    }
    FileInputStream fis = null;
    try {
        if (!sourceFile.isDirectory()) {
            TarArchiveEntry curEntry = new TarArchiveEntry(targetFilename);
            if (fileset.isFilter()) {
                byte[] bytes = processTemplate(freemarkerConfig, config, fileset.getSource());
                curEntry.setSize(bytes.length);
                tar.putArchiveEntry(curEntry);
                tar.write(bytes);
            } else {
                curEntry.setSize(sourceFile.length());
                tar.putArchiveEntry(curEntry);
                fis = new FileInputStream(sourceFile);
                IOUtils.copy(fis, tar);
            }
            tar.closeArchiveEntry();
        } else if (sourceFile.isDirectory()) {
            targetFilename += "/";
            if (!dirsAdded.contains(targetFilename)) {
                dirsAdded.add(targetFilename);
                writeDirectory(tar, targetFilename);
            }
        }
    } catch (Exception e) {
        throw new MojoExecutionException("unable to write", e);
    } finally {
        IOUtils.closeQuietly(fis);
    }

    if (sourceFile.isDirectory()) {
        File[] subFiles = sourceFile.listFiles();
        for (File curSubFile : subFiles) {
            Fileset curSubFileset = new Fileset(fileset.getSource() + "/" + curSubFile.getName(),
                    fileset.getTarget() + "/" + curSubFile.getName(), fileset.isFilter());
            addRecursively(config, tar, curSubFileset);
        }
    }
}

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

/**
 * Creates a tar file from the specified files.
 * <br><br>//www.j a  v a  2  s.com
 * See <a href="http://www.thoughtspark.org/node/53" target="_blank">Creating a tar.gz with commons-compress</a>.
 *
 * @param output   the output file to generate
 * @param files   the files to store in the tar file
 * @param stripRegExp   the regular expression used to strip the file names
 * @param bufferSize   the buffer size to use
 * @return      null if successful, otherwise error message
 */
@MixedCopyright(author = "Jeremy Whitlock (jcscoobyrs)", copyright = "2010 Jeremy Whitlock", license = License.APACHE2, url = "http://www.thoughtspark.org/node/53")
public static String compress(File output, File[] files, String stripRegExp, int bufferSize) {
    String result;
    int i;
    byte[] buf;
    int len;
    TarArchiveOutputStream out;
    BufferedInputStream in;
    FileInputStream fis;
    FileOutputStream fos;
    String filename;
    String msg;
    TarArchiveEntry entry;

    in = null;
    fis = null;
    out = null;
    fos = null;
    result = null;
    try {
        // does file already exist?
        if (output.exists())
            System.err.println("WARNING: overwriting '" + output + "'!");

        // create tar file
        buf = new byte[bufferSize];
        fos = new FileOutputStream(output.getAbsolutePath());
        out = openArchiveForWriting(output, fos);
        for (i = 0; i < files.length; i++) {
            fis = new FileInputStream(files[i].getAbsolutePath());
            in = new BufferedInputStream(fis);

            // Add tar entry to output stream.
            filename = files[i].getParentFile().getAbsolutePath();
            if (stripRegExp.length() > 0)
                filename = filename.replaceFirst(stripRegExp, "");
            if (filename.length() > 0)
                filename += File.separator;
            filename += files[i].getName();
            entry = new TarArchiveEntry(filename);
            if (files[i].isFile())
                entry.setSize(files[i].length());
            out.putArchiveEntry(entry);

            // Transfer bytes from the file to the tar file
            while ((len = in.read(buf)) > 0)
                out.write(buf, 0, len);

            // Complete the entry
            out.closeArchiveEntry();
            FileUtils.closeQuietly(in);
            FileUtils.closeQuietly(fis);
            in = null;
            fis = null;
        }

        // Complete the tar file
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
        out = null;
        fos = null;
    } catch (Exception e) {
        msg = "Failed to generate archive '" + output + "': ";
        System.err.println(msg);
        e.printStackTrace();
        result = msg + e;
    } finally {
        FileUtils.closeQuietly(in);
        FileUtils.closeQuietly(fis);
        FileUtils.closeQuietly(out);
        FileUtils.closeQuietly(fos);
    }

    return result;
}

From source file:freenet.client.async.ContainerInserter.java

/**
** OutputStream os will be close()d if this method returns successfully.
*///from ww  w . j  av  a 2s .  c o  m
private String createTarBucket(OutputStream os) throws IOException {
    if (logMINOR)
        Logger.minor(this, "Create a TAR Bucket");

    TarArchiveOutputStream tarOS = new TarArchiveOutputStream(os);
    try {
        tarOS.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        TarArchiveEntry ze;

        for (ContainerElement ph : containerItems) {
            if (logMINOR)
                Logger.minor(this, "Putting into tar: " + ph + " data length " + ph.data.size() + " name "
                        + ph.targetInArchive);
            ze = new TarArchiveEntry(ph.targetInArchive);
            ze.setModTime(0);
            long size = ph.data.size();
            ze.setSize(size);
            tarOS.putArchiveEntry(ze);
            BucketTools.copyTo(ph.data, tarOS, size);
            tarOS.closeArchiveEntry();
        }
    } finally {
        tarOS.close();
    }

    return ARCHIVE_TYPE.TAR.mimeTypes[0];
}

From source file:gdt.data.entity.ArchiveHandler.java

private boolean append(Entigrator entigrator, String root$, String source$, TarArchiveOutputStream aos) {
    try {/*from www  .  j  a  v  a  2 s.  c o  m*/

        File[] fa = null;
        File source = new File(source$);
        if (source.exists())
            if (source.isFile())
                fa = new File[] { source };
            else
                fa = source.listFiles();
        if (fa == null)
            return true;
        File recordFile = null;

        Stack<TarArchiveEntry> s = new Stack<TarArchiveEntry>();
        int cnt = 0;

        TarArchiveEntry entry = null;
        for (File aFa : fa) {
            recordFile = aFa;
            entry = new TarArchiveEntry(recordFile);
            entry.setSize(recordFile.length());
            s.clear();
            getTarEntries(entry, s, root$);
            cnt = s.size();
            //  System.out.println("EximpExpert:append:cnt=" + cnt);
            File nextFile = null;
            for (int j = 0; j < cnt; j++) {
                entry = (TarArchiveEntry) s.pop();
                try {
                    String nextFile$ = entigrator.getEntihome() + "/" + entry.getName();
                    //            System.out.println("EximpExpert:append:try next file=" + nextFile$);
                    nextFile = new File(nextFile$);
                    if (!nextFile.exists() || nextFile.length() < 1) {
                        System.out.println("ArchiveHandler:append:wrong next file=" + nextFile$);
                        continue;
                    }
                    aos.putArchiveEntry(entry);
                    IOUtils.copy(new FileInputStream(nextFile$), aos);
                    // System.out.println("EximpExpert:tar_write:j="+j);
                    aos.closeArchiveEntry();
                } catch (Exception ee) {
                    //   System.out.println("EximpExpert:append:" + ee.toString());
                    LOGGER.severe(":append:" + ee.toString());
                }
            }
        }
        //System.out.println("EximpExpert:tar_write:finish");
        return true;

        //System.out.println("EximpExpert:tar_write:exit");
    } catch (Exception e) {
        LOGGER.severe(":append:" + e.toString());
        return false;
    }
}

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

/**
 * writeTarZst writes a .tar.zst file to 'file'.
 *
 * <p>For each key:value in archiveContents, a file named 'key' with contents 'value' will be
 * created in the archive. File names ending with "/" are considered directories.
 *///from  w  ww.jav a 2 s  .co m
private void writeTarZst(Path file, Map<String, byte[]> archiveContents) throws IOException {
    try (OutputStream o = new BufferedOutputStream(Files.newOutputStream(file));
            OutputStream z = new ZstdCompressorOutputStream(o);
            TarArchiveOutputStream archive = new TarArchiveOutputStream(z)) {
        archive.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        for (Entry<String, byte[]> mapEntry : archiveContents.entrySet()) {
            String fileName = mapEntry.getKey();
            byte[] fileContents = mapEntry.getValue();
            boolean isRegularFile = !fileName.endsWith("/");

            TarArchiveEntry e = new TarArchiveEntry(fileName);
            if (isRegularFile) {
                e.setSize(fileContents.length);
                archive.putArchiveEntry(e);
                archive.write(fileContents);
            } else {
                archive.putArchiveEntry(e);
            }
            archive.closeArchiveEntry();
        }
        archive.finish();
    }
}

From source file:gov.noaa.pfel.coastwatch.util.FileVisitorDNLS.java

/** 
 * This makes a .tgz or .tar.gz file.//from w  ww.  jav  a  2s .c  om
 *
 * @param tResultName is the full result file name, usually 
 *   the name of the dir being archived, and ending in .tgz or .tar.gz.
 */
public static void makeTgz(String tDir, String tFileNameRegex, boolean tRecursive, String tPathRegex,
        String tResultName) throws Exception {
    TarArchiveOutputStream tar = null;
    String outerDir = File2.getDirectory(tDir.substring(0, tDir.length() - 1));
    tar = new TarArchiveOutputStream(
            new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(tResultName))));

    // Add data to out and flush stream
    Table filesTable = oneStep(tDir, tFileNameRegex, tRecursive, tPathRegex, false); //tDirectoriesToo
    StringArray directoryPA = (StringArray) filesTable.getColumn(DIRECTORY);
    StringArray namePA = (StringArray) filesTable.getColumn(NAME);
    LongArray lastModifiedPA = (LongArray) filesTable.getColumn(LASTMODIFIED);
    LongArray sizePA = (LongArray) filesTable.getColumn(SIZE);
    byte buffer[] = new byte[32768];
    int nBytes;
    for (int fi = 0; fi < namePA.size(); fi++) {
        String fullName = directoryPA.get(fi) + namePA.get(fi);
        TarArchiveEntry entry = new TarArchiveEntry(new File(fullName.substring(outerDir.length())));
        entry.setSize(sizePA.get(fi));
        entry.setModTime(lastModifiedPA.get(fi));
        tar.putArchiveEntry(entry);
        FileInputStream fis = new FileInputStream(fullName);
        while ((nBytes = fis.read(buffer)) > 0)
            tar.write(buffer, 0, nBytes);
        fis.close();
        tar.closeArchiveEntry();
    }
    tar.close();
}

From source file:com.facebook.buck.core.build.engine.impl.CachingBuildEngineTest.java

private static void writeEntriesToArchive(Path file, ImmutableMap<Path, String> entries,
        ImmutableList<Path> directories) throws IOException {
    try (OutputStream o = new BufferedOutputStream(Files.newOutputStream(file));
            OutputStream z = new ZstdCompressorOutputStream(o);
            TarArchiveOutputStream archive = new TarArchiveOutputStream(z)) {
        archive.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        for (Map.Entry<Path, String> mapEntry : entries.entrySet()) {
            TarArchiveEntry e = new TarArchiveEntry(mapEntry.getKey().toString());
            e.setModTime(ZipConstants.getFakeTime());
            byte[] bytes = mapEntry.getValue().getBytes(UTF_8);
            e.setSize(bytes.length);
            archive.putArchiveEntry(e);/*from   w w  w.  j  a  v  a2  s.  c  o  m*/
            archive.write(bytes);
            archive.closeArchiveEntry();
        }
        for (Path dir : directories) {
            TarArchiveEntry e = new TarArchiveEntry(dir.toString() + "/");
            e.setModTime(ZipConstants.getFakeTime());
        }
        archive.finish();
    }
}

From source file:org.apache.ant.compress.taskdefs.Tar.java

public Tar() {
    setFactory(new TarStreamFactory() {
        public ArchiveOutputStream getArchiveStream(OutputStream stream, String encoding) throws IOException {
            TarArchiveOutputStream o = (TarArchiveOutputStream) super.getArchiveStream(stream, encoding);
            if (format.equals(Format.OLDGNU)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
            } else if (format.equals(Format.GNU)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            } else if (format.equals(Format.STAR)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
            } else if (format.equals(Format.PAX)) {
                o.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
                o.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);
                o.setAddPaxHeadersForNonAsciiNames(true);
            }//w ww.j av  a2  s.  co m
            return o;
        }
    });
    setEntryBuilder(new ArchiveBase.EntryBuilder() {
        public ArchiveEntry buildEntry(ArchiveBase.ResourceWithFlags r) {
            boolean isDir = r.getResource().isDirectory();
            String name = r.getName();
            if (isDir && !name.endsWith("/")) {
                name += "/";
            } else if (!isDir && name.endsWith("/")) {
                name = name.substring(0, name.length() - 1);
            }
            TarArchiveEntry ent = new TarArchiveEntry(name, getPreserveLeadingSlashes());
            ent.setModTime(round(r.getResource().getLastModified(), 1000));
            ent.setSize(isDir ? 0 : r.getResource().getSize());

            if (!isDir && r.getCollectionFlags().hasModeBeenSet()) {
                ent.setMode(r.getCollectionFlags().getMode());
            } else if (isDir && r.getCollectionFlags().hasDirModeBeenSet()) {
                ent.setMode(r.getCollectionFlags().getDirMode());
            } else if (r.getResourceFlags().hasModeBeenSet()) {
                ent.setMode(r.getResourceFlags().getMode());
            } else {
                ent.setMode(isDir ? ArchiveFileSet.DEFAULT_DIR_MODE : ArchiveFileSet.DEFAULT_FILE_MODE);
            }

            if (r.getResourceFlags().hasUserIdBeenSet()) {
                ent.setUserId(r.getResourceFlags().getUserId());
            } else if (r.getCollectionFlags().hasUserIdBeenSet()) {
                ent.setUserId(r.getCollectionFlags().getUserId());
            }

            if (r.getResourceFlags().hasGroupIdBeenSet()) {
                ent.setGroupId(r.getResourceFlags().getGroupId());
            } else if (r.getCollectionFlags().hasGroupIdBeenSet()) {
                ent.setGroupId(r.getCollectionFlags().getGroupId());
            }

            if (r.getResourceFlags().hasUserNameBeenSet()) {
                ent.setUserName(r.getResourceFlags().getUserName());
            } else if (r.getCollectionFlags().hasUserNameBeenSet()) {
                ent.setUserName(r.getCollectionFlags().getUserName());
            }

            if (r.getResourceFlags().hasGroupNameBeenSet()) {
                ent.setGroupName(r.getResourceFlags().getGroupName());
            } else if (r.getCollectionFlags().hasGroupNameBeenSet()) {
                ent.setGroupName(r.getCollectionFlags().getGroupName());
            }

            return ent;
        }
    });
    setFileSetBuilder(new ArchiveBase.FileSetBuilder() {
        public ArchiveFileSet buildFileSet(Resource dest) {
            ArchiveFileSet afs = new TarFileSet();
            afs.setSrcResource(dest);
            return afs;
        }
    });
}

From source file:org.apache.camel.dataformat.tarfile.TarFileDataFormat.java

@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception {
    String filename = exchange.getIn().getHeader(FILE_NAME, String.class);
    Long filelength = exchange.getIn().getHeader(FILE_LENGTH, Long.class);
    if (filename != null) {
        filename = new File(filename).getName(); // remove any path elements
    } else {//from ww  w .  j  av  a  2s .  c  o m
        // generate the file name as the camel file component would do
        filename = StringHelper.sanitize(exchange.getIn().getMessageId());
    }

    TarArchiveOutputStream tos = new TarArchiveOutputStream(stream);
    tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
    tos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX);

    InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, graph);
    if (filelength == null) {
        filelength = new Long(is.available());
    }

    TarArchiveEntry entry = new TarArchiveEntry(filename);
    entry.setSize(filelength);
    tos.putArchiveEntry(entry);

    try {
        IOHelper.copy(is, tos);
    } finally {
        tos.closeArchiveEntry();
        IOHelper.close(is, tos);
    }

    String newFilename = filename + ".tar";
    exchange.getOut().setHeader(FILE_NAME, newFilename);
}

From source file:org.apache.camel.dataformat.tarfile.TarFileDataFormatTest.java

private static byte[] getTaredText(String entryName) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(TEXT.getBytes("UTF-8"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TarArchiveOutputStream tos = new TarArchiveOutputStream(baos);
    try {/*from w w w. ja  va  2s  .co  m*/
        TarArchiveEntry entry = new TarArchiveEntry(entryName);
        entry.setSize(bais.available());
        tos.putArchiveEntry(entry);
        IOHelper.copy(bais, tos);
    } finally {
        tos.closeArchiveEntry();
        IOHelper.close(bais, tos);
    }
    return baos.toByteArray();
}