PageRenderTime 29ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/play/app/models/FileManager.scala

https://github.com/Bochenski/stackcanon
Scala | 75 lines | 58 code | 15 blank | 2 comment | 0 complexity | 34e599e3d2a01177712daa638a57b8ca MD5 | raw file
  1. package models
  2. import play._
  3. import java.io._
  4. import com.mongodb.casbah.Imports._
  5. import com.mongodb.casbah.gridfs._
  6. object FileManager {
  7. def saveImage(image: File, parentType: String, parentId: String, sequence: Double): String = {
  8. //remove anything we already have at this address as we don't want to bloat the DB unnecessarily
  9. deleteFile(parentType,parentId,sequence)
  10. // Get extension
  11. val extensionRegex = """^.*\.([^.]+)$""".r
  12. val extension = image.getName match {
  13. case extensionRegex(x) => Some(x)
  14. case _ => None
  15. }
  16. Logger.info("Name:" + image.getName())
  17. Logger.info("path:" + image.getPath())
  18. Logger.info("ext: " + extension.get.toString)
  19. val photoStream = new FileInputStream(image)
  20. models.MongoDB.getGridFS(photoStream) {
  21. fh =>
  22. fh.filename = image.getName()
  23. fh.contentType = "image/" + extension.get.toString
  24. fh.metaData = MongoDBObject("parentType" -> parentType, "parentId" -> parentId, "sequence" -> sequence)
  25. }
  26. parentType + "/" + parentId + "/image/"+ sequence.toInt
  27. }
  28. def saveImage(image:Option[File], parentType: String, parentId: String, sequence: Double): String = {
  29. image match {
  30. case Some(image) =>
  31. saveImage(image,parentType,parentId,sequence)
  32. case None =>
  33. Logger.info("No Data Received")
  34. ""
  35. }
  36. }
  37. def saveImage(image:Option[File], parentType: String, parentId: String): String = {
  38. saveImage(image,parentType,parentId,0)
  39. }
  40. def saveImage(image: File, parentType: String, parentId: String): String = {
  41. saveImage(image,parentType,parentId,0)
  42. }
  43. def getFile(parentType: String, parentId: String, sequence: Int): Option[GridFSDBFile] = {
  44. MongoDB.getGridFS.findOne(MongoDBObject("metadata.parentType" -> parentType, "metadata.parentId" -> parentId, "metadata.sequence" -> sequence))
  45. }
  46. def getFileCount(parentType: String, parentId: String) = {
  47. val count = MongoDB.getDB("fs.files").count(MongoDBObject("metadata.parentType" -> parentType, "metadata.parentId" -> parentId))
  48. Logger.info("found " + count.toString + " files")
  49. count
  50. }
  51. def getFile(parentType: String, parentId: String): Option[GridFSDBFile] = {
  52. getFile(parentType,parentId,0)
  53. }
  54. def deleteFile(parentType: String, parentId: String) {
  55. deleteFile(parentType,parentId,0)
  56. }
  57. def deleteFile(parentType: String, parentId: String, sequence: Double) {
  58. MongoDB.getGridFS.remove(MongoDBObject("metadata.parentType" -> parentType, "metadata.parentId" -> parentId, "metadata.sequence" -> sequence))
  59. }
  60. }