Advertisement
Guest User

Untitled

a guest
Apr 9th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Groovy 8.03 KB | None | 0 0
  1. package beans
  2.  
  3. import br.com.gridnet.AuditService
  4. import br.com.gridnet.audit.Audit
  5. import br.com.gridnet.audit.AuditOrigin
  6. import br.com.gridnet.data.enumeration.AuditType
  7. import grails.util.Holders
  8. import org.hibernate.event.spi.*
  9. import org.springframework.context.ApplicationContext
  10.  
  11. class AuditHibernateEventListeners implements PreUpdateEventListener,
  12.     PostInsertEventListener,PostUpdateEventListener,PostDeleteEventListener {
  13.  
  14.     // No audit clazz
  15.     private static String[] notAuditedClasses = ['DBFile','IntegrationClientLog','AsynchronousMailMessage',
  16.                                                  'AsynchronousMailAttachment', 'Stock',
  17.                                                  'TicketDocument','Warehouse','Submenu', 'Menu', 'MenuXMenuItem',
  18.                                                  'MenuItem', 'UserPasswordHistory','IntegrationService','DocumentReference',
  19.                                                  'Movement', 'Receiving','Addressing', 'Separation', 'Inventory', 'Dispatch',
  20.                                                  'Operation', 'StockMirror', 'StockMirror','StockMirrorClassification',
  21.                                                  'StockMirrorFeature', 'StockMirrorGroup', 'StockMirrorOwner', 'StockMirrorProduct',
  22.                                                  'StockMirrorProductSerial', 'StockMirrorSubgroup', 'StockReserve', 'StockDivergenceErp',
  23.                                                  'SlowMoving', 'BillingAmount','BillingOperation','BillingPalletOperation',
  24.                                                  'BillingPosition','BillingServices','BillingStay','BillingWindow','BillingWindowStay',
  25.                                                  'AutomaticPrintDocument','SystemAlert','Audit','AuditOrigin','SeparationCheckingDiv',
  26.                                                  'SalesOrderGWDispatchPrograming', 'SalesOrderGWDocuments']
  27.  
  28.     private static String[] notAuditedFiels = ['stockEndDate','availableAmountInStock']
  29.  
  30.     private static ApplicationContext applicationContext
  31.  
  32.     private static saveLog = Boolean.TRUE
  33.  
  34.     private static ApplicationContext getContext() {
  35.         if(!applicationContext)
  36.             applicationContext = Holders.applicationContext
  37.  
  38.         return applicationContext
  39.     }
  40.     // Generic way to get service
  41.     private <T> T getService(Class<T> clazz) {
  42.         if(!clazz) return
  43.  
  44.         try{
  45.             return context.getBean(clazz.simpleName.replaceFirst(/^[A-Z]/){it.toLowerCase()})
  46.         }catch(Exception e){
  47.             print(e.stackTrace)
  48.         }
  49.     }
  50.  
  51.     @Override
  52.     boolean onPreUpdate(PreUpdateEvent event) {
  53.         event.entity.updatedProperties += event.entity.dirtyPropertyNames ?: []
  54.         return false
  55.     }
  56.  
  57.     @Override
  58.     void onPostDelete(PostDeleteEvent event) {
  59.  
  60.         if (saveLog && !(event.entity.class.simpleName in notAuditedClasses)){
  61.             def entity      = event.entity
  62.             def fieldChange = Boolean.FALSE
  63.             def information = '<table class="tableLog subtable"><thead><th>Campo</th><th>Valor</th></thead>'
  64.  
  65.             event.persister.propertyNames?.each {
  66.                 try {
  67.                     def _value = getValue(entity[it])
  68.                     def _isValidField = !it.equals('warehouse') && !it.equals('orderTimestamp')
  69.                     if (_value && _isValidField){
  70.                         fieldChange         = Boolean.TRUE
  71.                         def propertyLabel   = context.getMessage("${entity.class.simpleName?.toLowerCase()}.${it}.label".toString(), [] as String[], it, Locale.getDefault())
  72.                         information <<= "<tr><td><strong>${propertyLabel}</strong></td> <td>${_value}</td></tr>"
  73.                     }
  74.                 }catch(e) { }
  75.             }
  76.  
  77.             information <<= "</table>"
  78.  
  79.             if(fieldChange) Audit.withNewSession {
  80.                 getService(AuditService)?.addAudit(AuditType.DE,entity.class.simpleName,entity.id,"${information ?: entity}")
  81.             }
  82.         }
  83.     }
  84.  
  85.     @Override
  86.     void onPostInsert(PostInsertEvent event) {
  87.  
  88.         if (saveLog && !(event.entity.class.simpleName in notAuditedClasses)){
  89.             def entity      = event.entity
  90.             def fieldChange = Boolean.FALSE
  91.  
  92.             switch(entity.class) {
  93.                 case Audit :
  94.                 case AuditOrigin :
  95.                     return
  96.             }
  97.  
  98.             def information = '<table class="tableLog subtable"><thead><th>Campo</th><th>Valor</th></thead>'
  99.  
  100.             event.persister.propertyNames?.each {
  101.                 try {
  102.                     def _value = getValue(entity[it])
  103.                     def _isValidField = !it.equals('warehouse') && !it.equals('orderTimestamp')
  104.                     if (_value && _isValidField){
  105.                         fieldChange         = Boolean.TRUE
  106.                         def propertyLabel   = context.getMessage("${entity.class.simpleName?.toLowerCase()}.${it}.label".toString(), [] as String[], it, Locale.getDefault())
  107.                         information <<= "<tr><td><strong>${propertyLabel}</strong></td> <td>${_value}</td></tr>"
  108.                     }
  109.                 }catch(e) { }
  110.             }
  111.  
  112.             information <<= "</table>"
  113.  
  114.             if(fieldChange) Audit.withNewSession {
  115.                 getService(AuditService)?.addAudit(AuditType.IN,entity.class.simpleName,entity.id,information.toString())
  116.             }
  117.         }
  118.     }
  119.  
  120.     @Override
  121.     void onPostUpdate(PostUpdateEvent event) {
  122.  
  123.         if (saveLog && !(event.entity.class.simpleName in notAuditedClasses)){
  124.             def String information = '<table class="tableLog subtable"><thead><th>Campo</th><th>Antes</th><th>Depois</th><thead>'
  125.             def entity = event.entity
  126.             def nameList = event.persister.propertyNames
  127.  
  128.             if(entity.updatedProperties?.size() != event.dirtyProperties?.size()) return
  129.  
  130.             def propertiesChange = 0
  131.             event.dirtyProperties?.each {
  132.                 def _property = nameList[it]
  133.                 if (!(_property in notAuditedFiels)) {
  134.                     propertiesChange++
  135.                     def propertyLabel = context.getMessage("${entity.class.simpleName?.toLowerCase()}.${_property}.label".toString(), [] as String[], _property, Locale.getDefault())
  136.                     def oldValue = getValue(event.oldState[it] ?: ' ')
  137.                     def newValue = getValue(event.state[it] ?: ' ')
  138.  
  139.                     information <<= "<tr><td><strong>${propertyLabel}</strong></td> <td>${oldValue}</td><td>${newValue}</td></tr>"
  140.                 }
  141.             }
  142.             if (propertiesChange == 0) return
  143.  
  144.             /*
  145.             Put the Id information
  146.              */
  147.             def propertyLabel = "ID"
  148.             def _value = getValue(entity['id']?:' ')
  149.             information <<= "<tr><td><strong>${propertyLabel}</strong></td> <td colspan='2'>${_value}</td></tr>"
  150.  
  151.             def hasCode = event.persister.propertyNames?.find {'code'.equals(it)}
  152.             if (hasCode){
  153.                 propertyLabel = context.getMessage("${entity.class.simpleName?.toLowerCase()}.code.label".toString(), [] as String[], 'Codigo', Locale.getDefault())
  154.                 _value = getValue(entity['code']?:' ')
  155.                 information <<= "<tr><td><strong>${propertyLabel}</strong></td> <td colspan='2'>${_value}</td></tr>"
  156.             }
  157.  
  158.             information <<= "</table>"
  159.  
  160.             if(information) Audit.withNewSession {
  161.                 getService(AuditService)?.addAudit(AuditType.UP,entity.class.simpleName,entity.id,information.toString())
  162.             }
  163.         }
  164.  
  165.     }
  166.  
  167.     public boolean requiresPostCommitHanding(org.hibernate.persister.entity.EntityPersister entityPersister){
  168.         return false
  169.     }
  170.  
  171.     private Object getValue(Object obj){
  172.  
  173.         if (obj && obj?.toString()?.contains('label.') || obj?.toString()?.contains('.label')){
  174.             return context.getMessage(obj?.toString(), [] as String[], obj?.toString(), Locale.getDefault())
  175.         }
  176.         else return obj
  177.     }
  178. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement