记一些实用的工具类的使用

对接口地址、入参、出参、ip、类型进行日志打印的方法(为了查询日志可以看出相应的信息)

import com.alibaba.fastjson.JSONArray;
import com.sz.common.utils.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * web日志
 */
@Slf4j
@Aspect
@Component
public class WebLogAspect {

    /**
     * 以 controller 包下定义的所有请求为切入点
     */
    @Pointcut("execution(public * com.xwdBoy.web.controller..*.*(..))")
    public void webLog() {
    }


    /**
     * 在切点之前织入
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 打印请求相关参数
        log.info(
                "========================================== Start ==========================================");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());

        // 打印请求 contentType
        log.info("contentType    : {}", request.getContentType());

        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", getIpAddr(request));
        // 打印请求入参
        try {
            log.info("Request Args   : {}", JSONArray.toJSONString(joinPoint.getArgs()));
        } catch (Throwable e) {
            log.info("Request Args   : {}", joinPoint.getArgs());
        }

    }

    /**
     * 在切点之后织入
     */
    @After("webLog()")
    public void doAfter() throws Throwable {
        log.info("");
    }

    /**
     * 环绕
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result;
        try {
            result = proceedingJoinPoint.proceed();
            // 打印出参
            if (result instanceof String) {
                if(result.toString().length()<1000) {
                    log.info("Response Args  : {}", result);
                }else {
                    log.info("Response Args  : 返回数据太多不打印");
                }
            } else {
                if(JsonUtils.from(result).asString().length()<1000){
                    log.info("Response Args  : {}", JsonUtils.from(result).asString());
                }else {
                    log.info("Response Args  : jsonUtils返回数据太多不打印");
                }
            }
        } finally {
            // 执行耗时
            log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
            log.info( "=========================================== End ===========================================");
        }
        return result;
    }

    @AfterThrowing(value = "webLog()",
            throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, Exception e) {
        log.info("Response excepiton class  : {}", e.getClass().getName());
        log.info("Response excepiton msg  : {}", e.getMessage());
    }

    public String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}

JsonUtils.java

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.TextNode;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class JsonUtils {
    private static final ObjectMapper jackSonMapper = new ObjectMapper();

    static {
        //FAIL_ON_NULL_FOR_PRIMITIVES: 允许基本类型的值为null。
        jackSonMapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
        //FAIL_ON_NUMBERS_FOR_ENUM:控制枚举值是否被允许序列化/反序列化为数字
        //jackSonMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, false)
        //json 处理
    }

    private JsonNode jsonNode;

    private JsonUtils(JsonNode jsonNode) {
        this.jsonNode = jsonNode;
    }

    public static JsonUtils from(String jsonString) {

        try {
            if (StringUtils.isEmpty(jsonString)) {
                return new JsonUtils(TextNode.valueOf(""));
            }
            return new JsonUtils(jackSonMapper.readTree(jsonString));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static JsonUtils from(byte[] bytes) {
        try {
            return new JsonUtils(jackSonMapper.readTree(bytes));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static JsonArrayPatter fromArrayString(String jsonArrayString) {
        return new JsonArrayPatter(jsonArrayString);
    }


    public static JsonArrayPatter fromArray(List<?> jsonArray) {
        return new JsonArrayPatter(jsonArray);
    }


    public static JsonUtils from(Map<String, Object> jsonMap) {

        try {
            return new JsonUtils(jackSonMapper.valueToTree(jsonMap));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public static JsonUtils from(Object jsonObject) {

        if (jsonObject instanceof JsonUtils) {
            return (JsonUtils) jsonObject;
        }
        if (jsonObject instanceof JsonNode) {
            return new JsonUtils((JsonNode) jsonObject);
        }
        if (jsonObject instanceof String) {
            return from((String) jsonObject);
        }
        try {
            return new JsonUtils(jackSonMapper.valueToTree(jsonObject));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T toSnakeObject(String json, Class<T> clazz) {
        ObjectMapper mapper = new ObjectMapper();
        //mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        T reqJson = null;
        try {
            reqJson = mapper.readValue(json, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reqJson;
    }

    public String asString() {
        try {
            if (jsonNode.isTextual()) {
                return jsonNode.asText();
            }
            return jackSonMapper.writeValueAsString(jsonNode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T asJavaClass(Class<T> clazz) {
        try {
            return jackSonMapper.convertValue(jsonNode, clazz);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public <T> T asType(TypeReference<T> typeReference) {
        try {
            return jackSonMapper.convertValue(jsonNode, typeReference);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public Map asMap() {
        try {
            return jackSonMapper.convertValue(jsonNode, new TypeReference<Map<String, Object>>() {
            });
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public byte[] asBytes() {
        try {
            return jackSonMapper.writeValueAsBytes(jsonNode);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static class JsonArrayPatter {

        private String jsonArray;
        private JsonNode jsonNode;

        public JsonArrayPatter(String jsonArray) {
            this.jsonArray = jsonArray;
        }

        public JsonArrayPatter(List<?> list) {
            this.jsonNode = jackSonMapper.valueToTree(list);
        }

        /**
         * 获取泛型的Collection Type
         *
         * @param collectionClass 泛型的Collection
         * @param elementClasses 元素类
         * @return JavaType Java类型
         */
        public static JavaType getCollectionType(Class<?> collectionClass, Class<?>...
                elementClasses) {
            return jackSonMapper.getTypeFactory().constructParametricType(collectionClass,
                    elementClasses);
        }

        public String asArrayString() {
            try {
                JavaType javaType = jackSonMapper.getTypeFactory().constructParametricType(List
                        .class, Object.class);
                ArrayList<Object> arrayList = jackSonMapper.convertValue(jsonNode, javaType);
                return jackSonMapper.writeValueAsString(arrayList);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        public <T> List<T> asJavaList(Class<T> clazz) {
            try {

                JavaType javaType = getCollectionType(ArrayList.class, clazz);
                return jackSonMapper.readValue(jsonArray, javaType);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Data
    public static class TestBean {

        private Integer id;
    }

    @Data
    public static class TestTypeBean<T> {

        private T t;
        private String name;
    }
}

记List对象映射

        对list对象进行操作

import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Component
public class ListUtils<T> {

    /**
     * List对象映射
     * @param obj 源数据              eg: List<xxxx>
     * @param list2  需要赋值的数据    eg: list<xxxxVo>
     * @param classObj  对象class    eg: xxxxVo.class
     */
    public void copyList(Object obj, List<T> list2, Class<T> classObj) {
        if ((!Objects.isNull(obj)) && (!Objects.isNull(list2))) {
            List list1 = (List) obj;
            list1.forEach(item -> {
                try {
                    T data = classObj.newInstance();
                    BeanUtils.copyProperties(item, data);
                    list2.add(data);
                } catch (InstantiationException e) {
                } catch (IllegalAccessException e) {
                }
            });
        }
    }

    /**
     * List对象映射
     * @param list 源数据    eg: List<xxxx>
     * @param target     eg: xxxxVo.class
     */
    public static <T> List<T> copyList(List<?> list, Class<T> target) {
        if (ObjectUtil.isEmpty(list)) {
            return Collections.emptyList();
        }
        return list.stream().map(s -> copyProperties(s, target)).filter(ObjectUtil::isNotEmpty).collect(Collectors.toList());
    }

    public static <T> T copyProperties(Object source, Class<T> target){
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            log.error("【数据转换出错】", target.getName(), e);
            return null;
        }
    }

    public static List<String> repeatListWayTwo(List<String> list) {
        //初始化HashSet对象,并把list对象元素赋值给HashSet对象
        HashSet set = new HashSet(list);
        return new ArrayList<String>(set);
    }


}

使用方法:

@Service
public class XxxServiceImpl{
    
    @Resource
    private ListUtils listUtils;

    @Override
    public void XxxAdd(List<XxxAddParam> xxxAddParam){
        List<Xxx> xxx = new ArrayList<>();
        //该方法可以对List进行操作
        listUtils.copyList(xxxAddParam,xxx,Xxx.class);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值