com.caiyunworks.crm.business.aop.AuditAdvice.java Source code

Java tutorial

Introduction

Here is the source code for com.caiyunworks.crm.business.aop.AuditAdvice.java

Source

package com.caiyunworks.crm.business.aop;

import com.caiyunworks.crm.persist.model.GenericModel;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;

/**
 * Copyright (c) 2015, All Right Reserved, http://www.caiyunworks.com/
 * <br/>
 * This source is subject to the CaiYunWorks Software License.
 * Please see the License.txt file for more information.
 * All other rights reserved.
 * <br/>
 * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
 * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
 * PARTICULAR PURPOSE
 * <br/>
 * Created on 9/1/15.
 *
 * @author Tony Wang (ziscloud@gmail.com)
 */
@Aspect
public class AuditAdvice {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Before("@annotation(com.caiyunworks.crm.persist.aop.Auditable)")
    public void audit(JoinPoint joinPoint) {
        if (logger.isInfoEnabled()) {
            logger.info("auditable model is going to be persisted");
        }
        Object[] args = joinPoint.getArgs();
        if (ArrayUtils.isNotEmpty(args)) {
            Object arg = args[0];
            if (null != arg && arg instanceof GenericModel) {
                GenericModel model = (GenericModel) arg;
                LocalDateTime now = LocalDateTime.now();

                model.setCreatedBy(1);
                model.setCreationTime(now);

                model.setLastUpdatedBy(1);
                model.setLastUpdateTime(now);

                Integer versionNumber = model.getVersionNumber();
                if (null == versionNumber) {
                    versionNumber = 1;
                } else {
                    versionNumber += 1;
                }
                model.setVersionNumber(versionNumber);
            }
        }
    }
}