Example usage for org.apache.commons.compress.archivers.tar TarArchiveOutputStream close

List of usage examples for org.apache.commons.compress.archivers.tar TarArchiveOutputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the underlying OutputStream.

Usage

From source file:lk.score.androphsy.main.NewCase.java

private void compressFiles(ArrayList<File> list, File outFile) throws IOException {
    FileOutputStream fos = new FileOutputStream(outFile);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    GZIPOutputStream gos = new GZIPOutputStream(bos);
    TarArchiveOutputStream taos = new TarArchiveOutputStream(gos);

    taos.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
    taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

    for (File f : list) {
        addFileToCompression(taos, f, "");
    }/* www . j a  v a2  s  . co m*/
    taos.close();
    fos.close();
    // gos.close();
    // bos.close();
}

From source file:de.uzk.hki.da.pkg.TarGZArchiveBuilder.java

public void archiveFolder(File srcFolder, File destFile, boolean includeFolder) throws Exception {

    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    GzipCompressorOutputStream gzOut = null;
    TarArchiveOutputStream tOut = null;

    try {/*from  w  w w  .ja v a  2 s . c o m*/
        fOut = new FileOutputStream(destFile);
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);

        tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        tOut.setBigNumberMode(2);

        if (includeFolder)
            addFileToTarGZ(tOut, srcFolder, "");
        else {
            File children[] = srcFolder.listFiles();
            for (int i = 0; i < children.length; i++) {
                addFileToTarGZ(tOut, children[i], "");
            }
        }
    } finally {
        tOut.finish();

        tOut.close();
        gzOut.close();
        bOut.close();
        fOut.close();
    }
}

From source file:hudson.gridmaven.gridlayer.HadoopInstance.java

/**
 * This method opens a path and recursively adds all files into tar, then
 * inserts it to HDFS.//from ww  w .  ja v  a 2  s  . c  om
 */
public void tarAndInsert(String directoryPath, String tarGzPath) throws IOException {
    OutputStream fOut = null;
    //FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    TarArchiveOutputStream tOut = null;
    //tarGzPath = "test.tar";
    //File f = new File(tarGzPath);
    Path f = new Path(tarGzPath);

    String skipDirectoryPath = "";
    File l = new File(directoryPath);
    if (l.isDirectory())
        skipDirectoryPath = directoryPath;
    try {
        fs.delete(f, true);
        fOut = fs.create(f);
        //fOut = new FileOutputStream(f);
        bOut = new BufferedOutputStream(fOut);
        tOut = new TarArchiveOutputStream(bOut);

        addFileToTar(tOut, directoryPath, "", skipDirectoryPath);

        tOut.finish();
        tOut.close();
        bOut.close();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
        Logger.getLogger(HadoopInstance.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:ezbake.protect.ezca.EzCABootstrap.java

public static void createAndWriteTarball(String name, AppCerts certs, String filePath) {
    TarArchiveOutputStream os = null;
    try {//from www .ja va 2s .c  o  m
        File outputFile = new File(filePath, name + ".tar.gz");
        outputFile.createNewFile();
        outputFile.setWritable(false, false);
        outputFile.setWritable(true, true);
        outputFile.setReadable(false, false);
        outputFile.setReadable(true, true);
        FileOutputStream fos = new FileOutputStream(outputFile);

        CompressorOutputStream cos = new CompressorStreamFactory()
                .createCompressorOutputStream(CompressorStreamFactory.GZIP, fos);
        os = new TarArchiveOutputStream(cos);

        // For each field in the app certs, create an entry in the tar archive
        for (AppCerts._Fields field : AppCerts._Fields.values()) {
            Object o = certs.getFieldValue(field);
            if (o instanceof byte[]) {
                String fieldName = field.getFieldName().replace("_", ".");
                addTarArchiveEntry(os, fieldName, (byte[]) o);
            }
        }

    } catch (FileNotFoundException e) {
        logger.error("Unable to write tarball", e);
    } catch (CompressorException e) {
        logger.error("Error compressing tarball", e);
    } catch (IOException e) {
        logger.error("Error creating output file for tarball", e);
    } finally {
        if (os != null) {
            try {
                os.finish();
                os.close();
            } catch (IOException e) {
                logger.warn("Unable to close output stream", e);
            }
        }
    }
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GitProfileReader.java

@Override
public InputStream readArchiveProfile(String artifactName, String version, String profileName)
        throws IOException {
    Path profilePath = Paths.get(profilePath(artifactName, version, profileName));

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        int permissions = FileModeUtils.getFileMode(Files.getPosixFilePermissions(path));
        permissions = FileModeUtils.setFileBit(permissions);
        tarEntry.setMode(permissions);//w ww.j  a v a 2 s.c  o m
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:com.gitblit.utils.CompressionUtils.java

/**
 * Compresses/archives the contents of the tree at the (optionally)
 * specified revision and the (optionally) specified basepath to the
 * supplied outputstream.//from   w  w w  . j  av a 2s .  c  o m
 * 
 * @param algorithm
 *            compression algorithm for tar (optional)
 * @param repository
 * @param basePath
 *            if unspecified, entire repository is assumed.
 * @param objectId
 *            if unspecified, HEAD is assumed.
 * @param os
 * @return true if repository was successfully zipped to supplied output
 *         stream
 */
private static boolean tar(String algorithm, Repository repository, String basePath, String objectId,
        OutputStream os) {
    RevCommit commit = JGitUtils.getCommit(repository, objectId);
    if (commit == null) {
        return false;
    }

    OutputStream cos = os;
    if (!StringUtils.isEmpty(algorithm)) {
        try {
            cos = new CompressorStreamFactory().createCompressorOutputStream(algorithm, os);
        } catch (CompressorException e1) {
            error(e1, repository, "{0} failed to open {1} stream", algorithm);
        }
    }
    boolean success = false;
    RevWalk rw = new RevWalk(repository);
    TreeWalk tw = new TreeWalk(repository);
    try {
        tw.reset();
        tw.addTree(commit.getTree());
        TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
        tos.setAddPaxHeadersForNonAsciiNames(true);
        tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);
        if (!StringUtils.isEmpty(basePath)) {
            PathFilter f = PathFilter.create(basePath);
            tw.setFilter(f);
        }
        tw.setRecursive(true);
        MutableObjectId id = new MutableObjectId();
        long modified = commit.getAuthorIdent().getWhen().getTime();
        while (tw.next()) {
            FileMode mode = tw.getFileMode(0);
            if (mode == FileMode.GITLINK || mode == FileMode.TREE) {
                continue;
            }
            tw.getObjectId(id, 0);

            ObjectLoader loader = repository.open(id);
            if (FileMode.SYMLINK == mode) {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString(), TarArchiveEntry.LF_SYMLINK);
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                loader.copyTo(bos);
                entry.setLinkName(bos.toString());
                entry.setModTime(modified);
                tos.putArchiveEntry(entry);
                tos.closeArchiveEntry();
            } else {
                TarArchiveEntry entry = new TarArchiveEntry(tw.getPathString());
                entry.setMode(mode.getBits());
                entry.setModTime(modified);
                entry.setSize(loader.getSize());
                tos.putArchiveEntry(entry);
                loader.copyTo(tos);
                tos.closeArchiveEntry();
            }
        }
        tos.finish();
        tos.close();
        cos.close();
        success = true;
    } catch (IOException e) {
        error(e, repository, "{0} failed to {1} stream files from commit {2}", algorithm, commit.getName());
    } finally {
        tw.release();
        rw.dispose();
    }
    return success;
}

From source file:com.moss.simpledeb.core.DebWriter.java

private byte[] buildGzipTar(List<ArchivePath> paths) throws Exception {

    byte[] tarData;
    {//ww  w  .  j a  v  a 2 s .  co m
        ByteArrayOutputStream tarOut = new ByteArrayOutputStream();
        TarArchiveOutputStream tar = new TarArchiveOutputStream(tarOut);

        Set<String> writtenPaths = new HashSet<String>();
        for (ArchivePath path : paths) {
            String name = path.entry().getName();

            if (writtenPaths.contains(name)) {
                throw new RuntimeException("Duplicate archive entry: " + name);
            }

            writtenPaths.add(name);

            tar.putArchiveEntry(path.entry());

            if (!path.entry().isDirectory()) {
                InputStream in = path.read();
                byte[] buffer = new byte[1024 * 10];
                for (int numRead = in.read(buffer); numRead != -1; numRead = in.read(buffer)) {
                    tar.write(buffer, 0, numRead);
                }
                in.close();
            }

            tar.closeArchiveEntry();
        }

        tar.close();
        tarData = tarOut.toByteArray();
    }

    byte[] gzipData;
    {
        ByteArrayOutputStream gzipOut = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(gzipOut);
        gzip.write(tarData);
        gzip.close();

        gzipData = gzipOut.toByteArray();
    }

    return gzipData;
}

From source file:de.uzk.hki.da.pkg.ArchiveBuilder.java

/**
 * Create an archive file out of the given source folder
 * /*  w ww . ja  v a  2  s . com*/
 * @param srcFolder The folder to archive
 * @param destFile The archive file to build
 * @param includeFolder Indicates if the source folder will be included to the archive file on
 * the first level or not
 * @param compress Indicates if the archive file will be compressed (tgz file) or not (tar file)
 * @return false if the SIP creation process was aborted during the archive file creation process, otherwise true
 * @throws Exception
 */
public boolean archiveFolder(File srcFolder, File destFile, boolean includeFolder, boolean compress)
        throws Exception {

    FileOutputStream fOut = null;
    GzipCompressorOutputStream gzOut = null;
    TarArchiveOutputStream tOut = null;

    try {
        fOut = new FileOutputStream(destFile);

        if (compress) {
            gzOut = new GzipCompressorOutputStream(fOut);
            tOut = new TarArchiveOutputStream(gzOut, "UTF-8");
        } else
            tOut = new TarArchiveOutputStream(fOut, "UTF-8");

        tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        tOut.setBigNumberMode(2);

        if (includeFolder) {
            if (!addFileToArchive(tOut, srcFolder, ""))
                return false;
        } else {
            File children[] = srcFolder.listFiles();

            for (int i = 0; i < children.length; i++) {
                if (!addFileToArchive(tOut, children[i], ""))
                    return false;
            }
        }
    } finally {
        tOut.finish();
        tOut.close();
        if (gzOut != null)
            gzOut.close();
        fOut.close();
    }

    return true;
}

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

/**
** OutputStream os will be close()d if this method returns successfully.
*//*from ww w  .ja va 2 s . 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:com.mobilesorcery.sdk.builder.linux.deb.DebBuilder.java

/**
 * Adds the files in the file list in a tar+gz
 *
 * @param o Output file//  w w  w.  j a v  a 2  s. c  om
 *
 * @throws IOException If error occurs during writing
 * @throws FileNotFoundException If the output file could not be opened.
 */
private void doAddFilesToTarGZip(File o) throws IOException, FileNotFoundException

{
    FileOutputStream os = new FileOutputStream(o);
    GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(os);
    TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos);

    // Add files
    for (SimpleEntry<File, SimpleEntry<String, Integer>> fileEntry : m_fileList) {
        File file = fileEntry.getKey();
        String name = fileEntry.getValue().getKey();
        int mode = fileEntry.getValue().getValue();
        TarArchiveEntry e = new TarArchiveEntry(file, name);

        // Add to tar, user/group id 0 is always root
        e.setMode(mode);
        e.setUserId(0);
        e.setUserName("root");
        e.setGroupId(0);
        e.setGroupName("root");
        tos.putArchiveEntry(e);

        // Write bytes
        if (file.isFile())
            BuilderUtil.getInstance().copyFileToOutputStream(tos, file);
        tos.closeArchiveEntry();
    }

    // Done
    tos.close();
    gzos.close();
    os.close();
}