PageRenderTime 66ms CodeModel.GetById 40ms RepoModel.GetById 1ms app.codeStats 0ms

/src/main/scala/br/com/gfuture/mongodbhelper/DocumentTools.scala

https://github.com/josa/mongodb-scala-helper
Scala | 104 lines | 78 code | 13 blank | 13 comment | 14 complexity | 55c76bcb1316f475a0e063b5b19aa8f4 MD5 | raw file
  1. package br.com.gfuture.mongodbhelper
  2. import annotations.{CascadeType, Reference, AssociationType, DocElement}
  3. import com.mongodb.DBObject
  4. import reflect.ReflectUtil
  5. import org.bson.types.ObjectId
  6. import java.lang.reflect.Field
  7. import org.slf4j.LoggerFactory
  8. import com.mongodb.casbah.commons.MongoDBObject
  9. /**Ferramentas de apoio a manipulação dos documentos
  10. */
  11. object DocumentTools {
  12. protected lazy val logger = LoggerFactory.getLogger(DocumentTools.getClass)
  13. /**Converte o objeto em um objeto de persistencia do mongo
  14. *
  15. * @param document, a entidade a ser convertida
  16. * @return uma instancia da classe com.mongodb.DBObject
  17. */
  18. def toDBObject(document: Document): DBObject = {
  19. val builder = MongoDBObject.newBuilder
  20. def processAnnotationsAndGenerateElement(field: Field): (String, AnyRef) = {
  21. field.getAnnotation(classOf[Reference]) match {
  22. case refAnnotation: Reference =>
  23. val documentReference = field.get(document).asInstanceOf[Document]
  24. if (!refAnnotation.cascade.equals(CascadeType.SAVE) && documentReference.getObjectId == null)
  25. throw new MappingException(field.getName + "CascadeType.NONE using the objectId is required")
  26. documentReference.getObjectId match {
  27. case o: ObjectId =>
  28. field.getName -> documentReference.getObjectId
  29. case null =>
  30. documentReference.save
  31. field.getName -> documentReference.getObjectId
  32. }
  33. case null =>
  34. field.getName -> field.get(document)
  35. }
  36. }
  37. ReflectUtil.loadFieldsRecursively(document.documentClass).foreach {
  38. field =>
  39. field.setAccessible(true)
  40. if (field.isAnnotationPresent(classOf[DocElement]) && field.get(document) != null)
  41. builder += processAnnotationsAndGenerateElement(field)
  42. else {
  43. if (logger.isDebugEnabled) {
  44. if (!field.isAnnotationPresent(classOf[DocElement]))
  45. logger.debug("toObject[field excluded(%s), @DocElement not found]" format (field.getName))
  46. if (field.get(document) != null)
  47. logger.debug("toObject[field excluded(%s), is null]" format (field.getName))
  48. }
  49. }
  50. }
  51. builder += "_id" -> document.getObjectId
  52. builder.result
  53. }
  54. /**
  55. * Converte o _id em um objeto de persistencia do mongo
  56. *
  57. * @param _id, instancia da classe org.bson.types.ObjectId
  58. * @return uma instancia da classe com.mongodb.DBObject
  59. */
  60. def toOBObject(objectId: org.bson.types.ObjectId): DBObject = {
  61. MongoDBObject("_id" -> objectId)
  62. }
  63. def fromMongoObject(dbObject: DBObject, documentClass: Class[_ <: Document]): Document = dbObject match {
  64. case dbObjectMatch: Any =>
  65. def processAnnotationsAndGetProperty(field: Field): AnyRef = {
  66. field.getAnnotation(classOf[Reference]) match {
  67. case refAnnotation: Reference =>
  68. if (refAnnotation.association.equals(AssociationType.ONE_TO_ONE)) {
  69. val reference = new DocumentManager(field.getType.asInstanceOf[Class[Document]]).findById(dbObject.get(field.getName).asInstanceOf[ObjectId])
  70. reference
  71. } else {
  72. null.asInstanceOf[AnyRef]
  73. }
  74. case _ =>
  75. dbObject.get(field.getName)
  76. }
  77. }
  78. val document = documentClass.newInstance
  79. ReflectUtil.loadFieldsRecursively(documentClass).foreach {
  80. field =>
  81. field.setAccessible(true)
  82. if (field.isAnnotationPresent(classOf[DocElement])) {
  83. field.set(document, processAnnotationsAndGetProperty(field))
  84. }
  85. }
  86. document.setObjectId(dbObject.get("_id").asInstanceOf[ObjectId])
  87. document
  88. case _ =>
  89. null.asInstanceOf[Document]
  90. }
  91. }