• 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;
        }
    }


  • 相关阅读:
    【 USACO11JAN】 利润 【洛谷P3009】
    【诗和远方】一个蒟蒻的年初展望
    【眼前的苟且】一个蒟蒻的年终总结
    【NOJ2024】入栈序列和出栈序列
    【洛谷P1632】点的移动
    【洛谷】P1880 石子合并
    【洛谷】【USACO】P1118 数字三角形
    【CodeVS】1083 Cantor表
    【CODEVS】2833 奇怪的梦境
    【洛谷】P1876 开灯
  • 原文地址:https://www.cnblogs.com/person008/p/9494762.html
Copyright © 2020-2023  润新知