All Downloads are FREE. Search and download functionalities are using the official Maven repository.

blended.itestsupport.compress.TarFileSupport.scala Maven / Gradle / Ivy

Go to download

Define an integration test API for collaborating blended container(s) using docker as a runtime for the container(s) under test and an Akka based Camel framework to perform the integration tests as pure blackbox tests. Container(s) may be prestarted and discovered (for execution speed) or started by the integration test (for reproducability).

The newest version!
package blended.itestsupport.compress

import java.io._
import java.util.zip.GZIPOutputStream

import blended.util.StreamCopySupport
import org.apache.commons.compress.archivers.ArchiveStreamFactory
import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveOutputStream}
import org.slf4j.LoggerFactory

import scala.collection.mutable

object TarFileSupport {

  private[this] val log = LoggerFactory.getLogger(classOf[TarFileSupport])

  def untar(is : InputStream) : Map[String, Array[Byte]] = {
    val tar = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is))
    val bytes = new Array[Byte](8192)

    val content : mutable.Map[String, Array[Byte]] = mutable.Map.empty
    var entry = Option(tar.getNextEntry())

    while(entry.isDefined) {
      val bos = new ByteArrayOutputStream()
      StreamCopySupport.copyStream(tar, bos)

      bos.close()

      log.debug(s"Extracted [${entry.get.getName()}], size [${bos.size}].")
      content.put(entry.get.getName(), bos.toByteArray())

      entry = Option(tar.getNextEntry())
    }

    tar.close()
    is.close()

    content.toMap
  }

  def tar(file : File, os: OutputStream, user: Int = 0, group : Int = 0) : Unit = {

    def addFileToTar(tarOs: TarArchiveOutputStream, file: File, base : String) : Unit = {
      val entryName = base + file.getName()
      val entry = new TarArchiveEntry(file, entryName)

      entry.setUserId(user)
      entry.setGroupId(group)

      log.info(s"Adding [$entryName] to tar archive with [user($user), group($group)].")

      tarOs.putArchiveEntry(entry)

      if (file.isFile()) {
        StreamCopySupport.copyStream(new FileInputStream(file), tarOs)
        tarOs.closeArchiveEntry()
      } else {
        tarOs.closeArchiveEntry()

        val files = Option(file.listFiles())
        files.map { ff =>
          ff.foreach{ f => addFileToTar(tarOs, f, entryName + "/") }
        }
      }
    }

    if (!file.exists()) throw new FileNotFoundException(file.getAbsolutePath())

    val bOut = new BufferedOutputStream(os)
    var tarOut = new TarArchiveOutputStream(bOut)

    try {
      addFileToTar(tarOut, file, "")
    } finally {
      tarOut.finish()
      tarOut.close()
      bOut.close()
      os.close()
    }
  }
}

class TarFileSupport




© 2015 - 2024 Weber Informatics LLC | Privacy Policy