package cn.ac.cti.txfz.common.szs;

import cn.ac.cti.txfz.common.constant.BaseEnum;
import cn.ac.cti.txfz.common.constant.InfoEnum;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;

/**
 * @Author Lambert
 * @Date 2022/9/21 12:31
 */
public class My {

    static List<String> jars;
    // 类型对照字典
    static Map<String, String> typeDic;
    // 公用枚举类
    static Map<String, Class> enumMap;
    static Map<String, Class> allClassMap;

    // 存储jar包maps集合
    static ArrayList<Map> maps = new ArrayList<>();

    public static void mains(String[] args) {
        Class<InfoEnum> cls = InfoEnum.class;
        Field[] fields = cls.getFields();
//        ((DelStateEnum) enumConstants[0]).name()
        System.out.println(cls);
    }

    static void init() {
        maps = new ArrayList<>(10);
        jars = new ArrayList<>(10);
        typeDic = new HashMap<>();
        // 公用枚举类
        enumMap = new HashMap<>();
        allClassMap = new HashMap<>();
        // 创建目录
        File d = new File("./ts/");
        d.mkdirs();
        typeDic.put("short", "number");
        typeDic.put("Integer", "number");
        typeDic.put("Integer;", "number[]");
        typeDic.put("int", "number");
        typeDic.put("float", "number");
        typeDic.put("Float;", "number[]");
        typeDic.put("Float", "number");
        typeDic.put("long", "number");
        typeDic.put("Long", "number");
        typeDic.put("Long;", "number[]");
        typeDic.put("double", "number");
        typeDic.put("double;", "number[]");
        typeDic.put("Double", "number");
        typeDic.put("string", "string");
        typeDic.put("String", "string");
        typeDic.put("String;", "string[]");
        typeDic.put("char", "string");
        typeDic.put("Char;", "string[]");
        typeDic.put("Character", "string");
        typeDic.put("Object;", "object[]");
        typeDic.put("boolean", "boolean");
        typeDic.put("Boolean", "boolean");
        typeDic.put("void", "void");
        typeDic.put("Set", "any");
        typeDic.put("HashMap", "object");
        typeDic.put("Map", "object");
        typeDic.put("Date", "string");
        typeDic.put("Timestamp", "string");
        typeDic.put("List", "object");
        typeDic.put("JsonNode", "object");
    }

    static String findTsType(String type) {
        if (type.endsWith("Enum")) {
            String[] split;
            String typeName = "";
            ArrayList<String> list = new ArrayList<>(enumMap.keySet());
//            String fileName = list.get(1).split("-")[1].split("\\.")[0];
            List<String> collect = list.stream().filter(item -> item.split("\\.")[0].endsWith(type)).collect(Collectors.toList());
            if (collect.size() > 0) {
                split = collect.get(0).split("-");
                typeName = split[0].replace("Txfz", "") + "." + split[1].split("\\.")[0];
            }
            return typeName;
        }
        String s = typeDic.get(type);
        if (s == null) {
            Object o1 = new ArrayList<>(maps.get(0).keySet()).get(0);
            o1 = ((String) o1).split("-")[0].replaceAll("TxfzBean", "");
            s = o1 + "." + type;
        }
        return s;
    }

    static void findJar(String path) {
        File file = new File(path);
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                if (file.getName().endsWith(".jar")) {
                    jars.add(files[i].getAbsolutePath());
                }
                findJar(files[i].getAbsolutePath());
            }
        } else if (file.getName().endsWith(".jar")) {
            jars.add(file.getAbsolutePath());
        }
    }

    public static String upWord(String str, String mySplit) {
        str = str.replaceAll("\\d", "");
        StringBuilder str1 = new StringBuilder();
        String[] split = new String[0];
        if (mySplit.equals(".")) {
            split = str.split("\\.");
        } else if (mySplit.equals("-")) {
            split = str.split("-");
        } else {
            return str.substring(0, 1).toUpperCase() + str.substring(1);
        }
        for (String item : split) {
            str1.append(item.substring(0, 1).toUpperCase()).append(item.substring(1));
        }
        return str1.toString();
    }

    public static void main(String[] args) throws Exception {
        init();
        findJar("D:\\lambert\\txfz\\txfz-bean\\");
        // 遍历每个jar的class,并存进map
        jars.forEach(path -> {
            // todo 将所有的文件存入maps作为预加载资源,遇到枚举(a|b|c|d),继承将父类的上级展示出来,接口的话不用管
            try {
                String fileName = upWord(path.substring(path.indexOf("target\\") + 7).split("\\.")[0], "-");
//                jarsName.add(fileName);
                // 这个数组是所有的类map集合
                Map<String, Class> handlerMap = new HashMap<>();
                JarFile jar = new JarFile(new File(path));
                ClassLoader loader = new URLClassLoader(new URL[]{new URL("file:" + path)});
                Enumeration<JarEntry> es = jar.entries();
//                if (path.endsWith("txfz-common-1.0.jar"))
                while (es.hasMoreElements()) {
                    JarEntry entry = es.nextElement();
                    String name = entry.getName();
                    if (name != null && name.endsWith(".class")) {
                        Class<?> clz = loader.loadClass(name.replace("/", ".").substring(0, name.length() - 6));
                        String clzPath = clz.getName();
                        String names = fileName + "-" + clzPath.substring(clzPath.lastIndexOf(".") + 1, clzPath.length()) + ".class";
                        //判断是否有指定注解
                        ApiModel annotation = clz.getAnnotation(ApiModel.class);
                        Annotation[] annotations = clz.getAnnotations();
                        allClassMap.put(names, clz);
                        if (annotation != null || clz.isEnum() && clz.getEnumConstants()[0] instanceof BaseEnum) {
                            //将注解中的类型值作为key,对应的类作为 value
                            handlerMap.put(names, clz);
                            if (clz.isEnum()) {
                                enumMap.put(names, clz);
                            }
                        }
                    }
                }
                maps.add(handlerMap);
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        });
        // 对同意jar包的文件,生成d.ts文件
//        for (Map map : maps) {
        for (int k = 0; k < maps.size(); k++) {
            Map map = maps.get(k);
            if (map.size() == 0) continue;
            // 类集合
            ArrayList collectKey = new ArrayList<>(map.keySet());
            ArrayList collectValue = new ArrayList<>(map.values());
            String fileName = ((String) collectKey.get(0)).split("-")[0].substring(((String) collectKey.get(0)).split("-")[0].indexOf("TxfzBean") + 8);
            StringBuilder data = new StringBuilder();
            if (((String) collectKey.get(0)).indexOf("Common") > 0)
                fileName = upWord(((String) collectKey.get(0)).split("-")[0].replace("Txfz", ""), "");
            data.append("declare namespace ").append(fileName).append(" {\n");
            collectValue.forEach(item -> {
                Class itemClass = (Class) item;
                String className = itemClass.getName();
                String annotation = "";
                try {
                    annotation = "  /**\n    * " + ((ApiModel) itemClass.getAnnotation(ApiModel.class)).value() + "\n    **/\n";
                } catch (Exception e) {
                    System.out.println(className);
                    String name1 = ((Class) item).getName();
                    String path = "D:\\lambert\\txfz\\txfz-common\\src\\main\\java\\".replaceAll("\\\\", "/");
                    name1 = path + name1.replaceAll("\\.", "/") + ".java";
                    String string = null;
                    try {
                        string = FileUtils.readFileToString(new File(name1), "utf-8");
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    assert string != null;
                    int i = string.indexOf("/**");
                    int i1 = string.lastIndexOf("*/");
                    if (i >= 0 && i1 >= 0)
                        annotation = "  " + string.substring(i, i1 + 3).replaceAll("\n", "\n  ");
                }
                String tsClassName = className.substring(className.lastIndexOf(".") + 1);
                // 处理枚举类型,获取value值
                if (itemClass.isEnum()) {
                    data.append(annotation).append("  enum ").append(tsClassName).append("{\n");
                    String property = "";
                    Object name = "";
                    Object value = null;
                    Object[] enumConstants = itemClass.getEnumConstants();
                    for (Object enumConstant : enumConstants) {
                        try {
                            name = ((BaseEnum<Object>) (enumConstant)).getName();
                            value = ((BaseEnum<Object>) (enumConstant)).getValue() instanceof String ? "\"" + ((BaseEnum<Object>) (enumConstant)).getValue() + "\"" : ((BaseEnum<Object>) (enumConstant)).getValue();
                        } catch (Exception e) {
//                            e.printStackTrace();
                        }
                        String type = enumConstant.toString();
                        property = "    /** " + name + " **/\n";
                        data.append(property).append("    ").append(type).append("= ").append(value).append(",\n");
                    }
                } else {
                    data.append(annotation).append("  interface ").append(tsClassName).append("{\n");
                    List<Field> collect = Arrays.stream(itemClass.getDeclaredFields()).collect(Collectors.toList());
                    if (collect.size() > 0) { // 遍历所有属性
                        for (Field o : collect) {
                            String name = o.getName();
                            String fullType = o.getType().getName();
                            String[] split = fullType.split("\\.");
                            int length = split.length;
                            String type = split[length - 1];
                            String property;
                            try {
                                property = "    /** " + o.getAnnotation(ApiModelProperty.class).value() + " **/\n";
                            } catch (Exception e) {
                                property = "";
                            }
                            data.append(property).append("    ").append(name).append(": ").append(findTsType(type)).append(";\n");
                        }
                    }
                }
                data.append("  }\n\n");
            });
            data.append("}");
            FileUtils.writeStringToFile(new File("./ts/" + fileName + ".d.ts"), String.valueOf(data), "utf-8");
        }
    }
}


版权声明:本文为LiZiheng原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/LiZiheng/p/16725901.html