首页 > 编程语言 >my.java

my.java

时间:2022-09-24 16:34:23浏览次数:37  
标签:typeDic java String split put new my append

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");
        }
    }
}


标签:typeDic,java,String,split,put,new,my,append
From: https://www.cnblogs.com/LiZiheng/p/16725901.html

相关文章

  • Mysql小版本升级
    MySQL小版本升级操作步骤Bing@DBA于2020-11-2517:35:07发布2493收藏19分类专栏:MySQL版权MySQL专栏收录该内容38篇文章5订阅订阅专栏一、前言业务场景中需要......
  • 二 Java流程控制
    java流程控制Scanner对象实现程序和人的交互,通过Scanner类来获取用户的输入。Scanners=newScanner(System.in);通过Scanner类的next()与nextLine()方法获取输入......
  • 三 Java方法
    Java方法什么是方法Java方法是语句的集合,它们在一起执行一个功能。方法是解决一类问题的步骤的有序组合。方法包含于类或对象中。方法在程序中被创建,在其他地方被引......
  • 【MySQL】MySQL分区表
    本想整理一下MySQL分区表的内容。发现有人已经写了很详细了,这里整理一下链接第36期:MySQL原生水平拆表第37期:适当的使用MySQL原生表分区第38期:MySQL时间类分区具体实......
  • mysql 更换root密码简单操作
    usemysql;--切换数据库--更新密码updateusersetauthentication_string=password('123456')whereuser='root'; --刷新权限等信息flushprivileges; 执行......
  • Java基础 (1)
    IJ的使用快捷键:ctrl+d复制当前行到下一行psvmpublicstaticvoidmain(String[]args){}soutSystem.out.println();Java基础1.注释注释包括单行注释,......
  • mysql数据库漏洞修复方案之数据库版本升级
    Centos7二进制方式安装的mysql5.7.30升级为5.7.38解决CVE-2021-22946漏洞 一、背景由于进行安全扫描,发现mysql存在漏洞,高危漏洞编号为(CVE-2021-22946),此外还有多个中......
  • java static
    1.static关键字的目的:   主要用于内存管理2.static关键字的范围:     1)使用范围:javastatic关键字可以用在变量、方法、代码块和嵌套类伤。   2)作......
  • MySql主从复制
    Mysql主从复制是MySql数据库自带的功能,是多台Mysql数据库(salve,从库)从另一台MySql数据库(master,主库)进行日志复制再解析并应用到自身,最终实现从库的数据和主库的数据保......
  • JavaScript 的闭包(closure)
    以下内容为本人的学习笔记,如需要转载,请声明原文链接微信公众号「englyf」https://www.cnblogs.com/englyf/对于闭包的理解,其实可以归纳为,在创建函数时,同时创建了一个集......