后端通信Vo工具


import com.alibaba.fastjson.JSONObject;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * BeanMap 封装前后端通信的返回结果
 * interface Render 用来对值进行转换 如 传入ID 转为ID对应记录的name
 * interface Format 用来对值进行自定义格式化 可以通过 addFormat() 方法添加自定义格式转换
 * class Cover 用来对key进行转换
 * @Author 张闫
 */
@Slf4j
public class BeanMap extends HashMap<String,Object> {

    private static final int SUCCESS = 1;
    private static final int FAILED = 0;
    private static final String SUCCESS_STR = "success";
    private static final String MESSAGE = "message";
    private static final String DATA = "data";
    private static final String EMPTY = "";
    private List<Format> formats;
    private List<Render> renders;
    private boolean allin;

    public BeanMap(){}

    public BeanMap(int size){
        super(size);
    }

    /**
     * 创建对象 并传初始 key value
     * @param key
     * @param value
     */
    public BeanMap(String key,Object value){
        if(Objects.isNull(key) || key.isEmpty() || Objects.isNull(value)){
            return;
        }
        put(key,value);
    }

    public BeanMap(Map<String, Object> map){
        if(Objects.isNull(map) || map.isEmpty()){
            return;
        }
        super.putAll(map);
    }

    public BeanMap data(Object data){
        if(Objects.nonNull(data)){
            put(DATA,data);
        }
        return this;
    }

    public BeanMap success(String msg){
        put(SUCCESS_STR,SUCCESS);
        put(MESSAGE,msg);
        printData();
        return this;
    }

    public BeanMap failed(String msg){
        put(SUCCESS_STR,FAILED);
        put(MESSAGE,msg);
        printData();
        return this;
    }

    public BeanMap success(){
        put(SUCCESS_STR,SUCCESS);
        put(MESSAGE,"操作成功!");
        printData();
        return this;
    }

    public BeanMap failed(){
        put(SUCCESS_STR,FAILED);
        put(MESSAGE,"操作失败!");
        printData();
        return this;
    }

    public BeanMap allin(){
        this.allin = true;
        return this;
    }

    /**
     * 将 对象中 指定的属性 添加到 BeanMap 中
     * @param obj 对象
     * @param ins 指定要添加的属性(可使用 | 来进行属性名Cover) 若不传 则将所有属性添加进来 若传了还想将所有字段传进来 则先调用 allin()
     * @return
     */
    public BeanMap assign(Object obj,String ...ins){
        if(Objects.isNull(obj)){
            throw new NullPointerException();
        }
        Cover[] insCovers = Cover.toCoverArray(ins);
        Class clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        if(insCovers == null || insCovers.length <= 0){
            for(Field field:fields){
                try{
                    field.setAccessible(true);
                    putValue(field.getName(),field.get(obj));
                }catch (Exception e){
                    log.error("assignInCover",e);
                }
            }
        }else{
            for(Field field:fields){
                try{
                    String key = field.getName();
                    boolean insert = true;
                    for(Cover c:insCovers){
                        if(key.equals(c.getOld())){
                            insert = false;
                            field.setAccessible(true);
                            putValue(c.getKey(),field.get(obj));
                        }
                    }
                    if(this.allin && insert){
                        field.setAccessible(true);
                        putValue(key,field.get(obj));
                    }
                }catch (Exception e){
                    log.error("assignInCover",e);
                }
            }
        }
        return this;
    }

    public BeanMap assigns(String name,Object obj,String ...ins){
        if(name == null || name.isEmpty()){
            throw new NullPointerException();
        }
        put(name,newInstance().assign(obj,ins));
        return this;
    }

    /**
     * 将 List 添加
     * @param name
     * @param objs
     * @param ins
     * @return
     */
    public BeanMap assignList(String name,List<? extends Object> objs,String ...ins){
        if(name == null || name.isEmpty()){
            throw new NullPointerException();
        }
        if(Objects.isNull(objs) || objs.isEmpty()){
            put(name,new ArrayList<>());
            return this;
        }
        List<BeanMap> list = new ArrayList<>(objs.size());
        objs.forEach(v -> list.add(newInstance().assign(v,ins)));
        put(name,list);
        return this;
    }

    @Override
    public BeanMap put(String key,Object value){
        super.put(key,value);
        return this;
    }

    public BeanMap putMap(Map<String, Object> map){
        if(Objects.isNull(map) || map.isEmpty()){
            return this;
        }
        super.putAll(map);
        return this;
    }

    /**
     * 添加自定义的格式化
     * @param fv
     * @return
     */
    public BeanMap addFormat(Format fv){
        if(Objects.nonNull(fv)){
            if(Objects.isNull(formats)){
                formats = new ArrayList<>();
            }
            formats.add(fv);
        }
        return this;
    }

    private BeanMap addFormat(List<Format> fvs){
        if(Objects.nonNull(fvs)){
            if(Objects.isNull(formats)){
                formats = new ArrayList<>();
            }
            this.formats.addAll(fvs);
        }
        return this;
    }

    public BeanMap format(){
        formats = new ArrayList<>();
        formats.add((v) -> {
            if(v instanceof Date) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                return sdf.format(v);
            }
            return null;
        });
        return this;
    }

    public BeanMap addRender(Render render){
        if(Objects.isNull(render)){
            throw new NullPointerException();
        }
        if(Objects.isNull(renders)){
            renders = new ArrayList<>();
        }
        renders.add(render);
        return this;
    }

    private BeanMap addRender(List<Render> rs){
        if(Objects.nonNull(rs)){
            if(Objects.isNull(renders)){
                renders = new ArrayList<>();
            }
            this.renders.addAll(rs);
        }
        return this;
    }
    
    public BeanMap newInstance(){
        return new BeanMap().addFormat(this.formats).addRender(this.renders);
    }

    public BeanMap putValue(String key,Object obj){
        if(Objects.isNull(obj)){
            return put(key,EMPTY);
        }
        // 若有render 先进行render 不进行format 若需要format 则需要另外在render中实现
        if(Objects.nonNull(this.renders) && !this.renders.isEmpty()){
            for(Render r:renders){
                BeanMap result = r.render(key,obj);
                if(Objects.nonNull(result)){
                    return putMap(result);
                }
            }
        }
        // 对传入对象进行格式化
        if(Objects.nonNull(this.formats) && !this.formats.isEmpty()){
            for(Format fv:formats){
                String result = fv.format(obj);
                if(Objects.nonNull(result)){
                    return put(key,result);
                }
            }
        }
        return put(key,obj);
    }

    /* *
     * 传入Json字符串 返回BeanMap
     * @param jsonStr
     * @return
     */
    public BeanMap parseJson(String jsonStr){
        JSONObject json = JSONObject.parseObject(jsonStr);
        return this.putMap(json.getInnerMap());
    }

    public String toJson(){
        return JSONObject.toJSONString(this);
    }

    /**
     * 根据路径获取值 目前仅支持 xxx.xxx  不支持数组形式 xxx[0].xxx
     * @param path
     * @return
     */
    public Object getByPath(String path){
        if(!path.contains(".")){
            return get(path);
        }
        String[] paths = path.split("\\.");
        Object result = this;
        for(String p:paths){
            result = getByPath(p,result);
            if(result == null){
                return null;
            }
        }
        return result;
    }

    private Object getByPath(String path,Object obj){
        if(obj == null || path==null || path.trim().isEmpty()){
            return null;
        }
        if(obj instanceof Map){
            Map temp = (Map)obj;
            return temp.get(path);
        }
        try {
            Field field = obj.getClass().getField(path);
            return field.get(obj);
        } catch (Exception e) {}
        return null;
    }

    private void printData(){
        log.info("response data: {}", JSONObject.toJSONString(this));
    }

    public interface Format{
        /**
         * 对 object 进行格式化 若object 类型不符 则应返回null
         * @param t
         * @return
         */
        String format(Object t);
    }

    /**
     * 用来解决 值id问题 如 传入学生id 返回学生信息
     */
    public interface Render{
        /**
         * 若key不符合 则返回null 会将返回的BeanMap中的k,v添加到自己里面
         * @param key
         * @param value
         * @return
         */
        BeanMap render(String key,Object value);
    }

    @Getter
    @Setter
    public static class Cover{
        /**
         * 新的key
         */
        private String key;
        /**
         * 原本目标中的key
         */
        private String old;
        public Cover(String key){
            if(key.contains("|")){
                String[] str = key.split("\\|");
                this.key = str[0];
                this.old = str[1];
                return;
            }
            this.key = key;
            this.old = key;
        }
        public Cover(String key,String old){
            this.key = key;
            this.old = old;
        }
        public static Cover[] toCoverArray(String[] keys){
            if(Objects.isNull(keys) || keys.length == 0){
                return new Cover[0];
            }
            Cover[] arr = new Cover[keys.length];
            for(int i=0;i<keys.length;i++){
                arr[i] = new Cover(keys[i]);
            }
            return arr;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值