Aspect

package com.thinkgem.jeesite.modules.sys.aop;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.thinkgem.jeesite.common.persistence.BaseEntity;
import com.thinkgem.jeesite.common.service.CrudService;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.entity.Log;
import com.thinkgem.jeesite.modules.sys.utils.DictUtils;
import com.thinkgem.jeesite.modules.sys.utils.LogUtils;

/**
 * 日志处理
 * @author yanrui
 *
 */
@Aspect
public class LogAspect {
    /**
     * 日志对象
     */
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Log log = new Log();
    private String operateType = ""; // 操作类型(1:插入;2:修改;3:删除;4:审批;5:查看;)
    private String content = ""; // 日志内容
    private String moduleName = "";
    private Object oldObj = null;
    private static Map<String, Object> beforeResult = new HashMap<String, Object>();

    @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional) && execution(*(!com.rongda.huizhi.chat..*).*(..))")
    public void serviceAfterLog() {
    }

    @Pointcut("@annotation(org.springframework.transaction.annotation.Transactional) && execution(*(!com.rongda.huizhi.chat..*).*(..))")
    public void serviceAroundLog() {
    }

    @After(value = "serviceAfterLog()")
    public void doAfter(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        String id = request.getParameter("id");
        Object objEntity = getArgsEntity(joinPoint);
        Field fields[] = null;
        if (objEntity != null) {
            fields = objEntity.getClass().getDeclaredFields();
        }
        if (methodName.toLowerCase().contains("save")) {
            operateType = "insert";
            if (fields.length > 0) {
                if (StringUtils.isBlank(id)) {
                    content = DictUtils.getDictLabel("insert", "log_operate_type", "") + moduleName + ":{";
                    getContent(fields, objEntity);
                } else {
                    if (methodName.equals("saveAudit")) {
                        operateType = "audit";
                        content = DictUtils.getDictLabel("audit", "log_operate_type", "") + ":{";
                        getContent(fields, objEntity);
                        
                    } else {
                        operateType = "update";
                        content = DictUtils.getDictLabel("update", "log_operate_type", "") + moduleName + ":{id:" + id + ";";
                        Map<String, Object> maps = compare(oldObj, objEntity);
                        for (Field field : fields) {
                            FieldRemark fieldRemark = field.getAnnotation(FieldRemark.class);
                            for (Map.Entry<String, Object> map : maps.entrySet()) {
                                if (fieldRemark != null) {
                                    if (map.getKey() != null && map.getKey().equals(field.getName())) {
                                        content += fieldRemark.value() + ":[" + beforeResult.get(map.getKey()) + "]→["
                                                + map.getValue() + "]; ";
                                    }
                                }
                            }
                        }
                        content += "}";
                    }
                }
            }
        } else if (methodName.contains("delete")) {
            operateType = "delete";
            if(com.thinkgem.jeesite.common.utils.StringUtils.isNotBlank(id)){
                content = DictUtils.getDictLabel("delete", "log_operate_type", "") + moduleName + ":{id:" + id + ";";
            }else{
                content = DictUtils.getDictLabel("delete", "log_operate_type", "") + moduleName+":{";
            }
            getContent(fields, oldObj);
        }
        
        if(StringUtils.isNotBlank(content)){
            logger.info(content);
            log.setTitle(moduleName + "模块");
            log.setContent(content);
            log.setOperateType(operateType);
            String uri = request.getRequestURI();
            if (StringUtils.contains(uri, "/sys/") &&  uri.indexOf("/role/") == -1 && uri.indexOf("/menu/") == -1) {
                log.setLogType("sys");//系统管理
            } else if (StringUtils.contains(uri, "/sys/role/") || StringUtils.contains(uri, "/sys/menu/")) {
                log.setLogType("safe");//安全管理
            } else {
                log.setLogType("business");//业务管理
            }
            LogUtils.saveLog(request, log);
            content = "";
            
        }
    }

    public Object getArgsEntity(JoinPoint joinPoint) {
        Object[] arguments = joinPoint.getArgs();
        Object objEntity = null;
        if (arguments.length > 0) {
            for (Object arg : arguments) {
                if (arg instanceof BaseEntity) {
                    PojoRemark annotation = arg.getClass().getAnnotation(PojoRemark.class);
                    if (annotation != null) {
                        moduleName = annotation.value();
                    }
                    objEntity = arg;
                }
            }
        }
        return objEntity;
    }

    public void getContent(Field[] fields, Object obj) {
        if(fields!=null){
            try {
                for (Field field : fields) {
                    field.setAccessible(true);
                    FieldRemark fieldRemark = field.getAnnotation(FieldRemark.class);
                    if (fieldRemark != null && field.get(obj) != null) {
                        content += fieldRemark.value() + ":" + field.get(obj) + "; ";
                    }
                }
                content += "};";
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressWarnings("rawtypes")
    @Around(value = "serviceAroundLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        Object result = null;
        String id = request.getParameter("id");
        Class<? extends Object> oclass = joinPoint.getTarget().getClass();
        String className = oclass.getSimpleName();
        className = className.replaceFirst(String.valueOf(className.charAt(0)),
                String.valueOf(className.charAt(0)).toLowerCase());
        if(StringUtils.isBlank(id)){
            Object argsEntity = getArgsEntity(joinPoint);
            if(argsEntity!=null){
                BaseEntity baseObj = (BaseEntity) argsEntity;
                id = baseObj.getId();
            }    
        }
        if(CrudService.class.isAssignableFrom(oclass)){
            if (methodName.toLowerCase().contains("save") || methodName.equals("delete")) {
                    CrudService<?, ?> oService = (CrudService<?, ?>) ContextLoader.getCurrentWebApplicationContext()
                            .getBean(className);
                    if (StringUtils.isNotBlank(id)) {
                        oldObj = oService.get(id);
                    }
            }
        }
        try {
            result = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 比较对象值,取出不相同对象
     * 
     * @param obj1
     * @param Obj2
     * @return
     */
    public static <T> Map<String, Object> compare(T obj1, T Obj2) {
        Map<String, Object> result = new HashMap<String, Object>();
        Field[] fs = obj1.getClass().getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            Object v1 = null;
            try {
                v1 = f.get(obj1);
                Object v2 = f.get(Obj2);
                if (!equals(v1, v2)) {
                    result.put(f.getName(), v2);
                    beforeResult.put(f.getName(), v1);
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static boolean equals(Object obj1, Object obj2) {

        if (obj1 == obj2) {
            return true;
        }

        if (obj1 == null || obj1 == "") {
            obj1 = "";
        }

        if (obj2 == null || obj2 == "") {
            obj2 = "";
        }
        
        if (obj1 != null && obj2 != null) {
            return obj1.equals(obj2);
        }
        return false;
    }
}


猜你喜欢

转载自www.cnblogs.com/person008/p/9494762.html