首页 > 其他分享 >根据Servie接口 生成 Controller 代码-因业务需要简单应付勿喷

根据Servie接口 生成 Controller 代码-因业务需要简单应付勿喷

时间:2023-06-01 19:06:14浏览次数:38  
标签:String Servie 接口 Controller tempString import null new append


根据Servie接口 生成 Controller 代码-因业务需要简单应付勿喷_后端

附上垃圾代码(勿喷,只不过为了应付工作需求 ,百十来个service 都要创建对应的 controller的需求,复制实在吃不消,说明一下 就是简单的字符串替换操作)


ApplicationController


import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ApplicationController {

    /**
     * 根据 Service接口 生成 Controller 文件
     */
    public static void main(String[] args) throws IOException {
        String[] suffixPaths = {
                "gray",
                "group",
                "home"
        };
        for (String suffixPath : suffixPaths) {
            run(suffixPath);
        }
        System.out.println("操作成功");
    }

    private static void run(String suffixPath) {
        // 读取目录 接口文件所在目录
        String readPath = "D:\\Projects\\ideaProjects\\联想车辆\\aoac_dev\\aoac\\thinkiot-mno\\thinkiot-sdk\\src\\main\\java\\com\\lenovo\\thinkiot\\interfaces\\" +
                suffixPath;
        // controller生成文件当值目录
        String writePath = "D:\\Projects\\ideaProjects\\createTest\\src\\main\\resources\\controller\\" + suffixPath + "\\";
        // controller类的包名
        String packageName = "package com.lenovo.thinkiot.controller";

        List<File> fileList = new ArrayList<>();

        createFile(writePath);
        getFile(readPath, fileList);

        for (File file : fileList) {
            String fileName = file.getName();
            String oldClassName = file.getName().substring(0, file.getName().lastIndexOf("."));
            String oldcontent = readFileByLines(file.getPath());

            System.out.print("文件名:" + fileName);
            // System.out.println("类名:" + oldClassName);
            // System.out.println("内容:\n" + oldcontent);

            try {
                StringBuffer newContent = new StringBuffer();
                String[] split = file.getPath().split("\\\\");
                String pack = split[split.length - 2];
                String newPackage = packageName + "." + pack + ";";
                String newClassName = oldClassName.replace("Service", "Controller");

                // 读取内容
                BufferedReader reader = new BufferedReader(new FileReader(file));
                String tempString = null;
                int line = 0;
                while ((tempString = reader.readLine()) != null) {
                    line++;
                    if (line == 1) {
                        // 修改包
                        newContent.append(newPackage + "\n\n");
                        newContent.append("import org.springframework.stereotype.Controller;\n");
                        newContent.append("import org.springframework.beans.factory.annotation.Autowired;\n");
                        newContent.append("import org.springframework.web.bind.annotation.PostMapping;\n");
                        newContent.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
                        newContent.append("import org.springframework.web.bind.annotation.RequestBody;\n");
                        newContent.append("import org.springframework.web.bind.annotation.RequestParam;\n");

                        String[] params = file.getPath().split("\\\\");
                        StringBuffer attrs = new StringBuffer("import ");
                        for (int i = 0; i < params.length; i++) {
                            String param = params[i].trim();
                            if (param.equals("com")) {
                                for (int j = i; j < params.length; j++) {
                                    if (params[j].contains(".")) {
                                        params[j] = params[j].substring(0, params[j].indexOf("."));
                                    }
                                    attrs.append(params[j]);

                                    if (j != params.length - 1) {
                                        attrs.append(".");
                                    } else {
                                        attrs.append(";\n");
                                    }
                                }
                                break;
                            }
                        }
                        newContent.append(attrs);
                        continue;
                    }

                    if (tempString.contains("/**")) {
                        String temp = tempString;
                        while (!temp.contains("*/")) {
                            newContent.append(temp + "\n");
                            temp = reader.readLine();
                        }
                        newContent.append(temp + "\n");
                        continue;
                    }

                    if (tempString.contains("public interface ")) {
                        // 添加新的 import包 和 @controller
                        String prefix = "@Controller\n" +
                                "@RequestMapping(\"/" + toLowerCaseFirstOne(newClassName.replace("Controller", "")) + "\")\n";
                        tempString = prefix + tempString;
                        // 修改接口为类
                        tempString = tempString.replace("interface", "class");
                        // 设置类名称
                        tempString = tempString.replace(oldClassName, newClassName);

                        // 设置 @Autowired
                        tempString = tempString + "\n\n\t@Autowired\n";
                        tempString = tempString + "\tprivate " + oldClassName + " " + toLowerCaseFirstOne(oldClassName) + ";\n";
                        newContent.append(tempString + "\n");
                        continue;
                    }
                    if (tempString.trim().length() > 2 && tempString.trim().startsWith("//")) {
                        continue;
                    }
                    if (tempString.trim().length() > 1 && tempString.trim().endsWith(",")) {
                        String twoLineCon = null;
                        do {
                            twoLineCon = reader.readLine();
                            tempString = tempString + twoLineCon.trim();
                        } while (!twoLineCon.contains(";"));
                    }

                    if (tempString.contains(";") && !tempString.contains("import ") && !tempString.contains("* ")) {
                        // 设置方法内容(代码块)
                        boolean idVoid = tempString.contains("void ");

                        tempString = "\tpublic " + tempString.trim();
                        tempString = tempString.substring(0, tempString.indexOf(";"));

                        int i1 = tempString.indexOf(")");
                        int i2 = tempString.indexOf("(");
                        if (i1 - i2 > 1) {
                            // 设置方法形参
                            String funAttr = "";
                            String funAttrStr = tempString.substring(tempString.indexOf("(") + 1, tempString.indexOf(")"));
                            String[] split1 = funAttrStr.split(",");
                            int i = 0;
                            for (String str : split1) {
                                if (checkType(str)) {
                                    // 复炸对象
                                    funAttr = funAttr + "@RequestBody " + str;
                                } else {
                                    funAttr = funAttr + "@RequestParam " + str;
                                }
                                if (i != split1.length - 1) {
                                    funAttr = funAttr + ", ";
                                }
                                i++;
                            }
                            tempString = tempString.replace(funAttrStr, funAttr);
                        }

                        tempString = tempString + " {\n";

                        // 获取方法名称
                        String fun = null;
                        int endIndex = tempString.indexOf("(");
                        String substring = null;
                        try {
                            substring = tempString.substring(0, endIndex);
                        } catch (Exception e) {
                            throw new IOException("错误文件:" + file.getPath() + "  错误内容:" + tempString);
                        }
                        char[] chars = substring.toCharArray();
                        for (int i = chars.length - 1; i >= 0; i--) {
                            if (Character.toString(chars[i]).equals(" ")) {
                                fun = substring.substring(i + 1, endIndex);
                                break;
                            }
                        }
                        String con = "\t\t" + (!idVoid ? "return " : "") + (toLowerCaseFirstOne(oldClassName)).trim() + "." + fun.trim();
                        String tmp = tempString.substring(endIndex + 1, (tempString.indexOf(")")));
                        String[] params = tmp.split(",");

                        StringBuffer attrs = new StringBuffer();
                        for (int i = 0; i < params.length; i++) {
                            String param = params[i].trim();
                            param = param.replace("@RequestParam", "");
                            param = param.replace("@RequestBody", "");
                            param = param.trim();
                            int num = param.indexOf(" ");
                            if (num == -1) {
                                continue;
                            }
                            param = param.substring(num);
                            param = param.substring(param.indexOf(" "));
                            params[i] = param;
                            attrs.append(param.trim());
                            if (i != params.length - 1) {
                                attrs.append(", ");
                            }
                        }

                        tmp = con + "(" + attrs.toString().trim() + ");\n";
                        tempString = tempString + tmp;

                        String postRequest = "\t@PostMapping(\"/" + toLowerCaseFirstOne(fun.trim()) + "\")\n";
                        tempString = postRequest + tempString;
                        newContent.append(tempString + "\t}\n");
                        continue;
                    }

                    newContent.append(tempString + "\n");
                }
                reader.close();

                // 写入
                FileExport.creatTxtFile(writePath, newClassName + ".java");
                FileExport.writeTxtFile(newContent.toString());
            } catch (IOException e) {
                System.out.println(" - 失败");
                e.printStackTrace();
            }
            System.out.println(" - 成功");
        }

    }

    private static void createFile(String writePath) {
        File file = new File(writePath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdir();
        }
    }

    private static boolean checkType(String str) {
        String[] types = {"Integer",
                "Double",
                "Float",
                "Long",
                "Short",
                "Byte",
                "Boolean",
                "Character",
                "String",
                "Date",
                "int", "double", "long", "short", "byte", "boolean", "char", "float"};
        List<String> list = Arrays.asList(types);
        boolean contains = !list.contains(str.trim().split(" ")[0]);
        return contains;
    }

    // 给定目录的绝对路径,获取该目录下的所有文件(子目录的文件也可递归得到)
    public static void getFile(String path, List<File> fileList) {
        // File对象 可以是文件或者目录
        File file = new File(path);
        File[] array = file.listFiles();

        for (int i = 0; i < array.length; i++) {
            if (array[i].isFile()) {
                fileList.add(array[i]);
            } else if (array[i].isDirectory()) {
                getFile(array[i].getPath(), fileList);
            }
        }
    }


    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     */
    public static String readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer con = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                // 显示行号
                // System.out.println("line " + line + ": " + tempString);
                con.append(tempString);
                con.append("\n");
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return con.toString();
    }

    //首字母转小写
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    //首字母转大写
    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

}


FileExport 文件操作


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class FileExport {

    private static String filenameTemp;

    public static void main(String[] args) {
//        FileExport.creatTxtFile("你好");
//        FileExport.writeTxtFile("你好");
    }


    /**
     * 创建文件
     *
     * @throws IOException
     */
    public static boolean creatTxtFile(String path, String name) throws IOException {
        boolean flag = false;
        filenameTemp = path + name;
        File filename = new File(filenameTemp);
        if (!filename.exists()) {
            filename.createNewFile();
            flag = true;
        }
        return flag;
    }

    /**
     * 写文件
     *
     * @param newStr
     *            新内容
     * @throws IOException
     */
    public static boolean writeTxtFile(String newStr) throws IOException {
        // 先读取原有文件内容,然后进行写入操作
        boolean flag = false;
        String filein = newStr + "\r\n";
        String temp = "";

        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;

        FileOutputStream fos = null;
        PrintWriter pw = null;
        try {
            // 文件路径
            File file = new File(filenameTemp);
            // 将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();

            // 保存该文件原有的内容
            for (int j = 1; (temp = br.readLine()) != null; j++) {
                buf = buf.append(temp);
                // System.getProperty("line.separator")
                // 行与行之间的分隔符 相当于“\n”
                buf = buf.append(System.getProperty("line.separator"));
            }
            buf.append(filein);

            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buf.toString().toCharArray());
            pw.flush();
            flag = true;
        } catch (IOException e1) {
            // TODO 自动生成 catch 块
            throw e1;
        } finally {
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return flag;
    }

}

 

标签:String,Servie,接口,Controller,tempString,import,null,new,append
From: https://blog.51cto.com/u_14671216/6397678

相关文章

  • API接口调用的优势以及获取方式
     API接口调用的优势:简化了系统集成:API接口提供了一种方便、快捷的方式,允许不同的系统之间进行通信和集成,降低了系统集成的难度和复杂度。提供了标准化的接口:API接口通常采用标准化的协议和数据格式,方便不同系统之间进行交换和共享信息。提高了数据安全性:API接口可以......
  • 获得淘宝天猫搜索词推荐商品全网搜索接口演示示例(支持高并发)
    ​ 淘宝天猫是中国最大的电商平台之一,淘宝天猫通过不同的形式来满足用户的需求,为商家提供多样化的销售渠道,持续扩大服务范围和用户基础。我们如果需要获得搜索词推荐商品,又因为受其他的种种限制无法达到这一目的,那我们完全可以通过代码的形式使用该接口对接实现;【接口使用教程......
  • Wi-Fi 6E路由器LAN接口浪涌静电保护,如何选用ESD静电防护二极管?
    如今,Wi-Fi技术可谓无处不在,Wi-Fi协议也在不断地发展和更新,最新一代的Wi-Fi6E是Wi-Fi6的增强版本,其中字母E代表Extended。除了Wi-Fi6原先支持的2.4GHz及5GHz的频段外,Wi-Fi6E新增了6GHz的频段,拥有更高的并发、更低的时延和更大的带宽。Wi-Fi的核心是路由器,为此随着Wi-Fi版本的更......
  • Swagger-接口分组篇
    分组需求开发中使用Swagger进行Api接口测试时常常会遇到以下情况:1.Controller中的Action、Model、DTO过多导致单页面加载时页面响应速度太慢 2.接口太多,如果用一个页面展示查找某个接口会很麻烦。虽然可以采用搜索方式解决此问题,但不推荐。分组功能实现1.新建目录ApiGroup,并......
  • 有赞 调用 api 接口(有赞开放平台)
    ps:先注册有赞账号有赞https://www.youzan.com/有赞开放平台http://open.youzan.com/有赞开发者后台http://open.youzan.com/developer/app/index接入说明:http://open.youzan.com/docAPI文档:http://open.youzan.com/api***********************************************......
  • 对接第三方接口教程(发送Http请求及返回参数处理)
    1.首先Http工具类建议使用 packagecn.hutool.http;//这个包下面的HttpUtil.post(StringurlString,Stringbody)这个方法会省去很多事情,不用去设置header的一些基本东西,get就不说了,get也能用post请求,把参数拼url后边就行了2.要看第三方接口的鉴权是如何做的,如果是t......
  • BMCOIN: 清单和工艺路线接口
      导入BOM出错。运行“清单和工艺路线接口”请求。路径:BOM>>清单和工艺路线接口。解决方式:Updateinv.mtl_system_items_bSetreplenish_to_order_flag=‘Y’–按订单装配WHEREINVENTORY_ITEM_ID=2054193 --料号#150305130013AM*2054192ANDORGAINIZATION_ID=......
  • vue+element项目中统一处理接口异常,只提示一次异常信息
     有时候一个页面会同时调多个接口,但是多个接口异常,需要做提示,那么提示的时候会弹出很多的提示信息,这无疑让体验感降低很多。 所以针对这种情况,我们配合elementUI统一做一个异常状态的处理,只能显示一次提示的功能,后续代码调接口的时候也可以省略去写异常状态下的逻辑了。首先......
  • [SprigMVC/SpringBoot] JSON序列化专题之日期序列化问题:接口报Jackson框架错误“Inva
    0序言今日工作中遇到的一个bug。各位看官且听我娓娓道来。1问题描述请求接口时,service层返回到controller层的数据结构为List<Map<Strig,Object>>,而Map中存在一个key=date,valuetype=java.time.LocalDate的Entry,且日志报如下错误:InvalidDefinitionException:Java8date......
  • 接口和抽象类的区别
    接口和抽象类的区别:(1)接口接口使用interface修饰;接口不能实例化;类可以实现多个接口;①java8之前,接口中的方法都是抽象方法,省略了publicabstract。②java8之后;接口中可以定义静态方法,静态方法必须有方法体,普通方法没有方法体,需要被实现;(2)抽象类抽象类使用abstract修饰;抽象类不能......