sss.openstar.attachments.FileStreamPersister.scala Maven / Gradle / Ivy
package sss.openstar.attachments
import java.io.{File, FileOutputStream, InputStream}
import java.net.URL
import java.nio.file.{Files, Paths}
import com.google.common.io.ByteStreams
import scala.util.Try
class FileStreamPersister(attachmentsFolder: File) extends StreamPersister {
require(attachmentsFolder.exists(), s"Folder $attachmentsFolder must exist")
require(attachmentsFolder.isDirectory, s"Folder $attachmentsFolder must be a directory")
require(attachmentsFolder.canWrite, s"Folder $attachmentsFolder must be writable")
require(attachmentsFolder.canRead, s"Folder $attachmentsFolder must be readable")
private val fileUrlPrefix = "file://"
override def saveStream(in: InputStream, path: String*): Try[UniqueLocator] = Try {
val saveTo = createFileToSaveTo(path: _*)
val size = saveFile(in, saveTo)
val location = fileToLocation(saveTo)
UniqueLocator(location, Some(size))
}
override def getStream(locator: UniqueLocator): Try[InputStream] = Try {
new URL(locator.location).openStream()
}
private def saveFile(in: InputStream, file: File): Long = {
val os = new FileOutputStream(file)
try {
ByteStreams.copy(in, os)
} finally {
os.close()
//end of the line
in.close()
}
}
private def fileToLocation(file: File): String = {
s"$fileUrlPrefix${file.getAbsolutePath}"
}
private def createFileToSaveTo(path: String*): File = {
val targetPath = Paths.get(attachmentsFolder.getAbsolutePath, path: _*)
Files.createDirectories(targetPath.getParent)
targetPath.toFile
}
}