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

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Ends the TAR archive without closing the underlying OutputStream.

Usage

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.//  www .j  ava  2 s.  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:de.uzk.hki.da.pkg.ArchiveBuilder.java

/**
 * Create an archive file out of the given source folder
 * //from ww w  .  j  a  va  2  s  .c o m
 * @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:de.uzk.hki.da.pkg.NativeJavaTarArchiveBuilder.java

/**
 * There is an option to override the name of the first level entry if you want to pack 
 * a directory. Set includeFolder = true so that it not only packs the contents but also
 * the containing folder. Then use the setter setFirstLevelEntryName and set the name
 * of the folder which contains the files to pack. The name of the folder then gets replaced
 * in the resulting tar. Note that after calling archiveFolder once, the variable gets automatically
 * reset so that you have to call the setter again if you want to set the override setting again.
 *//*from   w w w .  j av a 2  s  .  c o m*/
public void archiveFolder(File srcFolder, File destFile, boolean includeFolder) throws Exception {

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

    fOut = new FileOutputStream(destFile);
    bOut = new BufferedOutputStream(fOut);
    tOut = new TarArchiveOutputStream(bOut);

    tOut.setLongFileMode(longFileMode);
    tOut.setBigNumberMode(bigNumberMode);

    try {

        String base = "";
        if (firstLevelEntryName.isEmpty())
            firstLevelEntryName = srcFolder.getName() + "/";

        if (includeFolder) {
            logger.debug("addFileToTar: " + firstLevelEntryName);
            TarArchiveEntry entry = (TarArchiveEntry) tOut.createArchiveEntry(srcFolder, firstLevelEntryName);
            tOut.putArchiveEntry(entry);
            tOut.closeArchiveEntry();
            base = firstLevelEntryName;
        }

        File children[] = srcFolder.listFiles();
        for (int i = 0; i < children.length; i++) {
            addFileToTar(tOut, children[i], base);
        }

    } finally {
        tOut.finish();

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

        firstLevelEntryName = "";
    }
}

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

private void tarHalconfig(String halconfigDir, String halconfigTar) throws IOException {
    FileOutputStream tarOutput = null;
    BufferedOutputStream bufferedTarOutput = null;
    TarArchiveOutputStream tarArchiveOutputStream = null;
    IOException fatalCleanup = null;
    try {//ww  w .ja va 2s  .c  om
        tarOutput = new FileOutputStream(new File(halconfigTar));
        bufferedTarOutput = new BufferedOutputStream(tarOutput);
        tarArchiveOutputStream = new TarArchiveOutputStream(bufferedTarOutput);
        TarArchiveOutputStream finalTarArchiveOutputStream = tarArchiveOutputStream;
        Arrays.stream(new File(halconfigDir).listFiles()).filter(Objects::nonNull)
                .forEach(f -> addFileToTar(finalTarArchiveOutputStream, f.getAbsolutePath(), ""));
    } catch (HalException e) {
        log.info("HalException caught during tar operation", e);
        throw e;
    } catch (IOException e) {
        log.info("IOException caught during tar operation", e);
        throw new HalException(Problem.Severity.FATAL, "Failed to backup halconfig: " + e.getMessage(), e);
    } finally {
        if (tarArchiveOutputStream != null) {
            try {
                tarArchiveOutputStream.finish();
                tarArchiveOutputStream.close();
            } catch (IOException e) {
                fatalCleanup = e;
            }
        }

        if (bufferedTarOutput != null) {
            bufferedTarOutput.close();
        }

        if (tarOutput != null) {
            tarOutput.close();
        }
    }

    if (fatalCleanup != null) {
        throw fatalCleanup;
    }
}

From source file:com.gitblit.servlet.PtServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {/*from  ww  w . j  a  va  2  s  .  c om*/
        response.setContentType("application/octet-stream");
        response.setDateHeader("Last-Modified", lastModified);
        response.setHeader("Cache-Control", "none");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        boolean windows = false;
        try {
            String useragent = request.getHeader("user-agent").toString();
            windows = useragent.toLowerCase().contains("windows");
        } catch (Exception e) {
        }

        byte[] pyBytes;
        File file = runtimeManager.getFileOrFolder("tickets.pt", "${baseFolder}/pt.py");
        if (file.exists()) {
            // custom script
            pyBytes = readAll(new FileInputStream(file));
        } else {
            // default script
            pyBytes = readAll(getClass().getResourceAsStream("/pt.py"));
        }

        if (windows) {
            // windows: download zip file with pt.py and pt.cmd
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.zip\"");

            OutputStream os = response.getOutputStream();
            ZipArchiveOutputStream zos = new ZipArchiveOutputStream(os);

            // add the Python script
            ZipArchiveEntry pyEntry = new ZipArchiveEntry("pt.py");
            pyEntry.setSize(pyBytes.length);
            pyEntry.setUnixMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setTime(lastModified);
            zos.putArchiveEntry(pyEntry);
            zos.write(pyBytes);
            zos.closeArchiveEntry();

            // add a Python launch cmd file
            byte[] cmdBytes = readAll(getClass().getResourceAsStream("/pt.cmd"));
            ZipArchiveEntry cmdEntry = new ZipArchiveEntry("pt.cmd");
            cmdEntry.setSize(cmdBytes.length);
            cmdEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            cmdEntry.setTime(lastModified);
            zos.putArchiveEntry(cmdEntry);
            zos.write(cmdBytes);
            zos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            ZipArchiveEntry txtEntry = new ZipArchiveEntry("readme.txt");
            txtEntry.setSize(txtBytes.length);
            txtEntry.setUnixMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setTime(lastModified);
            zos.putArchiveEntry(txtEntry);
            zos.write(txtBytes);
            zos.closeArchiveEntry();

            // cleanup
            zos.finish();
            zos.close();
            os.flush();
        } else {
            // unix: download a tar.gz file with pt.py set with execute permissions
            response.setHeader("Content-Disposition", "attachment; filename=\"pt.tar.gz\"");

            OutputStream os = response.getOutputStream();
            CompressorOutputStream cos = new CompressorStreamFactory()
                    .createCompressorOutputStream(CompressorStreamFactory.GZIP, os);
            TarArchiveOutputStream tos = new TarArchiveOutputStream(cos);
            tos.setAddPaxHeadersForNonAsciiNames(true);
            tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX);

            // add the Python script
            TarArchiveEntry pyEntry = new TarArchiveEntry("pt");
            pyEntry.setMode(FileMode.EXECUTABLE_FILE.getBits());
            pyEntry.setModTime(lastModified);
            pyEntry.setSize(pyBytes.length);
            tos.putArchiveEntry(pyEntry);
            tos.write(pyBytes);
            tos.closeArchiveEntry();

            // add a brief readme
            byte[] txtBytes = readAll(getClass().getResourceAsStream("/pt.txt"));
            TarArchiveEntry txtEntry = new TarArchiveEntry("README");
            txtEntry.setMode(FileMode.REGULAR_FILE.getBits());
            txtEntry.setModTime(lastModified);
            txtEntry.setSize(txtBytes.length);
            tos.putArchiveEntry(txtEntry);
            tos.write(txtBytes);
            tos.closeArchiveEntry();

            // cleanup
            tos.finish();
            tos.close();
            cos.close();
            os.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.lizardtech.expresszip.model.Job.java

private void writeTarFile(File baseDir, File archive, List<String> files) throws IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    GzipCompressorOutputStream gzOut = null;
    TarArchiveOutputStream tOut = null;
    try {//  w  ww  . j av a 2s.  com
        fOut = new FileOutputStream(archive);
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);

        for (String f : files) {
            File myfile = new File(baseDir, f);
            String entryName = myfile.getName();
            logger.info(String.format("Writing %s to TAR archive %s", f, archive));

            TarArchiveEntry tarEntry = new TarArchiveEntry(myfile, entryName);
            tOut.putArchiveEntry(tarEntry);

            FileInputStream fis = new FileInputStream(myfile);
            IOUtils.copy(fis, tOut);
            fis.close();
            tOut.closeArchiveEntry();
        }
    } finally {
        tOut.finish();
        tOut.close();
        gzOut.close();
        bOut.close();
        fOut.close();
    }
}

From source file:com.linuxbox.enkive.workspace.searchFolder.SearchFolder.java

/**
 * Writes a tar.gz file to the provided outputstream
 * //from  ww  w  .j ava2  s.  co m
 * @param outputStream
 * @throws IOException
 */
public void exportSearchFolder(OutputStream outputStream) throws IOException {
    BufferedOutputStream out = new BufferedOutputStream(outputStream);
    GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(out);
    TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut);

    File mboxFile = File.createTempFile("mbox-export", ".mbox");
    BufferedWriter mboxWriter = new BufferedWriter(new FileWriter(mboxFile));
    // Write mbox to tempfile?
    for (String messageId : getMessageIds()) {
        try {
            Message message = retrieverService.retrieve(messageId);

            mboxWriter.write("From " + message.getDateStr() + "\r\n");
            BufferedReader reader = new BufferedReader(new StringReader(message.getReconstitutedEmail()));
            String tmpLine;
            while ((tmpLine = reader.readLine()) != null) {
                if (tmpLine.startsWith("From "))
                    mboxWriter.write(">" + tmpLine);
                else
                    mboxWriter.write(tmpLine);
                mboxWriter.write("\r\n");
            }
        } catch (CannotRetrieveException e) {
            // Add errors to report
            // if (LOGGER.isErrorEnabled())
            // LOGGER.error("Could not retrieve message with id"
            // + messageId);
        }
    }
    mboxWriter.flush();
    mboxWriter.close();
    // Add mbox to tarfile
    TarArchiveEntry mboxEntry = new TarArchiveEntry(mboxFile, "filename.mbox");
    tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
    tOut.putArchiveEntry(mboxEntry);
    IOUtils.copy(new FileInputStream(mboxFile), tOut);
    tOut.flush();
    tOut.closeArchiveEntry();
    mboxWriter.close();
    mboxFile.delete();
    // Create report in tempfile?

    // Add report to tarfile

    // Close out stream
    tOut.finish();
    outputStream.flush();
    tOut.close();
    outputStream.close();

}

From source file:org.apache.whirr.util.Tarball.java

/**
 * Creates a tarball from the source directory and writes it into the target directory.
 *
 * @param sourceDirectory directory whose files will be added to the tarball
 * @param targetName      directory where tarball will be written to
 * @throws IOException when an exception occurs on creating the tarball
 *//*from  w w w.j  a v  a 2s. c  o  m*/
public static void createFromDirectory(String sourceDirectory, String targetName) throws IOException {
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    GzipCompressorOutputStream gzipOutputStream = null;
    TarArchiveOutputStream tarArchiveOutputStream = null;

    try {
        fileOutputStream = new FileOutputStream(new File(targetName));
        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        gzipOutputStream = new GzipCompressorOutputStream(bufferedOutputStream);
        tarArchiveOutputStream = new TarArchiveOutputStream(gzipOutputStream);

        addFilesInDirectory(tarArchiveOutputStream, sourceDirectory);
    } finally {
        if (tarArchiveOutputStream != null) {
            tarArchiveOutputStream.finish();
        }
        if (tarArchiveOutputStream != null) {
            tarArchiveOutputStream.close();
        }
        if (gzipOutputStream != null) {
            gzipOutputStream.close();
        }
        if (bufferedOutputStream != null) {
            bufferedOutputStream.close();
        }
        if (fileOutputStream != null) {
            fileOutputStream.close();
        }
    }
}

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());/* w w  w  .j  a  v  a 2s  .c  o  m*/
        tar.putArchiveEntry(tarEntry);
        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.jenkinsci.plugins.os_ci.utils.CompressUtils.java

public static void tarGzDirectory(String baseDir, String targetFile) throws FileNotFoundException, IOException {
    FileOutputStream fOut = null;
    BufferedOutputStream bOut = null;
    TarArchiveOutputStream tOut = null;
    GzipCompressorOutputStream gzOut = null;
    try {/*from w w w.j a  v  a  2  s.c om*/
        System.out.println(new File(".").getAbsolutePath());
        fOut = new FileOutputStream(new File(targetFile));
        bOut = new BufferedOutputStream(fOut);
        gzOut = new GzipCompressorOutputStream(bOut);
        tOut = new TarArchiveOutputStream(gzOut);
        tOut.setLongFileMode(LONGFILE_POSIX);
        addFileToTarGz(tOut, baseDir, "");
    } finally {
        if (tOut != null) {
            tOut.finish();
            tOut.close();
        }
        if (gzOut != null) {
            gzOut.close();
        }
        if (bOut != null) {
            bOut.close();
        }
        if (fOut != null) {
            fOut.close();
        }
    }

}