├── .gitignore ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main ├── java │ └── com │ │ └── fintechlabs │ │ └── auditlogs │ │ ├── AuditLogsApplication.java │ │ ├── ServletInitializer.java │ │ ├── audit │ │ ├── AuditAware.java │ │ ├── AuditLogInterceptor.java │ │ └── AuditLogListener.java │ │ ├── config │ │ └── HibernateListenerConfigurer.java │ │ ├── controller │ │ └── StudentController.java │ │ ├── dto │ │ ├── AuditTrailDTO.java │ │ └── StudentDTO.java │ │ ├── model │ │ ├── AuditTrail.java │ │ └── Student.java │ │ ├── repository │ │ ├── AuditTrailRepository.java │ │ └── StudentRepository.java │ │ ├── service │ │ └── AuditLogService.java │ │ └── util │ │ ├── ApplicationContextProvider.java │ │ └── Enums.java └── resources │ ├── application.properties │ ├── static │ └── css │ │ └── sticky-footer-navbar.css │ └── templates │ ├── layout │ └── layout.html │ └── student │ ├── create.html │ ├── edit.html │ └── list.html └── test └── java └── com └── fintechlabs └── auditlogs └── AuditLogsApplicationTests.java /.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | .gradle 3 | build/ 4 | !gradle/wrapper/gradle-wrapper.jar 5 | !**/src/main/** 6 | !**/src/test/** 7 | 8 | ### STS ### 9 | .apt_generated 10 | .classpath 11 | .factorypath 12 | .project 13 | .settings 14 | .springBeans 15 | .sts4-cache 16 | 17 | ### IntelliJ IDEA ### 18 | .idea 19 | *.iws 20 | *.iml 21 | *.ipr 22 | out/ 23 | 24 | ### NetBeans ### 25 | /nbproject/private/ 26 | /nbbuild/ 27 | /dist/ 28 | /nbdist/ 29 | /.nb-gradle/ 30 | 31 | ### VS Code ### 32 | .vscode/ 33 | 34 | .DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # spring-boot-audit-log 2 | Audit Logging in Spring Boot JPA 3 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'org.springframework.boot' version '2.1.6.RELEASE' 3 | id 'java' 4 | id 'war' 5 | } 6 | 7 | apply plugin: 'io.spring.dependency-management' 8 | 9 | group = 'com.fintechlabs' 10 | version = '0.0.1-SNAPSHOT' 11 | sourceCompatibility = '1.8' 12 | 13 | configurations { 14 | compileOnly { 15 | extendsFrom annotationProcessor 16 | } 17 | } 18 | 19 | repositories { 20 | mavenCentral() 21 | } 22 | 23 | dependencies { 24 | implementation 'org.springframework.boot:spring-boot-starter-data-jpa' 25 | implementation 'org.springframework.boot:spring-boot-starter-web' 26 | implementation 'org.springframework.boot:spring-boot-starter-thymeleaf' 27 | compile group: 'nz.net.ultraq.thymeleaf', name: 'thymeleaf-layout-dialect', version: '2.4.1' 28 | implementation 'org.springframework.boot:spring-boot-devtools' 29 | compileOnly 'org.projectlombok:lombok' 30 | runtimeOnly 'mysql:mysql-connector-java' 31 | annotationProcessor 'org.projectlombok:lombok' 32 | providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' 33 | testImplementation 'org.springframework.boot:spring-boot-starter-test' 34 | } 35 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FintechLabs/spring-boot-audit-log/8da99556f89458d52093ec6616b20d6b701dfe76/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Tue Jul 23 16:25:22 IST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS='"-Xmx64m"' 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS="-Xmx64m" 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | pluginManagement { 2 | repositories { 3 | gradlePluginPortal() 4 | } 5 | } 6 | rootProject.name = 'audit-logs' 7 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/AuditLogsApplication.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs; 2 | 3 | import org.springframework.boot.SpringApplication; 4 | import org.springframework.boot.autoconfigure.SpringBootApplication; 5 | 6 | @SpringBootApplication 7 | public class AuditLogsApplication { 8 | 9 | public static void main(String[] args) { 10 | SpringApplication.run(AuditLogsApplication.class, args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/ServletInitializer.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs; 2 | 3 | import org.springframework.boot.builder.SpringApplicationBuilder; 4 | import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; 5 | 6 | public class ServletInitializer extends SpringBootServletInitializer { 7 | 8 | @Override 9 | protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { 10 | return application.sources(AuditLogsApplication.class); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/audit/AuditAware.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.audit; 2 | 3 | public interface AuditAware { 4 | } 5 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/audit/AuditLogInterceptor.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.audit; 2 | 3 | import com.fintechlabs.auditlogs.dto.AuditTrailDTO; 4 | import com.fintechlabs.auditlogs.service.AuditLogService; 5 | import com.fintechlabs.auditlogs.util.ApplicationContextProvider; 6 | import com.fintechlabs.auditlogs.util.Enums; 7 | import org.hibernate.CallbackException; 8 | import org.hibernate.EmptyInterceptor; 9 | import org.hibernate.type.Type; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.io.Serializable; 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | @Component 17 | public class AuditLogInterceptor extends EmptyInterceptor { 18 | 19 | @Override 20 | public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException { 21 | if (entity instanceof AuditAware) { 22 | List auditTrailDTOList = new ArrayList<>(); 23 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 24 | for (int i = 0; i < currentState.length; i++) { 25 | if (!previousState[i].equals(currentState[i])) { 26 | System.out.println("Inside On Flush Dirty ************ ************** ==>> " + propertyNames[i]); 27 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), id.toString(), Enums.AuditEvent.UPDATE.name(), propertyNames[i], previousState[i].toString(), currentState[i].toString())); 28 | } 29 | } 30 | auditTrailDTOList.forEach(auditLogService::save); 31 | } 32 | return true; 33 | } 34 | 35 | @Override 36 | public boolean onSave(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { 37 | if (entity instanceof AuditAware) { 38 | List auditTrailDTOList = new ArrayList<>(); 39 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 40 | for (int i = 0; i < propertyNames.length; i++) { 41 | System.out.println("Inside On Save ************ ************** ===>>> " + propertyNames[i]); 42 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), id.toString(), Enums.AuditEvent.INSERT.name(), propertyNames[i], null, state[i].toString())); 43 | } 44 | auditTrailDTOList.forEach(auditLogService::save); 45 | } 46 | return super.onSave(entity, id, state, propertyNames, types); 47 | } 48 | 49 | @Override 50 | public void onDelete(Object entity, Serializable id, Object[] state, String[] propertyNames, Type[] types) throws CallbackException { 51 | if (entity instanceof AuditAware) { 52 | List auditTrailDTOList = new ArrayList<>(); 53 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 54 | for (int i = 0; i < propertyNames.length; i++) { 55 | System.out.println("Inside On Delete ************ ************** ===>>> " + propertyNames[i]); 56 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), id.toString(), Enums.AuditEvent.DELETE.name(), propertyNames[i], state[i].toString(), null)); 57 | } 58 | auditTrailDTOList.forEach(auditLogService::save); 59 | } 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/audit/AuditLogListener.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.audit; 2 | 3 | import com.fintechlabs.auditlogs.dto.AuditTrailDTO; 4 | import com.fintechlabs.auditlogs.service.AuditLogService; 5 | import com.fintechlabs.auditlogs.util.ApplicationContextProvider; 6 | import com.fintechlabs.auditlogs.util.Enums; 7 | import org.hibernate.event.spi.*; 8 | import org.hibernate.persister.entity.EntityPersister; 9 | import org.springframework.stereotype.Component; 10 | 11 | import java.util.ArrayList; 12 | import java.util.List; 13 | 14 | @Component 15 | public class AuditLogListener implements PostInsertEventListener, PostUpdateEventListener, PostDeleteEventListener { 16 | 17 | @Override 18 | public void onPostInsert(PostInsertEvent event) { 19 | Object entity = event.getEntity(); 20 | if (entity instanceof AuditAware) { 21 | List auditTrailDTOList = new ArrayList<>(); 22 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 23 | String[] propertyNames = event.getPersister().getPropertyNames(); 24 | Object[] states = event.getState(); 25 | for (int i = 0; i < propertyNames.length; i++) { 26 | System.out.println("Inside On Save ************ ************** ===>>> " + propertyNames[i]); 27 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), event.getId().toString(), Enums.AuditEvent.INSERT.name(), propertyNames[i], null, states[i].toString())); 28 | } 29 | auditTrailDTOList.forEach(auditLogService::save); 30 | } 31 | } 32 | 33 | @Override 34 | public boolean requiresPostCommitHanding(EntityPersister persister) { 35 | return false; 36 | } 37 | 38 | @Override 39 | public void onPostUpdate(PostUpdateEvent event) { 40 | Object entity = event.getEntity(); 41 | if (entity instanceof AuditAware) { 42 | String[] propertyNames = event.getPersister().getPropertyNames(); 43 | Object[] currentState = event.getState(); 44 | Object[] previousState = event.getOldState(); 45 | List auditTrailDTOList = new ArrayList<>(); 46 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 47 | for (int i = 0; i < currentState.length; i++) { 48 | if (!previousState[i].equals(currentState[i])) { 49 | System.out.println("Inside On Flush Dirty ************ ************** ==>> " + propertyNames[i]); 50 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), event.getId().toString(), Enums.AuditEvent.UPDATE.name(), propertyNames[i], previousState[i].toString(), currentState[i].toString())); 51 | } 52 | } 53 | auditTrailDTOList.forEach(auditLogService::save); 54 | } 55 | } 56 | 57 | @Override 58 | public void onPostDelete(PostDeleteEvent event) { 59 | Object entity = event.getEntity(); 60 | if (entity instanceof AuditAware) { 61 | String[] propertyNames = event.getPersister().getPropertyNames(); 62 | Object[] state = event.getDeletedState(); 63 | List auditTrailDTOList = new ArrayList<>(); 64 | AuditLogService auditLogService = (AuditLogService) ApplicationContextProvider.getApplicationContext().getBean("auditLogService"); 65 | for (int i = 0; i < propertyNames.length; i++) { 66 | System.out.println("Inside On Delete ************ ************** ===>>> " + propertyNames[i]); 67 | auditTrailDTOList.add(new AuditTrailDTO(entity.getClass().getCanonicalName(), event.getId().toString(), Enums.AuditEvent.DELETE.name(), propertyNames[i], state[i].toString(), null)); 68 | } 69 | auditTrailDTOList.forEach(auditLogService::save); 70 | } 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/config/HibernateListenerConfigurer.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.config; 2 | 3 | import com.fintechlabs.auditlogs.audit.AuditLogListener; 4 | import org.hibernate.event.service.spi.EventListenerRegistry; 5 | import org.hibernate.event.spi.EventType; 6 | import org.hibernate.internal.SessionFactoryImpl; 7 | import org.springframework.beans.factory.annotation.Autowired; 8 | import org.springframework.stereotype.Component; 9 | 10 | import javax.annotation.PostConstruct; 11 | import javax.persistence.EntityManagerFactory; 12 | import javax.persistence.PersistenceUnit; 13 | 14 | @Component 15 | public class HibernateListenerConfigurer { 16 | 17 | @PersistenceUnit 18 | private EntityManagerFactory emf; 19 | 20 | @Autowired 21 | private AuditLogListener auditLogListener; 22 | 23 | 24 | @PostConstruct 25 | protected void init() { 26 | SessionFactoryImpl sessionFactory = emf.unwrap(SessionFactoryImpl.class); 27 | EventListenerRegistry registry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class); 28 | registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(auditLogListener); 29 | registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(auditLogListener); 30 | registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(auditLogListener); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/controller/StudentController.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.controller; 2 | 3 | import com.fintechlabs.auditlogs.dto.StudentDTO; 4 | import com.fintechlabs.auditlogs.model.Student; 5 | import com.fintechlabs.auditlogs.repository.StudentRepository; 6 | import org.springframework.stereotype.Controller; 7 | import org.springframework.ui.Model; 8 | import org.springframework.web.bind.annotation.GetMapping; 9 | import org.springframework.web.bind.annotation.PathVariable; 10 | import org.springframework.web.bind.annotation.PostMapping; 11 | import org.springframework.web.bind.annotation.RequestMapping; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | 16 | @Controller 17 | @RequestMapping(value = "/student") 18 | public class StudentController { 19 | 20 | private final StudentRepository studentRepository; 21 | 22 | public StudentController(StudentRepository studentRepository) { 23 | this.studentRepository = studentRepository; 24 | } 25 | 26 | @GetMapping("/list") 27 | public String list(Model model) { 28 | List studentDTOList = new ArrayList<>(); 29 | studentRepository.findAll().forEach(student -> { 30 | studentDTOList.add(new StudentDTO(student)); 31 | }); 32 | model.addAttribute("studentDTOList", studentDTOList); 33 | return "student/list"; 34 | } 35 | 36 | @GetMapping("/create") 37 | public String create() { 38 | return "student/create"; 39 | } 40 | 41 | @PostMapping(value = "/save") 42 | public String save(Student student) { 43 | studentRepository.save(student); 44 | return "redirect:/student/list"; 45 | } 46 | 47 | @GetMapping("/delete/{id}") 48 | public String delete(@PathVariable Long id) { 49 | studentRepository.deleteById(id); 50 | return "redirect:/student/list"; 51 | } 52 | 53 | @GetMapping("/edit/{id}") 54 | public String edit(@PathVariable Long id, Model model) { 55 | Student student = studentRepository.findById(id).get(); 56 | model.addAttribute("student", student); 57 | return "student/edit"; 58 | } 59 | 60 | @PostMapping(value = "/update") 61 | public String update(StudentDTO studentDTO) { 62 | Student student = studentRepository.findById(studentDTO.getId()).get(); 63 | student.setFirstName(studentDTO.getFirstName()); 64 | student.setLastName(studentDTO.getLastName()); 65 | student.setEmailAddress(studentDTO.getEmailAddress()); 66 | student.setPhoneNumber(studentDTO.getPhoneNumber()); 67 | studentRepository.save(student); 68 | return "redirect:/student/list"; 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/dto/AuditTrailDTO.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.dto; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | @Data 7 | @NoArgsConstructor 8 | public class AuditTrailDTO { 9 | 10 | private String className; 11 | private String persistedObjectId; 12 | private String eventName; 13 | private String propertyName; 14 | private String oldValue; 15 | private String newValue; 16 | 17 | public AuditTrailDTO(String className, String persistedObjectId, String eventName, String propertyName, String oldValue, String newValue) { 18 | this.className = className; 19 | this.persistedObjectId = persistedObjectId; 20 | this.eventName = eventName; 21 | this.propertyName = propertyName; 22 | this.oldValue = oldValue; 23 | this.newValue = newValue; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/dto/StudentDTO.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.dto; 2 | 3 | import com.fintechlabs.auditlogs.model.Student; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | @Data 8 | @NoArgsConstructor 9 | public class StudentDTO { 10 | 11 | private Long id; 12 | private String firstName; 13 | private String lastName; 14 | private String emailAddress; 15 | private String phoneNumber; 16 | 17 | public StudentDTO(Student student) { 18 | this.id = student.getId(); 19 | this.firstName = student.getFirstName(); 20 | this.lastName = student.getLastName(); 21 | this.phoneNumber = student.getPhoneNumber(); 22 | this.emailAddress = student.getEmailAddress(); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/model/AuditTrail.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.model; 2 | 3 | import com.fintechlabs.auditlogs.dto.AuditTrailDTO; 4 | import lombok.Data; 5 | import lombok.NoArgsConstructor; 6 | 7 | import javax.persistence.*; 8 | import java.time.LocalDate; 9 | 10 | @Entity 11 | @Data 12 | @NoArgsConstructor 13 | public class AuditTrail { 14 | 15 | @Id 16 | @GeneratedValue(strategy = GenerationType.IDENTITY) 17 | private Long id; 18 | private LocalDate dateCreated; 19 | private LocalDate lastUpdated; 20 | private String className; 21 | private String persistedObjectId; 22 | private String eventName; 23 | private String propertyName; 24 | private String oldValue; 25 | private String newValue; 26 | 27 | @PrePersist 28 | void beforeInsert() { 29 | this.dateCreated = LocalDate.now(); 30 | this.lastUpdated = LocalDate.now(); 31 | } 32 | 33 | @PreUpdate 34 | void beforeUpdate() { 35 | this.lastUpdated = LocalDate.now(); 36 | } 37 | 38 | public AuditTrail(AuditTrailDTO auditTrailDTO) { 39 | this.className = auditTrailDTO.getClassName(); 40 | this.persistedObjectId = auditTrailDTO.getPersistedObjectId(); 41 | this.eventName = auditTrailDTO.getEventName(); 42 | this.propertyName = auditTrailDTO.getPropertyName(); 43 | this.oldValue = auditTrailDTO.getOldValue(); 44 | this.newValue = auditTrailDTO.getNewValue(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/model/Student.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.model; 2 | 3 | import com.fintechlabs.auditlogs.audit.AuditAware; 4 | import com.fintechlabs.auditlogs.audit.AuditLogListener; 5 | import lombok.Data; 6 | import lombok.NoArgsConstructor; 7 | 8 | import javax.persistence.*; 9 | import java.io.Serializable; 10 | 11 | @Entity 12 | @Data 13 | @NoArgsConstructor 14 | @EntityListeners(value = {AuditLogListener.class}) 15 | public class Student implements Serializable, AuditAware { 16 | 17 | @Id 18 | @GeneratedValue(strategy = GenerationType.IDENTITY) 19 | private Long id; 20 | private String firstName; 21 | private String lastName; 22 | private String emailAddress; 23 | private String phoneNumber; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/repository/AuditTrailRepository.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.repository; 2 | 3 | import com.fintechlabs.auditlogs.model.AuditTrail; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | public interface AuditTrailRepository extends CrudRepository { 7 | } 8 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/repository/StudentRepository.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.repository; 2 | 3 | import com.fintechlabs.auditlogs.model.Student; 4 | import org.springframework.data.repository.CrudRepository; 5 | 6 | public interface StudentRepository extends CrudRepository { 7 | 8 | 9 | 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/service/AuditLogService.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.service; 2 | 3 | import com.fintechlabs.auditlogs.dto.AuditTrailDTO; 4 | import com.fintechlabs.auditlogs.model.AuditTrail; 5 | import com.fintechlabs.auditlogs.repository.AuditTrailRepository; 6 | import org.springframework.beans.factory.annotation.Autowired; 7 | import org.springframework.stereotype.Service; 8 | 9 | @Service 10 | public class AuditLogService { 11 | 12 | private final AuditTrailRepository auditTrailRepository; 13 | 14 | public AuditLogService(AuditTrailRepository auditTrailRepository) { 15 | this.auditTrailRepository = auditTrailRepository; 16 | } 17 | 18 | public void save(AuditTrailDTO auditTrailDTO){ 19 | auditTrailRepository.save(new AuditTrail(auditTrailDTO)); 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/util/ApplicationContextProvider.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.util; 2 | 3 | import org.springframework.context.ApplicationContext; 4 | import org.springframework.context.ApplicationContextAware; 5 | import org.springframework.stereotype.Component; 6 | 7 | @Component("applicationContextProvider") 8 | public class ApplicationContextProvider implements ApplicationContextAware { 9 | 10 | private static ApplicationContext context; 11 | 12 | public static ApplicationContext getApplicationContext() { 13 | return context; 14 | } 15 | 16 | @Override 17 | public void setApplicationContext(ApplicationContext ctx) { 18 | context = ctx; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/fintechlabs/auditlogs/util/Enums.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs.util; 2 | 3 | public class Enums { 4 | 5 | public enum AuditEvent { 6 | INSERT, UPDATE, DELETE 7 | } 8 | 9 | } 10 | -------------------------------------------------------------------------------- /src/main/resources/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=Audit Logging 2 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 3 | spring.datasource.username= 4 | spring.datasource.password= 5 | spring.datasource.url=jdbc:mysql://localhost:3306/spring_audit?createDatabaseIfNotExist=true 6 | spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect 7 | spring.jpa.hibernate.ddl-auto=update 8 | #spring.jpa.properties.hibernate.ejb.interceptor=com.fintechlabs.auditlogs.audit.AuditLogInterceptor 9 | -------------------------------------------------------------------------------- /src/main/resources/static/css/sticky-footer-navbar.css: -------------------------------------------------------------------------------- 1 | /* Sticky footer styles 2 | -------------------------------------------------- */ 3 | html { 4 | position: relative; 5 | min-height: 100%; 6 | } 7 | body { 8 | /* Margin bottom by footer height */ 9 | margin-bottom: 60px; 10 | } 11 | .footer { 12 | position: absolute; 13 | bottom: 0; 14 | width: 100%; 15 | /* Set the fixed height of the footer here */ 16 | height: 60px; 17 | line-height: 60px; /* Vertically center the text there */ 18 | background-color: #f5f5f5; 19 | } 20 | 21 | 22 | /* Custom page CSS 23 | -------------------------------------------------- */ 24 | /* Not required for template or sticky footer method. */ 25 | 26 | body > .container { 27 | padding: 60px 15px 0; 28 | } 29 | 30 | .footer > .container { 31 | padding-right: 15px; 32 | padding-left: 15px; 33 | } 34 | 35 | code { 36 | font-size: 80%; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/resources/templates/layout/layout.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Spring Boot Auditing 5 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 17 |
18 |
19 |
20 |
21 |
22 |

Page content goes here

23 |
24 |
25 |
26 |
27 | © FintechLabs Technologies 28 |
29 |
30 | 31 | -------------------------------------------------------------------------------- /src/main/resources/templates/student/create.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Student List 6 | 7 | 8 |
9 |
10 |
11 |
12 |
13 |
Create Student
14 |
15 |
16 | List 17 |
18 |
19 |
20 |
21 | 22 | 24 |
25 |
26 | 27 | 28 |
29 |
30 | 31 | 33 |
34 |
35 | 36 | 38 |
39 | 40 |
41 |
42 |
43 |
44 | 45 | -------------------------------------------------------------------------------- /src/main/resources/templates/student/edit.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Student List 6 | 7 | 8 |
9 |
10 |
11 |
12 |
13 |
Update Student
14 |
15 |
16 | List 17 |
18 |
19 |
20 | 21 |
22 | 23 | 25 |
26 |
27 | 28 | 30 |
31 |
32 | 33 | 35 |
36 |
37 | 38 | 40 |
41 | 42 |
43 |
44 |
45 |
46 | 47 | -------------------------------------------------------------------------------- /src/main/resources/templates/student/list.html: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | Student List 6 | 7 | 8 |
9 |
10 |
11 |
12 |
13 |
Student List
14 |
15 |
16 | Create 17 |
18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 42 | 43 | 44 |
#First NameLast NameEmail AddressPhone Number
Otto@mdo@mdo 38 | Edit |  39 | Delete 41 |
45 |
46 |
47 |
48 | 49 | -------------------------------------------------------------------------------- /src/test/java/com/fintechlabs/auditlogs/AuditLogsApplicationTests.java: -------------------------------------------------------------------------------- 1 | package com.fintechlabs.auditlogs; 2 | 3 | import org.junit.Test; 4 | import org.junit.runner.RunWith; 5 | import org.springframework.boot.test.context.SpringBootTest; 6 | import org.springframework.test.context.junit4.SpringRunner; 7 | 8 | @RunWith(SpringRunner.class) 9 | @SpringBootTest 10 | public class AuditLogsApplicationTests { 11 | 12 | @Test 13 | public void contextLoads() { 14 | } 15 | 16 | } 17 | --------------------------------------------------------------------------------