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: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  www .  j a  v 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 {//from  w ww.  j av  a 2s.c o  m
        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:gdt.data.entity.ArchiveHandler.java

/**
 * Compress the database into the tar archive file. 
 * @param  entigrator entigrator instance,
 * @param locator$ container of arguments 
 * in the string form. //from   w  ww  .j  ava2  s . com
 * @return true if success false otherwise.
 */
public boolean compressDatabaseToTar(Entigrator entigrator, String locator$) {
    try {
        System.out.println("ArchiveHandler:compressDatabaseToTar:locator=" + locator$);
        Properties locator = Locator.toProperties(locator$);
        archiveType$ = locator.getProperty(ARCHIVE_TYPE);
        archiveFile$ = locator.getProperty(ARCHIVE_FILE);
        String tarfile$ = archiveFile$;
        File tarfile = new File(tarfile$);
        if (!tarfile.exists())
            tarfile.createNewFile();
        TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream("tar", new FileOutputStream(tarfile$));
        aos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        String entihome$ = entigrator.getEntihome();
        append(entigrator, entihome$, entihome$, aos);
        aos.close();
        return true;
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
        return false;
    }
}

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

/**
   * Compress the database into the tgz archive file. 
   * @param  entigrator entigrator instance
   * @param locator$ container of arguments in the string form. 
   * @return true if success false otherwise.
   *///from w w  w .  j  a  v a 2  s.c o  m
public boolean compressDatabaseToTgz(Entigrator entigrator, String locator$) {
    try {
        Properties locator = Locator.toProperties(locator$);
        archiveType$ = locator.getProperty(ARCHIVE_TYPE);
        archiveFile$ = locator.getProperty(ARCHIVE_FILE);
        String tgzFile$ = archiveFile$;
        File tgzFile = new File(tgzFile$);
        if (!tgzFile.exists())
            tgzFile.createNewFile();
        // String userHome$=System.getProperty("user.home");
        File tarFile = new File(tgzFile$.replace(".tgz", "") + ".tar");
        if (!tarFile.exists())
            tarFile.createNewFile();
        TarArchiveOutputStream aos = (TarArchiveOutputStream) new ArchiveStreamFactory()
                .createArchiveOutputStream("tar", new FileOutputStream(tarFile));
        aos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
        String entihome$ = entigrator.getEntihome();
        append(entigrator, entihome$, entihome$, aos);
        aos.close();
        compressGzipFile(tarFile.getPath(), tgzFile.getPath());
        tarFile.delete();
        return true;
    } catch (Exception e) {
        Logger.getLogger(getClass().getName()).severe(e.toString());
        return false;
    }
}

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

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {//from  www.j  a va  2  s. c o  m
        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:edu.wisc.doit.tcrypt.BouncyCastleFileEncrypter.java

@Override
public void encrypt(String fileName, int size, InputStream inputStream, OutputStream outputStream)
        throws InvalidCipherTextException, IOException {
    final TarArchiveOutputStream tarArchiveOutputStream = new TarArchiveOutputStream(outputStream, 512,
            ENCODING);/*from w w w  . j  a  v a 2  s . c  om*/

    final BufferedBlockCipher cipher = createCipher(tarArchiveOutputStream);

    startEncryptedFile(fileName, size, tarArchiveOutputStream, cipher);

    //Setup cipher output stream, has to protect from close as the cipher stream must close but the tar cannot get closed yet
    final CipherOutputStream cipherOutputStream = new CipherOutputStream(
            new CloseShieldOutputStream(tarArchiveOutputStream), cipher);

    //Setup digester
    final DigestOutputStream digestOutputStream = new DigestOutputStream(this.createDigester());

    //Perform streaming encryption and hashing of the file
    IOUtils.copy(inputStream, new TeeOutputStream(cipherOutputStream, digestOutputStream));
    cipherOutputStream.close();

    tarArchiveOutputStream.closeArchiveEntry();

    //Capture the hash code of the encrypted file
    digestOutputStream.close();
    final byte[] hashBytes = digestOutputStream.getDigest();

    this.writeHashfile(tarArchiveOutputStream, hashBytes);

    //Close the TAR stream, nothing else should be written to it
    tarArchiveOutputStream.close();
}

From source file:com.mobilesorcery.sdk.builder.linux.deb.DebBuilder.java

/**
 *
 * @param os/*from w ww  .ja  v  a2  s  .  co m*/
 * @throws IOException
 */
private void doCreateControlTarGZip(File f) throws Exception {
    File ftemp;
    FileOutputStream os = new FileOutputStream(f);
    GzipCompressorOutputStream gzos = new GzipCompressorOutputStream(os);
    TarArchiveOutputStream tos = new TarArchiveOutputStream(gzos);

    // Write control file
    ftemp = File.createTempFile(System.currentTimeMillis() + "", "control");
    doWriteControl(ftemp);
    tos.putArchiveEntry(new TarArchiveEntry(ftemp, "./control"));
    BuilderUtil.getInstance().copyFileToOutputStream(tos, ftemp);
    tos.closeArchiveEntry();
    ftemp.delete();

    // Write md5sums
    ftemp = File.createTempFile(System.currentTimeMillis() + "", "md5sums");
    doWriteMD5SumsToFile(ftemp);
    tos.putArchiveEntry(new TarArchiveEntry(ftemp, "./md5sums"));
    BuilderUtil.getInstance().copyFileToOutputStream(tos, ftemp);
    tos.closeArchiveEntry();
    ftemp.delete();

    // Add prerm, postrm, preinst, postinst scripts
    for (Entry<String, String> s : m_scriptMap.entrySet()) {
        TarArchiveEntry e = new TarArchiveEntry("./" + s.getKey());
        e.setSize(s.getValue().length());
        tos.putArchiveEntry(e);
        BuilderUtil.getInstance().copyStringToOutputStream(tos, s.getValue());
        tos.closeArchiveEntry();
    }

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

From source file:io.anserini.index.IndexUtils.java

public void dumpRawDocuments(String reqDocidsPath, boolean prependDocid)
        throws IOException, NotStoredException {
    LOG.info("Start dump raw documents" + (prependDocid ? " with Docid prepended" : "."));

    InputStream in = getReadFileStream(reqDocidsPath);
    BufferedReader bRdr = new BufferedReader(new InputStreamReader(in));
    FileOutputStream fOut = new FileOutputStream(new File(reqDocidsPath + ".output.tar.gz"));
    BufferedOutputStream bOut = new BufferedOutputStream(fOut);
    GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(bOut);
    TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut);

    String docid;/*w ww.ja  va  2 s.c  o m*/
    int counter = 0;
    while ((docid = bRdr.readLine()) != null) {
        counter += 1;
        Document d = reader.document(convertDocidToLuceneDocid(docid));
        IndexableField doc = d.getField(LuceneDocumentGenerator.FIELD_RAW);
        if (doc == null) {
            throw new NotStoredException("Raw documents not stored!");
        }
        TarArchiveEntry tarEntry = new TarArchiveEntry(new File(docid));

        byte[] bytesOut = doc.stringValue().getBytes(StandardCharsets.UTF_8);
        tarEntry.setSize(
                bytesOut.length + (prependDocid ? String.format("<DOCNO>%s</DOCNO>\n", docid).length() : 0));
        tOut.putArchiveEntry(tarEntry);
        if (prependDocid) {
            tOut.write(String.format("<DOCNO>%s</DOCNO>\n", docid).getBytes());
        }
        tOut.write(bytesOut);
        tOut.closeArchiveEntry();

        if (counter % 100000 == 0) {
            LOG.info(counter + " files have been dumped.");
        }
    }
    tOut.close();
    LOG.info(String.format("Raw documents are output to: %s", reqDocidsPath + ".output.tar.gz"));
}

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 {//from  w ww.jav  a2  s  .co m
        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  . java  2 s.  c o 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();

}