1 package org.itracker.persistence.dao;
2
3 import org.apache.log4j.Logger;
4 import org.hibernate.EmptyInterceptor;
5 import org.hibernate.type.Type;
6 import org.itracker.model.AbstractEntity;
7
8 import java.io.Serializable;
9 import java.util.Date;
10
11
12
13
14
15
16
17
18 public class TimestampInterceptor extends EmptyInterceptor {
19
20
21
22
23 private static final long serialVersionUID = 1L;
24
25
26
27
28 private static final String CREATE_DATE_PROPERTY = "createDate";
29
30
31
32
33 private static final String LAST_MODIFIED_DATE_PROPERTY = "lastModifiedDate";
34
35 @SuppressWarnings("unused")
36 private static final transient Logger logger = Logger.getLogger(TimestampInterceptor.class);
37
38
39
40
41 public TimestampInterceptor() {
42 }
43
44
45
46
47
48
49
50
51
52
53
54 public boolean onSave(Object entity, Serializable id,
55 Object[] state, String[] propertyNames, Type[] types) {
56
57 if (entity instanceof AbstractEntity) {
58 final Date timestamp = new Date();
59
60
61 int propertiesSet = 0;
62
63
64 for (int i = 0; i < propertyNames.length; i++) {
65
66 if (CREATE_DATE_PROPERTY.equals(propertyNames[i])
67 || LAST_MODIFIED_DATE_PROPERTY.equals(propertyNames[i])) {
68 state[i] = timestamp;
69
70
71
72
73
74
75 if (++propertiesSet == 2) {
76 break;
77 }
78 }
79 }
80 return (propertiesSet > 0);
81 }
82 return false;
83 }
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101 public boolean onFlushDirty(Object entity, Serializable id,
102 Object[] currentState, Object[] previousState,
103 String[] propertyNames, Type[] types) {
104
105 if (entity instanceof AbstractEntity) {
106 final Date timestamp = new Date();
107
108
109 for (int i = 0; i < propertyNames.length; i++) {
110
111 if (LAST_MODIFIED_DATE_PROPERTY.equals(propertyNames[i])) {
112 currentState[i] = timestamp;
113
114
115
116
117
118 return true;
119 }
120 }
121 }
122 return false;
123 }
124
125 }