All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.lq.cli.init.CreateConfigTask Maven / Gradle / Ivy

There is a newer version: 1.2.RELEASE
Show newest version
package com.lq.cli.init;

import com.lq.cli.comment.CreateTask;
import com.lq.cli.comment.FileUtil;
import com.lq.cli.comment.TaskArgs;

import java.io.File;
import java.io.IOException;
import java.net.InetAddress;


public class CreateConfigTask extends CreateTask {

    public CreateConfigTask(TaskArgs taskArgs) {
        super(taskArgs);
    }

    @Override
    public Boolean call() throws Exception {
        if (taskArgs.cliConfig.isUseWeb()) {
            createCorsConfigClass();
            createGlobExceptionHandler();
            createWebCommentResponse();
        }
        if (taskArgs.cliConfig.isUseDruid()) {
            createDruidConfigClass();
        }
        if (taskArgs.cliConfig.isUseLog4j2()) {
            createLog4j();
        }
        return createSpringBootApplication();
    }

    private boolean createSpringBootApplication() throws IOException {
        File file = new File(taskArgs.rootPackagePath + "Application.java");
        if (!file.exists()) {
            if (!file.createNewFile()) {
                return false;
            } else {
                String sb = "package " + taskArgs.packageName + ";" + "\n\n" +
                        "import " +
                        "org.mybatis.spring.annotation.MapperScan;\n" +
                        "import " +
                        "org.springframework.boot.SpringApplication;\n" +
                        "import " +
                        "org.springframework.boot.autoconfigure.SpringBootApplication;\n\n";
                if (taskArgs.cliConfig.isUseMybatis()) {
                    sb += "@MapperScan(\"" +
                            taskArgs.packageName +
                            ".mapper\")\n";
                }
                sb += "@SpringBootApplication\n" +
                        "public class Application {\n\n\tpublic static void main(String[] args){\n\t\tSpringApplication.run(Application.class, args);\n\t}\n}";
                FileUtil.createWriteFile(file, sb);
            }
        }
        return true;
    }

    private void createCorsConfigClass() throws IOException {
        String configDirPath = taskArgs.rootPackagePath + "config" + File.separator;
        File configDir = new File(configDirPath);
        if (!configDir.exists()) {
            if (!configDir.mkdir()) {
                return;
            }
        }
        File file = new File(configDirPath + "CorsConfig.java");
        if (!file.exists()) {
            if (file.createNewFile()) {
                String corsConfig = "package " + taskArgs.packageName +
                        ".config;\n\nimport org.springframework.context.annotation.Bean;" +
                        "\nimport org.springframework.context.annotation.Configuration;" +
                        "\nimport org.springframework.web.cors.CorsConfiguration;" +
                        "\nimport org.springframework.web.cors.UrlBasedCorsConfigurationSource;\nimport org.springframework.web.filter.CorsFilter;" +
                        "\n\n@Configuration\npublic class CorsConfig {\n\n\tprivate CorsConfiguration buildConfig() {\n\t\tCorsConfiguration corsConfiguration = new CorsConfiguration();\n\t\t" +
                        "corsConfiguration.addAllowedOrigin(\"*\");\n\t\tcorsConfiguration.addAllowedHeader(\"*\");\n\t\tcorsConfiguration.addAllowedMethod(\"*\");\n\t\treturn corsConfiguration;\n\t}" +
                        "\n\n\t@Bean\n\tpublic CorsFilter corsFilter() {\n\t\tUrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();" +
                        "\n\t\tsource.registerCorsConfiguration(\"/**\", buildConfig());\n\t\treturn new CorsFilter(source);\n\t}\n\n}";
                FileUtil.createWriteFile(file, corsConfig);
            }
        }

    }


    private void createDruidConfigClass() throws IOException {
        String configDirPath = taskArgs.rootPackagePath + "config" + File.separator;
        File configDir = new File(configDirPath);
        if (!configDir.exists()) {
            if (!configDir.mkdir()) {
                return;
            }
        }
        File file = new File(configDirPath + "DruidConfig.java");
        if (!file.exists()) {
            if (file.createNewFile()) {
                String druidConfig = "package " + taskArgs.packageName +
                        ".config;\n\nimport com.alibaba.druid.pool.DruidDataSource;" +
                        "\nimport com.alibaba.druid.support.http.StatViewServlet;" +
                        "\nimport com.alibaba.druid.support.http.WebStatFilter;" +
                        "\nimport org.springframework.boot.context.properties.ConfigurationProperties;" +
                        "\nimport org.springframework.boot.web.servlet.FilterRegistrationBean;" +
                        "\nimport org.springframework.boot.web.servlet.ServletRegistrationBean;" +
                        "\nimport org.springframework.context.annotation.Bean;" +
                        "\nimport org.springframework.context.annotation.Configuration;\n\n" +
                        "\nimport javax.sql.DataSource;\nimport java.util.Collections;" +
                        "\nimport java.util.HashMap;\nimport java.util.Map;\n\n@Configuration\npublic class DruidConfig {\n\n"
                        + "\t@ConfigurationProperties(prefix = \"spring.datasource\")\n\t@Bean\n\tpublic DataSource druid() {\n\t\treturn new DruidDataSource();\n\t}"
                        + "\n\n\t@Bean\n\tpublic ServletRegistrationBean statViewServlet() {\n\t\t" +
                        "ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), \"/druid/*\");\n\t\t" +
                        "Map initParams = new HashMap<>();\n\t\t" +
                        "initParams.put(\"loginUsername\", \"" + taskArgs.cliConfig.getDruidMonitorUsername() + "\");\n\t\t" +
                        "initParams.put(\"loginPassword\", \"" + taskArgs.cliConfig.getDruidMonitorPwd() + "\");\n\t\t" +
                        "initParams.put(\"allow\", \"\");\n\t\t" +
                        "initParams.put(\"deny\", \"" + InetAddress.getLocalHost().getHostAddress() + "\");\n\t\t" +
                        "bean.setInitParameters(initParams);\n\t\t" +
                        "return bean;\n\t" +
                        "}\n\n\t@Bean\n\tpublic FilterRegistrationBean webStatFilter() {\n\t\tFilterRegistrationBean bean = new FilterRegistrationBean();" +
                        "\n\t\tbean.setFilter(new WebStatFilter());\n\t\tMap initParams = new HashMap<>();\n\t\t" +
                        "initParams.put(\"exclusions\", \"*.js,*.css,/druid/*\");\n\t\tbean.setInitParameters(initParams);\n\t\t" +
                        "bean.setUrlPatterns(Collections.singletonList(\"/*\"));\n\t\treturn bean;\n\t}\n\n}";
                FileUtil.createWriteFile(file, druidConfig);
            }
        }
    }

    private void createLog4j() throws IOException {
        String log4j2Path = taskArgs.projectPath + File.separator + "src" + File.separator + "main"
                + File.separator + "resources" + File.separator + "log4j2-spring.xml";
        File log4j2File = new File(log4j2Path);
        if (!log4j2File.exists()) {
            if (log4j2File.createNewFile()) {
                String log4j = "\n" +
                        "\n" +
                        "    \n" +
                        "        \n" +
                        "        \n" +
                        "    \n" +
                        "\n" +
                        "    \n" +
                        "        \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "        \n" +
                        "\n" +
                        "        \n" +
                        "            \n" +
                        "        \n" +
                        "\n" +
                        "        \n" +
                        "            \n" +
                        "                \n" +
                        "                \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "                \n" +
                        "                \n" +
                        "            \n" +
                        "        \n" +
                        "\n" +
                        "        \n" +
                        "            \n" +
                        "                \n" +
                        "                \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "                \n" +
                        "                \n" +
                        "            \n" +
                        "            \n" +
                        "        \n" +
                        "\n" +
                        "        \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "                \n" +
                        "                \n" +
                        "            \n" +
                        "        \n" +
                        "    \n" +
                        "\n" +
                        "\n" +
                        "    \n" +
                        "        \n" +
                        "        \n" +
                        "        \n" +
                        "        \n" +
                        "        \n" +
                        "        \n" +
                        "        \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "            \n" +
                        "        \n" +
                        "    \n" +
                        "\n" +
                        "";
                FileUtil.createWriteFile(log4j2File, log4j);
            }
        }
    }

    private void createWebCommentResponse() throws IOException {
        String utilDirPath = taskArgs.rootPackagePath + "util" + File.separator;
        File utilDir = new File(utilDirPath);
        if (!utilDir.exists()) {
            if (!utilDir.mkdir()) {
                return;
            }
        }
        File commentResponseFile = new File(utilDirPath + "CommentResponse.java");
        if (!commentResponseFile.exists()) {
            if (!commentResponseFile.createNewFile()) {
                return;
            } else {
                String commentResponse = "package " + taskArgs.packageName + ".util;\n\n";
                commentResponse += "import java.net.HttpURLConnection;\n" +
                        "\n" +
                        "public class CommentResponse {\n" +
                        "\n" +
                        "    private static final String SUCCESS_MSG = \"success\";\n" +
                        "    static final String FAIL_MSG = \"fail\";\n" +
                        "    static final int FAIL_CODE = 240;\n" +
                        "    private static final CommentResponse FAIL_COMMENT_RESPONSE = new CommentResponse<>(FAIL_CODE, null, FAIL_MSG);\n" +
                        "    private static final CommentResponse SUCCESS_COMMENT_RESPONSE = new CommentResponse<>(HttpURLConnection.HTTP_OK,SUCCESS_MSG,null );\n" +
                        "\n" +
                        "    private int status;\n" +
                        "\n" +
                        "    private T data;\n" +
                        "\n" +
                        "    private String errorInfo;\n" +
                        "\n" +
                        "    CommentResponse(int status, T data, String errorInfo) {\n" +
                        "        this.status = status;\n" +
                        "        this.data = data;\n" +
                        "        this.errorInfo = errorInfo;\n" +
                        "    }\n" +
                        "\n" +
                        "    public int getStatus() {\n" +
                        "        return status;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setStatus(int status) {\n" +
                        "        this.status = status;\n" +
                        "    }\n" +
                        "\n" +
                        "    public T getData() {\n" +
                        "        return data;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setData(T data) {\n" +
                        "        this.data = data;\n" +
                        "    }\n" +
                        "\n" +
                        "    public String getErrorInfo() {\n" +
                        "        return errorInfo;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setErrorInfo(String errorInfo) {\n" +
                        "        this.errorInfo = errorInfo;\n" +
                        "    }\n" +
                        "\n" +
                        "    public static  CommentResponse success(T t) {\n" +
                        "        return new CommentResponse<>(HttpURLConnection.HTTP_OK, t, null);\n" +
                        "    }\n" +
                        "\n" +
                        "    public static CommentResponse success() {\n" +
                        "        return SUCCESS_COMMENT_RESPONSE;\n" +
                        "    }\n" +
                        "\n" +
                        "    public static CommentResponse fail() {\n" +
                        "        return FAIL_COMMENT_RESPONSE;\n" +
                        "    }\n" +
                        "\n" +
                        "    public static  CommentResponse fail(String msg) {\n" +
                        "        return new CommentResponse<>(FAIL_CODE, null, msg);\n" +
                        "    }\n" +
                        "}";
                FileUtil.createWriteFile(commentResponseFile, commentResponse);
            }
        }
        File commentPageResponseFile = new File(utilDirPath + "CommentPageResponse.java");
        if (!commentPageResponseFile.exists()) {
            if (commentPageResponseFile.createNewFile()) {
                String commentPageResponse = "package " + taskArgs.packageName + ".util;\n\n";
                commentPageResponse += "import java.net.HttpURLConnection;\n" +
                        "\n" +
                        "public class CommentPageResponse extends CommentResponse {\n" +
                        "\n" +
                        "    private static final CommentPageResponse FAIL_COMMENT_RESPONSE =  new CommentPageResponse<>(FAIL_CODE, null, FAIL_MSG);\n" +
                        "\n" +
                        "    private Integer totalPage;\n" +
                        "    private Integer totalSize;\n" +
                        "    private Integer page;\n" +
                        "    private Integer pageSize;\n" +
                        "\n" +
                        "    private CommentPageResponse(int status, T data, String errorInfo) {\n" +
                        "        super(status, data, errorInfo);\n" +
                        "    }\n" +
                        "\n" +
                        "    private CommentPageResponse(int status, T data, String errorInfo, Integer totalPage, Integer totalSize, Integer page, Integer pageSize) {\n" +
                        "        super(status, data, errorInfo);\n" +
                        "        this.totalPage = totalPage;\n" +
                        "        this.totalSize = totalSize;\n" +
                        "        this.page = page;\n" +
                        "        this.pageSize = pageSize;\n" +
                        "    }\n" +
                        "\n" +
                        "    public Integer getTotalPage() {\n" +
                        "        return totalPage;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setTotalPage(Integer totalPage) {\n" +
                        "        this.totalPage = totalPage;\n" +
                        "    }\n" +
                        "\n" +
                        "    public Integer getTotalSize() {\n" +
                        "        return totalSize;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setTotalSize(Integer totalSize) {\n" +
                        "        this.totalSize = totalSize;\n" +
                        "    }\n" +
                        "\n" +
                        "    public Integer getPage() {\n" +
                        "        return page;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setPage(Integer page) {\n" +
                        "        this.page = page;\n" +
                        "    }\n" +
                        "\n" +
                        "    public Integer getPageSize() {\n" +
                        "        return pageSize;\n" +
                        "    }\n" +
                        "\n" +
                        "    public void setPageSize(Integer pageSize) {\n" +
                        "        this.pageSize = pageSize;\n" +
                        "    }\n" +
                        "\n" +
                        "    public static  CommentPageResponse success(T t,Integer totalPage, Integer totalSize, Integer page, Integer pageSize) {\n" +
                        "        return new CommentPageResponse<>(HttpURLConnection.HTTP_OK, t, null,totalPage,totalSize,page,pageSize);\n" +
                        "    }\n" +
                        "\n" +
                        "    public static  CommentPageResponse fail(String msg) {\n" +
                        "        return new CommentPageResponse<>(FAIL_CODE, null, msg);\n" +
                        "    }\n" +
                        "\n" +
                        "    public static  CommentPageResponse selfFail() {\n" +
                        "        return  FAIL_COMMENT_RESPONSE;\n" +
                        "    }\n" +
                        "}";
                FileUtil.createWriteFile(commentPageResponseFile, commentPageResponse);
            }
        }
        File jacksonUtilFile = new File(utilDirPath + "JacksonUtil.java");
        if (!jacksonUtilFile.exists()) {
            if (jacksonUtilFile.createNewFile()) {
                String jacksonUtil = "package " + taskArgs.packageName + ".util;\n\n";
                jacksonUtil += "import com.fasterxml.jackson.core.JsonProcessingException;\n" +
                        "import com.fasterxml.jackson.databind.JavaType;\n" +
                        "import com.fasterxml.jackson.databind.ObjectMapper;\n" +
                        "import org.springframework.beans.factory.annotation.Autowired;\n" +
                        "import org.springframework.stereotype.Component;\n" +
                        "\n" +
                        "import java.util.List;\n" +
                        "\n" +
                        "@Component\n" +
                        "public class JacksonUtil{\n" +
                        "\n" +
                        "    @Autowired\n" +
                        "    private ObjectMapper objectMapper;\n" +
                        "\n" +
                        "    public String objectToJson(Object data) {\n" +
                        "        try {\n" +
                        "            return objectMapper.writeValueAsString(data);\n" +
                        "        } catch (JsonProcessingException e) {\n" +
                        "            System.err.println(e.toString());\n" +
                        "        }\n" +
                        "        return null;\n" +
                        "    }\n" +
                        "\n" +
                        "    public  T jsonToPojo(String jsonData, Class beanType) {\n" +
                        "        try {\n" +
                        "            return objectMapper.readValue(jsonData, beanType);\n" +
                        "        } catch (Exception e) {\n" +
                        "            System.err.println(e.toString());\n" +
                        "        }\n" +
                        "        return null;\n" +
                        "    }\n" +
                        "\n" +
                        "    public  List jsonToList(String jsonData, Class beanType) {\n" +
                        "        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(List.class, beanType);\n" +
                        "        try {\n" +
                        "            return objectMapper.readValue(jsonData, javaType);\n" +
                        "        } catch (Exception e) {\n" +
                        "            System.err.println(e.toString());\n" +
                        "        }\n" +
                        "        return null;\n" +
                        "    }\n" +
                        "\n" +
                        "}\n";
                FileUtil.createWriteFile(jacksonUtilFile, jacksonUtil);
            }
        }

        File webUtilFile = new File(utilDirPath + "WebUtil.java");
        if (!webUtilFile.exists()) {
            if (webUtilFile.createNewFile()) {
                String webUtil = "package " + taskArgs.packageName + ".util;\n\n";
                webUtil += "import org.springframework.validation.BindingResult;\n" +
                        "import org.springframework.validation.FieldError;\n" +
                        "import java.time.format.DateTimeFormatter;\n" +
                        "\n" +
                        "public class WebUtil {\n" +
                        "\n" +
                        "    private WebUtil(){}\n" +
                        "\n" +
                        "    public static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(\"yyyy-MM-dd HH:mm:ss\");\n" +
                        "\n" +
                        "    public static CommentResponse bindingResult(BindingResult result){\n" +
                        "        StringBuilder sb = new StringBuilder();\n" +
                        "        for (FieldError fieldError : result.getFieldErrors()) {\n" +
                        "            sb.append(fieldError.getDefaultMessage()).append(\";\");\n" +
                        "        }\n" +
                        "        String errorInfo = sb.toString();\n" +
                        "        return CommentResponse.fail(errorInfo);\n" +
                        "    }\n" +
                        "\n" +
                        "}";
                FileUtil.createWriteFile(webUtilFile, webUtil);
            }
        }
    }

    private void createGlobExceptionHandler() throws IOException {
        String exceptionDirPath = taskArgs.rootPackagePath + "exception" + File.separator;
        File exceptionDir = new File(exceptionDirPath);
        if (!exceptionDir.exists()) {
            if (!exceptionDir.mkdir()) {
                return;
            }
        }
        File globExceptionHandlerFile = new File(exceptionDirPath + "GlobExceptionHandler.java");
        if (!globExceptionHandlerFile.exists()) {
            if (globExceptionHandlerFile.createNewFile()) {
                String globExceptionHandler = "package " + taskArgs.packageName + ".exception;\n\n";
                globExceptionHandler += "import com.alibaba.fastjson.support.spring.FastJsonJsonView;\n" +
                        "import org.springframework.stereotype.Component;\n" +
                        "import org.springframework.web.servlet.HandlerExceptionResolver;\n" +
                        "import org.springframework.web.servlet.ModelAndView;\n" +
                        "\n" +
                        "import javax.servlet.http.HttpServletRequest;\n" +
                        "import javax.servlet.http.HttpServletResponse;\n" +
                        "import java.util.HashMap;\n" +
                        "import java.util.Map;\n" +
                        "\n" +
                        "@Component\n" +
                        "public class GlobExceptionHandler implements HandlerExceptionResolver {\n" +
                        "\n" +
                        "    @Override\n" +
                        "    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse response, Object handler, Exception ex) {\n" +
                        "        ModelAndView mv = new ModelAndView();\n" +
                        "        FastJsonJsonView view = new FastJsonJsonView();\n" +
                        "        Map attributes = new HashMap<>();\n" +
                        "        attributes.put(\"data\", null);\n" +
                        "        attributes.put(\"errorInfo\", ex.getMessage());\n" +
                        "        attributes.put(\"status\", 240);\n" +
                        "        view.setAttributesMap(attributes);\n" +
                        "        mv.setView(view);\n" +
                        "        return mv;\n" +
                        "    }\n" +
                        "\n" +
                        "}\n";
                FileUtil.createWriteFile(globExceptionHandlerFile, globExceptionHandler);
            }
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy