diff --git a/.project b/.project deleted file mode 100644 index 4838758e3..000000000 --- a/.project +++ /dev/null @@ -1,17 +0,0 @@ - - - jedp - - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - - diff --git a/.settings/org.eclipse.core.resources.prefs b/.settings/org.eclipse.core.resources.prefs deleted file mode 100644 index 99f26c020..000000000 --- a/.settings/org.eclipse.core.resources.prefs +++ /dev/null @@ -1,2 +0,0 @@ -eclipse.preferences.version=1 -encoding/=UTF-8 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index f897a7f1c..000000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/jun_api_online/.gitignore b/jun_api_online/.gitignore new file mode 100644 index 000000000..659f73625 --- /dev/null +++ b/jun_api_online/.gitignore @@ -0,0 +1,30 @@ +*.class +.DS_Store +application.pid + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +# *.jar +*.war +*.ear + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# Eclipse +.classpath +.project +target +classes +.settings +.factorypath + +# Idea +.idea +*.iml + +# git +*.orig +doc2 \ No newline at end of file diff --git a/jun_api_online/README.md b/jun_api_online/README.md new file mode 100644 index 000000000..5c9989b07 --- /dev/null +++ b/jun_api_online/README.md @@ -0,0 +1,81 @@ +# jun_springboot_admin_layui + +## 简介 +jun_springboot_admin_layui 是一个基于Layui + Spring Boot & MyBatis的API接口服务项目, +项目使用Spring boot2.0+shiro+redis+mybatis架构,可以适用 前后端分离项目后台或者APP接口后台,使用了Shiro-Redis实现分布式Session共享 +基于当前项目,可快速构建中小型API、RESTful API接口,项目含有代码生成器,单表标接口一键生成 +该项目已经有过多个真实项目的实践,稳定、简单、快速,让码农脱离重复劳动,专注于业务代码的编写,减少加班。 + + +- Swagger地址:http://localhost:8080/swagger-ui.html +- 登录地址:localhost:8080/api/user/login?username=admin&password=admin +- 接口地址:localhost:8080/api/public/company/list +- session超时,30分; + + + +### 使用框架如下: +* 核心框架:spring boot 2.1.6 +* 持久层框架:mybatis +* 数据库连接池:alibaba druid +* 安全框架:apache shiro +* 缓存框架:redis(自定义 RedisTemplate 序列化) +* 日志框架:logback +* 接口文档:swagger 2.9.2 +* 接口文档:Fastjson +* MyBatis([查看官方中文文档](http://www.mybatis.org/mybatis-3/zh/index.html)) +* MyBatisb通用Mapper插件([查看官方中文文档](https://mapperhelper.github.io/docs/)) +* MyBatis PageHelper分页插件([查看官方中文文档](https://pagehelper.github.io/)) +* 其他略 + +### 功能截图: +- 一键生成表接口测试 +![](https://github.com/wujun728/jun_springboot_admin_layui/blob/main/jun_springboot_api/doc/images/1.png) +- 登录接口测试 +![](https://github.com/wujun728/jun_springboot_admin_layui/blob/main/jun_springboot_api/doc/images/2.png) +- swagger接口清单 +![](https://github.com/wujun728/jun_springboot_admin_layui/blob/main/jun_springboot_api/doc/images/3.png) + + +C:\Windows\System32\drivers\etc\hosts文件中添加域名: +* qixing.fly666.cn qixing.hbqxcpa.cn +* api.qixing.fly666.cn api.qixing.hbqxcpa.cn +127.0.0.1 qixing.fly666.cn +127.0.0.1 qixing.hbqxcpa.cn +127.0.0.1 api.qixing.fly666.cn +127.0.0.1 api.qixing.hbqxcpa.cn + + + ### 特征&提供 +- 最佳实践的项目结构、配置文件、精简的POM +- 统一响应结果封装及生成工具 +- 统一异常处理 +- 简单的接口签名认证 +- 常用基础方法抽象封装 +- 使用Druid Spring Boot Starter 集成Druid数据库连接池与监控 +- 使用FastJsonHttpMessageConverter,提高JSON序列化速度 +- 集成MyBatis、通用Mapper插件、PageHelper分页插件,实现单表业务零SQL +- 使用SpringFox-Swagger2管理API文档 +- 使用lombok简化POJO +- 提供代码生成器根据表名生成对应的Model、Mapper、MapperXML、Service、ServiceImpl、Controller等基础代码, +- 其中Controller模板默认提供POST和RESTful两套,根据需求在```CodeGenerator.genController(tableName)```方法中自己选择,默认使用POST模板。 +- 代码模板可根据实际项目的需求来扩展,由于每个公司业务都不太一样,所以只提供了一些比较基础、通用的模板,**主要是提供一个思路**来减少重复代码的编写,我在实际项目的使用中,其实根据公司业务的抽象编写了大量的模板。另外,使用模板也有助于保持团队代码风格的统一 + +### 快速开始 +1. 下载项目 +2. 对```test```包内的代码生成器```CodeGenerator```进行配置,主要是JDBC,因为要根据表名来生成代码 +3. 如果只是想根据上面的演示来亲自试试的话可以使用```test resources```目录下的```sys_user.sql```,否则忽略该步 +3. 输入表名,运行```CodeGenerator.main()```方法,生成基础代码(可能需要刷新项目目录才会出来) +4. 根据业务在基础代码上进行扩展 +5. 对开发环境配置文件```application-dev.properties```进行配置,启动项目! + +### 开发建议 +- 表名,建议使用小写,多个单词使用下划线拼接 +- Model内成员变量建议与表字段数量对应,如需扩展成员变量(比如连表查询)建议创建DTO,否则需在扩展的成员变量上加```@Transient```注解,详情见[通用Mapper插件文档说明](https://mapperhelper.github.io/docs/2.use/) +- 建议业务失败直接使用```ServiceException("message")```抛出,由统一异常处理器来封装业务失败的响应结果,比如```throw new ServiceException("该手机号已被注册")```,会直接被封装为```{"code":400,"message":"该手机号已被注册"}```返回,无需自己处理,尽情抛出 +- 需要工具类的话建议先从```apache-commons-*```和```guava```中找,实在没有再造轮子或引入类库,尽量精简项目 +- 开发规范建议遵循阿里巴巴Java开发手册([最新版下载](https://github.com/alibaba/p3c)) +- 建议在公司内部使用[SpringFox-Swagger2](https://github.com/springfox/springfox) 、[RAP](https://github.com/thx/RAP)等开源项目来编写、管理API文档 + +反射兼容问题 +这是由于 JDK 8 中有关反射相关的功能自从 JDK 9 开始就已经被限制了,为了兼容原先的版本,需要在运行项目时添加 --add-opens java.base/java.lang=ALL-UNNAMED \ No newline at end of file diff --git a/jun_api_online/jun_admin/pom.xml b/jun_api_online/jun_admin/pom.xml new file mode 100644 index 000000000..a51a0f2bd --- /dev/null +++ b/jun_api_online/jun_admin/pom.xml @@ -0,0 +1,227 @@ + + + 4.0.0 + com.jun.plugin + jun_admin + 1.0 + 主应用Main + + + + org.projectlombok + lombok + 1.18.30 + + + org.springframework.boot + spring-boot-devtools + true + runtime + + + org.springframework.boot + spring-boot-starter-web + + + com.jun.plugin + jun_common + 1.0 + + + com.jun.plugin + jun-dynamic-form-spring-boot-starter + 1.0.13 + + + com.jun.plugin + jun-code-generator-spring-boot-starter + 1.0.13 + + + com.jun.plugin + generator + 1.0 + + + commons-beanutils + commons-beanutils + + + commons-lang + commons-lang + + + commons-logging + commons-logging + + + + + com.jun.plugin + quartz + 1.0 + + + com.jun.plugin + jun_system + 1.0 + + + com.jun.plugin + fileservice + 1.0 + + + com.jun.plugin + sms + 1.0 + + + com.jun.plugin + snakerflow + 1.0 + compile + + + cglib-nodep + cglib + + + commons-logging + commons-logging + + + + + + + org.springframework.boot + spring-boot-devtools + runtime + true + + + + org.springframework.boot + spring-boot-starter-mail + + + org.springframework.boot + spring-boot-starter-websocket + + + org.springframework.boot + spring-boot-starter-data-jdbc + + + + com.alibaba + druid-spring-boot-starter + 1.2.18 + + + org.springframework.boot + spring-boot-test + test + + + org.springframework + spring-test + test + + + junit + junit + test + + + junit + junit + test + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + org.flywaydb + flyway-mysql + 9.22.3 + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + manager + + + + + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/OnlineApplication.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/OnlineApplication.java new file mode 100644 index 000000000..984c7b23c --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/OnlineApplication.java @@ -0,0 +1,66 @@ +package com.jun.plugin.project; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.util.Arrays; + +import cn.hutool.core.util.IdUtil; +import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure; +import com.jun.plugin.rest.filter.ResourceFilter; +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.CommandLineRunner; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.annotation.EnableScheduling; + +import lombok.extern.slf4j.Slf4j; + +@Slf4j +@EnableScheduling +@SpringBootApplication(exclude = DruidDataSourceAutoConfigure.class) // 多数据源 (exclude = DruidDataSourceAutoConfigure.class) +@MapperScan({"com.jun.plugin.**.mapper","com.jun.plugin.online.dao"}) +@ComponentScan(basePackages = {"com.jun.plugin.project","com.jun.plugin.common","com.jun.plugin.rest","com.jun.plugin.generator", + "com.jun.plugin.quartz","com.jun.plugin.online","com.jun.plugin.generate","com.jun.plugin.system"}) +@ServletComponentScan(basePackages = {"com.jun.plugin.**.filter"}) +public class OnlineApplication extends SpringBootServletInitializer { + public static void main(String[] args) throws Exception { +// SpringApplication application = new SpringApplication(SpringbootApplication.class); +// application.setBannerMode(Banner.Mode.OFF); +// application.run(args); + //System.setProperty("spring.devtools.restart.enabled", "true"); + ConfigurableApplicationContext application = SpringApplication.run(OnlineApplication.class, args); + Environment env = application.getEnvironment(); + InetAddress inetAddress = Inet4Address.getLocalHost(); + String hostAddress = inetAddress.getHostAddress(); + String serverPort = env.getProperty("server.port"); + String serverPath = env.getProperty("spring.application.name"); + String url = env.getProperty("spring.datasource.url"); + log.info("项目启动成功!访问地址: http://{}:{}/{}", hostAddress, serverPort, serverPath); + log.info("本机地址: http://localhost:{}", serverPort); + } + + @Override // 为了打包springboot项目 + protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) { + return builder.sources(this.getClass()); + } + + @Bean + public CommandLineRunner commandLineRunner(ApplicationContext ctx) { + return args -> { + System.out.println("Let's inspect the beans provided by Spring Boot:"); + String[] beanNames = ctx.getBeanDefinitionNames(); + System.err.println("beanNames size = "+ beanNames.length); + //Arrays.stream(beanNames).forEach(System.out::println); + }; + } +} + + diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/BaseController.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/BaseController.java new file mode 100644 index 000000000..f43d12a6c --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/BaseController.java @@ -0,0 +1,58 @@ +package com.jun.plugin.project.config; + +import cn.hutool.core.util.IdUtil; +import cn.hutool.extra.spring.SpringUtil; +import com.jun.plugin.common.Result; +//import com.jun.plugin.common.util.SpringContextUtil; +import com.jun.plugin.common.utils.spring.SpringUtils; +import io.swagger.annotations.ApiOperation; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.RestController; + +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.UnknownHostException; + + +/** + * 客户信息 + * + * @author wujun + * @email wujun728@mail.com + * @date 2022-02-28 16:28:58 + */ +@RequestMapping("/") +@RestController +public class BaseController { + + @ApiOperation("404请求") + @GetMapping("404") + public String e404() { + System.out.println("404............"); + return "这真的是一个404页面,你看看"; + } + + @GetMapping("/") + public Result root() throws UnknownHostException { + Environment env = SpringUtil.getApplicationContext().getEnvironment(); + InetAddress inetAddress = Inet4Address.getLocalHost(); + String hostAddress = inetAddress.getHostAddress(); + String serverPort = env.getProperty("server.port"); + String serverPath = env.getProperty("spring.application.name"); + String url = env.getProperty("spring.datasource.url"); + Result result = Result.success("项目启动成功!"); + result.put("local",String.format("本机地址: http://localhost:%s", serverPort)); + result.put("ipadress",String.format("访问地址: http://%s:%s/%s", hostAddress, serverPort, serverPath)); + return result; + } + + +// public static void main(String[] args) { +//// System.out.println(IdUtil.getSnowflake(10,8).nextId()); +// } + +} diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice.java new file mode 100644 index 000000000..f6e73467b --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/GlobalRequestBodyAdvice.java @@ -0,0 +1,91 @@ +package com.jun.plugin.project.config; + +import org.springframework.core.MethodParameter; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpInputMessage; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * @title 全局请求参数处理类 + */ +@ControllerAdvice(basePackages = "com.jun.plugin.*.controller")//此处设置需要当前Advice执行的域 , 省略默认全局生效 +public class GlobalRequestBodyAdvice implements RequestBodyAdvice { + + + /** 此处如果返回false , 则不执行当前Advice的业务 */ + @Override + public boolean supports(MethodParameter methodParameter, Type targetType, Class extends HttpMessageConverter>> converterType) { +// return methodParameter.getMethod().isAnnotationPresent(XXApiReq.class); + return false; + } + + /** + * @title 读取参数前执行 + * @description 在此做些编码 / 解密 / 封装参数为对象的操作 + * + * */ + @Override + public HttpInputMessage beforeBodyRead(HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType) throws IOException { + // 提取数据 + InputStream is = inputMessage.getBody(); + byte[] data = new byte[is.available()]; + is.read(data); + //转数据类型 + ObjectMapper mapper = new ObjectMapper(); + Map m = mapper.readValue(new String(data), Map.class); + //m.forEach(null); + return new XHttpInputMessage(inputMessage, "UTF-8"); + } + + /** + * @title 读取参数后执行 + * @author Xingbz + */ + @Override + public Object afterBodyRead(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType) { + return inputMessage; + } + + /** + * @title 无请求时的处理 + */ + @Override + public Object handleEmptyBody(Object body, HttpInputMessage inputMessage, MethodParameter parameter, Type targetType, Class extends HttpMessageConverter>> converterType) { + return body; + } +} + +//这里实现了HttpInputMessage 封装一个自己的HttpInputMessage +class XHttpInputMessage implements HttpInputMessage { + private HttpHeaders headers; + private InputStream body; + + public XHttpInputMessage(HttpInputMessage httpInputMessage, String encode) throws IOException { + this.headers = httpInputMessage.getHeaders(); + this.body = encode(httpInputMessage.getBody(), encode); + } + + private InputStream encode(InputStream body, String encode) { + //省略对流进行编码的操作 + return body; + } + + @Override + public InputStream getBody() { + return body; + } + + @Override + public HttpHeaders getHeaders() { + return null; + } +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig.java new file mode 100644 index 000000000..a37f9c0ef --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaObjectHandlerConfig.java @@ -0,0 +1,86 @@ +package com.jun.plugin.project.config; + +import cn.hutool.core.util.ClassLoaderUtil; +import cn.hutool.core.util.ClassUtil; +import cn.hutool.core.util.ReflectUtil; +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +//import com.jun.plugin.project.service.HttpSessionService; +import com.jun.plugin.common.constant.Constant; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.stereotype.Component; + +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; + + +/** + * mybatis plus 默认值配置 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Component +public class MetaObjectHandlerConfig implements MetaObjectHandler { + +// @Lazy +// @Resource +// HttpSessionService httpSessionService; + + @Override + public void insertFill(MetaObject metaObject) { + Date currentDate = new Date(); + String[] setterNames = metaObject.getSetterNames(); + HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); + if (setterNameSet.contains("deleted")) { + //默认未删除 + setFieldValByName("deleted", Constant.DATA_NOT_DELETED, metaObject); + } + if (setterNameSet.contains("createTime")) { + //创建时间默认当前时间 + setFieldValByName("createTime", currentDate, metaObject); + } + if (setterNameSet.contains("createDate")) { + //创建时间默认当前时间 + setFieldValByName("createDate", currentDate, metaObject); + } +// if (setterNameSet.contains("createId")) { +// //创建时间默认当前时间 +// setFieldValByName("createId", httpSessionService.getCurrentUserId(), metaObject); +// } +// if (setterNameSet.contains("updateId")) { +// //创建时间默认当前时间 +// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); +// } + if (setterNameSet.contains("updateTime")) { + //创建时间默认当前时间 + setFieldValByName("updateTime", currentDate, metaObject); + } + if (setterNameSet.contains("updateDate")) { + //创建时间默认当前时间 + setFieldValByName("updateDate", currentDate, metaObject); + } + + + } + + @Override + public void updateFill(MetaObject metaObject) { + Date currentDate = new Date(); + String[] setterNames = metaObject.getSetterNames(); + HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); + if (setterNameSet.contains("updateTime")) { + //创建时间默认当前时间 + setFieldValByName("updateTime", currentDate, metaObject); + } + if (setterNameSet.contains("updateDate")) { + //创建时间默认当前时间 + setFieldValByName("updateDate", currentDate, metaObject); + } +// if (setterNameSet.contains("updateId")) { +// //创建时间默认当前时间 +// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); +// } + } +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaRecordFillHandlerConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaRecordFillHandlerConfig.java new file mode 100644 index 000000000..e8750eb84 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MetaRecordFillHandlerConfig.java @@ -0,0 +1,95 @@ +//package com.jun.plugin.project.config; +// +//import cn.hutool.db.meta.Table; +//import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +//import com.jun.plugin.common.constant.Constant; +//import com.jun.plugin.db.record.Record; +//import com.jun.plugin.rest.handler.RecordFillHandler; +//import org.apache.ibatis.reflection.MetaObject; +//import org.springframework.stereotype.Component; +// +//import java.util.Arrays; +//import java.util.Date; +//import java.util.HashSet; +// +// +///** +// * mybatis plus 默认值配置 +// * +// * @author wujun +// * @version V1.0 +// * @date 2020年3月18日 +// */ +//@Component +//public class MetaRecordFillHandlerConfig implements RecordFillHandler { +// +//// @Lazy +//// @Resource +//// HttpSessionService httpSessionService; +// +//// @Override +//// public void insertFill(MetaObject metaObject) { +//// Date currentDate = new Date(); +//// String[] setterNames = metaObject.getSetterNames(); +//// HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); +//// if (setterNameSet.contains("deleted")) { +//// //默认未删除 +//// setFieldValByName("deleted", Constant.DATA_NOT_DELETED, metaObject); +//// } +//// if (setterNameSet.contains("createTime")) { +//// //创建时间默认当前时间 +//// setFieldValByName("createTime", currentDate, metaObject); +//// } +//// if (setterNameSet.contains("createDate")) { +//// //创建时间默认当前时间 +//// setFieldValByName("createDate", currentDate, metaObject); +//// } +////// if (setterNameSet.contains("createId")) { +////// //创建时间默认当前时间 +////// setFieldValByName("createId", httpSessionService.getCurrentUserId(), metaObject); +////// } +////// if (setterNameSet.contains("updateId")) { +////// //创建时间默认当前时间 +////// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); +////// } +//// if (setterNameSet.contains("updateTime")) { +//// //创建时间默认当前时间 +//// setFieldValByName("updateTime", currentDate, metaObject); +//// } +//// if (setterNameSet.contains("updateDate")) { +//// //创建时间默认当前时间 +//// setFieldValByName("updateDate", currentDate, metaObject); +//// } +//// +//// +//// } +//// +//// @Override +//// public void updateFill(MetaObject metaObject) { +//// Date currentDate = new Date(); +//// String[] setterNames = metaObject.getSetterNames(); +//// HashSet setterNameSet = new HashSet<>(Arrays.asList(setterNames)); +//// if (setterNameSet.contains("updateTime")) { +//// //创建时间默认当前时间 +//// setFieldValByName("updateTime", currentDate, metaObject); +//// } +//// if (setterNameSet.contains("updateDate")) { +//// //创建时间默认当前时间 +//// setFieldValByName("updateDate", currentDate, metaObject); +//// } +////// if (setterNameSet.contains("updateId")) { +////// //创建时间默认当前时间 +////// setFieldValByName("updateId", httpSessionService.getCurrentUserId(), metaObject); +////// } +//// } +// +// @Override +// public void insertFill(Table table, Record record) { +// +// } +// +// @Override +// public void updateFill(Table table, Record record) { +// +// } +//} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig.java new file mode 100644 index 000000000..f078d62a4 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/MyBatisPlusConfig.java @@ -0,0 +1,30 @@ +package com.jun.plugin.project.config; + +import com.baomidou.mybatisplus.annotation.DbType; +import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor; +import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * mybatis plus config + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Configuration +public class MyBatisPlusConfig { + /** + * 配置mybatis-plus 分页查件 + */ + + /** 配置分页插件*/ + @Bean + public MybatisPlusInterceptor mybatisPlusInterceptor() { + MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor(); + interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL)); + return interceptor; + } + +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RecordHandlerConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RecordHandlerConfig.java new file mode 100644 index 000000000..bad14d2e1 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RecordHandlerConfig.java @@ -0,0 +1,70 @@ +package com.jun.plugin.project.config; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.util.ObjUtil; +import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.jun.plugin.common.base.interfaces.IRecordHandler; +import com.jun.plugin.common.constant.Constant; +import com.jun.plugin.common.service.HttpSessionService; +import com.jun.plugin.db.record.Record; +import org.apache.ibatis.reflection.MetaObject; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; + + +/** + * mybatis plus 默认值配置 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Component +public class RecordHandlerConfig implements IRecordHandler { + + @Lazy + @Resource + HttpSessionService httpSessionService; + + @Override + public String tableName() { + return "all"; + } + + @Override + public void insertFill(Record record) { + if(ObjUtil.isNotNull(record.get("update_time"))){ + record.set("update_time", DateUtil.now()); + } + if(ObjUtil.isNotNull(record.get("create_time"))){ + record.set("create_time", DateUtil.now()); + } + if(ObjUtil.isNotNull(record.get("create_id"))){ + record.set("create_id", httpSessionService.getCurrentUserId()); + } + if(ObjUtil.isNotNull(record.get("update_id"))){ + record.set("update_id", httpSessionService.getCurrentUserId()); + } + } + + @Override + public void updateFill(Record record) { + if(ObjUtil.isNotNull(record.get("update_time"))){ + record.set("update_time", DateUtil.now()); + } + if(ObjUtil.isNotNull(record.get("create_time"))){ + record.set("create_time", DateUtil.now()); + } + if(ObjUtil.isNotNull(record.get("create_id"))){ + record.set("create_id", httpSessionService.getCurrentUserId()); + } + if(ObjUtil.isNotNull(record.get("update_id"))){ + record.set("update_id", httpSessionService.getCurrentUserId()); + } + } +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RedisCacheConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RedisCacheConfig.java new file mode 100644 index 000000000..f0a90e8c8 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/RedisCacheConfig.java @@ -0,0 +1,103 @@ +package com.jun.plugin.project.config; + +import java.time.Duration; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cache.annotation.EnableCaching; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.data.redis.cache.RedisCacheConfiguration; +import org.springframework.data.redis.cache.RedisCacheManager; +import org.springframework.data.redis.cache.RedisCacheWriter; +import org.springframework.data.redis.connection.RedisConnectionFactory; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; +import org.springframework.data.redis.serializer.RedisSerializationContext; +import org.springframework.data.redis.serializer.RedisSerializer; +import org.springframework.data.redis.serializer.StringRedisSerializer; + +import com.fasterxml.jackson.annotation.JsonAutoDetect; +import com.fasterxml.jackson.annotation.PropertyAccessor; +import com.fasterxml.jackson.databind.ObjectMapper; + +import javax.annotation.Resource; + +/** + * Redis缓存配置。 + */ +@Configuration +@EnableCaching +public class RedisCacheConfig { + +// @Autowired +// private RedisTemplate redisTemplate; + + @Resource + private RedisConnectionFactory factory; + + @Bean + public RedisTemplate redisTemplate() { + RedisTemplate redisTemplate = new RedisTemplate<>(); + redisTemplate.setConnectionFactory(factory); + // 字符串Key序列化 + StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); + redisTemplate.setKeySerializer(stringRedisSerializer); + redisTemplate.setHashKeySerializer(stringRedisSerializer); + // 对象值序列化 +// ObjectRedisSerializer objectRedisSerializer = new ObjectRedisSerializer(); + RedisSerializer objectRedisSerializer = new GenericJackson2JsonRedisSerializer(); + redisTemplate.setValueSerializer(objectRedisSerializer); + redisTemplate.setHashValueSerializer(objectRedisSerializer); + return redisTemplate; + } + + @Bean(name = "redisCacheManager") + public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) { + + // 初始化一个RedisCacheWriter + RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); + // 设置CacheManager的值序列化方式为json序列化 + RedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(); + RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair + .fromSerializer(jsonSerializer); + RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); + config.entryTtl(Duration.ofSeconds(60*2)).disableCachingNullValues();// 不缓存空值 +// // 初始化RedisCacheManager + return new RedisCacheManager(redisCacheWriter, config, getRedisCacheConfigurationMap()); + } + + + private Map getRedisCacheConfigurationMap() { + Map redisCacheConfigurationMap = new HashMap<>(); + redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60)); + //自定义设置缓存时间 + redisCacheConfigurationMap.put("userCache", this.getRedisCacheConfigurationWithTtl(60)); + redisCacheConfigurationMap.put("cache4h", this.getRedisCacheConfigurationWithTtl(60*60*4)); + redisCacheConfigurationMap.put("cache5m", this.getRedisCacheConfigurationWithTtl(60*2)); + redisCacheConfigurationMap.put("cache2m", this.getRedisCacheConfigurationWithTtl(60*2)); + redisCacheConfigurationMap.put("cache1m", this.getRedisCacheConfigurationWithTtl(60)); + + return redisCacheConfigurationMap; + } + + private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) { +// RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(factory); + // 设置CacheManager的值序列化方式为json序列化 + RedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(); + RedisSerializationContext.SerializationPair pair = RedisSerializationContext.SerializationPair + .fromSerializer(jsonSerializer); + RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().serializeValuesWith(pair); + redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith( + RedisSerializationContext + .SerializationPair + .fromSerializer(jsonSerializer) + ).entryTtl(Duration.ofSeconds(seconds)); + return redisCacheConfiguration; + } + +} diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration.java new file mode 100644 index 000000000..732e5daba --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/SwaggerConfiguration.java @@ -0,0 +1,51 @@ +package com.jun.plugin.project.config; + +import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j; +import com.google.common.base.Predicates; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; +import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration; +import springfox.documentation.builders.ApiInfoBuilder; +import springfox.documentation.builders.PathSelectors; +import springfox.documentation.builders.RequestHandlerSelectors; +import springfox.documentation.service.ApiInfo; +import springfox.documentation.spi.DocumentationType; +import springfox.documentation.spring.web.plugins.Docket; +import springfox.documentation.swagger2.annotations.EnableSwagger2; + + +/** + * SwaggerConfiguration + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Configuration +@EnableSwagger2 +@EnableKnife4j +@Import(BeanValidatorPluginsConfiguration.class) +public class SwaggerConfiguration { + + @Bean + public Docket createRestApi() { + return new Docket(DocumentationType.SWAGGER_2) + .apiInfo(apiInfo()) + .select() + .apis(Predicates.or(RequestHandlerSelectors.basePackage("com.jun.plugin.system.controller"), + RequestHandlerSelectors.basePackage("com.jun.plugin.bizservice.controller"))) + .paths(PathSelectors.any()) + .build(); + } + + private ApiInfo apiInfo() { + return new ApiInfoBuilder() + .title("Springboot-api APIs") + .description("Springboot-api APIs") + .termsOfServiceUrl("http://localhost:8080/") + .version("1.0") + .build(); + } +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration.java new file mode 100644 index 000000000..f3b5c7736 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/ThymeleafConfigration.java @@ -0,0 +1,74 @@ +//package com.jun.plugin.project.config; +// +//import java.io.File; +//import java.io.FileNotFoundException; +// +//import org.springframework.context.annotation.Bean; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.util.ResourceUtils; +//import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver; +//import org.thymeleaf.templatemode.TemplateMode; +//import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver; +// +//@Configuration +//public class ThymeleafConfigration { +// +// @Bean +// public SpringResourceTemplateResolver firstTemplateResolver() { +// SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver(); +// //templateResolver.setPrefix("classpath:/templates/"); +// +// File path = null; +// try { +// path = new File(ResourceUtils.getURL("classpath:").getPath()); +// //file:/data/github/testmanagement/target/testmanagement-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes! +// System.out.println(path.getPath()); +// } catch (FileNotFoundException e) { +// e.printStackTrace(); +// } +// //server.tomcat.basedir=outsidefile/jacococoverage +// String outside_templates=path.getParentFile().getParentFile().getParent()+File.separator; +// //String outside_templates=path.getParentFile().getParentFile().getParent()+File.separator+"outsidefile"+File.separator+"jacococoverage"+File.separator; +// +// System.out.println(outside_templates); +// outside_templates=outside_templates.substring(5,outside_templates.length()); +// //file:/data/github/testmanagement/target/outsidefile/jacococoverage/ +// +// System.out.println("new outside_templates is "+outside_templates); +// templateResolver.setPrefix("file://"+outside_templates); +// +// templateResolver.setSuffix(".html"); +// templateResolver.setTemplateMode(TemplateMode.HTML); +// templateResolver.setCharacterEncoding("UTF-8"); +// templateResolver.setOrder(0); +// templateResolver.setCheckExistence(true); +// //Spring Boot中Thymeleaf引擎动态刷新 +// templateResolver.setCacheable(false); +// return templateResolver; +// } +// +//// @Bean +//// public ClassLoaderTemplateResolver secondaryTemplateResolver() { +//// ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); +//// secondaryTemplateResolver.setPrefix("templates2/"); +//// secondaryTemplateResolver.setSuffix(".html"); +//// secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); +//// secondaryTemplateResolver.setCharacterEncoding("UTF-8"); +//// secondaryTemplateResolver.setOrder(1); +//// secondaryTemplateResolver.setCacheable(false); +//// secondaryTemplateResolver.setCheckExistence(true); +//// return secondaryTemplateResolver; +//// } +// @Bean +// public ClassLoaderTemplateResolver secondaryTemplateResolver3() { +// ClassLoaderTemplateResolver secondaryTemplateResolver = new ClassLoaderTemplateResolver(); +// secondaryTemplateResolver.setPrefix("templates3/"); +// secondaryTemplateResolver.setSuffix(".html"); +// secondaryTemplateResolver.setTemplateMode(TemplateMode.HTML); +// secondaryTemplateResolver.setCharacterEncoding("UTF-8"); +// secondaryTemplateResolver.setOrder(1); +// secondaryTemplateResolver.setCacheable(false); +// secondaryTemplateResolver.setCheckExistence(true); +// return secondaryTemplateResolver; +// } +//} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/WebConfig.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/WebConfig.java new file mode 100644 index 000000000..6ed742d9b --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/WebConfig.java @@ -0,0 +1,138 @@ +package com.jun.plugin.project.config; + + +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer; +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer; +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer; +import com.fasterxml.jackson.module.paramnames.ParameterNamesModule; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder; +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; +import org.springframework.web.servlet.config.annotation.*; +import org.springframework.web.servlet.view.InternalResourceViewResolver; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; +import java.util.List; + +/** + * spring mvc配置类 + * sunxh 2023/2/26 + */ +@Configuration +@EnableWebMvc +public class WebConfig implements WebMvcConfigurer { + +// @Resource +// private MyWebInterceptor myWebInterceptor; +// @Resource +// private LoggerInterceptor loggerInterceptor; + + /** + * 资源跨域设置 + */ + @Override + public void addCorsMappings(CorsRegistry registry) { + //super.addCorsMappings(registry); + //registry.addMapping("/api/**").allowedOrigins("*").maxAge(3600); + registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST", "GET", "PUT", "DELETE") + .allowedOrigins("*"); + } + + /** + * 请求拦截器 + */ + @Override + public void addInterceptors(InterceptorRegistry registry) { + WebMvcConfigurer.super.addInterceptors(registry); + //loggerInterceptor.addInterceptor(registry); + //myWebInterceptor.addInterceptor(registry); +// registry.addInterceptor(new RepeatSubmitInterceptor() { +// @Override +// public boolean isRepeatSubmit(HttpServletRequest request) { +// return false; +// } +// }).addPathPatterns("/**") +// .excludePathPatterns("/emp/toLogin","/emp/login","/js/**","/css/**","/images/**"); + } + + /** + * @description: 访问静态文件,发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 + * @date: 2021/4/15 + */ + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + /** 本地文件上传路径 */ +// registry.addResourceHandler(Constants.RESOURCE_PREFIX + "/**").addResourceLocations("file:" + Global.getProfile() + "/"); + + registry.addResourceHandler("/**").addResourceLocations("classpath:/static/","classpath:/static2/","classpath:/static3/","classpath:/templates/","classpath:/templates3/","classpath:/views/"); +// registry.addResourceHandler("/**").addResourceLocations("classpath:/templates/"); + registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/","classpath:/static2/","classpath:/static3/"); + registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + + /** swagger配置 */ + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + /** 文件下载映射配置,同下 */ +// registry.addResourceHandler(fileUploadProperties.getAccessUrl()).addResourceLocations("file:" + fileUploadProperties.getPath()); + } + + /** + * 定义全局默认时间序列化 + */ + private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; + private static final String DATE_FORMAT = "yyyy-MM-dd"; + @Override + public void configureMessageConverters(List> converters) { + Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder() + .indentOutput(true) + .dateFormat(new SimpleDateFormat("yyyy-MM-dd")) + .simpleDateFormat(DATE_TIME_FORMAT) + .serializers(new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))) + .serializers(new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT))) + .deserializers(new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT))) + .deserializers(new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT))) + .modulesToInstall(new ParameterNamesModule()); + converters.add(new MappingJackson2HttpMessageConverter(builder.build())); + } + + /** + * 视图配置 + * @param registry + */ + @Override + public void configureViewResolvers(ViewResolverRegistry registry) { + //super.configureViewResolvers(registry); + registry.viewResolver(resourceViewResolver()); + /*registry.jsp("/WEB-INF/jsp/",".jsp");*/ + } + + @Bean + public InternalResourceViewResolver resourceViewResolver() + { + InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver(); + //请求视图文件的前缀地址 + internalResourceViewResolver.setPrefix("/WEB-INF/jsp/"); + //请求视图文件的后缀 + internalResourceViewResolver.setSuffix(".jsp"); + return internalResourceViewResolver; + } + + + /** + * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 + */ + @Override + public void addViewControllers(ViewControllerRegistry registry) { +// registry.addViewController("/").setViewName("forward:" + indexUrl); + registry.addViewController("/").setViewName("forward:" + "login.html"); + } +} + diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor.java new file mode 100644 index 000000000..fc1d84f86 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MyInterceptor.java @@ -0,0 +1,40 @@ +package com.jun.plugin.project.config.interceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; + +/** + * @author HongYi + * @createTime 2021年02月01日 14:00:00 + */ +@Component +public class MyInterceptor implements HandlerInterceptor { + private static final Logger logger = LoggerFactory.getLogger(MyInterceptor.class); + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { + logger.info("------------------ preHandle"); + request.setAttribute("startTime",System.currentTimeMillis()); + return true; + } + + + @Override + public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { + logger.info("------------------ postHandle"); + long startTime = (long) request.getAttribute("startTime"); + request.removeAttribute("startTime"); + logger.info("请求处理时间: " + (System.currentTimeMillis() - startTime) + "毫秒"); + } + + @Override + public void afterCompletion(HttpServletRequest request, HttpServletResponse response, + Object handler, Exception ex) { + logger.info("------------------ after"); + } +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor.java b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor.java new file mode 100644 index 000000000..e59b8fd55 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/java/com/jun/plugin/project/config/interceptor/MybatisExecutor.java @@ -0,0 +1,87 @@ +package com.jun.plugin.project.config.interceptor; + +//import com.fen.dou.entity.BaseEntity; +//import com.fen.dou.entity.User; +import lombok.extern.slf4j.Slf4j; +import org.apache.ibatis.executor.Executor; +import org.apache.ibatis.mapping.MappedStatement; +import org.apache.ibatis.mapping.SqlCommandType; +import org.apache.ibatis.plugin.*; +import org.springframework.stereotype.Component; + +import com.jun.plugin.common.entity.BaseEntity; + +import java.util.Map; +import java.util.Properties; + +@Slf4j +@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) }) +@Component +public class MybatisExecutor implements Interceptor { + @Override + @SuppressWarnings("unchecked") + public Object intercept(Invocation invocation) throws Throwable { + // 根据签名指定的args顺序获取具体的实现类 + // 1. 获取MappedStatement实例, 并获取当前SQL命令类型 + MappedStatement ms = (MappedStatement) invocation.getArgs()[0]; + SqlCommandType commandType = ms.getSqlCommandType(); + + // 2. 获取当前正在被操作的类, 有可能是Java Bean, 也可能是普通的操作对象, 比如普通的参数传递 + // 普通参数, 即是 @Param 包装或者原始 Map 对象, 普通参数会被 Mybatis 包装成 Map 对象 + // 即是 org.apache.ibatis.binding.MapperMethod$ParamMap + Object parameter = invocation.getArgs()[1]; + // 获取拦截器指定的方法类型, 通常需要拦截 update + String methodName = invocation.getMethod().getName(); + log.info("NormalPlugin, methodName; {}, commandType: {}", methodName, commandType); + + // 3. 获取当前用户信息 +// User user = new User(1,"yangcai","sssss"); + // 默认测试参数值 + int creator = 2, updater = 3; + + if (parameter instanceof BaseEntity) { + // 4. 实体类 + BaseEntity entity = (BaseEntity) parameter; +// if (user != null) { +// creator = entity.getCreateIds(); +// updater = entity.getUpdater(); +// } + if (methodName.equals("update")) { + if (commandType.equals(SqlCommandType.INSERT)) { +// entity.setCreator(creator); +// entity.setUpdater(updater); +// entity.setCreateTime(System.currentTimeMillis()); +// entity.setUpdateTime(System.currentTimeMillis()); + } else if (commandType.equals(SqlCommandType.UPDATE)) { +// entity.setUpdater(updater); +// entity.setUpdateTime(System.currentTimeMillis()); + } + } + } else if (parameter instanceof Map) { + // 5. @Param 等包装类 + // 更新时指定某些字段的最新数据值 + if (commandType.equals(SqlCommandType.UPDATE)) { + // 遍历参数类型, 检查目标参数值是否存在对象中, 该方式需要应用编写有一些统一的规范 + // 否则均统一为实体对象, 就免去该重复操作 + Map map = (Map) parameter; + if (map.containsKey("creator")) { + map.put("creator", creator); + } + if (map.containsKey("updateTime")) { + map.put("updateTime", System.currentTimeMillis()); + } + } + } + // 6. 均不是需要被拦截的类型, 不做操作 + return invocation.proceed(); + } + + @Override + public Object plugin(Object target) { + return Plugin.wrap(target, this); + } + + @Override + public void setProperties(Properties properties) { + } +} diff --git a/jun_api_online/jun_admin/src/main/resources/application-dev.yml b/jun_api_online/jun_admin/src/main/resources/application-dev.yml new file mode 100644 index 000000000..457a6bc51 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/application-dev.yml @@ -0,0 +1,69 @@ +# 开发环境配置 +spring: + thymeleaf: + cache: false + datasource: + url: jdbc:mysql://175.24.233.55:3307/db_qixing?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull&useInformationSchema=true + username: ENC(i9EHZ6vsnfpTeKGvHmH+fA==) +# password: ENC(KX2tfUq8cZG3IXeAwZgk5w==) + password: ENC(DRxUQYNs+FWrr9vlmZfJN+lLEV1GxqCX) + driver-class-name: com.mysql.cj.jdbc.Driver + redis: + host: localhost # Redis服务器地址 + database: 1 # Redis数据库索引(默认为0) + port: 6379 # Redis服务器连接端口 + password: # Redis服务器连接密码(默认为空) + jedis: + pool: + max-active: 8 # 连接池最大连接数(使用负值表示没有限制) + max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) + max-idle: 8 # 连接池中的最大空闲连接 + min-idle: 0 # 连接池中的最小空闲连接 + timeout: 13000 # 连接超时时间(毫秒 + + flyway: + # 是否启用flyway + enabled: false + # 编码格式,默认UTF-8 + encoding: UTF-8 + # 迁移sql脚本文件存放路径,默认db/migration + locations: classpath:db/migration + # 迁移sql脚本文件名称的前缀,默认V + sql-migration-prefix: V + # 迁移sql脚本文件名称的分隔符,默认2个下划线__ + sql-migration-separator: __ + # 迁移sql脚本文件名称的后缀 + sql-migration-suffixes: .sql + # 迁移时是否进行校验,默认true + validate-on-migrate: true + # 当迁移发现数据库非空且存在没有元数据的表时,自动执行基准迁移,新建schema_version表 + +filepath: "D:\\files\\" +file: + #文件上传目录 绝对路径 末尾请加 / + path: D:/files/ #windows + #path: /home/data/files/ #linux + #文件预览、下载的url, 末尾请勿加 / + url: http://qiniu.hbqxcpa.cn/files + qiniuAccessKey: ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 + qiniuBucketName: qixing-files + qiniuDomain: http://qiniu.hbqxcpa.cn + qiniuPrefix: upload + qiniuSecretKey: c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL + type: 1 + + +# AES密码加密私钥(Base64加密) +encryptAESKey: V2FuZzkyNjQ1NGRTQkFQSUpXVA== +# JWT认证加密私钥(Base64加密) +encryptJWTKey: U0JBUElKV1RkV2FuZzkyNjQ1NA== +# AccessToken过期时间-5分钟-5*60(秒为单位) +accessTokenExpireTime: 300 +# RefreshToken过期时间-30分钟-30*60(秒为单位) +refreshTokenExpireTime: 1800 +# Shiro缓存过期时间-5分钟-5*60(秒为单位)(一般设置与AccessToken过期时间一致) +shiroCacheExpireTime: 300 +shiro: + enable: true +knife4j: + production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/application-local.yml b/jun_api_online/jun_admin/src/main/resources/application-local.yml new file mode 100644 index 000000000..8aa9de1d1 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/application-local.yml @@ -0,0 +1,67 @@ +# 开发环境配置 +spring: + thymeleaf: + cache: false + datasource: + url: jdbc:mysql://localhost:3306/db_qixing_bk?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=GMT%2b8&zeroDateTimeBehavior=convertToNull&useInformationSchema=true + username: ENC(i9EHZ6vsnfpTeKGvHmH+fA==) + password: ENC(KX2tfUq8cZG3IXeAwZgk5w==) + driver-class-name: com.mysql.cj.jdbc.Driver + redis: + host: localhost # Redis服务器地址 + database: 1 # Redis数据库索引(默认为0) + port: 6379 # Redis服务器连接端口 + password: # Redis服务器连接密码(默认为空) + jedis: + pool: + max-active: 8 # 连接池最大连接数(使用负值表示没有限制) + max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制) + max-idle: 8 # 连接池中的最大空闲连接 + min-idle: 0 # 连接池中的最小空闲连接 + timeout: 13000 # 连接超时时间(毫秒 + + flyway: + # 是否启用flyway + enabled: false + # 编码格式,默认UTF-8 + encoding: UTF-8 + # 迁移sql脚本文件存放路径,默认db/migration + locations: classpath:db/migration + # 迁移sql脚本文件名称的前缀,默认V + sql-migration-prefix: V + # 迁移sql脚本文件名称的分隔符,默认2个下划线__ + sql-migration-separator: __ + # 迁移sql脚本文件名称的后缀 + sql-migration-suffixes: .sql + # 迁移时是否进行校验,默认true + validate-on-migrate: true + # 当迁移发现数据库非空且存在没有元数据的表时,自动执行基准迁移,新建schema_version表 + +filepath: "D:\\files\\" +file: + #文件上传目录 绝对路径 末尾请加 / + path: /home/data/files/ #linux + #文件预览、下载的url, 末尾请勿加 / + url: http://qiniu.hbqxcpa.cn/files + qiniuAccessKey: ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 + qiniuBucketName: qixing-files + qiniuDomain: http://qiniu.hbqxcpa.cn + qiniuPrefix: upload + qiniuSecretKey: c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL + type: 1 + + +# AES密码加密私钥(Base64加密) +encryptAESKey: V2FuZzkyNjQ1NGRTQkFQSUpXVA== +# JWT认证加密私钥(Base64加密) +encryptJWTKey: U0JBUElKV1RkV2FuZzkyNjQ1NA== +# AccessToken过期时间-5分钟-5*60(秒为单位) +accessTokenExpireTime: 300 +# RefreshToken过期时间-30分钟-30*60(秒为单位) +refreshTokenExpireTime: 1800 +# Shiro缓存过期时间-5分钟-5*60(秒为单位)(一般设置与AccessToken过期时间一致) +shiroCacheExpireTime: 300 +shiro: + enable: true +knife4j: + production: true #生成环境禁用查看文档 \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/application.yml b/jun_api_online/jun_admin/src/main/resources/application.yml new file mode 100644 index 000000000..c948f9abd --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/application.yml @@ -0,0 +1,209 @@ +# 端口 +server: + port: 8082 + compression: + enabled: true + min-response-size: 1KB + mime-types: application/json,application/xml,text/html,text/xml,text/plain,application/javascript,text/css + max-http-header-size: 102400 + tomcat: + uri-encoding: UTF-8 + servlet: + encoding: + charset: UTF-8 + force: true + enabled: true + +spring: + profiles: + active: local +# active: prod + mvc: + throw-exception-if-no-handler-found: true +# static-path-pattern: /static/** + resources: + add-mappings: false + main: + allow-bean-definition-overriding: true + allow-circular-references: true + application: + name: jun-code-online + jackson: + date-format: yyyy-MM-dd HH:mm:ss + time-zone: GMT+8 + # 文件大小限制 + servlet: + multipart: + max-file-size: 100MB + max-request-size: 100MB + # redis token信息 + redis: + key: + prefix: + userToken: "user:token:" + passwordError: "user:password:error:" + permissionRefresh: "user:token:permissionRefresh:" + expire: + #userToken: 604800 # 7天 1*24*3600 + userToken: 86400 # 1天 1*24*3600 + passwordError: 3600 # 一个小时 + #permissionRefresh: 604800 # 7天 7*24*3600 + permissionRefresh: 86400 # 1天 1*24*3600 + allowMultipleLogin: true # 允许多处登陆 + +mybatis-plus: + configuration: + log-impl: org.apache.ibatis.logging.stdout.StdOutImpl + cache-enabled: false + mapper-locations: + ## classpath:mapper/*.xml,classpath:mapper/*Mapper.xml + - classpath*:mapper/*.xml # 扫描子模块下的 mapper.xml文件 + - classpath:mapper/*.xml # 扫描当前模块下的 mapper.xml 文件 +# mapper-locations: classpath:mapper/*.xml,classpath:mapper/${project.database}/**/*.xml + type-aliases-package: org.snaker.engine.entity + global-config: + enable-sql-runner: true + db-config: + logic-delete-value: 0 + logic-not-delete-value: 1 + logic-delete-field: deleted + +project: + database: mysql + config: + packages: 'com.jun.plugin.abcd,com.jun.plugin.abc' + datasource: + dsname: 'main' + url: ${spring.datasource.url} + driver: ${spring.datasource.driver-class-name} + username: ${spring.datasource.username} + password: ${spring.datasource.password} + runApi: + enable: true + devMode: true + serviceName: jun-runA + api_config: api_config + context: / + + +jasypt: + algorithm: PBEWithMD5AndDES + encryptor: + password: 123456@@ + +shiro: + enable: false + +# 防止XSS攻击 +xss: + # 过滤开关 + enabled: true + # 排除链接(多个用逗号分隔) + excludes: + # 匹配链接 + urlPatterns: /system/*,/tool/* +# 工作流参数定义 +workflows: + list: + - processName: leave + flowName: 请假流程 + pageURl: oapomsworkmarksleave/list + tname: oa_poms_workmarks_leave + taskName: 的请假流程 + - processName: project + flowName: 立项流程 + pageURl: pjProject/list + tname: pj_project + taskName: 的立项流程 + - processName: contract + flowName: 业务约定书流程 + pageURl: pjContract/list + tname: pj_contract + taskName: 的合同审批流程 + - processName: plan + flowName: 项目计划流程 + pageURl: pjProjectPlan/list + tname: pj_project_plan + taskName: 的项目计划流程 + - processName: daily + flowName: 日报审批流程 + pageURl: pjProjectDaily/list + tname: pj_project_daily + taskName: 的日报流程 + - processName: draft + flowName: 底稿审批流程 + pageURl: pjProjectDraft/list + tname: pj_project_draft + taskName: 的底稿 + - processName: recheck + flowName: 复核审批流程 + pageURl: pjProjectReport/list + tname: pj_project_report + taskName: 的复核 + - processName: member + flowName: 成员结算审批流程 + pageURl: pjProjectMember/list + tname: pj_project_member + taskName: 的成员结算 + - processName: invoice + flowName: 开票审批流程 + pageURl: pjProjectInvoice/list + tname: pj_project_invoice + taskName: 的开票申请 + - processName: borrow + flowName: 项目借阅审批流程 + pageURl: pjProjectBorrow/list + tname: pj_project_borrow + taskName: 的项目借阅 + - processName: office + flowName: 办公用品领用审批流程 + pageURl: oaOfficeCount/list + tname: oa_office_count + taskName: 的领用申购 + - processName: office2 + flowName: 办公用品申购审批流程 + pageURl: oaOfficeCount2/list + tname: oa_office_count2 + taskName: 的领用申购 + - processName: outsite + flowName: 外出审批流程 + pageURl: oaPomsWorkmarksOutsite/list + tname: oa_poms_workmarks_outsite + taskName: 的外出申请 + - processName: expense + flowName: 报销审批流程 + pageURl: oaPomsWorkmarksClaimExpense/list + tname: oa_poms_workmarks_claim_expense + taskName: 的报销申请 + - processName: hire + flowName: 录用审批流程 + pageURl: hrUserHire/list + tname: hr_user_hire + taskName: 的录用申请电子流 + - processName: hire + flowName: 录用审批流程 + pageURl: hrUserHire/list + tname: hr_user_hire + taskName: 的录用申请电子流 + - processName: becomemember + flowName: 转正审批流程 + pageURl: hrUserBecomeMember/list + tname: hr_user_become_member + taskName: 的转正申请电子流 + - processName: dimission + flowName: 离职审批流程 + pageURl: hrUserDimission/list + tname: hr_user_dimission + taskName: 的离职申请电子流 + - processName: assessment + flowName: 考核电子流 + pageURl: hrAssessmentUserRecord/list + tname: hr_assessment_user_record + taskName: 的考核电子流 + - processName: customer + flowName: 客户审批电子流 + pageURl: pjCustomer/list + tname: pj_customer + taskName: 的客户审批电子流 + - processName: your_name + pageURl: your_id \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/db/migration/V1.0__engine_create_ddl.sql b/jun_api_online/jun_admin/src/main/resources/db/migration/V1.0__engine_create_ddl.sql new file mode 100644 index 000000000..f64970ca7 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/db/migration/V1.0__engine_create_ddl.sql @@ -0,0 +1,47 @@ + +/*!40101 SET NAMES utf8 */; + +/*!40101 SET SQL_MODE=''*/; + +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +/*Table structure for table `app_action` */ + + +# DROP TABLE IF EXISTS `app_config`; + +CREATE TABLE `app_config` ( + `project_id` bigint(20) DEFAULT NULL COMMENT '项目Id', + `app_path` varchar(255) DEFAULT NULL COMMENT '应用目录地址', + `certificate_path` varchar(255) DEFAULT NULL COMMENT '应用证书配置', + `create_date` datetime(6) DEFAULT NULL COMMENT '新建时间', + `creator` varchar(255) DEFAULT NULL COMMENT '新建用户', + `db_address` varchar(255) DEFAULT NULL COMMENT '数据库地址', + `db_password` varchar(255) DEFAULT NULL COMMENT '数据库密码', + `db_user` varchar(255) DEFAULT NULL COMMENT '数据库用户', + `id` bigint(20) NOT NULL COMMENT 'id', + `ip_address` varchar(255) DEFAULT NULL COMMENT '创建IP地址', + `repository_address` varchar(255) DEFAULT NULL COMMENT '代码库', + `tenant` varchar(255) DEFAULT NULL COMMENT '租户code', + `update_date` datetime(6) DEFAULT NULL COMMENT '修改时间', + `updater` varchar(255) DEFAULT NULL COMMENT '修改用户', + `db_type` varchar(255) DEFAULT NULL COMMENT '数据库类型', + `keyword` varchar(255) DEFAULT NULL COMMENT '应用对应关键字', + `app_id` bigint(20) DEFAULT NULL COMMENT '应用Id', + `type` varchar(255) DEFAULT NULL COMMENT '数据库类型', + `defaultdbconfig` varchar(255) DEFAULT NULL, + `database_create_flag` int(11) NOT NULL COMMENT '是否创建数据库: 0 代表不初始化, 大于0 代表初始化', + `database_init_flag` int(11) NOT NULL COMMENT '是否初始化数据库: 0 代表不初始化, 大于0 代表初始化', + `db_admin_create_flag` int(11) NOT NULL COMMENT '是否创建数据库管理员: 0 代表不初始化, 大于0 代表初始化', + PRIMARY KEY (`id`), + UNIQUE KEY `idx_app_config` (`project_id`), + UNIQUE KEY `idx_app_id_config` (`app_id`), + UNIQUE KEY `idx_project_id_config` (`project_id`) +) ENGINE=InnoDB DEFAULT CHARSET=gbk; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; diff --git a/jun_api_online/jun_admin/src/main/resources/files/logo_resume.jpg b/jun_api_online/jun_admin/src/main/resources/files/logo_resume.jpg new file mode 100644 index 000000000..ace375766 Binary files /dev/null and b/jun_api_online/jun_admin/src/main/resources/files/logo_resume.jpg differ diff --git "a/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2771.docx" "b/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2771.docx" new file mode 100644 index 000000000..541427ae9 Binary files /dev/null and "b/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2771.docx" differ diff --git "a/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" "b/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" new file mode 100644 index 000000000..43058590f Binary files /dev/null and "b/jun_api_online/jun_admin/src/main/resources/files/\347\256\200\345\216\206\346\250\241\346\235\2772.docx" differ diff --git a/jun_api_online/jun_admin/src/main/resources/logback-spring.xml b/jun_api_online/jun_admin/src/main/resources/logback-spring.xml new file mode 100644 index 000000000..82058f74c --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/logback-spring.xml @@ -0,0 +1,60 @@ + + + + + + + + + + + + + + ${CONSOLE_LOG_PATTERN} + + + + + + + ${LOG_PATH}/${LOG_FILE} + + ${FILE_LOG_PATTERN} + + + ${LOG_PATH}/${LOG_HISTORY} + 30 + + + + + + + + 0 + 500 + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/mapper/SysConfigDao.xml.bak b/jun_api_online/jun_admin/src/main/resources/mapper/SysConfigDao.xml.bak new file mode 100644 index 000000000..9073a15ef --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/mapper/SysConfigDao.xml.bak @@ -0,0 +1,53 @@ + + + + + select * from sys_config where id = #{id} + + + + select * from sys_config where status = 1 + + and `key` like concat('%',#{key},'%') + + + limit #{offset}, #{limit} + + + + + select count(*) from sys_config where status = 1 + + and `key` like concat('%',#{key},'%') + + + + + insert into sys_config(`key`, `value`, remark) + values(#{key},#{value},#{remark}) + + + + update sys_config set `key` = #{key}, `value` = #{value}, remark = #{remark} + where id = #{id} + + + + + update sys_config set `value` = #{value} where `key` = #{key} + + + + + select value from sys_config where `key` = #{key} + + + + delete from sys_config where id in + + #{id} + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/mapper/SysGeneratorMapper.xml b/jun_api_online/jun_admin/src/main/resources/mapper/SysGeneratorMapper.xml new file mode 100644 index 000000000..a262b1bba --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/mapper/SysGeneratorMapper.xml @@ -0,0 +1,139 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + id, table_name, menu_name, pid, gen_time + + + + + + SELECT + TABLE_NAME AS tableName, + TABLE_COMMENT AS tableComment, + CREATE_TIME AS createTime + FROM + information_schema.TABLES + WHERE + TABLE_SCHEMA = ( SELECT DATABASE ( ) ) + + and TABLE_NAME LIKE concat('%',#{vo.tableName},'%') + + ORDER BY + CREATE_TIME DESC + + + + + + select table_name tableName, engine, table_comment tableComment, create_time createTime from information_schema.tables + where table_schema = (select database()) and table_name = #{tableName} + + + + select column_name columnName, data_type dataType, column_comment columnComment, column_key columnKey, extra + ,character_maximum_length maxLength,IS_NULLABLE isNull from information_schema.columns + where table_name = #{tableName} and table_schema = (select database()) order by ordinal_position + + + + + + select table_name , engine, table_comment , create_time from information_schema.tables + where table_schema = (select database()) + + and table_name = #{tableName} + + order by create_time desc + + + + + select + TABLE_CATALOG as table_catalog + ,TABLE_SCHEMA as table_schema + ,TABLE_NAME as table_name + ,COLUMN_NAME as column_name + ,ORDINAL_POSITION as ordinal_position + ,COLUMN_DEFAULT as column_default + ,IS_NULLABLE as is_nullable + ,DATA_TYPE as data_type + ,CHARACTER_MAXIMUM_LENGTH as character_maximum_length + + ,COLUMN_TYPE as column_type + ,COLUMN_KEY as column_key + ,EXTRA as extra + + ,COLUMN_COMMENT as column_comment + + from information_schema.columns + where table_name = #{tableName} and table_schema = (select database()) order by ordinal_position + + + + select + TABLE_CATALOG as table_catalog + ,TABLE_SCHEMA as table_schema + ,TABLE_NAME as table_name + ,COLUMN_NAME as column_name + ,ORDINAL_POSITION as ordinal_position + ,COLUMN_DEFAULT as column_default + ,IS_NULLABLE as is_nullable + ,DATA_TYPE as data_type + ,CHARACTER_MAXIMUM_LENGTH as character_maximum_length + + ,COLUMN_TYPE as column_type + ,COLUMN_KEY as column_key + ,EXTRA as extra + + ,COLUMN_COMMENT as column_comment + + from information_schema.columns + where table_name = #{tableName} and table_schema = (select database()) order by ordinal_position + + + diff --git a/jun_api_online/jun_admin/src/main/resources/mapper/SysOssDao.xml.bak b/jun_api_online/jun_admin/src/main/resources/mapper/SysOssDao.xml.bak new file mode 100644 index 000000000..d2ec63e91 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/mapper/SysOssDao.xml.bak @@ -0,0 +1,53 @@ + + + + + + select * from sys_oss where id = #{value} + + + + select * from sys_oss order by id desc + + limit #{offset}, #{limit} + + + + + select count(*) from sys_oss + + + + insert into sys_oss + ( + `url`, + `create_date` + ) + values + ( + #{url}, + #{createDate} + ) + + + + update sys_oss + + `url` = #{url}, + `create_date` = #{createDate} + + where id = #{id} + + + + delete from sys_oss where id = #{value} + + + + delete from sys_oss where id in + + #{id} + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/mapper/UserMapper.xml.bak b/jun_api_online/jun_admin/src/main/resources/mapper/UserMapper.xml.bak new file mode 100644 index 000000000..34fea9a80 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/mapper/UserMapper.xml.bak @@ -0,0 +1,16 @@ + + + + + insert into file_system (name,password) values (#{name},#{password}); + + + select * from file_system where name = #{name}; + + + select * from file_system where name = #{name} and password = #{password}; + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/qiniu.properties b/jun_api_online/jun_admin/src/main/resources/qiniu.properties new file mode 100644 index 000000000..b95e022ef --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/qiniu.properties @@ -0,0 +1,6 @@ +bucketName=qixing-files +domain=http://qiniu.hbqxcpa.cn +prefix=upload +type=1 +ACCESS_KEY=ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2 +SECRET_KEY=c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL diff --git a/jun_api_online/jun_admin/src/main/resources/vm/Controller.java.vm b/jun_api_online/jun_admin/src/main/resources/vm/Controller.java.vm new file mode 100644 index 000000000..1768ee9d8 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/Controller.java.vm @@ -0,0 +1,181 @@ +package ${package}.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.util.CollectionUtils; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.core.metadata.IPage; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import java.util.List; +import com.jun.plugin.system.common.utils.DataResult; +import com.jun.plugin.common.aop.annotation.DataScope; +import com.jun.plugin.module.flow.process.BaseFlowController; + +import ${package}.entity.${className}Entity; +import ${package}.mapper.${className}Mapper; +import ${package}.service.${className}Service; + + + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +@Controller +@RequestMapping("/") +@Slf4j +public class ${className}Controller extends BaseFlowController{ + + @Autowired + private ${className}Service ${classname}Service; + + @Autowired + private ${className}Mapper ${classname}Mapper; + + + /** + * 跳转到页面 + */ + @GetMapping("/index/${classname}") + public String ${classname}() { + return "${classNameLower}/list"; + } + + @ApiOperation(value = "新增") + @PostMapping("${classname}/add") + @RequiresPermissions("${classname}:add") + @ResponseBody + public DataResult add(@RequestBody ${className}Entity ${classname}){ + if(this.checkExists(${classname})) { + return DataResult.fail("同名记录信息已存在!"); + } + ${classname}Service.save(${classname}); + return DataResult.success(); + } + + @ApiOperation(value = "删除") + @DeleteMapping("${classname}/delete") + @RequiresPermissions("${classname}:delete") + @ResponseBody + public DataResult delete(@RequestBody @ApiParam(value = "id集合") List ids){ + ${classname}Service.removeByIds(ids); + return DataResult.success(); + } + + @ApiOperation(value = "更新") + @PutMapping("${classname}/update") + @RequiresPermissions("${classname}:update") + @ResponseBody + public DataResult update(@RequestBody ${className}Entity ${classname}){ + ${classname}Service.updateById(${classname}); + return DataResult.success(); + } + + @ApiOperation(value = "查询分页数据") + @PostMapping("${classname}/listByPage") + @RequiresPermissions("${classname}:list") + @ResponseBody + @DataScope + public DataResult findListByPage(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()==null?"":${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + //关联流程查询待办、处理人、状态 + List<${className}Entity> records = iPage.getRecords(); + records.forEach(item -> { + if((item.getOrderId()!=null && item.getOrderId().length()>0) && (item.getOrderStatus()==null)) { + this.setFlowStatusInfo(item); + System.err.println(item.getOrderStatus()); + if(item.getOrderState()==0) { + if((item.getOrderStatus()==null || item.getOrderStatus()!=0)) { + item.setOrderStatus(item.getOrderState()); + ${classname}Service.updateById(item); + } + } + }else { + item.setOrderState(item.getOrderStatus()); + } + + }); + return DataResult.success(iPage); + } + + + @ApiOperation(value = "查询下拉列表数据") + @PostMapping("${classname}/listBySelect") + @ResponseBody + @DataScope + public DataResult listBySelect(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //查询条件示例 + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + return DataResult.success(iPage); + } + + @ApiOperation(value = "查询单条数据") + @PostMapping("${classname}/findOne") + @ResponseBody + public DataResult findOne(@RequestBody ${className}Entity ${classname}){ + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //queryWrapper.eq(${className}Entity::getId, ${classname}.getId()); + //${className}Entity one = ${classname}Service.getOne(queryWrapper); + ${className}Entity one = ${classname}Service.getById(${classname}.getId()); + return DataResult.success(one); + } + + @ApiOperation(value = "查询下拉框数据") + @PostMapping("${classname}/findListBySelect") + @ResponseBody + @DataScope + public DataResult findListBySelect(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + log.info("\n this.${classname}Mapper.selectCountUser()="+this.${classname}Mapper.selectCountUser()); + return DataResult.success(iPage); + } + + @PostMapping("${classname}/checkExists") + @ResponseBody + public Boolean checkExists(@RequestBody ${className}Entity ${classname}){ + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + queryWrapper.eq(${className}Entity::getId, ${classname}.getId());// 这里换成自己查询的关键条件 + ${className}Entity one = ${classname}Service.getOne(queryWrapper.last("LIMIT 1")); + if(one == null) { + return false; + }else { + return true; + } + } + +} diff --git a/jun_api_online/jun_admin/src/main/resources/vm/Dao.java.vm b/jun_api_online/jun_admin/src/main/resources/vm/Dao.java.vm new file mode 100644 index 000000000..36a5f4563 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/Dao.java.vm @@ -0,0 +1,20 @@ +package ${package}.mapper; + +import ${package}.entity.${className}Entity; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +public interface ${className}Mapper extends BaseMapper<${className}Entity> { + + @Select("SELECT count(1) from sys_user") + int selectCountUser(); + +} diff --git a/jun_api_online/jun_admin/src/main/resources/vm/Dao.xml.vm b/jun_api_online/jun_admin/src/main/resources/vm/Dao.xml.vm new file mode 100644 index 000000000..9b44ded64 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/Dao.xml.vm @@ -0,0 +1,14 @@ + + + + + + + +#foreach($column in $columns) + +#end + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/Entity.java.vm b/jun_api_online/jun_admin/src/main/resources/vm/Entity.java.vm new file mode 100644 index 000000000..c51dc91f3 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/Entity.java.vm @@ -0,0 +1,60 @@ +package ${package}.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.jun.plugin.common.entity.BaseFlowEntity; +import org.springframework.data.annotation.Id; + +#if(${hasBigDecimal}) +#end +import java.io.Serializable; + +import lombok.Data; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +@Data +@TableName("${tableName}") +public class ${className}Entity extends BaseFlowEntity implements Serializable { + private static final long serialVersionUID = 1L; + +##循环,遍历字段信息 +#foreach ($column in $columns) + /** + * $column.comments + */ +##判断是否主键1 +#if($column.columnName == $pk.columnName) + @Id + @TableId("$column.columnName") + private $column.attrType $column.attrname; +#end +##判断是否主键 +#if($column.columnName != $pk.columnName) +##循环列,新增字段描述备注 + @TableField(value = "$column.columnName" ## +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted")) +, fill = FieldFill.INSERT ## +#elseif($column.columnName.toString().contains("update")) +, fill = FieldFill.INSERT_UPDATE ## +#end ) +##循环列,新增字段描述备注dataType +#if($column.dataType == 'datetime') + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") +#elseif($column.dataType == 'date') + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") +#end + private $column.attrType $column.attrname; +#end +##循环,结束 +#end + +} diff --git a/jun_api_online/jun_admin/src/main/resources/vm/Service.java.vm b/jun_api_online/jun_admin/src/main/resources/vm/Service.java.vm new file mode 100644 index 000000000..847833676 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/Service.java.vm @@ -0,0 +1,16 @@ +package ${package}.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import ${package}.entity.${className}Entity; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +public interface ${className}Service extends IService<${className}Entity> { + +} + diff --git a/jun_api_online/jun_admin/src/main/resources/vm/ServiceImpl.java.vm b/jun_api_online/jun_admin/src/main/resources/vm/ServiceImpl.java.vm new file mode 100644 index 000000000..8d8891f2d --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/ServiceImpl.java.vm @@ -0,0 +1,15 @@ +package ${package}.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import ${package}.mapper.${className}Mapper; +import ${package}.entity.${className}Entity; +import ${package}.service.${className}Service; + + +@Service("${classname}Service") +public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}Entity> implements ${className}Service { + + +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/controller.java.ftl b/jun_api_online/jun_admin/src/main/resources/vm/controller.java.ftl new file mode 100644 index 000000000..b2429b779 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/controller.java.ftl @@ -0,0 +1,78 @@ +package ${package.Controller}; + +import cn.hutool.core.collection.CollUtil; +import org.springframework.web.bind.annotation.RequestMapping; +import ${package.Entity}.${entity}; +import ${package.Service}.${table.serviceName}; +<#if restControllerStyle> + import org.springframework.web.bind.annotation.RestController; +<#else> + import org.springframework.stereotype.Controller; +#if> +import com.laker.admin.framework.model.Response; +import com.laker.admin.framework.model.PageResponse; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +<#if superControllerClassPackage??> + import ${superControllerClassPackage}; +#if> + +/** +* + * ${table.comment!} 前端控制器 + * +* +* @author ${author} +* @since ${date} +*/ +<#if restControllerStyle> + @RestController +<#else> + @Controller +#if> +@RequestMapping("/${cfg.easyModule}/${cfg.easyMain}") +<#if superControllerClass??> + public class ${table.controllerName} extends ${superControllerClass} { +<#else> + public class ${table.controllerName} { +#if> +@Autowired +${table.serviceName} ${table.serviceName?substring(1)?uncap_first}; + +@GetMapping +@ApiOperation(value = "${table.comment!}分页查询") +public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page, +@RequestParam(required = false, defaultValue = "10") long limit) { +Page roadPage = new Page<>(page, limit); +LambdaQueryWrapper<${table.entityName}> queryWrapper = new QueryWrapper().lambda(); +Page pageList = ${table.serviceName?substring(1)?uncap_first}.page(roadPage, queryWrapper); +return PageResponse.ok(pageList.getRecords(), pageList.getTotal()); +} + +@PostMapping +@ApiOperation(value = "新增或者更新${table.comment!}") +public Response saveOrUpdate(@RequestBody ${table.entityName} param) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.saveOrUpdate(param)); +} + +@GetMapping("/{id}") +@ApiOperation(value = "根据id查询${table.comment!}") +public Response get(@PathVariable Long id) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.getById(id)); +} + +@DeleteMapping("/{id}") +@ApiOperation(value = "根据id删除${table.comment!}") +public Response delete(@PathVariable Long id) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.removeById(id)); +} +@DeleteMapping("/batch/{ids}") +@ApiOperation(value = "根据批量删除ids删除") +public Response batchRemove(@PathVariable Long[] ids) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.removeByIds(CollUtil.toList(ids))); +} +} \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/list.html.vm b/jun_api_online/jun_admin/src/main/resources/vm/list.html.vm new file mode 100644 index 000000000..0bf010994 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/list.html.vm @@ -0,0 +1,604 @@ + + + + + Title + + + + + + + + + + +#* + + 基本信息 + +*# + +###遍历新增修改表单 +#foreach($column in $columns) + #if($column.columnName == $pk.columnName) + + #else +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end + + + +#if($column.dataType != 'text') #end + ${column.comments} + +##注解支持,不展示 +#if($column.dataType == 'datetime') + +#elseif($column.columnName.toString().contains("dict")) + + 请选择 + + +#elseif($column.dataType == 'text') + +#else + #if($column.isNull == 'NO') + + #else + + #end +#end + + #if($column.dataType != 'text') #end + + +#end +#end + + + 保存 + 返回 + + + + + + + + + + + + + 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! + + + +###遍历查询条件 +#foreach($column in $columns) +#if($column.columnName != $pk.columnName && $column.isNull == 'NO') +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("create") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end +#if($column.dataType == 'datetime') + + + +#else + + + +#end +#end +#end + + 查询 + 导出全部 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/menu.sql.vm b/jun_api_online/jun_admin/src/main/resources/vm/menu.sql.vm new file mode 100644 index 000000000..0f66241e7 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/menu.sql.vm @@ -0,0 +1,26 @@ +-- 默认上级目录菜单为其他 +INSERT INTO sys_permission (id, name, pid, url,target, type,order_num, deleted, status,create_time,update_time) + VALUES ('${identity}', '${comments}' ,'54', '/index/${classname}','_self', '2', '910',1, 1,now(),now()); +-- 菜单对应按钮SQL +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${selectId}', '${identity}', '列表' , '${classname}/listByPage','${classname}:list', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${addId}', '${identity}', '新增' , '${classname}/add','${classname}:add', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${updateId}', '${identity}', '修改' , '${classname}/update','${classname}:update', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${deleteId}', '${identity}', '删除' , '${classname}/delete','${classname}:delete', '3',1, 1,now(),now()); + +-- INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) +-- VALUES ('${deleteId}11', '${identity}', '提交' , '${classname}/submit','${classname}:submit', '3',1, 1,now(),now()); + + + +select +#foreach($column in $columns) + ${column.columnName} as ${column.attrname}, +#end + 1 as gen +from + ${tableName} +where id != null ; \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/web/add.html.ftl b/jun_api_online/jun_admin/src/main/resources/vm/web/add.html.ftl new file mode 100644 index 000000000..d95915f7c --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/web/add.html.ftl @@ -0,0 +1,63 @@ + + + + + Title + + + + + + + + <#list table.fields as field> + <#if !field.keyFlag && field.propertyName != 'enable'> + + ${field.comment} + + + + + #if> + <#if field.propertyName == 'enable'> + + 字典状态 + + + + + + #if> + #list> + + + + + + + 提交 + + + + 重置 + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_admin/src/main/resources/vm/web/edit.html.ftl b/jun_api_online/jun_admin/src/main/resources/vm/web/edit.html.ftl new file mode 100644 index 000000000..f72341635 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/web/edit.html.ftl @@ -0,0 +1,74 @@ + + + + + + + + + + + + <#list table.fields as field> + <#if field.keyFlag > + + + id + + + + + #if> + + <#if !field.keyFlag && field.propertyName != 'enable'> + + ${field.comment} + + + + + #if> + <#if field.propertyName == 'enable'> + + 字典状态 + + + + + + #if> + #list> + + + + + + + + 提交 + + + + 重置 + + + + + + + + + + + diff --git a/jun_api_online/jun_admin/src/main/resources/vm/web/main.html.ftl b/jun_api_online/jun_admin/src/main/resources/vm/web/main.html.ftl new file mode 100644 index 000000000..a69beae59 --- /dev/null +++ b/jun_api_online/jun_admin/src/main/resources/vm/web/main.html.ftl @@ -0,0 +1,113 @@ + + + + + ${table.comment} + + + + + + + + 关键字 + + + + + + 查询 + + + + 重置 + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_api_online/jun_admin/src/test/java/com/jun/plugin/JasyptExample.java b/jun_api_online/jun_admin/src/test/java/com/jun/plugin/JasyptExample.java new file mode 100644 index 000000000..57d61fba0 --- /dev/null +++ b/jun_api_online/jun_admin/src/test/java/com/jun/plugin/JasyptExample.java @@ -0,0 +1,24 @@ +package com.jun.plugin; + +import org.jasypt.util.text.BasicTextEncryptor; + +public class JasyptExample { + public static void main(String[] args) { + BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); + + // 设置加密密钥 + textEncryptor.setPassword("123456@@"); +// textEncryptor.setPassword("myEncryptionPassword"); + + // 要加密的数据 + String myText = "This is a text to encrypt"; + + // 加密 + String encryptedText = textEncryptor.encrypt(myText); + System.out.println("Encrypted text: " + encryptedText); + + // 解密 + String decryptedText = textEncryptor.decrypt(encryptedText); + System.out.println("Decrypted text: " + decryptedText); + } +} \ No newline at end of file diff --git a/jun_api_online/jun_api/bizservice/pom.xml b/jun_api_online/jun_api/bizservice/pom.xml new file mode 100644 index 000000000..d012646ed --- /dev/null +++ b/jun_api_online/jun_api/bizservice/pom.xml @@ -0,0 +1,79 @@ + + + 4.0.0 + + com.jun.plugin + bizservice + 1.0 + jar + 示例业务模块 + + + + com.jun.plugin + jun_common + 1.0 + + + org.apache.shiro + shiro-core + 1.13.0 + compile + + + org.mybatis + mybatis-spring + 3.0.0 + compile + + + com.baomidou + mybatis-plus-core + 3.5.3.2 + compile + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/Base64.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/Base64.java new file mode 100644 index 000000000..ad0965efb --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/Base64.java @@ -0,0 +1,80 @@ +package com.jun.plugin.bizservice; + + +import org.apache.commons.io.FileUtils; +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.charset.StandardCharsets; +import java.util.zip.GZIPInputStream; + +import sun.misc.BASE64Decoder; +import sun.misc.BASE64Encoder; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; +import java.util.zip.GZIPOutputStream; + +public class Base64 implements Serializable { + public static void main(String[] args) throws IOException { + + File file = new File("C:\\Users\\whbj_wujun\\Desktop\\base64.txt"); + String content = FileUtils.readFileToString(file,StandardCharsets.UTF_8); + //String content = "" + ""; + String compressStr = Base64.compressBase64(content,StandardCharsets.UTF_8.toString()); + + File base64= new File("C:\\Users\\whbj_wujun\\Desktop\\base64-v2.txt"); + FileUtils.writeByteArrayToFile(base64,compressStr.getBytes(StandardCharsets.UTF_8)); + System.out.println(compressStr); +// System.out.println("11111111111111111111111111111111111111111111111111111L"); +// System.out.println(Base64.decodeGzipBase64(compressStr)); + } + + public static String compressBase64(String str, String charset) throws IOException { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + try { + GZIPOutputStream gzip = new GZIPOutputStream(out); + gzip.write(str.getBytes(charset)); + if (gzip != null) { + gzip.close(); + } + BASE64Encoder baseEn = new BASE64Encoder(); + String zipStr = baseEn.encode(out.toByteArray()); + return zipStr; + } catch (Exception e) { + throw new IOException(e); + } finally { + if (out != null) { + out.close(); + } + } + } + + public static String decodeGzipBase64(String str){ + ByteArrayOutputStream out =new ByteArrayOutputStream(); + BASE64Decoder baseDe =new BASE64Decoder(); + try { + byte [] bytes=baseDe.decodeBuffer(str); + + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes); + GZIPInputStream gzip = new GZIPInputStream(byteArrayInputStream); + byte [] b =new byte[128]; + int n; + while ((n=gzip.read(b))>=0){ + out.write(b,0,n); + } + }catch (Exception e){ + return null; + } + return out.toString(); + } + + +} + diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/config/BizAutoConfig.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/config/BizAutoConfig.java new file mode 100644 index 000000000..8f45a370b --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/config/BizAutoConfig.java @@ -0,0 +1,15 @@ +package com.jun.plugin.bizservice.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.bizservice") +@MapperScan(basePackages = "com.jun.plugin.bizservice.mapper") +public class BizAutoConfig { +} diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/controller/BizTestController.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/controller/BizTestController.java new file mode 100644 index 000000000..bb425547c --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/controller/BizTestController.java @@ -0,0 +1,100 @@ +package com.jun.plugin.bizservice.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.jun.plugin.common.Result; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.stereotype.Controller; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.core.metadata.IPage; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import java.util.List; + +import com.jun.plugin.bizservice.entity.BizTestEntity; +import com.jun.plugin.bizservice.service.BizTestService; + + + +/** + * 客户信息 + * + * @author wujun + * @email wujun728@mail.com + * @date 2022-02-28 16:28:58 + */ +@Controller +@RequestMapping("/public") +public class BizTestController { + @Autowired + private BizTestService bizTestService; + + + /** + * 跳转到页面 + */ + @GetMapping("/test") + @ResponseBody + public Result bizTest1() { + return Result.success("11111111111"); + } + /** + * 跳转到页面 + */ + @GetMapping("/json") + @ResponseBody + public Result bizTest2() { + return Result.success(getClass()); + } + + /** + * 跳转到页面 + */ + @GetMapping("/index/bizTest") + public String bizTest() { + return "biztest/list"; + } + + @ApiOperation(value = "新增") + @PostMapping("bizTest/add") + @RequiresPermissions("bizTest:add") + @ResponseBody + public Result add(@RequestBody BizTestEntity bizTest){ + bizTestService.save(bizTest); + return Result.success(); + } + + @ApiOperation(value = "删除") + @DeleteMapping("bizTest/delete") + @RequiresPermissions("bizTest:delete") + @ResponseBody + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids){ + bizTestService.removeByIds(ids); + return Result.success(); + } + + @ApiOperation(value = "更新") + @PutMapping("bizTest/update") + @RequiresPermissions("bizTest:update") + @ResponseBody + public Result update(@RequestBody BizTestEntity bizTest){ + bizTestService.updateById(bizTest); + return Result.success(); + } + + @ApiOperation(value = "查询分页数据") + @PostMapping("bizTest/listByPage") + @RequiresPermissions("bizTest:list") + @ResponseBody + public Result findListByPage(@RequestBody BizTestEntity bizTest){ + Page page = new Page(bizTest.getPage(), bizTest.getLimit()); + LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //queryWrapper.eq(BizTestEntity::getId, bizTest.getId()); + IPage iPage = bizTestService.page(page, queryWrapper); + return Result.success(iPage); + } + +} diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/entity/BizTestEntity.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/entity/BizTestEntity.java new file mode 100644 index 000000000..94d100343 --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/entity/BizTestEntity.java @@ -0,0 +1,94 @@ +package com.jun.plugin.bizservice.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.TableField; +import com.jun.plugin.common.entity.BaseEntity; + + +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Date; + +import lombok.Data; + +/** + * 客户信息 + * + * @author wujun + * @email wujun728@mail.com + * @date 2022-02-28 16:28:58 + */ +@Data +@TableName("biz_test") +public class BizTestEntity extends BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * + */ + @TableId("id") + private String id; + + /** + * 客户名称 + */ + @TableField("cusname") + private String cusname; + + /** + * 注册金额 + */ + @TableField("money") + private BigDecimal money; + + /** + * 客户描述 + */ + @TableField("cusdesc") + private String cusdesc; + + /** + * 客户全称 + */ + @TableField("fullname") + private String fullname; + + /** + * 客户性质 + */ + @TableField("dict_cussex") + private String dictCussex; + + /** + * 注册时间 + */ + @TableField("register_date") + private Date registerDate; + + /** + * 客户类型 + */ + @TableField("dict_custype") + private String dictCustype; + + /** + * + */ + @TableField("ref_id") + private String refId; + + /** + * 关联子客户名称 + */ + @TableField("ref_title_username") + private String refTitleUsername; + + /** + * 备注 + */ + @TableField("remark") + private String remark; + + +} diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/mapper/BizTestMapper.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/mapper/BizTestMapper.java new file mode 100644 index 000000000..675ff62f7 --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/mapper/BizTestMapper.java @@ -0,0 +1,16 @@ +package com.jun.plugin.bizservice.mapper; + +import com.jun.plugin.bizservice.entity.BizTestEntity; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; + +/** + * 客户信息 + * + * @author wujun + * @email wujun728@mail.com + * @date 2022-02-28 16:28:58 + */ +public interface BizTestMapper extends BaseMapper { + +} diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/BizTestService.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/BizTestService.java new file mode 100644 index 000000000..c924bc19f --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/BizTestService.java @@ -0,0 +1,16 @@ +package com.jun.plugin.bizservice.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.jun.plugin.bizservice.entity.BizTestEntity; + +/** + * 客户信息 + * + * @author wujun + * @email wujun728@mail.com + * @date 2022-02-28 16:28:58 + */ +public interface BizTestService extends IService { + +} + diff --git a/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/impl/BizTestServiceImpl.java b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/impl/BizTestServiceImpl.java new file mode 100644 index 000000000..edd4ec4a8 --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/java/com/jun/plugin/bizservice/service/impl/BizTestServiceImpl.java @@ -0,0 +1,15 @@ +package com.jun.plugin.bizservice.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import com.jun.plugin.bizservice.mapper.BizTestMapper; +import com.jun.plugin.bizservice.entity.BizTestEntity; +import com.jun.plugin.bizservice.service.BizTestService; + + +@Service("bizTestService") +public class BizTestServiceImpl extends ServiceImpl implements BizTestService { + + +} \ No newline at end of file diff --git a/jun_api_online/jun_api/bizservice/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_api/bizservice/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..4983c2e99 --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.bizservice.config.BizAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_api/bizservice/src/main/resources/mapper/BizTestMapper.xml b/jun_api_online/jun_api/bizservice/src/main/resources/mapper/BizTestMapper.xml new file mode 100644 index 000000000..94245a63b --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/resources/mapper/BizTestMapper.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_api/bizservice/src/main/resources/templates/biztest/list.html b/jun_api_online/jun_api/bizservice/src/main/resources/templates/biztest/list.html new file mode 100644 index 000000000..8339baa84 --- /dev/null +++ b/jun_api_online/jun_api/bizservice/src/main/resources/templates/biztest/list.html @@ -0,0 +1,300 @@ + + + + + Title + + + + + + + + + + + 客户名称 + + + + + + 注册金额 + + + + + + 客户描述 + + + + + + 客户全称 + + + + + + 客户性质 + + + + + + 注册时间 + + + + + + 客户类型 + + + + + + + + + + + + 关联子客户名称 + + + + + + 备注 + + + + + + + 保存 + 返回 + + + + + + + + + + + + + + + 查询 + 导出全部 + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_api/pom.xml b/jun_api_online/jun_api/pom.xml new file mode 100644 index 000000000..44e2db5a9 --- /dev/null +++ b/jun_api_online/jun_api/pom.xml @@ -0,0 +1,15 @@ + + + 4.0.0 + com.jun.plugin + jun_api + pom + 1.0 + 业务功能模块 + + + bizservice + + \ No newline at end of file diff --git a/jun_api_online/jun_common/pom.xml b/jun_api_online/jun_common/pom.xml new file mode 100644 index 000000000..18a0766e5 --- /dev/null +++ b/jun_api_online/jun_common/pom.xml @@ -0,0 +1,66 @@ + + + 4.0.0 + + com.jun.plugin + jun_common + 1.0 + jar + 公共模块 + + + + io.github.wujun728 + jun-common + 1.0.15 + + + io.github.wujun728 + jun-groovy-api-spring-boot-starter + 1.0.15 + + + com.github.xiaoymin + knife4j-spring-boot-starter + 2.0.2 + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_common/src/main/java/com/jun/plugin/bizservice/config/CommonAutoConfig.java b/jun_api_online/jun_common/src/main/java/com/jun/plugin/bizservice/config/CommonAutoConfig.java new file mode 100644 index 000000000..79578f539 --- /dev/null +++ b/jun_api_online/jun_common/src/main/java/com/jun/plugin/bizservice/config/CommonAutoConfig.java @@ -0,0 +1,15 @@ +package com.jun.plugin.bizservice.config; + +//import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.bizservice") +//@MapperScan(basePackages = "com.jun.plugin.bizservice.mapper") +public class CommonAutoConfig { +} diff --git a/jun_api_online/jun_common/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_common/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..ba7a25eaa --- /dev/null +++ b/jun_api_online/jun_common/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.bizservice.config.CommonAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_generator/pom.xml b/jun_api_online/jun_generator/pom.xml new file mode 100644 index 000000000..e494b65f1 --- /dev/null +++ b/jun_api_online/jun_generator/pom.xml @@ -0,0 +1,119 @@ + + + 4.0.0 + + com.jun.plugin + 1.0 + jun_generator + jar + 代码生成器 + + + + UTF-8 + 1.8 + 1.8 + + + + + com.jun.plugin + jun_common + 1.0 + + + + com.baomidou + mybatis-plus-generator + 3.5.3.1 + + + com.baomidou + mybatis-plus-core + 3.5.3.2 + compile + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + velocity + org.apache.velocity + 1.7 + + + commons-configuration + commons-configuration + 1.10 + compile + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + jdk-1.8 + + true + 1.8 + + + 1.8 + 1.8 + 1.8 + + + + + + + + + src/main/resources + true + + + src/main/java + + **/*.tpl + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/AutoConfigModel.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/AutoConfigModel.java new file mode 100644 index 000000000..e09842c9c --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/AutoConfigModel.java @@ -0,0 +1,45 @@ +//package com.jun.plugin.system.code; +// +//import java.util.List; +// +///** +// */ +//public class AutoConfigModel { +// /**表名称**/ +// private String tableName; +// /**表描述**/ +// private String tableComment; +// +// private List beanColumns; +// public String getTableName() { +// return tableName; +// } +// public void setTableName(String tableName) { +// this.tableName = tableName; +// } +// public String getTableComment() { +// return tableComment; +// } +// public void setTableComment(String tableComment) { +// this.tableComment = tableComment; +// } +// +// public AutoConfigModel() { +// super(); +// } +// public List getBeanColumns() { +// return beanColumns; +// } +// public void setBeanColumns(List beanColumns) { +// this.beanColumns = beanColumns; +// } +// public AutoConfigModel(String tableName, String tableComment, +// List beanColumns) { +// super(); +// this.tableName = tableName; +// this.tableComment = tableComment; +// this.beanColumns = beanColumns; +// } +// +// +//} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/BeanColumn.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/BeanColumn.java new file mode 100644 index 000000000..e8d2476bb --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/BeanColumn.java @@ -0,0 +1,509 @@ +package com.jun.plugin.generator.code; + + +/** + * 实体列 + */ +public class BeanColumn { + public String getDictTypeName() { + return dictTypeName; + } + + public void setDictTypeName(String dictTypeName) { + this.dictTypeName = dictTypeName; + } + + + + /** 表\目录 **/ + private String table_catalog; + /** 是否为null **/ + private String is_nullable; + /** 表名 **/ + private String table_name; + /** 数据库 **/ + private String table_schema; + /** 额外的 EXTRA": "auto_increment 自增id **/ + private String extra; + /** 列名 **/ + private String column_name; + /**主键 PRI**/ + private String column_key; + /**数字精度**/ + private String numeric_precision; + /**权限**/ + private String privileges; + /**列注释**/ + private String column_comment; + /**数字刻度**/ + private String numeric_scale; + /**列/类型**/ + private String column_type; + /**生成表达式**/ + private String generation_expression; + /**序数位置**/ + private String ordinal_position; + /**数据类型**/ + private String data_type; + /**默认值**/ + private String column_default; + /**字符最大长度**/ + private String character_maximum_length; + /**字符\八位字节\长度**/ + private String character_octet_length; + /**日期时间精度**/ + private String datetime_precision; + /**字符集名称**/ + private String character_set_name; + /**排序规则名称**/ + private String collation_name; + + /**实体类型 java.lang.String**/ + private String beanType; + + /**实体bean列名 例如:nameVc **/ + private String beanName; + /**mapperxml需要类型 例如:jdbcType="VARCHAR" **/ + private String jdbcType; + + /**java类型**/ + private String javaType; + /**java 首字母大写**/ + private String javaName; + + private Integer htmlType=1;//是字符串类型 + + //字典表名字 + private String dictTypeName; + /**字典表里面的数据**/ + + enum htmlType{ + //字符串类型,labne类型,switch按钮类型,时间类型,上传类型 + STRING("String",1), + LABLE("lable",2), + SWITCH("switch",3), + TIME("time",4), + UPLOAD("upload",5); + + htmlType(String type, int value) { + this.type = type; + this.value = value; + } + public String type; + public int value; + + } + + + public BeanColumn() { + super(); + } + + public String getTable_catalog() { + return table_catalog; + } + + public void setTable_catalog(String table_catalog) { + this.table_catalog = table_catalog; + } + + public String getIs_nullable() { + return is_nullable; + } + + public void setIs_nullable(String is_nullable) { + this.is_nullable = is_nullable; + } + + public String getTable_name() { + return table_name; + } + + public void setTable_name(String table_name) { + this.table_name = table_name; + } + + public String getTable_schema() { + return table_schema; + } + + public void setTable_schema(String table_schema) { + this.table_schema = table_schema; + } + + public String getExtra() { + return extra; + } + + public void setExtra(String extra) { + this.extra = extra; + } + + public String getColumn_name() { + return column_name; + } + + public void setColumn_name(String column_name) { + this.column_name = column_name; + } + + public String getColumn_key() { + return column_key; + } + + public void setColumn_key(String column_key) { + this.column_key = column_key; + } + + public String getNumeric_precision() { + return numeric_precision; + } + + public void setNumeric_precision(String numeric_precision) { + this.numeric_precision = numeric_precision; + } + + public String getPrivileges() { + return privileges; + } + + public void setPrivileges(String privileges) { + this.privileges = privileges; + } + + public String getColumn_comment() { + return column_comment; + } + + public void setColumn_comment(String column_comment) { + this.column_comment = column_comment; + } + + public String getNumeric_scale() { + return numeric_scale; + } + + public void setNumeric_scale(String numeric_scale) { + this.numeric_scale = numeric_scale; + } + + public String getColumn_type() { + return column_type; + } + + public void setColumn_type(String column_type) { + this.column_type = column_type; + } + + public String getGeneration_expression() { + return generation_expression; + } + + public void setGeneration_expression(String generation_expression) { + this.generation_expression = generation_expression; + } + + public String getOrdinal_position() { + return ordinal_position; + } + + public void setOrdinal_position(String ordinal_position) { + this.ordinal_position = ordinal_position; + } + + public String getData_type() { + return data_type; + } + + public void setData_type(String data_type) { + this.data_type = data_type; + } + + public String getColumn_default() { + return column_default; + } + + public void setColumn_default(String column_default) { + this.column_default = column_default; + } + + public String getCharacter_maximum_length() { + return character_maximum_length; + } + + public void setCharacter_maximum_length(String character_maximum_length) { + this.character_maximum_length = character_maximum_length; + } + + public String getCharacter_octet_length() { + return character_octet_length; + } + + public void setCharacter_octet_length(String character_octet_length) { + this.character_octet_length = character_octet_length; + } + + public String getDatetime_precision() { + return datetime_precision; + } + + public void setDatetime_precision(String datetime_precision) { + this.datetime_precision = datetime_precision; + } + + public String getCharacter_set_name() { + return character_set_name; + } + + public void setCharacter_set_name(String character_set_name) { + this.character_set_name = character_set_name; + } + + public String getCollation_name() { + return collation_name; + } + + public void setCollation_name(String collation_name) { + this.collation_name = collation_name; + } + + public String getJavaType() { + String beanType=this.getBeanType(); + String returnStr="String"; + if(beanType==null) { + return returnStr; + }else { + returnStr=beanType.substring(beanType.lastIndexOf(".")+1,beanType.length()); + } + javaType=returnStr; + return javaType; + } + + public void setJavaType(String javaType) { + this.javaType = javaType; + } + + public String getBeanType() { + String type=this.getData_type(); + String returnStr="java.lang.String"; + if(type==null) { + return returnStr; + } + switch(type) { + case "tinyint" : + returnStr="java.lang.Integer"; + break; + case "smallint" : + returnStr="java.lang.Integer"; + break; + case "int" : + returnStr="java.lang.Integer"; + break; + case "bigint" : + returnStr="java.lang.Long"; + break; + case "mediumint" : + returnStr="java.lang.Integer"; + break; + case "integer" : + returnStr="java.lang.Integer"; + break; + case "float" : + returnStr="java.lang.Float"; + break; + case "double" : + returnStr="java.lang.Double"; + break; + case "decimal" : + returnStr="java.math.BigDecimal"; + break; + case "bit" : + returnStr="java.lang.Byte"; + break; + case "char" : + returnStr="java.lang.Character"; + break; + case "varchar" : + returnStr="java.lang.String"; + break; + case "tinytext" : + returnStr="java.lang.String"; + break; + case "text" : + returnStr="java.lang.String"; + break; + case "mediumtext" : + returnStr="java.lang.String"; + break; + case "longtext" : + returnStr="java.lang.String"; + break; + case "date" : + returnStr="java.util.Date"; + break; + case "datetime" : + returnStr="java.util.Date"; + break; + case "timestamp" : + returnStr="java.util.Date"; + break; + default: + break; + } + beanType=returnStr; + return beanType; + } + + public void setBeanType(String beanType) { + this.beanType = beanType; + } + + public String getBeanName() { + if(getColumn_name()!=null) { + return StringUtils.upperCase_(this.column_name,false); + } + return beanName; + } + public void setBeanName(String beanName) { + this.beanName = beanName; + } + public String getJavaName() { + javaName=StringUtils.firstUpperCase(getBeanName()); + return javaName; + } + + public void setJavaName(String javaName) { + this.javaName = javaName; + } + + public String getJdbcType() { + String datetype=getData_type(); + String returnStr="VARCHAR"; + if(datetype==null) { + return returnStr; + } + switch(datetype) { + case "tinyint" : + returnStr="TINYINT"; + break; + case "smallint" : + returnStr="SMALLINT"; + break; + case "int" : + returnStr="INTEGER"; + break; + case "bigint" : + returnStr="BIGINT"; + break; + case "mediumint" : + returnStr="INTEGER"; + break; + case "integer" : + returnStr="INTEGER"; + break; + case "float" : + returnStr="REAL"; + break; + case "double" : + returnStr="DOUBLE"; + break; + case "decimal" : + returnStr="DECIMAL"; + break; + case "bit" : + returnStr="OTHER"; + break; + case "char" : + returnStr="CHAR"; + break; + case "varchar" : + returnStr="VARCHAR"; + break; + case "tinytext" : + returnStr="VARCHAR"; + break; + case "text" : + returnStr="VARCHAR"; + break; + case "mediumtext" : + returnStr="VARCHAR"; + break; + case "longtext" : + returnStr="VARCHAR"; + break; + case "date" : + returnStr="TIMESTAMP"; + break; + case "datetime" : + returnStr="TIMESTAMP"; + break; + case "timestamp" : + returnStr="TIMESTAMP"; + break; + default: + break; + } + jdbcType=returnStr; + return jdbcType; + } + + public void setJdbcType(String jdbcType) { + this.jdbcType = jdbcType; + } + + public BeanColumn(String table_catalog, String is_nullable, String table_name, String table_schema, String extra, + String column_name, String column_key, String numeric_precision, String privileges, String column_comment, + String numeric_scale, String column_type, String generation_expression, String ordinal_position, + String data_type, String column_default, String character_maximum_length, String character_octet_length, + String datetime_precision, String character_set_name, String collation_name,String htmlType,String dictTypeName + + ) { + super(); + this.table_catalog = table_catalog; + this.is_nullable = is_nullable; + this.table_name = table_name; + this.table_schema = table_schema; + this.extra = extra; + this.column_name = column_name; + this.column_key = column_key; + this.numeric_precision = numeric_precision; + this.privileges = privileges; + this.column_comment = column_comment; + this.numeric_scale = numeric_scale; + this.column_type = column_type; + this.generation_expression = generation_expression; + this.ordinal_position = ordinal_position; + this.data_type = data_type; + this.column_default = column_default; + this.character_maximum_length = character_maximum_length; + this.character_octet_length = character_octet_length; + this.datetime_precision = datetime_precision; + this.character_set_name = character_set_name; + this.collation_name = collation_name; + this.beanType = getBeanType(); + this.beanName = getBeanName(); + this.jdbcType=getJdbcType(); + this.javaType=getJavaType(); + this.javaName=getJavaName(); + this.htmlType=getHtmlType(); + this.dictTypeName=getDictTypeName(); + } + + public Integer getHtmlType() { + return htmlType; + } + + public void setHtmlType(Integer htmlType) { + this.htmlType = htmlType; + } + + + + + + + + + + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/StringUtils.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/StringUtils.java new file mode 100644 index 000000000..94d371d8f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/StringUtils.java @@ -0,0 +1,98 @@ +package com.jun.plugin.generator.code; + + + + + +/** + * 字符串工具类 + * + * @author fc + */ +public class StringUtils extends org.apache.commons.lang3.StringUtils +{ + /** 空字符串 */ + private static final String NULLSTR = ""; + + + + + + + + + /** + * * 判断一个字符串是否为空串 + * + * @param str String + * @return true:为空 false:非空 + */ + public static boolean isEmpty(String str) + { + return isNull(str) || NULLSTR.equals(str.trim()); + } + + /** + * * 判断一个对象是否为空 + * + * @param object Object + * @return true:为空 false:非空 + */ + public static boolean isNull(Object object) + { + return object == null; + } + + + + + + /** + * 首字母大写 + * + * @param name + * @return + */ + public static String firstUpperCase(String name) { + name = name.substring(0, 1).toUpperCase() + name.substring(1); + return name; + } + /** + * 首字母小写 + * + * @param name + * @return + */ + public static String firstLowerCase(String name) { + name = name.substring(0, 1).toLowerCase() + name.substring(1); + return name; + + } + + /** + * 将下划线转化为大写 + * + * @param name + * @param firstCase 首字母是否大写 true:大写 false;小写 + * @return + */ + public static String upperCase_(String name, boolean firstCase) { + if(isEmpty(name)){ + return ""; + } + String[] s = name.split("_"); + StringBuffer stringBuffer = new StringBuffer(); + for (String s1 : s) { + stringBuffer.append(s1.substring(0, 1).toUpperCase() + s1.substring(1)); + } + if(!firstCase){ + return firstLowerCase(stringBuffer.toString()); + } + return stringBuffer.toString(); + } + + + + + +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TableInfo.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TableInfo.java new file mode 100644 index 000000000..bc9d77376 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TableInfo.java @@ -0,0 +1,141 @@ +package com.jun.plugin.generator.code; + +import com.jun.plugin.generator.utils.GenUtils; +import org.apache.commons.lang.WordUtils; + +import java.util.List; +import java.util.Objects; + +/** + * 数据库表对象 + */ +public class TableInfo { + + /** + * 数据库表名字 t_fifle + */ + private String tableName; + + /** + * java表名字例如 SysOperLog + */ + private String javaTableName; + + /** + * 数据表注释 例如文件管理系统 + */ + private String tableComment; + + /** + * java表名字例如 sysOperLog + */ + private String javaTableName_a; + + /** + * 字段集合 + */ + List beanColumns; + + /** + * Entity基类字段 + */ + public static final String[] BASE_ENTITY = {"createBy" , "createTime" , "updateBy" , "updateTime" , "remark"}; + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getJavaTableName() { + return javaTableName; + } + + public void setJavaTableName(String javaTableName) { + this.javaTableName = javaTableName; + } + + public List getBeanColumns() { + return beanColumns; + } + + public void setBeanColumns(List beanColumns) { + this.beanColumns = beanColumns; + } + + public String getTableComment() { + return tableComment; + } + + public void setTableComment(String tableComment) { + this.tableComment = tableComment; + } + + public String getJavaTableName_a() { + return javaTableName_a; + } + + public void setJavaTableName_a(String javaTableName_a) { + this.javaTableName_a = javaTableName_a; + } + + public TableInfo(String tableName, List beanColumns, String tableComment) { + super(); + this.tableName = tableName; + this.javaTableName = tableToJava(tableName); + this.beanColumns = beanColumns; + this.tableComment = tableComment; + this.javaTableName_a = tableToJava_a(tableName); + } + + public TableInfo() { + super(); + } + + /** + * 列名转换成Java属性名 + * + * @param columnName + * @return + */ + public String columnToJava(String columnName) { + return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_" , ""); + } + + /** + * 表名转换成Java类名 + * + * @param tableName + * @return + */ + public String tableToJava(String tableName) { + String tablePrefix = Objects.requireNonNull(GenUtils.getConfig().getString("tablePrefix")); + if (StringUtils.isNotBlank(tablePrefix)) { + tableName = tableName.replaceFirst(tablePrefix, ""); + } + return columnToJava(tableName); + } + + /** + * 首字母小写 + * + * @param tableName + * @return + */ + public String tableToJava_a(String tableName) { + String str = tableToJava(tableName); + return StringUtils.firstLowerCase(str); + } + + /** + * + * + * @param javaField + * @return + */ + public static boolean isSuperColumn(String javaField) { + return StringUtils.equalsAnyIgnoreCase(javaField, BASE_ENTITY); + } +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TsysTables.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TsysTables.java new file mode 100644 index 000000000..c7a491e68 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/code/TsysTables.java @@ -0,0 +1,59 @@ +package com.jun.plugin.generator.code; + +import com.fasterxml.jackson.annotation.JsonFormat; + +import java.io.Serializable; +import java.util.Date; + + +public class TsysTables implements Serializable{ + private static final long serialVersionUID = 1L; + private String tableName;//表名 + private String engine;//表引擎 + private String tableComment;//表注释 + private String tableModel;//表实体名字 + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8") + private Date createTime; + public String getTableName() { + return tableName; + } + public void setTableName(String tableName) { + this.tableName = tableName; + } + public String getEngine() { + return engine; + } + public void setEngine(String engine) { + this.engine = engine; + } + public String getTableComment() { + return tableComment; + } + public void setTableComment(String tableComment) { + this.tableComment = tableComment; + } + public String getTableModel() { + return tableModel; + } + public void setTableModel(String tableModel) { + this.tableModel = tableModel; + } + public Date getCreateTime() { + return createTime; + } + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + public TsysTables(String tableName, String engine, String tableComment, String tableModel, Date createTime) { + super(); + this.tableName = tableName; + this.engine = engine; + this.tableComment = tableComment; + this.tableModel = tableModel; + this.createTime = createTime; + } + public TsysTables() { + super(); + } + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/config/DevtoolsAutoConfig.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/config/DevtoolsAutoConfig.java new file mode 100644 index 000000000..ba06d41dd --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/config/DevtoolsAutoConfig.java @@ -0,0 +1,15 @@ +package com.jun.plugin.generator.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@ComponentScan(basePackages = "com.jun.plugin.generator") +@MapperScan(basePackages = "com.jun.plugin.generator.mapper") +@Configuration +public class DevtoolsAutoConfig { +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/CodeController.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/CodeController.java new file mode 100644 index 000000000..96ffd30bf --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/CodeController.java @@ -0,0 +1,42 @@ +package com.jun.plugin.generator.controller; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.db.meta.MetaUtil; +import cn.hutool.db.meta.Table; +import cn.hutool.extra.spring.SpringUtil; +import com.jun.plugin.common.Result; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import javax.sql.DataSource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@RestController +@RequestMapping("/code") +public class CodeController { + + //RestServiceController + + @GetMapping("/getTableList") + public Result getTableList(){ + DataSource dataSource = SpringUtil.getBean(DataSource.class); + List tables = MetaUtil.getTables(dataSource); + List tablemap = new ArrayList<>(); + for(String tab : tables){ + Table table = MetaUtil.getTableMeta(dataSource,tab); + Map map = new HashMap(){{ + put("tableName",table.getTableName()); + put("tableComment",table.getComment()); + put("createTime", DateUtil.now()); + put("updateTime", DateUtil.now()); + }}; + tablemap.add(map); + } + return Result.success(tablemap); + } + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/SysGeneratorController.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/SysGeneratorController.java new file mode 100644 index 000000000..c2fc6d349 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/controller/SysGeneratorController.java @@ -0,0 +1,127 @@ +package com.jun.plugin.generator.controller; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +//import com.jun.plugin.common.utils.DataResult; +import com.jun.plugin.common.Result; +import com.jun.plugin.generator.code.BeanColumn; +import com.jun.plugin.generator.code.TableInfo; +import com.jun.plugin.generator.entity.SysGenerator; +import com.jun.plugin.generator.service.ISysGeneratorService; +import com.jun.plugin.generator.utils.GenUtils; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; +//import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.ui.ModelMap; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipOutputStream; + +/** + * 代码生成 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Api(tags = "系统模块-代码生成") +@Slf4j +@Controller +@RequestMapping("/sysGenerator") +public class SysGeneratorController { + @Resource + private ISysGeneratorService sysGeneratorService; + + private String prefix = "generator"; +// @Autowired +// private ITGeneratorService generatorService; + + /** + * 生成代码 + */ + @ApiOperation(value = "生成") + @GetMapping("/gen") +// //@RequiresPermissions("sysGenerator:add") + @ResponseBody + public void code(String tables, HttpServletResponse response) throws IOException { + byte[] data = sysGeneratorService.generatorCode(tables.split(",")); + + response.reset(); + response.setHeader("Content-Disposition", "attachment; filename=\""+tables+".zip\""); + response.addHeader("Content-Length", "" + data.length); + response.setContentType("application/octet-stream; charset=UTF-8"); + + IOUtils.write(data, response.getOutputStream()); + } + + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPage") + //@RequiresPermissions("sysGenerator:list") + @ResponseBody + public Result findListByPage(@RequestBody SysGenerator vo) { + Page page = new Page(vo.getPage(), vo.getLimit()); + IPage iPage = sysGeneratorService.selectAllTables(page, vo); + return Result.success(iPage); + } + + + /** + * 生成文件Zip + * + * @throws IOException + * @author fuce + * @Date 2021年1月15日 下午2:21:55 + */ + @GetMapping("/createAutoZip") + @ResponseBody + public void createAutoZip(String tableName,String tableComment, HttpServletResponse response) throws IOException { + byte[] b; + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + // 根据表名查询表字段集合 + List list = sysGeneratorService.queryColumns2(tableName); + // 初始化表信息 + TableInfo tableInfo = new TableInfo(tableName, list, tableComment); + // 自动生成 + GenUtils.autoCodeOneModel(tableInfo, tableName,tableComment, zip); + IOUtils.closeQuietly(zip); + b = outputStream.toByteArray(); + response.reset(); + response.setHeader("Content-Disposition", "attachment; filename=\""+tableName+".zip\""); + response.addHeader("Content-Length", "" + b.length); + response.setContentType("application/octet-stream; charset=UTF-8"); + IOUtils.write(b, response.getOutputStream()); + } + + + /** + * 预览生成文件 + * + * @author fuce + * @Date 2021年1月15日 下午2:21:55 + */ + @GetMapping("/viewAuto") + public String viewAuto(@RequestParam String tableName ,String tableComment, ModelMap model) { + List list = sysGeneratorService.queryColumns2(tableName); + TableInfo tableInfo = new TableInfo(tableName, list, tableComment);//获取表信息 + //查询表信息 + Map table = sysGeneratorService.queryTable(tableName); + //查询列信息 + List> columns = sysGeneratorService.queryColumns(tableName); + //生成代码VIEW + Map map = GenUtils.generatorCode(table, columns, null,true); + model.put("viewmap", map); + return "generator/view"; + } + + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/ColumnEntity.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/ColumnEntity.java new file mode 100644 index 000000000..d50f1a865 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/ColumnEntity.java @@ -0,0 +1,115 @@ +package com.jun.plugin.generator.entity; + +import lombok.Data; + +/** + * 代码生成 列属性 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Data +public class ColumnEntity { + /** + * 列名 + */ + private String columnName; + + /** + * 列名类型 + */ + private String dataType; + + /** + * 列名备注 + */ + private String comments; + + /** + * 属性名称(第一个字母大写),如:user_name => UserName + */ + private String attrName; + + /** + * 属性名称(第一个字母小写),如:user_name => userName + */ + private String attrname; + + /** + * 属性类型 + */ + private String attrType; + + /** + * 属性长度 + */ + private String maxLength; + + /** + * 属性是否必填 + */ + private String isNull; + + /** + * auto_increment + */ + private String extra; + + public String getColumnName() { + return columnName; + } + + public void setColumnName(String columnName) { + this.columnName = columnName; + } + + public String getDataType() { + return dataType; + } + + public void setDataType(String dataType) { + this.dataType = dataType; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public String getAttrname() { + return attrname; + } + + public void setAttrname(String attrname) { + this.attrname = attrname; + } + + public String getAttrName() { + return attrName; + } + + public void setAttrName(String attrName) { + this.attrName = attrName; + } + + public String getAttrType() { + return attrType; + } + + public void setAttrType(String attrType) { + this.attrType = attrType; + } + + public String getExtra() { + return extra; + } + + public void setExtra(String extra) { + this.extra = extra; + } + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/SysGenerator.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/SysGenerator.java new file mode 100644 index 000000000..f46cdb6a0 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/SysGenerator.java @@ -0,0 +1,34 @@ +package com.jun.plugin.generator.entity; + +import com.jun.plugin.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; +import lombok.experimental.Accessors; + +import java.io.Serializable; +import java.util.Date; + +import com.fasterxml.jackson.annotation.JsonFormat; + +/** + * 代码生成 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Accessors(chain = true) +public class SysGenerator extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + + private String tableName; + + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") + private Date createTime; + + private String tableComment; + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/TableEntity.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/TableEntity.java new file mode 100644 index 000000000..6ac4e0b43 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/entity/TableEntity.java @@ -0,0 +1,84 @@ +package com.jun.plugin.generator.entity; + +import java.util.List; + +/** + * 代码生成 表数据 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public class TableEntity { + //表的名称 + private String tableName; + //表的备注 + private String comments; + //表的主键 + private ColumnEntity pk; + //表的列名(不包含主键) + private List columns; + + //类名(第一个字母大写),如:sys_user => SysUser + private String className; + //类名(第一个字母小写),如:sys_user => sysUser + private String classname; + //类名(都小写),如:sys_user => sysuser + private String classNameLower; + + public String getTableName() { + return tableName; + } + + public void setTableName(String tableName) { + this.tableName = tableName; + } + + public String getComments() { + return comments; + } + + public void setComments(String comments) { + this.comments = comments; + } + + public ColumnEntity getPk() { + return pk; + } + + public void setPk(ColumnEntity pk) { + this.pk = pk; + } + + public List getColumns() { + return columns; + } + + public void setColumns(List columns) { + this.columns = columns; + } + + public String getClassName() { + return className; + } + + public void setClassName(String className) { + this.className = className; + } + + public String getClassname() { + return classname; + } + + public void setClassname(String classname) { + this.classname = classname; + } + + public String getClassNameLower() { + return classNameLower; + } + + public void setClassNameLower(String classNameLower) { + this.classNameLower = classNameLower; + } +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/mapper/GeneratorMapper.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/mapper/GeneratorMapper.java new file mode 100644 index 000000000..c48ddca80 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/mapper/GeneratorMapper.java @@ -0,0 +1,45 @@ +package com.jun.plugin.generator.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.generator.code.BeanColumn; +import com.jun.plugin.generator.code.TsysTables; +import com.jun.plugin.generator.entity.SysGenerator; + +import org.apache.ibatis.annotations.Param; + +import java.util.List; +import java.util.Map; + +/** + * 代码生成 Mapper + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface GeneratorMapper extends BaseMapper { + + IPage selectAllTables(Page page, @Param(value = "vo") SysGenerator vo); + + Map queryTable(String tableName); + + List> queryColumns(String tableName); + + + /** + * 查询当前所有表 + * @param tableName 条件搜索 + * @return + */ + List queryList(String tableName); + + /** + * 查询表详情 + * @param tableName + * @return + */ + List queryColumns2(String tableName); + List> queryColumns3(String tableName); +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/ISysGeneratorService.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/ISysGeneratorService.java new file mode 100644 index 000000000..a96c5d668 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/ISysGeneratorService.java @@ -0,0 +1,61 @@ +package com.jun.plugin.generator.service; + +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.generator.code.BeanColumn; +import com.jun.plugin.generator.code.TsysTables; +import com.jun.plugin.generator.entity.SysGenerator; + +import java.util.List; +import java.util.Map; + +/** + * 代码生成 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface ISysGeneratorService { + + /** + * 获取所有表 + * + * @param page page + * @param vo vo + * @return IPage + */ + IPage selectAllTables(Page page, SysGenerator vo); + + /** + * 生成代码 + * + * @param tables tables + * @return byte[] + */ + byte[] generatorCode(String[] tables); + + + Map queryTable(String tableName); + + List> queryColumns(String tableName); + + /** + * 查询具体某表信息 + * + * @param tableName + * @return + */ + public List queryList(String tableName); + + /** + * 查询表详情 + * + * @param tableName + * @return + */ + public List queryColumns2(String tableName); + + + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/impl/SysGeneratorServiceImpl.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/impl/SysGeneratorServiceImpl.java new file mode 100644 index 000000000..874db789c --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/service/impl/SysGeneratorServiceImpl.java @@ -0,0 +1,96 @@ +package com.jun.plugin.generator.service.impl; + +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.generator.code.BeanColumn; +import com.jun.plugin.generator.code.TsysTables; +import com.jun.plugin.generator.entity.SysGenerator; +import com.jun.plugin.generator.mapper.GeneratorMapper; +import com.jun.plugin.generator.service.ISysGeneratorService; +import com.jun.plugin.generator.utils.GenUtils; + +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.io.IOUtils; +import org.springframework.stereotype.Service; + +import javax.annotation.Resource; +import java.io.ByteArrayOutputStream; +import java.util.List; +import java.util.Map; +import java.util.zip.ZipOutputStream; + +/** + * 代码生成 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Service +@Slf4j +public class SysGeneratorServiceImpl implements ISysGeneratorService { + @Resource + GeneratorMapper generatorMapper; + +// public SysGeneratorServiceImpl(GeneratorMapper generatorMapper) { +// this.generatorMapper = generatorMapper; +// } + + @Override + public IPage selectAllTables(Page page, SysGenerator vo) { + return generatorMapper.selectAllTables(page, vo); + } + + @Override + public byte[] generatorCode(String[] tableNames) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ZipOutputStream zip = new ZipOutputStream(outputStream); + + for (String tableName : tableNames) { + //查询表信息 + Map table = queryTable(tableName); + //查询列信息 + List> columns = queryColumns(tableName); + //生成代码 + GenUtils.generatorCode(table, columns, zip,false); + } + IOUtils.closeQuietly(zip); + return outputStream.toByteArray(); + } + @Override + public Map queryTable(String tableName) { + return generatorMapper.queryTable(tableName); + } + @Override + public List> queryColumns(String tableName) { + return generatorMapper.queryColumns(tableName); + } + + + + /** + * 查询具体某表信息 + * + * @param tableName + * @return + */ + @Override + public List queryList(String tableName) { + return generatorMapper.queryList(tableName); + } + + /** + * 查询表详情 + * + * @param tableName + * @return + */ + @Override + public List queryColumns2(String tableName) { + System.out.println("queryColumns2>>>" + JSONUtil.toJsonPrettyStr(generatorMapper.queryColumns3(tableName))); + return generatorMapper.queryColumns2(tableName); + } + + +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/BuildController.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/BuildController.java new file mode 100644 index 000000000..fc8b198c8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/BuildController.java @@ -0,0 +1,27 @@ +package com.jun.plugin.generator.swagger; + +import org.springframework.stereotype.Controller; +import org.springframework.ui.Model; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +/** + * @author 小懒虫 + * @date 2018/8/14 + */ +@Controller +@RequestMapping("/dev/build") +public class BuildController { + + @GetMapping("/index") + public String index(Model model){ + return "/devtools/build/index"; + } + + @GetMapping("/test111") + @ResponseBody + public String test1(Model model){ + return "1111"; + } +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/SwaggerController.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/SwaggerController.java new file mode 100644 index 000000000..22d190d64 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/swagger/SwaggerController.java @@ -0,0 +1,19 @@ +package com.jun.plugin.generator.swagger; + +//import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.GetMapping; + +/** + * @author 小懒虫 + * @date 2018/12/9 + */ +@Controller +public class SwaggerController { + + @GetMapping("/dev/swagger") +// @RequiresPermissions("/dev/swagger") + public String index(){ + return "redirect:/doc.html"; + } +} diff --git a/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/utils/GenUtils.java b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/utils/GenUtils.java new file mode 100644 index 000000000..62be5837f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/java/com/jun/plugin/generator/utils/GenUtils.java @@ -0,0 +1,544 @@ +package com.jun.plugin.generator.utils; + +import cn.hutool.core.date.DateTime; +import com.baomidou.mybatisplus.core.toolkit.IdWorker; +import com.jun.plugin.common.exception.BusinessException; + +import com.jun.plugin.common.utils.DateUtils; +import com.jun.plugin.generator.code.TableInfo; +import com.jun.plugin.generator.entity.ColumnEntity; +import com.jun.plugin.generator.entity.TableEntity; +import org.apache.commons.configuration.Configuration; +import org.apache.commons.configuration.ConfigurationException; +import org.apache.commons.configuration.PropertiesConfiguration; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.velocity.Template; +import org.apache.velocity.VelocityContext; +import org.apache.velocity.app.Velocity; + +import java.io.*; +import java.util.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipOutputStream; + +/** + * 代码生成器 工具类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public class GenUtils { + + static Configuration config = getConfig(); + + public static List getTemplates() { + if(false){ + return getTemplates2(); + }else{ + List templates = new ArrayList<>(); + templates.add("vm/Entity.java.vm"); + templates.add("vm/Dao.java.vm"); + templates.add("vm/Dao.xml.vm"); + templates.add("vm/Service.java.vm"); + templates.add("vm/ServiceImpl.java.vm"); + templates.add("vm/Controller.java.vm"); + templates.add("vm/menu.sql.vm"); + templates.add("vm/list.html.vm"); + return templates; + } + } + + public static List getTemplates2() { + List templates = new ArrayList(); + + //java代码模板 + templates.add("vm2/model/Entity.java.vm"); + //templates.add("auto_code/model/EntityExample.java.vm"); + templates.add("vm2/mapperxml/EntityMapper.xml.vm"); + templates.add("vm2/service/EntityService.java.vm"); + templates.add("vm2/service/impl/EntityServiceImpl.java.vm"); + templates.add("vm2/mapper/EntityMapper.java.vm"); + templates.add("vm2/controller/EntityController.java.vm"); + //前端模板 + templates.add("vm2/html/list.html.vm"); + templates.add("vm2/html/add.html.vm"); + templates.add("vm2/html/edit.html.vm"); + //sql模板 + templates.add("vm2/sql/menu.sql.vm"); + //templates.add("auto_code/说明.txt.vm"); + return templates; + } + + /** + * 生成代码 + */ + public static Map generatorCode(Map table, List> columns, ZipOutputStream zip,Boolean isView) { + Map velocityMap = new HashMap(); + + //配置信息 + Configuration config = getConfig(); + boolean hasBigDecimal = false; + //表信息 + TableEntity tableEntity = new TableEntity(); + tableEntity.setTableName(table.get("tableName")); + tableEntity.setComments(table.get("tableComment")); + //表名转换成Java类名 + String className = tableToJava(tableEntity.getTableName(), config.getStringArray("tablePrefix")); + tableEntity.setClassName(className); + tableEntity.setClassname(StringUtils.uncapitalize(className)); + tableEntity.setClassNameLower(className.toLowerCase()); + + //列信息 + List columsList = new ArrayList<>(); + for (Map column : columns) { + ColumnEntity columnEntity = new ColumnEntity(); + columnEntity.setColumnName(column.get("columnName")); + columnEntity.setDataType(column.get("dataType")); + columnEntity.setComments(column.get("columnComment")); + columnEntity.setExtra(column.get("extra")); + columnEntity.setMaxLength(String.valueOf(column.get("maxLength"))); + columnEntity.setIsNull(column.get("isNull")); + + //列名转换成Java属性名 + String attrName = columnToJava(columnEntity.getColumnName()); + columnEntity.setAttrName(attrName); + columnEntity.setAttrname(StringUtils.uncapitalize(attrName)); + + //列的数据类型,转换成Java类型 + String attrType = config.getString(columnEntity.getDataType(), "unknowType"); + columnEntity.setAttrType(attrType); + if (!hasBigDecimal && "BigDecimal".equals(attrType)) { + hasBigDecimal = true; + } + //是否主键 + if ("PRI".equalsIgnoreCase(column.get("columnKey")) && tableEntity.getPk() == null) { + tableEntity.setPk(columnEntity); + } + + columsList.add(columnEntity); + } + tableEntity.setColumns(columsList); + + //没主键,则第一个字段为主键 + if (tableEntity.getPk() == null) { + tableEntity.setPk(tableEntity.getColumns().get(0)); + } + + //设置velocity资源加载器 + Properties prop = new Properties(); + prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(prop); + String mainPath = config.getString("mainPath"); + mainPath = StringUtils.isBlank(mainPath) ? "com.jun.plugin" : mainPath; + //封装模板数据 + Map map = new HashMap<>(15); + map.put("tableName", tableEntity.getTableName()); + map.put("comments", tableEntity.getComments()); + map.put("pk", tableEntity.getPk()); + map.put("className", tableEntity.getClassName()); + map.put("classname", tableEntity.getClassname()); + map.put("pathName", tableEntity.getClassname().toLowerCase()); + map.put("columns", tableEntity.getColumns()); + map.put("classNameLower", tableEntity.getClassNameLower()); + map.put("hasBigDecimal", hasBigDecimal); + map.put("mainPath", mainPath); + map.put("package", config.getString("package")); + map.put("author", config.getString("author")); + map.put("email", config.getString("email")); + map.put("datetime", DateUtils.dateTime()); + map.put("identity", IdWorker.getId()); + map.put("addId", IdWorker.getId()); + map.put("updateId", IdWorker.getId()); + map.put("deleteId", IdWorker.getId()); + map.put("selectId", IdWorker.getId()); + + + VelocityContext context = new VelocityContext(map); + + //获取模板列表 + List templates = getTemplates(); + for (String template : templates) { + //渲染模板 + StringWriter sw = new StringWriter(); + Template tpl = Velocity.getTemplate(template, "UTF-8"); + tpl.merge(context, sw); + + try { + if(!isView){ + //添加到zip + zip.putNextEntry(new ZipEntry(Objects.requireNonNull(getFileName(template, tableEntity.getClassName(), config.getString("package"), config.getString("package"))))); + IOUtils.write(sw.toString(), zip, "UTF-8"); + IOUtils.closeQuietly(sw); + zip.closeEntry(); + } + } catch (IOException e) { + throw new BusinessException("渲染模板失败,表名:" + tableEntity.getTableName()); + } + velocityMap.put(template.substring(template.lastIndexOf("/") + 1, template.lastIndexOf(".vm")), sw.toString()); + } + return velocityMap; + + } + + + /** + * 预览方法 + * + * @param tableInfo 数据库表 + * @return + * @author fuce + * @Date 2021年1月18日 上午2:10:55 + */ + public static Map viewAuto(TableInfo tableInfo, String tableName , String tableComment) { + Map velocityMap = new HashMap(); + + //设置velocity资源加载器 + Properties prop = new Properties(); + prop.put("file.resource.loader.class" , "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(prop); + Map map = new HashMap<>(); + //数据库表数据 + map.put("tableInfo" , tableInfo); + //字段集合 + map.put("beanColumns" , tableInfo.getBeanColumns()); + //配置文件 + map.put("SnowflakeIdWorker" , "SnowflakeIdWorker.class"); + //class类路径 + map.put("parentPack" , config.getString("package")); + //作者 + map.put("author" , config.getString("author")); + //时间 + map.put("datetime" , new DateTime()); + //sql需要的权限父级pid + map.put("pid" , "0"); + + VelocityContext velocityContext = new VelocityContext(map); + //获取模板列表 + List templates = getTemplates(); + for (String template : templates) { + Template tpl = Velocity.getTemplate(template, "UTF-8"); + StringWriter sw = new StringWriter(); + tpl.merge(velocityContext, sw); + System.out.println("输出模板"); + System.out.println(sw); + System.out.println("输出模板 end"); + velocityMap.put(template.substring(template.lastIndexOf("/") + 1, template.lastIndexOf(".vm")), sw.toString()); + } + return velocityMap; + } + + + /** + * 列名转换成Java属性名 + */ + public static String columnToJava(String field) { + String[] fields = field.split("_"); + StringBuilder sbuilder = new StringBuilder(fields[0]); + for (int i = 1; i < fields.length; i++) { + char[] cs = fields[i].toCharArray(); + cs[0] -= 32; + sbuilder.append(String.valueOf(cs)); + } + return sbuilder.toString().substring(0, 1).toUpperCase() + sbuilder.toString().substring(1); + } + + + /** + * 表名转换成Java类名 + */ + public static String tableToJava(String tableName, String[] tablePrefixArray) { + tableName = tableName.toLowerCase(); + if (null != tablePrefixArray && tablePrefixArray.length > 0) { + for (String tablePrefix : tablePrefixArray) { + tablePrefix = tablePrefix.toLowerCase(); + tableName = tableName.replace(tablePrefix, ""); + } + } + return columnToJava(tableName); + } + + /** + * 获取配置信息 + */ + public static Configuration getConfig() { + try { + return new PropertiesConfiguration("generator.properties"); + } catch (ConfigurationException e) { + throw new BusinessException("获取配置文件失败"); + } + } + + /** + * 获取文件名 + */ + public static String getFileName(String template, String className, String packageName, String targetPath) { + String packagePath = "main" + File.separator + "java" + File.separator; + if (StringUtils.isNotBlank(packageName)) { + packagePath += packageName.replace(".", File.separator) + File.separator; + } + + if (template.contains("Entity.java.vm")) { + return packagePath + "entity" + File.separator + className + "Entity.java"; + } + + if (template.contains("Dao.java.vm")) { + return packagePath + "mapper" + File.separator + className + "Mapper.java"; + } + + if (template.contains("Service.java.vm")) { + return packagePath + "service" + File.separator + className + "Service.java"; + } + + if (template.contains("ServiceImpl.java.vm")) { + return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java"; + } + + if (template.contains("Controller.java.vm")) { + return packagePath + "controller" + File.separator + className + "Controller.java"; + } + + if (template.contains("Dao.xml.vm")) { + return "main" + File.separator + "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml"; + } + + if (template.contains("menu.sql.vm")) { + return className.toLowerCase() + "_menu.sql"; + } + + if (template.contains("generator.html.vm")) { + return "main" + File.separator + "resources" + File.separator + "templates2" + File.separator + className.toLowerCase() + File.separator + "list" + ".html"; + } + return getCoverFileName(template,className,packageName,config.getString("parentPath")); + +// return null; + } + // **************************************************************************************************************** + // **************************************************************************************************************** + // **************************************************************************************************************** + + /** + * @param template + * @return + * @author fuce + * @Date 2021年1月17日 下午6:40:57 + */ + public static String getCoverFileName(String template, String className, String packageName, String targetPath) { + + String separator = File.separator; + String packagePath = targetPath + separator + "src" + separator + "main" + separator + "java" + separator; + String resourcesPath = targetPath + separator + "src" + separator + "main" + separator + "resources" + separator; + ; + if (StringUtils.isNotBlank(packageName)) { + packagePath += packageName.replace("." , separator) + separator; + } + + //model.java + if (template.contains("Entity.java.vm")) { + return packagePath + "model" + separator + "original" + separator + className + ".java"; + } +// if(template.contains("EntityExample.java.vm")) {//modelExample.java +// return packagePath+"model" +separator+ "auto" + separator + className + "Example.java"; +// } + + //daomapper.java + if (template.contains("EntityMapper.java.vm")) { + return packagePath + "Mapper" + separator + "original" + separator+ className + "Mapper.java"; + } + + //daomapper.xml + if (template.contains("EntityMapper.xml.vm")) { + return resourcesPath + "mybatis" + separator + "auto" + separator+ className + "Mapper.xml"; + } + + if (template.contains("EntityService.java.vm")) { + return packagePath + "Service" + separator + "original" + separator+ "" + className + "Service.java"; + } + + if (template.contains("EntityServiceImpl.java.vm")) { + return packagePath + "Service" + separator + "impl" + separator + className + "ServiceImpl.java"; + } + + if (template.contains("EntityController.java.vm")) { + return packagePath + "Controller" + separator + "original" + separator+ className + "Controller.java"; + } + + if (template.contains("generator.html.vm")) { + return resourcesPath + "templates" + separator + "admin" + separator + firstLowerCase(className) + separator + "generator.html"; + } + + if (template.contains("add.html.vm")) { + return resourcesPath + "templates" + separator + "admin" + separator + firstLowerCase(className) + separator + "add.html"; + } + + if (template.contains("edit.html.vm")) { + return resourcesPath + "templates" + separator + "admin" + separator + firstLowerCase(className) + separator + "edit.html"; + } + + if (template.contains("menu.sql.vm")) { + return resourcesPath + "sql" + separator + "menu.sql"; + } + return ""; + } + + /** + * 列名转换成Java属性名 + * + * @param columnName + * @return + */ +// public String columnToJava(String columnName) { +// return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_" , ""); +// } + + /** + * 表名转换成Java类名 + * + * @param tableName + * @return + */ + public String tableToJava(String tableName) { + String tablePrefix = Objects.requireNonNull(GenUtils.getConfig().getString("tablePrefix")); + if (StringUtils.isNotBlank(tablePrefix)) { + tableName = tableName.replaceFirst(tablePrefix, ""); + } + return columnToJava(tableName); + } + + public static String firstLowerCase(String name) { + name = name.substring(0, 1).toLowerCase() + name.substring(1); + return name; + + } + + + /** + * 创建单表 + * + * @author fuce + * @Date 2019年8月24日 下午11:44:54 + */ + public static void autoCodeOneModel(TableInfo tableInfo, String tableName ,String tableComment) { + //设置velocity资源加载器 + Properties prop = new Properties(); + prop.put("file.resource.loader.class" , "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(prop); + Map map = new HashMap<>(); + //数据库表数据 + map.put("tableInfo" , tableInfo); + //字段集合 + map.put("beanColumns" , tableInfo.getBeanColumns()); + //配置文件 + map.put("SnowflakeIdWorker" , "SnowflakeIdWorker.class"); + //class类路径 + map.put("parentPack" , config.getString("package")); + //作者 + map.put("author" , config.getString("author")); + //时间 + map.put("datetime" , new DateTime()); + //sql需要的权限父级pid + map.put("pid" , "0"); + + VelocityContext context = new VelocityContext(map); + + //获取模板列表 + List templates = getTemplates(); + /* + * if(vhtml!=true) { templates.remove("auto_code/html/generator.html.vm"); + * templates.remove("auto_code/html/add.html.vm"); + * templates.remove("auto_code/html/edit.html.vm"); } if (vController!=true) { + * templates.remove("auto_code/controller/EntityController.java.vm"); } if + * (vService!=true) { + * templates.remove("auto_code/service/EntityService.java.vm"); } if + * (vMapperORdao!=true) { templates.remove("auto_code/model/Entity.java.vm"); + * templates.remove("auto_code/model/EntityExample.java.vm"); + * templates.remove("auto_code/mapperxml/EntityMapper.xml.vm"); + * templates.remove("auto_code/mapper/EntityMapper.java.vm"); } + */ + for (String template : templates) { + try { + String targetPath = config.getString("parentPath"); + String filepath = getCoverFileName(template, tableInfo.getJavaTableName(), config.getString("package"), targetPath); + // 读取模板 + Template tpl = Velocity.getTemplate(template, "UTF-8"); + File file = new File(filepath); + if (!file.getParentFile().exists()) { + file.getParentFile().mkdirs(); + } + + if (!file.exists()) { + file.createNewFile(); + } + try (FileOutputStream outStream = new FileOutputStream(file); + OutputStreamWriter writer = new OutputStreamWriter(outStream, "UTF-8"); + BufferedWriter sw = new BufferedWriter(writer)) { + tpl.merge(context, sw);//进行模板渲染 + sw.flush(); + System.out.println("成功生成Java文件:" + filepath); + } + } catch (IOException e) { + try { + throw new Exception("渲染模板失败,表名:" + "c" + "\n" + e.getMessage()); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + } + } + + + + /** + * 自动生成压缩文件方法 + * + * @param tableInfo + * @param zip + * @author fuce + * @Date 2021年1月17日 下午7:37:50 + */ + public static void autoCodeOneModel(TableInfo tableInfo, String tableName ,String tableComment, ZipOutputStream zip) { + //设置velocity资源加载器 + Properties prop = new Properties(); + prop.put("file.resource.loader.class" , "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + Velocity.init(prop); + Map map = new HashMap<>(); + //数据库表数据 + map.put("tableInfo" , tableInfo); + //字段集合 + map.put("beanColumns" , tableInfo.getBeanColumns()); + //配置文件 + map.put("SnowflakeIdWorker" , "SnowflakeIdWorker.class"); + //class类路径 + map.put("parentPack" , config.getString("package")); + //作者 + map.put("author" , config.getString("author")); + //时间 + map.put("datetime" , new DateTime()); + //sql需要的权限父级pid + map.put("pid" , "0"); + VelocityContext velocityContext = new VelocityContext(map); + //获取模板列表 + List templates = getTemplates(); + for (String template : templates) { + try { + String filepath = getCoverFileName(template, tableInfo.getJavaTableName(), config.getString("package"), ""); + Template tpl = Velocity.getTemplate(template, "UTF-8"); + StringWriter sw = new StringWriter(); + tpl.merge(velocityContext, sw); + zip.putNextEntry(new ZipEntry(filepath)); + IOUtils.write(sw.toString(), zip, "UTF-8"); + IOUtils.closeQuietly(sw); + zip.closeEntry(); + } catch (IOException e) { + try { + throw new Exception("渲染模板失败,表名:" + "c" + "\n" + e.getMessage()); + } catch (Exception e1) { + e1.printStackTrace(); + } + } + } + } + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/META-INF/spring.factories.bk b/jun_api_online/jun_generator/src/main/resources/META-INF/spring.factories.bk new file mode 100644 index 000000000..679bab61f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/META-INF/spring.factories.bk @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +#com.jun.plugin.generator.config.DevtoolsAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/config.properties b/jun_api_online/jun_generator/src/main/resources/config.properties new file mode 100644 index 000000000..6a9fff246 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/config.properties @@ -0,0 +1,38 @@ +################################################# step1 for modify datasource +jdbc.url=jdbc:mysql://localhost:3306/db_test666?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC&useInformationSchema=true +jdbc.username=root +jdbc.password= +jdbc.driver=com.mysql.cj.jdbc.Driver +#mysql 5.7 com.mysql.jdbc.Driver ,mysql 8.0 com.mysql.cj.jdbc.Driver + +################################################# step2 for modify author package project_path +authorName=Wujun +packageName=com.bjc.byk.test +project_path=D:/workspace/github/jun_api_service/jun_api_service_online/plugins/generator +#className=${className}Controller.subfix.ftl +#jsp namespace: web/${namespace}/${className}/list.jsp +template_path=src/main/resources/templates +javaPath=src/main/java +resourcesPath=src/main/resources +tableRemovePrefixes=T_AR,T_BD,T_CD,T_PD,T_CL,T_IP,T_LO,T_RI,T_EV,T_, +rowRemovePrefixes=S_,B_,I_,DT_,TS_,M_,F_,PK_I_N,PK_I_S + +################################################# +isLombok=true +isAutoImport=true +isWithPackage=true +isSwagger=true +isComment=true + +################################################# + +java.sql.Timestamp=Date +java.sql.Date=Date +java.sql.Time=Date +java.util.Date=Date +java.lang.Byte=Integer +java.lang.Short=Integer +java.lang.Integer=Integer +java.lang.Long=Long +java.lang.String=String +java.math.BigDecimal=java.math.BigDecimal \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/generator.properties b/jun_api_online/jun_generator/src/main/resources/generator.properties new file mode 100644 index 000000000..216aab525 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/generator.properties @@ -0,0 +1,64 @@ +#\u4EE3\u7801\u751F\u6210\u5668\uFF0C\u914D\u7F6E\u4FE1\u606F + +mainPath=com.jun.plugin +parentPack=com.jun.plugin +#\u5305\u540D +package=com.jun.plugin.bizservice +#\u4F5C\u8005 +author=wujun +#Email +email=wujun728@mail.com +#\u8868\u524D\u7F00 +tablePrefix= +parentPath= +#parentPath=D:\\CodeGenerator + +#\u7C7B\u578B\u8F6C\u6362\uFF0C\u914D\u7F6E\u4FE1\u606F +tinyint=Integer +smallint=Integer +mediumint=Integer +int=Integer +integer=Integer +bigint=Long +float=Float +double=Double +decimal=BigDecimal +bit=Boolean + +char=String +varchar=String +tinytext=String +text=String +mediumtext=String +longtext=String + +date=Date +datetime=Date +timestamp=Date + +NUMBER=Integer +INT=Integer +INTEGER=Integer +BINARY_INTEGER=Integer +LONG=String +FLOAT=Float +BINARY_FLOAT=Float +DOUBLE=Double +BINARY_DOUBLE=Double +DECIMAL=BigDecimal +CHAR=String +VARCHAR=String +VARCHAR2=String +NVARCHAR=String +NVARCHAR2=String +CLOB=String +BLOB=String +DATE=Date +DATETIME=Date +TIMESTAMP=Date +TIMESTAMP(6)=Date + +int8=Long +int4=Integer +int2=Integer +numeric=BigDecimal \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl new file mode 100644 index 000000000..65be7585a --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlcontroller.ftl @@ -0,0 +1,75 @@ +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import java.util.List; +import java.util.Map; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Autowired + private SQLManager sqlManager; + + /** + * 新增或编辑 + */ + @PostMapping("/save") + public Object save(${classInfo.className} ${classInfo.className?uncap_first}){ + ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,${classInfo.className?uncap_first}.getId()); + if(${classInfo.className?uncap_first}!=null){ + sqlManager.updateById(${classInfo.className?uncap_first}); + return ${returnUtilSuccess}("编辑成功"); + }else{ + sqlManager.insert(${classInfo.className?uncap_first}); + return ${returnUtilFailure}("保存成功"); + } + } + + /** + * 删除 + */ + @PostMapping("/delete") + public Object delete(int id){ + ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,id); + if(${classInfo.className?uncap_first}!=null){ + sqlManager.deleteById(id); + return ${returnUtilSuccess}("删除成功"); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 查询 + */ + @PostMapping("/find") + public Object find(int id){ + ${classInfo.className} ${classInfo.className?uncap_first}=sqlManager.unique(${classInfo.className}.class,id); + if(${classInfo.className?uncap_first}!=null){ + return ${returnUtilSuccess}(${classInfo.className?uncap_first}); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 分页查询 + */ + @PostMapping("/list") + public Object list(${classInfo.className} ${classInfo.className?uncap_first}, + @RequestParam(required = false, defaultValue = "0") int pageNumber, + @RequestParam(required = false, defaultValue = "10") int pageSize) { + List<${classInfo.className}> list = sqlManager.query(${classInfo.className}.class).select(); + return ${returnUtilSuccess}(list); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl new file mode 100644 index 000000000..de7e7609e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlentity.ftl @@ -0,0 +1,31 @@ +<#if isAutoImport?exists && isAutoImport==true> +import java.io.Serializable; +import lombok.Data; +import java.util.Date; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Data<#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className} implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> + public ${classInfo.className}() { + } +#if> + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl new file mode 100644 index 000000000..2dcdb64ac --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/beetlsql/beetlmd.ftl @@ -0,0 +1,31 @@ +sample +=== + +select #use("cols")# from ${classInfo.tableName} where #use("condition")# + +cols +=== +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + `${fieldItem.columnName}`<#if fieldItem_has_next>,#if> + #list> +#if> + +updateSample +=== +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + `${fieldItem.columnName}=#${fieldItem.fieldName}#`<#if fieldItem_has_next>,#if> + #list> +#if> + +condition +=== + 1 = 1 +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + @if(!isEmpty(${fieldItem.fieldName})){ + and `${fieldItem.columnName}`=#${fieldItem.fieldName}# + @} + #list> +#if> diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl new file mode 100644 index 000000000..742dcb271 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkentity.ftl @@ -0,0 +1,50 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import javax.persistence.*; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if> +<#if isComment?exists && isComment==true>@Table(name="${classInfo.originTableName}")#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className} implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if isComment?exists && isComment==true>@Column(name="${fieldItem.columnName}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> + public ${classInfo.className}() { + } +#if> + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl new file mode 100644 index 000000000..3fdb96059 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common-mapper/tkmapper.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import tk.mybatis.mapper.common.Mapper; +import org.apache.ibatis.annotations.Mapper; +import ${packageName}.entity.${classInfo.className}; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends Mapper<${classInfo.className}> { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/controller.ftl new file mode 100644 index 000000000..0b928a89f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/controller.ftl @@ -0,0 +1,73 @@ +package ${packageController}; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import ${packageModel}.${classInfo.className}; +import ${packageService}.${classInfo.className}Service; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Controller +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + /** + * 新增 + */ + @RequestMapping("/insert") + @ResponseBody + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.insert(${classInfo.className?uncap_first}); + } + + /** + * 删除 + */ + @RequestMapping("/delete") + @ResponseBody + public ReturnT delete(int id){ + return ${classInfo.className?uncap_first}Service.delete(id); + } + + /** + * 更新 + */ + @RequestMapping("/update") + @ResponseBody + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}); + } + + /** + * Load查询 + */ + @RequestMapping("/load") + @ResponseBody + public ${classInfo.className} load(int id){ + return ${classInfo.className?uncap_first}Service.load(id); + } + + /** + * 分页查询 + */ + @RequestMapping("/pageList") + @ResponseBody + public Map pageList(@RequestParam(required = false, defaultValue = "0") int offset, + @RequestParam(required = false, defaultValue = "10") int pagesize) { + return ${classInfo.className?uncap_first}Service.pageList(offset, pagesize); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/dao.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/dao.ftl new file mode 100644 index 000000000..6ed153d42 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/dao.ftl @@ -0,0 +1,49 @@ +package ${packageDao}; + +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; +import ${packageModel}.${classInfo.className}; + +import java.util.List; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Component +public interface ${classInfo.className}Dao { + + /** + * 新增 + */ + public int insert(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 删除 + */ + public int delete(@Param("id") int id); + + /** + * 更新 + */ + public int update(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * Load查询 + */ + public ${classInfo.className} load(@Param("id") int id); + + /** + * 分页查询Data + */ + public List<${classInfo.className}> pageList(@Param("offset") int offset, + @Param("pagesize") int pagesize); + + /** + * 分页查询Count + */ + public int pageListCount(@Param("offset") int offset, + @Param("pagesize") int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/model.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/model.ftl new file mode 100644 index 000000000..7a28cc64a --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/model.ftl @@ -0,0 +1,45 @@ +package ${packageModel}; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.fieldClass == "Date"> + <#assign importDdate = true /> + #if> + #list> +#if> +import java.io.Serializable; +<#if importDdate?? && importDdate> +import java.util.Date; +#if> + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +public class ${classInfo.className} implements Serializable { + private static final long serialVersionUID = 42L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + /** + * ${fieldItem.fieldComment} + */ + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> +#if> + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } + +#list> +#if> +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/mybatis.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/mybatis.ftl new file mode 100644 index 000000000..0e1a7560e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/mybatis.ftl @@ -0,0 +1,82 @@ + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + #list> + #if> + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + `${fieldItem.columnName}`<#if fieldItem_has_next>,#if> + #list> + #if> + + + + INSERT INTO ${classInfo.tableName} ( + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" > + `${fieldItem.columnName}`<#if fieldItem_has_next>,#if> + #if> + #list> + #if> + ) + VALUES( + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" > + <#if fieldItem.columnName="AddTime" || fieldItem.columnName="UpdateTime" > + NOW()<#if fieldItem_has_next>,#if> + <#else> + ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>,#if> + #if> + #if> + #list> + #if> + ) + + + + DELETE FROM ${classInfo.tableName} + WHERE `id` = ${r"#{id}"} + + + + UPDATE ${classInfo.tableName} + SET + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" && fieldItem.columnName != "AddTime" && fieldItem.columnName != "UpdateTime" > + ${fieldItem.columnName} = ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}, + #if> + #list> + UpdateTime = NOW() + WHERE `id` = ${r"#{"}${classInfo.className?uncap_first}.id${r"}"} + + + + + SELECT + FROM ${classInfo.tableName} + WHERE `id` = ${r"#{id}"} + + + + SELECT + FROM ${classInfo.tableName} + LIMIT ${r"#{offset}"}, ${r"#{pagesize}"} + + + + SELECT count(1) + FROM ${classInfo.tableName} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service.ftl new file mode 100644 index 000000000..b3295ddab --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service.ftl @@ -0,0 +1,39 @@ +package ${packageService}; +import java.util.Map; + +import ${packageModel}.${classInfo.className}; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +public interface ${classInfo.className}Service { + + /** + * 新增 + */ + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 删除 + */ + public ReturnT delete(int id); + + /** + * 更新 + */ + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * Load查询 + */ + public ${classInfo.className} load(int id); + + /** + * 分页查询 + */ + public Map pageList(int offset, int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service_impl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service_impl.ftl new file mode 100644 index 000000000..44ca00df8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/common/service_impl.ftl @@ -0,0 +1,85 @@ +package ${packageServiceImpl}; + +import org.springframework.stereotype.Service; + +import com.jun.plugin.biz.dao.${classInfo.className}Dao; +import ${packageModel}.${classInfo.className}; +import ${packageService}.${classInfo.className}Service; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Service +public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { + + @Resource + private ${classInfo.className}Dao ${classInfo.className?uncap_first}Dao; + + /** + * 新增 + */ + @Override + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}) { + + // valid + if (${classInfo.className?uncap_first} == null) { + return new ReturnT(ReturnT.FAIL_CODE, "必要参数缺失"); + } + + ${classInfo.className?uncap_first}Dao.insert(${classInfo.className?uncap_first}); + return ReturnT.SUCCESS; + } + + /** + * 删除 + */ + @Override + public ReturnT delete(int id) { + int ret = ${classInfo.className?uncap_first}Dao.delete(id); + return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; + } + + /** + * 更新 + */ + @Override + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}) { + int ret = ${classInfo.className?uncap_first}Dao.update(${classInfo.className?uncap_first}); + return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; + } + + /** + * Load查询 + */ + @Override + public ${classInfo.className} load(int id) { + return ${classInfo.className?uncap_first}Dao.load(id); + } + + /** + * 分页查询 + */ + @Override + public Map pageList(int offset, int pagesize) { + + List<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Dao.pageList(offset, pagesize); + int totalCount = ${classInfo.className?uncap_first}Dao.pageListCount(offset, pagesize); + + // result + Map result = new HashMap(); + result.put("pageList", pageList); + result.put("totalCount", totalCount); + + return result; + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/controller.ftl new file mode 100644 index 000000000..0b928a89f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/controller.ftl @@ -0,0 +1,73 @@ +package ${packageController}; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import ${packageModel}.${classInfo.className}; +import ${packageService}.${classInfo.className}Service; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Controller +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + /** + * 新增 + */ + @RequestMapping("/insert") + @ResponseBody + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.insert(${classInfo.className?uncap_first}); + } + + /** + * 删除 + */ + @RequestMapping("/delete") + @ResponseBody + public ReturnT delete(int id){ + return ${classInfo.className?uncap_first}Service.delete(id); + } + + /** + * 更新 + */ + @RequestMapping("/update") + @ResponseBody + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}); + } + + /** + * Load查询 + */ + @RequestMapping("/load") + @ResponseBody + public ${classInfo.className} load(int id){ + return ${classInfo.className?uncap_first}Service.load(id); + } + + /** + * 分页查询 + */ + @RequestMapping("/pageList") + @ResponseBody + public Map pageList(@RequestParam(required = false, defaultValue = "0") int offset, + @RequestParam(required = false, defaultValue = "10") int pagesize) { + return ${classInfo.className?uncap_first}Service.pageList(offset, pagesize); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/dao.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/dao.ftl new file mode 100644 index 000000000..6ed153d42 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/dao.ftl @@ -0,0 +1,49 @@ +package ${packageDao}; + +import org.apache.ibatis.annotations.Param; +import org.springframework.stereotype.Component; +import ${packageModel}.${classInfo.className}; + +import java.util.List; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Component +public interface ${classInfo.className}Dao { + + /** + * 新增 + */ + public int insert(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 删除 + */ + public int delete(@Param("id") int id); + + /** + * 更新 + */ + public int update(@Param("${classInfo.className?uncap_first}") ${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * Load查询 + */ + public ${classInfo.className} load(@Param("id") int id); + + /** + * 分页查询Data + */ + public List<${classInfo.className}> pageList(@Param("offset") int offset, + @Param("pagesize") int pagesize); + + /** + * 分页查询Count + */ + public int pageListCount(@Param("offset") int offset, + @Param("pagesize") int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl new file mode 100644 index 000000000..681518fb1 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdao.ftl @@ -0,0 +1,21 @@ +<#if isAutoImport?exists && isAutoImport==true> +import java.util.List; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface I${classInfo.className}DAO { + + int add(${classInfo.className} ${classInfo.className?uncap_first}); + + int update(${classInfo.className} ${classInfo.className?uncap_first}); + + int delete(int id); + + ${classInfo.className} findById(int id); + + List<${classInfo.className}> findAllList(Map param); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl new file mode 100644 index 000000000..f3e93889e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jdbc-template/jtdaoimpl.ftl @@ -0,0 +1,61 @@ +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.jdbc.core.BeanPropertyRowMapper; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.stereotype.Repository; +import java.util.List; +#if> + +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Repository +public class ${classInfo.className}DaoImpl implements I${classInfo.className}Dao{ + + @Autowired + private JdbcTemplate jdbcTemplate; + + @Override + public int add(${classInfo.className} ${classInfo.className?uncap_first}) { + return jdbcTemplate.update("insert into ${classInfo.tableName} (<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>,#if>#list>#if> ) values (<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >?<#if fieldItem_has_next>,#if>#list>#if> )", + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()<#if fieldItem_has_next>,#if>#list>#if>); + } + + @Override + public int update(${classInfo.className} ${classInfo.className?uncap_first}) { + return jdbcTemplate.update("UPDATE ${classInfo.tableName} SET <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index gt 0 >${fieldItem.columnName}=?<#if fieldItem_has_next>,#if>#if>#list>#if>" + +" where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >#if>#list>#if>", + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem ><#if fieldItem_index gt 0 >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}(),#if>#list> + <#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0 >${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()#if>#list> + #if>); + } + + @Override + public int delete(int id) { + return jdbcTemplate.update("DELETE from ${classInfo.tableName} where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >#if>#list>#if>",id); + } + + @Override + public ${classInfo.className} findById(int id) { + List<${classInfo.className}> list = jdbcTemplate.query("select * from ${classInfo.tableName} where <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0><#list classInfo.fieldList as fieldItem ><#if fieldItem_index = 0>${fieldItem.columnName}=?<#break >#if>#list>#if>", new Object[]{id}, new BeanPropertyRowMapper<${classInfo.className}>(${classInfo.className}.class)); + if(list!=null && !list.isEmpty() ){ + return list.get(0); + }else{ + return null; + } + } + + @Override + public List<${classInfo.className}> findAllList(Map params) { + List<${classInfo.className}> list = jdbcTemplate.query("select * from ${classInfo.tableName}", new Object[]{}, new BeanPropertyRowMapper<${classInfo.className}>(${classInfo.className}.class)); + if(list!=null && !list.isEmpty() ){ + return list; + }else{ + return Collections.emptyList(); + } + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/controller.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/controller.java.ftl new file mode 100644 index 000000000..225c35839 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/controller.java.ftl @@ -0,0 +1,165 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import ${packageName}.vo.${classInfo.className}Vo; +import ${packageName}.dto.${classInfo.className}Dto; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; +//import com.bjc.lcp.common.cnt.service.CntService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ObjectUtils; +<#--import org.apache.shiro.authz.annotation.RequiresPermissions;--> +import org.springframework.web.servlet.ModelAndView; +import com.jun.plugin.common.Result; +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @Version666 +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Api(tags = "${classInfo.classComment}-管理") +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + @ApiOperation(value = "${classInfo.classComment}-新增") + @PostMapping("/add") + //@RequiresPermissions("${classInfo.className?uncap_first}:add") + public Result add(@Validated(${classInfo.className}Vo.Create.class) @RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.nullable==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + BeanUtils.copyProperties(dto, entity); + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(entity); + if (list.size() > 0) { + return Result.fail("数据已存在"); + } + return Result.success(${classInfo.className?uncap_first}Service.save(entity)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/remove") + //@RequiresPermissions("${classInfo.className?uncap_first}:remove") + public Result delete(@Validated(${classInfo.className}Vo.Delete.class) @RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + return Result.success(${classInfo.className?uncap_first}Service.deleteById(dto.getId())); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/delete") + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { + ids.stream().forEach(item->{ + try { + ${classInfo.className?uncap_first}Service.deleteById(Long.valueOf(item)); + } catch (Exception e) { + throw new RuntimeException(e); + } + }); + return Result.success(); + } + + + @ApiOperation(value = "${classInfo.classComment}-更新") + @PutMapping("/update") + //@RequiresPermissions("${classInfo.className?uncap_first}:update") + public Result update(@Validated(${classInfo.className}Vo.Update.class) @RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.findById(vo.getId()); + if (entity == null) { + return Result.fail("数据不存在"); + //entity = new AdminEntity(); + } + BeanUtils.copyProperties(dto, entity); + return Result.success(${classInfo.className?uncap_first}Service.update(entity)); + } + + + + @ApiOperation(value = "${classInfo.classComment}-查询单条") + @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:getOne") + public Result getOne(@RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.findById(dto.getId()); + return Result.success(entity); + } + + + @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") + @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) + public Result listByPage(@RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + BeanUtils.copyProperties(vo, entity); + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(entity); + return Result.success(list); + } + + @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") + @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:list") + public Result findListByPage(@RequestBody ${classInfo.className}Vo vo) throws Exception { + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + BeanUtils.copyProperties(vo, entity); + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(entity); + return Result.success(list); + } + + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dao.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dao.java.ftl new file mode 100644 index 000000000..ff02be668 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dao.java.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; + +import ${packageName}.entity.${classInfo.className}Entity; + import com.jun.plugin.common.base.IDAO; +#if> +/** + * @description ${classInfo.classComment}数据层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Dao extends IDAO { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dto.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dto.java.ftl new file mode 100644 index 000000000..2b435e593 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/dto.java.ftl @@ -0,0 +1,44 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Dto implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Dto() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/entity.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/entity.java.ftl new file mode 100644 index 000000000..b45cac811 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/entity.java.ftl @@ -0,0 +1,70 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +<#assign isSwagger=false /> +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +import io.swagger.annotations.ApiModel; +import com.bjc.base.entity.LongEntity; +import lombok.EqualsAndHashCode; +import javax.persistence.*; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +@EqualsAndHashCode(callSuper = false) +@Entity +@Table +@ApiModel(description = "${classInfo.classComment}") +public class ${classInfo.className}Entity extends LongEntity implements Serializable { + + private static final long serialVersionUID = 3724658580544666556L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */ + #if> + <#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}") + #if> + <#if fieldItem.isPrimaryKey==true> + <#--@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )--> + <#else> + @Column(nullable = false) + #if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + + <#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + + @Override + public void beforeCreate() { + super.beforeCreate(); + } + + @Override + public void beforeUpdate() { + super.beforeUpdate(); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/mapper.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/mapper.java.ftl new file mode 100644 index 000000000..c6e239c8b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/mapper.java.ftl @@ -0,0 +1,41 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}Entity; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { + + @Select( + "") + List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); + + @Select("") + int countAll(${classInfo.className}Entity dto); + + @Select("SELECT count(1) from ${classInfo.tableName} ") + int countAll(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.impl.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.impl.java.ftl new file mode 100644 index 000000000..2700183ab --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.impl.java.ftl @@ -0,0 +1,62 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}服务层实现 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { + + + @Override + public boolean save(${classInfo.className}Entity vo) throws Exception { + return false; + } + + @Override + public boolean update(${classInfo.className}Entity vo) throws Exception { + return false; + } + + @Override + public boolean delete(${classInfo.className}Entity vo) throws Exception { + return false; + } + + @Override + public boolean deleteById(Long id) throws Exception { + return false; + } + + @Override + public ${classInfo.className}Entity findById(Long id) throws Exception { + return null; + } + + @Override + public List<${classInfo.className}Entity> list(${classInfo.className}Entity vo) throws Exception { + return null; + } + + @Override + public List<${classInfo.className}Entity> page(${classInfo.className}Entity vo, int page, int size) throws Exception { + return null; + } + + @Override + public int count(${classInfo.className}Entity vo) throws Exception { + return 0; + } + +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.java.ftl new file mode 100644 index 000000000..39a651d2b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/service.java.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; + +import ${packageName}.entity.${classInfo.className}Entity; + import com.jun.plugin.common.base.IDAO; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service extends IDAO { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/vo.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/vo.java.ftl new file mode 100644 index 000000000..baec341e7 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa-byk/vo.java.ftl @@ -0,0 +1,62 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Vo implements Serializable { + + public interface Retrieve{} + public interface Delete {} + public interface Update {} + public interface Create {} + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if> + <#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}") + #if> + <#if fieldItem.nullable==true> + @NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class}) + #if> + <#if fieldItem.nullable==true> + @Size( max = ${fieldItem.columnSize?c},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize?c}位") + #if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Vo() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/entity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/entity.ftl new file mode 100644 index 000000000..ceb1456dc --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/entity.ftl @@ -0,0 +1,55 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.Id; +import javax.persistence.Table; +import javax.persistence.GeneratedValue; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Entity +<#if isLombok?exists && isLombok==true>@Data#if> +<#if isComment?exists && isComment==true>@Table(name="${classInfo.tableName}")#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className} implements Serializable { + + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if isComment?exists && isComment==true>@Column(name="${fieldItem.columnName}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> + public ${classInfo.className}() { + } +#if> + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl new file mode 100644 index 000000000..c6c98299b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/jpacontroller.ftl @@ -0,0 +1,83 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import ${packageName}.entity.${classInfo.className}; +import ${packageName}.repository.${classInfo.className}Repository; +import org.springframework.data.domain.Example; +import org.springframework.data.domain.Pageable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.data.domain.ExampleMatcher; +import org.springframework.data.domain.PageRequest; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; +import java.util.List; +import java.util.Map; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Autowired + private ${classInfo.className}Repository ${classInfo.className?uncap_first}Repository; + + /** + * 新增或编辑 + */ + @PostMapping("/save") + public Object save(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Repository.save(${classInfo.className?uncap_first}); + } + + /** + * 删除 + */ + @PostMapping("/delete") + public Object delete(int id){ + Optional<${classInfo.className}> ${classInfo.className?uncap_first}=${classInfo.className?uncap_first}Repository.findById(id); + if(${classInfo.className?uncap_first}.isPresent()){ + ${classInfo.className?uncap_first}Repository.deleteById(id); + return ${returnUtilSuccess}("删除成功"); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 查询 + */ + @PostMapping("/find") + public Object find(int id){ + Optional<${classInfo.className}> ${classInfo.className?uncap_first}=${classInfo.className?uncap_first}Repository.findById(id); + if(${classInfo.className?uncap_first}.isPresent()){ + return ${returnUtilSuccess}(${classInfo.className?uncap_first}.get()); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 分页查询 + */ + @PostMapping("/list") + public Object list(${classInfo.className} ${classInfo.className?uncap_first}, + @RequestParam(required = false, defaultValue = "0") int pageNumber, + @RequestParam(required = false, defaultValue = "10") int pageSize) { + + //创建匹配器,需要查询条件请修改此处代码 + ExampleMatcher matcher = ExampleMatcher.matchingAll(); + + //创建实例 + Example<${classInfo.className}> example = Example.of(${classInfo.className?uncap_first}, matcher); + //分页构造 + Pageable pageable = PageRequest.of(pageNumber,pageSize); + + return ${classInfo.className?uncap_first}Repository.findAll(example, pageable); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/repository.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/repository.ftl new file mode 100644 index 000000000..c2a8affb8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/jpa/repository.ftl @@ -0,0 +1,26 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true>import ${packageName}.entity.${classInfo.className}; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.fieldClass == "Date"> + <#assign importDdate = true /> + #if> + #list> +#if> +import java.util.List; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Repository +public interface ${classInfo.className}Repository extends JpaRepository<${classInfo.className},Integer> { + + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/model.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/model.ftl new file mode 100644 index 000000000..7a28cc64a --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/model.ftl @@ -0,0 +1,45 @@ +package ${packageModel}; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.fieldClass == "Date"> + <#assign importDdate = true /> + #if> + #list> +#if> +import java.io.Serializable; +<#if importDdate?? && importDdate> +import java.util.Date; +#if> + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +public class ${classInfo.className} implements Serializable { + private static final long serialVersionUID = 42L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + /** + * ${fieldItem.fieldComment} + */ + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> +#if> + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } + +#list> +#if> +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/controller.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/controller.java.ftl new file mode 100644 index 000000000..01824bed3 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/controller.java.ftl @@ -0,0 +1,230 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import ${packageName}.vo.${classInfo.className}Vo; +import ${packageName}.dto.${classInfo.className}Dto; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; +//import com.bjc.lcp.common.cnt.service.CntService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ObjectUtils; +<#--import org.apache.shiro.authz.annotation.RequiresPermissions;--> +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.web.servlet.ModelAndView; +import com.jun.plugin.common.Result; +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Api(tags = "${classInfo.classComment}-管理") +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + @Resource + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + @ApiOperation(value = "${classInfo.classComment}-新增") + @PostMapping("/add") + //@RequiresPermissions("${classInfo.className?uncap_first}:add") + public Result add(@Validated(${classInfo.className}Vo.Create.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.nullable==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + if (list.size() > 0) { + return Result.fail("数据已存在"); + } + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + + BeanUtils.copyProperties(dto, entity); + return Result.success(${classInfo.className?uncap_first}Service.save(entity)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/remove") + //@RequiresPermissions("${classInfo.className?uncap_first}:remove") + public Result delete(@Validated(${classInfo.className}Vo.Delete.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + return Result.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/delete") + //@RequiresPermissions("${classInfo.className?uncap_first}:delete") + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { + return Result.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); + } + + + @ApiOperation(value = "${classInfo.classComment}-更新") + @PutMapping("/update") + //@RequiresPermissions("${classInfo.className?uncap_first}:update") + public Result update(@Validated(${classInfo.className}Vo.Update.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + if (entity == null) { + //return Result.fail("数据不存在"); + entity = new ${classInfo.className}Entity(); + } + BeanUtils.copyProperties(dto, entity); + return Result.success(${classInfo.className?uncap_first}Service.saveOrUpdate(entity)); + } + + + + @ApiOperation(value = "${classInfo.classComment}-查询单条") + @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:getOne") + public Result getOne(@RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + return Result.success(entity); + } + + + + + @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") + @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:listByPage") + public Result listByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); + return Result.success(iPage); + } + + @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") + @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:list") + public Result findListByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + return Result.success(list); + } + + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/dto.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/dto.java.ftl new file mode 100644 index 000000000..918648f83 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/dto.java.ftl @@ -0,0 +1,44 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Dto extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Dto() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/edit.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/edit.html.ftl new file mode 100644 index 000000000..6299a1b24 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/edit.html.ftl @@ -0,0 +1,64 @@ + + + + + + + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + ${fieldItem.fieldComment} + + + <#--${fieldItem.fieldComment}--> + + + #list> +#if> + + + + 确认保存 + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/entity.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/entity.java.ftl new file mode 100644 index 000000000..612f07aa8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/entity.java.ftl @@ -0,0 +1,51 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.jun.plugin.common.entity.BaseEntity; +<#assign isSwagger=false /> +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +@TableName("${classInfo.tableName}") +public class ${classInfo.className}Entity extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" )#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Entity() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.ftl new file mode 100644 index 000000000..d36251c32 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.ftl @@ -0,0 +1,266 @@ + + + + + + + XXXX管理 + + + + + + + + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.nullable==false> + + ${fieldItem.fieldComment}: + + + + + #if> + #list> + #if> + <#-- + 角色名: + + + + + + 角色代码: + + + + + + 备 注: + + + + --> + + + 搜索 + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.v1.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.v1.ftl new file mode 100644 index 000000000..3fb144273 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.v1.ftl @@ -0,0 +1,234 @@ + + + + + + + XXX管理 + + + + + + + + + 搜索信息 + + + + + ${classInfo.classComment}Id + + + + + + ${classInfo.classComment}名称 + + + + + + 搜 索 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.vm.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.vm.ftl new file mode 100644 index 000000000..447a9cae3 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/list.html.vm.ftl @@ -0,0 +1,604 @@ + + + + + Title + + + + + + + + + + +#* + + 基本信息 + +*# + +###遍历新增修改表单 +#foreach($column in $columns) + #if($column.columnName == $pk.columnName) + + #else +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end + + + +#if($column.dataType != 'text') #end + ${column.comments} + +##注解支持,不展示 +#if($column.dataType == 'datetime') + +#elseif($column.columnName.toString().contains("dict")) + + 请选择 + + +#elseif($column.dataType == 'text') + +#else + #if($column.isNull == 'NO') + + #else + + #end +#end + + #if($column.dataType != 'text') #end + + +#end +#end + + + 保存 + 返回 + + + + + + + + + + + + + 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! + + + +###遍历查询条件 +#foreach($column in $columns) +#if($column.columnName != $pk.columnName && $column.isNull == 'NO') +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("create") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end +#if($column.dataType == 'datetime') + + + +#else + + + +#end +#end +#end + + 查询 + 导出全部 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/mapper.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/mapper.java.ftl new file mode 100644 index 000000000..c6e239c8b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/mapper.java.ftl @@ -0,0 +1,41 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}Entity; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { + + @Select( + "") + List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); + + @Select("") + int countAll(${classInfo.className}Entity dto); + + @Select("SELECT count(1) from ${classInfo.tableName} ") + int countAll(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/menu.sql.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/menu.sql.ftl new file mode 100644 index 000000000..2b3193a3f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/menu.sql.ftl @@ -0,0 +1,17 @@ +-- 菜单SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +VALUES ('1', '${classInfo.classComment}', 'generator/${classInfo.className?uncap_first}', NULL, '1', 'config', '6'); + +-- 按钮父菜单ID +set @parentId = @@identity; + +-- 菜单对应按钮SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '查看', null, 'generator:${classInfo.className?uncap_first}:list,generator:${classInfo.className?uncap_first}:info', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '新增', null, 'generator:${classInfo.className?uncap_first}:save', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '修改', null, 'generator:${classInfo.className?uncap_first}:update', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '删除', null, 'generator:${classInfo.className?uncap_first}:delete', '2', null, '6'; + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.impl.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.impl.java.ftl new file mode 100644 index 000000000..6b3a91a11 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.impl.java.ftl @@ -0,0 +1,26 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.service.${classInfo.className}Service; + +#if> +/** + * @description ${classInfo.classComment}服务层实现 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.java.ftl new file mode 100644 index 000000000..76483b1fe --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/service.java.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.IService; + +import ${packageName}.entity.${classInfo.className}Entity; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/vo.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/vo.java.ftl new file mode 100644 index 000000000..77144a165 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single-v2/vo.java.ftl @@ -0,0 +1,56 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Vo extends BaseEntity implements Serializable { + + public interface Retrieve{} + public interface Delete {} + public interface Update {} + public interface Create {} + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class})#if> + <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize?c},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize?c}位")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Vo() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.ftl new file mode 100644 index 000000000..762410df5 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.ftl @@ -0,0 +1,232 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.alibaba.fastjson.JSON; +import ${packageName}.vo.${classInfo.className}Vo; +import ${packageName}.dto.${classInfo.className}Dto; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; +//import com.bjc.lcp.common.cnt.service.CntService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ObjectUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.bjc.lcp.system.common.utils.DataResult; +import org.springframework.web.servlet.ModelAndView; +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Api(tags = "${classInfo.classComment}-管理") +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + @Resource + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + //@Autowired + //private CntService cntService; + + @ApiOperation(value = "${classInfo.classComment}-新增") + @PostMapping("/add") + @RequiresPermissions("${classInfo.className?uncap_first}:add") + public DataResult add(@Validated(${classInfo.className}Vo.Create.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.nullable==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + if (list.size() > 0) { + return DataResult.fail("数据已存在"); + } + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + + BeanUtils.copyProperties(dto, entity); + return DataResult.success(${classInfo.className?uncap_first}Service.save(entity)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/remove") + @RequiresPermissions("${classInfo.className?uncap_first}:remove") + public DataResult delete(@Validated(${classInfo.className}Vo.Delete.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + return DataResult.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/delete") + @RequiresPermissions("${classInfo.className?uncap_first}:delete") + public DataResult delete(@RequestBody @ApiParam(value = "id集合") List ids) { + return DataResult.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); + } + + + @ApiOperation(value = "${classInfo.classComment}-更新") + @PutMapping("/update") + @RequiresPermissions("${classInfo.className?uncap_first}:update") + public DataResult update(@Validated(${classInfo.className}Vo.Update.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + if (entity == null) { + return DataResult.fail("数据不存在"); + } + BeanUtils.copyProperties(dto, entity); + return DataResult.success(${classInfo.className?uncap_first}Service.updateById(entity)); + } + + + + @ApiOperation(value = "${classInfo.classComment}-查询单条") + @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:getOne") + public DataResult getOne(@RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + return DataResult.success(entity); + } + + + + + @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") + @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:listByPage") + public DataResult listByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); + return DataResult.success(iPage); + } + + @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") + @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:list") + public DataResult findListByPage(@RequestBody ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + return DataResult.success(list); + } + + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl new file mode 100644 index 000000000..44946cb7d --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/controller.java.ftl @@ -0,0 +1,235 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import ${packageName}.vo.${classInfo.className}Vo; +import ${packageName}.dto.${classInfo.className}Dto; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; +//import com.bjc.lcp.common.cnt.service.CntService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ObjectUtils; +<#--import org.apache.shiro.authz.annotation.RequiresPermissions;--> +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.web.servlet.ModelAndView; +import com.jun.plugin.common.Result; +import javax.annotation.Resource; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @Version666 +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Api(tags = "${classInfo.classComment}-管理") +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + @Resource + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + @ApiOperation(value = "${classInfo.classComment}-新增") + @PostMapping("/add") + //@RequiresPermissions("${classInfo.className?uncap_first}:add") + public Result add(@Validated(${classInfo.className}Vo.Create.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.nullable==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + if (list.size() > 0) { + return Result.fail("数据已存在"); + } + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + + BeanUtils.copyProperties(dto, entity); + return Result.success(${classInfo.className?uncap_first}Service.save(entity)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/remove") + //@RequiresPermissions("${classInfo.className?uncap_first}:remove") + public Result delete(@Validated(${classInfo.className}Vo.Delete.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + return Result.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/delete") + //@RequiresPermissions("${classInfo.className?uncap_first}:delete") + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { + return Result.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); + } + + + @ApiOperation(value = "${classInfo.classComment}-更新") + @PutMapping("/update") + //@RequiresPermissions("${classInfo.className?uncap_first}:update") + public Result update(@Validated(${classInfo.className}Vo.Update.class) @RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + if (entity == null) { + //return Result.fail("数据不存在"); + entity = new ${classInfo.className}Entity(); + } + BeanUtils.copyProperties(dto, entity); + return Result.success(${classInfo.className?uncap_first}Service.saveOrUpdate(entity)); + } + + + + @ApiOperation(value = "${classInfo.classComment}-查询单条") + @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:getOne") + public Result getOne(@RequestBody ${classInfo.className}Vo vo) { + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return Result.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + return Result.success(entity); + } + + + + + @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") + @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:listByPage") + public Result listByPage(@RequestBody(required = false) ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); + ${classInfo.className}Dto dto = new ${classInfo.className}Dto(); + BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + if(!ObjectUtils.isEmpty(${classInfo.className?uncap_first})){ +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> + } +#if> + IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); + return Result.success(iPage); + } + + @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") + @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) + //@RequiresPermissions("${classInfo.className?uncap_first}:list") + public Result findListByPage(@RequestBody(required = false) ${classInfo.className}Vo ${classInfo.className?uncap_first}) { + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + if(!ObjectUtils.isEmpty(${classInfo.className?uncap_first})){ +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> + } +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + return Result.success(list); + } + + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.ftl new file mode 100644 index 000000000..7b017013d --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.ftl @@ -0,0 +1,44 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.bjc.lcp.system.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Dto extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Dto() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl new file mode 100644 index 000000000..918648f83 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/dto.java.ftl @@ -0,0 +1,44 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Dto extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Dto() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl new file mode 100644 index 000000000..6299a1b24 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/edit.html.ftl @@ -0,0 +1,64 @@ + + + + + + + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + ${fieldItem.fieldComment} + + + <#--${fieldItem.fieldComment}--> + + + #list> +#if> + + + + 确认保存 + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.ftl new file mode 100644 index 000000000..1b0bd65ff --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.ftl @@ -0,0 +1,51 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.bjc.lcp.system.entity.BaseEntity; +<#assign isSwagger=false /> +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +@TableName("${classInfo.tableName}") +public class ${classInfo.className}Entity extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" )#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Entity() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl new file mode 100644 index 000000000..612f07aa8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/entity.java.ftl @@ -0,0 +1,51 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.jun.plugin.common.entity.BaseEntity; +<#assign isSwagger=false /> +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +@TableName("${classInfo.tableName}") +public class ${classInfo.className}Entity extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" )#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Entity() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl new file mode 100644 index 000000000..d36251c32 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.ftl @@ -0,0 +1,266 @@ + + + + + + + XXXX管理 + + + + + + + + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.nullable==false> + + ${fieldItem.fieldComment}: + + + + + #if> + #list> + #if> + <#-- + 角色名: + + + + + + 角色代码: + + + + + + 备 注: + + + + --> + + + 搜索 + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl new file mode 100644 index 000000000..3fb144273 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.v1.ftl @@ -0,0 +1,234 @@ + + + + + + + XXX管理 + + + + + + + + + 搜索信息 + + + + + ${classInfo.classComment}Id + + + + + + ${classInfo.classComment}名称 + + + + + + 搜 索 + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl new file mode 100644 index 000000000..447a9cae3 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/list.html.vm.ftl @@ -0,0 +1,604 @@ + + + + + Title + + + + + + + + + + +#* + + 基本信息 + +*# + +###遍历新增修改表单 +#foreach($column in $columns) + #if($column.columnName == $pk.columnName) + + #else +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end + + + +#if($column.dataType != 'text') #end + ${column.comments} + +##注解支持,不展示 +#if($column.dataType == 'datetime') + +#elseif($column.columnName.toString().contains("dict")) + + 请选择 + + +#elseif($column.dataType == 'text') + +#else + #if($column.isNull == 'NO') + + #else + + #end +#end + + #if($column.dataType != 'text') #end + + +#end +#end + + + 保存 + 返回 + + + + + + + + + + + + + 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! + + + +###遍历查询条件 +#foreach($column in $columns) +#if($column.columnName != $pk.columnName && $column.isNull == 'NO') +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("create") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end +#if($column.dataType == 'datetime') + + + +#else + + + +#end +#end +#end + + 查询 + 导出全部 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.ftl new file mode 100644 index 000000000..c6e239c8b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.ftl @@ -0,0 +1,41 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}Entity; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { + + @Select( + "") + List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); + + @Select("") + int countAll(${classInfo.className}Entity dto); + + @Select("SELECT count(1) from ${classInfo.tableName} ") + int countAll(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl new file mode 100644 index 000000000..c6e239c8b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/mapper.java.ftl @@ -0,0 +1,41 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}Entity; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { + + @Select( + "") + List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); + + @Select("") + int countAll(${classInfo.className}Entity dto); + + @Select("SELECT count(1) from ${classInfo.tableName} ") + int countAll(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl new file mode 100644 index 000000000..2b3193a3f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/menu.sql.ftl @@ -0,0 +1,17 @@ +-- 菜单SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +VALUES ('1', '${classInfo.classComment}', 'generator/${classInfo.className?uncap_first}', NULL, '1', 'config', '6'); + +-- 按钮父菜单ID +set @parentId = @@identity; + +-- 菜单对应按钮SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '查看', null, 'generator:${classInfo.className?uncap_first}:list,generator:${classInfo.className?uncap_first}:info', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '新增', null, 'generator:${classInfo.className?uncap_first}:save', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '修改', null, 'generator:${classInfo.className?uncap_first}:update', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '删除', null, 'generator:${classInfo.className?uncap_first}:delete', '2', null, '6'; + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.ftl new file mode 100644 index 000000000..76483b1fe --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.IService; + +import ${packageName}.entity.${classInfo.className}Entity; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.ftl new file mode 100644 index 000000000..6b3a91a11 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.ftl @@ -0,0 +1,26 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.service.${classInfo.className}Service; + +#if> +/** + * @description ${classInfo.classComment}服务层实现 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl new file mode 100644 index 000000000..6b3a91a11 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.impl.java.ftl @@ -0,0 +1,26 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.service.${classInfo.className}Service; + +#if> +/** + * @description ${classInfo.classComment}服务层实现 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl new file mode 100644 index 000000000..76483b1fe --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/service.java.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.IService; + +import ${packageName}.entity.${classInfo.className}Entity; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.ftl new file mode 100644 index 000000000..37be5085f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.ftl @@ -0,0 +1,56 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import com.bjc.lcp.system.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Vo extends BaseEntity implements Serializable { + + public interface Retrieve{} + public interface Delete {} + public interface Update {} + public interface Create {} + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class})#if> + <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize}位")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Vo() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl new file mode 100644 index 000000000..77144a165 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-single/vo.java.ftl @@ -0,0 +1,56 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import com.jun.plugin.common.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}Vo extends BaseEntity implements Serializable { + + public interface Retrieve{} + public interface Delete {} + public interface Update {} + public interface Create {} + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class})#if> + <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize?c},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize?c}位")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Vo() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl new file mode 100644 index 000000000..0039f4c8e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-controller.ftl @@ -0,0 +1,232 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.alibaba.fastjson.JSON; +import ${packageName}.vo.${classInfo.className}VO; +import ${packageName}.dto.${classInfo.className}DTO; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +//import com.bjc.lcp.common.cnt.enums.CntTableNameEnum; +//import com.bjc.lcp.common.cnt.service.CntService; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.annotation.Validated; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.beans.BeanUtils; +import org.springframework.util.ObjectUtils; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.bjc.lcp.system.common.utils.DataResult; +import org.springframework.web.servlet.ModelAndView; +import javax.annotation.Resource; +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Api(tags = "${classInfo.classComment}-管理") +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + @Resource + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + //@Autowired + //private CntService cntService; + + @ApiOperation(value = "${classInfo.classComment}-新增") + @PostMapping("/add") + @RequiresPermissions("${classInfo.className?uncap_first}:add") + public DataResult add(@Validated(${classInfo.className}VO.Create.class) @RequestBody ${classInfo.className}VO vo) { + ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.nullable==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + if (list.size() > 0) { + return DataResult.fail("数据已存在"); + } + ${classInfo.className}Entity entity = new ${classInfo.className}Entity(); + + BeanUtils.copyProperties(dto, entity); + return DataResult.success(${classInfo.className?uncap_first}Service.save(entity)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/remove") + @RequiresPermissions("${classInfo.className?uncap_first}:remove") + public DataResult delete(@Validated(${classInfo.className}VO.Delete.class) @RequestBody ${classInfo.className}VO vo) { + ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + return DataResult.success(${classInfo.className?uncap_first}Service.remove(queryWrapper)); + } + + @ApiOperation(value = "${classInfo.classComment}-删除") + @DeleteMapping("/delete") + @RequiresPermissions("${classInfo.className?uncap_first}:delete") + public DataResult delete(@RequestBody @ApiParam(value = "id集合") List ids) { + return DataResult.success(${classInfo.className?uncap_first}Service.removeByIds(ids)); + } + + + @ApiOperation(value = "${classInfo.classComment}-更新") + @PutMapping("/update") + @RequiresPermissions("${classInfo.className?uncap_first}:update") + public DataResult update(@Validated(${classInfo.className}VO.Update.class) @RequestBody ${classInfo.className}VO vo) { + ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + if (entity == null) { + return DataResult.fail("数据不存在"); + } + BeanUtils.copyProperties(dto, entity); + return DataResult.success(${classInfo.className?uncap_first}Service.updateById(entity)); + } + + + + @ApiOperation(value = "${classInfo.classComment}-查询单条") + @RequestMapping(value = "/getOne",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:getOne") + public DataResult getOne(@RequestBody ${classInfo.className}VO vo) { + ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); + BeanUtils.copyProperties(vo, dto); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (ObjectUtils.isEmpty(dto.get${fieldItem.fieldName?cap_first}())) { + return DataResult.fail("参数[${fieldItem.fieldName}]不能为空"); + } +#if> +#list> +#if> + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); +#if> +#list> +#if> + ${classInfo.className}Entity entity = ${classInfo.className?uncap_first}Service.getOne(queryWrapper);; + return DataResult.success(entity); + } + + + + + @ApiOperation(value = "${classInfo.classComment}-查询列表分页数据") + @RequestMapping(value = "/listByPage",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:listByPage") + public DataResult listByPage(@RequestBody ${classInfo.className}VO ${classInfo.className?uncap_first}) { + Page page = new Page(${classInfo.className?uncap_first}.getPage(), ${classInfo.className?uncap_first}.getLimit()); + ${classInfo.className}DTO dto = new ${classInfo.className}DTO(); + BeanUtils.copyProperties(${classInfo.className?uncap_first}, dto); + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, dto.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + IPage<${classInfo.className}Entity> iPage = ${classInfo.className?uncap_first}Service.page(page, queryWrapper); + return DataResult.success(iPage); + } + + @ApiOperation(value = "${classInfo.classComment}-查询全部列表数据") + @RequestMapping(value = "/list",method = {RequestMethod.GET,RequestMethod.POST}) + @RequiresPermissions("${classInfo.className?uncap_first}:list") + public DataResult findListByPage(@RequestBody ${classInfo.className}VO ${classInfo.className?uncap_first}) { + LambdaQueryWrapper<${classInfo.className}Entity> queryWrapper = Wrappers.lambdaQuery(); +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > +<#if fieldItem.isPrimaryKey==true> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +<#else> + if (!ObjectUtils.isEmpty(${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}())) { + queryWrapper.eq(${classInfo.className}Entity::get${fieldItem.fieldName?cap_first}, ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); + } +#if> +#list> +#if> + List<${classInfo.className}Entity> list = ${classInfo.className?uncap_first}Service.list(queryWrapper); + return DataResult.success(list); + } + + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl new file mode 100644 index 000000000..132f5e406 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-dto.ftl @@ -0,0 +1,44 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.dto;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.bjc.lcp.system.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}DTO extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}DTO() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl new file mode 100644 index 000000000..1b0bd65ff --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-entity.ftl @@ -0,0 +1,51 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.bjc.lcp.system.entity.BaseEntity; +<#assign isSwagger=false /> +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +@TableName("${classInfo.tableName}") +public class ${classInfo.className}Entity extends BaseEntity implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.isPrimaryKey==true>@TableId(value = "${fieldItem.columnName}" ,type = IdType.AUTO )<#else>@TableField(value = "${fieldItem.columnName}" )#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}Entity() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl new file mode 100644 index 000000000..c6e239c8b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-mapper.ftl @@ -0,0 +1,41 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}Entity; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}Entity> { + + @Select( + "") + List<${classInfo.className}Entity> pageAll(${classInfo.className}Entity dto,int page,int limit); + + @Select("") + int countAll(${classInfo.className}Entity dto); + + @Select("SELECT count(1) from ${classInfo.tableName} ") + int countAll(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl new file mode 100644 index 000000000..76483b1fe --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-service.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.IService; + +import ${packageName}.entity.${classInfo.className}Entity; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service extends IService<${classInfo.className}Entity> { + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl new file mode 100644 index 000000000..6b3a91a11 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-serviceimpl.ftl @@ -0,0 +1,26 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service.impl;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.service.${classInfo.className}Service; + +#if> +/** + * @description ${classInfo.classComment}服务层实现 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl extends ServiceImpl<${classInfo.className}Mapper, ${classInfo.className}Entity> implements ${classInfo.className}Service { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl new file mode 100644 index 000000000..9e958ba13 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/plus-vo.ftl @@ -0,0 +1,56 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.vo;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import io.swagger.annotations.ApiModelProperty; +import lombok.Data; +import javax.validation.constraints.NotNull; +import javax.validation.constraints.Size; +import java.io.Serializable; +import com.bjc.lcp.system.entity.BaseEntity; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className}VO extends BaseEntity implements Serializable { + + public interface Retrieve{} + public interface Delete {} + public interface Update {} + public interface Create {} + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + <#if fieldItem.nullable==true>@NotNull(message = "${fieldItem.fieldComment}不能为空", groups = {Create.class,Update.class,Delete.class})#if> + <#if fieldItem.nullable==true>@Size( max = ${fieldItem.columnSize},message = "${fieldItem.fieldComment}长度限制${fieldItem.columnSize}位")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}VO() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl new file mode 100644 index 000000000..2aaa8d7a0 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus-v2/pluscontroller.ftl @@ -0,0 +1,166 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.alibaba.fastjson.JSON; +import ${packageName}.vo.${classInfo.className}VO; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @description ${classInfo.classComment} +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + @Autowired + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + /** + * 新增或编辑 + */ + @PostMapping("/save") + public Object save(@RequestBody ${classInfo.className} ${classInfo.className?uncap_first}){ + log.info("${classInfo.className?uncap_first}:"+JSON.toJSONString(${classInfo.className?uncap_first})); + ${classInfo.className} old${classInfo.className} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",${classInfo.className?uncap_first}.get${classInfo.className}Id())); + ${classInfo.className?uncap_first}.setUpdateTime(new Date()); + if(old${classInfo.className}!=null){ + ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); + }else{ + if(${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_name",${classInfo.className?uncap_first}.get${classInfo.className}Name()))!=null){ + return ${returnUtilFailure}("保存失败,名字重复"); + } + ${classInfo.className?uncap_first}.setCreateTime(new Date()); + ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); + } + return ${returnUtilSuccess}("保存成功"); + } + + /** + * 删除 + */ + @PostMapping("/delete") + public Object delete(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + ${classInfo.className?uncap_first}Mapper.deleteById(id); + return ${returnUtilSuccess}("删除成功"); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 查询 + */ + @PostMapping("/find") + public Object find(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + return ${returnUtilSuccess}(${classInfo.className?uncap_first}); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 自动分页查询 + */ + @PostMapping("/list") + public Object list(String searchParams, + @RequestParam(required = false, defaultValue = "0") int page, + @RequestParam(required = false, defaultValue = "10") int limit) { + log.info("page:"+page+"-limit:"+limit+"-json:"+ JSON.toJSONString(searchParams)); + //分页构造器 + Page<${classInfo.className}> buildPage = new Page<${classInfo.className}>(page,limit); + //条件构造器 + QueryWrapper<${classInfo.className}> queryWrapper = new QueryWrapper<${classInfo.className}>(); + if(StringUtils.isNotEmpty(searchParams)&&JSON.isValid(searchParams)) { + ${classInfo.className} ${classInfo.className?uncap_first} = JSON.parseObject(searchParams, ${classInfo.className}.class); + queryWrapper.eq(StringUtils.isNoneEmpty(${classInfo.className?uncap_first}.get${classInfo.className}Name()), "${classInfo.className?uncap_first}_name", ${classInfo.className?uncap_first}.get${classInfo.className}Name()); + } + //执行分页 + IPage<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.selectPage(buildPage, queryWrapper); + //返回结果 + return ${returnUtil}.PAGE(pageList.getRecords(),pageList.getTotal()); + } + /** + * 手工分页查询(按需使用) + */ + /*@PostMapping("/list2") + public Object list2(String searchParams, + @RequestParam(required = false, defaultValue = "0") int page, + @RequestParam(required = false, defaultValue = "10") int limit) { + log.info("searchParams:"+ JSON.toJSONString(searchParams)); + //通用模式 + ${classInfo.className} queryParamDTO = JSON.parseObject(searchParams, ${classInfo.className}.class); + //专用DTO模式 + //QueryParamDTO queryParamDTO = JSON.parseObject(searchParams, QueryParamDTO.class); + //queryParamDTO.setPage((page - 1)* limit); + //queryParamDTO.setLimit(limit); + //(page - 1) * limit, limit + List<${classInfo.className}> itemList = ${classInfo.className?uncap_first}Mapper.pageAll(queryParamDTO,(page - 1)* limit,limit); + Integer itemCount = ${classInfo.className?uncap_first}Mapper.countAll(queryParamDTO); + //返回结果 + return ${returnUtilSuccess}.PAGE(itemList,itemCount); + }*/ + @GetMapping("/list") + public ModelAndView listPage(){ + return new ModelAndView("${classInfo.className?uncap_first}-list"); + } + + @GetMapping("/edit") + public ModelAndView editPage(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + return new ModelAndView("${classInfo.className?uncap_first}-edit","${classInfo.className?uncap_first}",${classInfo.className?uncap_first}); + } + + /** + * 发布/暂停(如不需要请屏蔽) + */ + @PostMapping("/publish") + public Object publish(int id,Integer status){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + ${classInfo.className?uncap_first}.setUpdateTime(new Date()); + ${classInfo.className?uncap_first}.setStatus(status); + ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); + return ${returnUtilSuccess}((status==1)?"已发布":"已暂停"); + }else if(status.equals(${classInfo.className?uncap_first}.getStatus())){ + return ${returnUtilFailure}("状态不正确"); + }else{ + return ${returnUtilFailure}(); + } + } + + /** + * 执行(如不需要请屏蔽) + */ + @PostMapping("/execute") + public Object execute(){ + return ${returnUtilSuccess}; + } +} +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl new file mode 100644 index 000000000..f18e4429c --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/pluscontroller.ftl @@ -0,0 +1,161 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.alibaba.fastjson.JSON; +import ${packageName}.entity.${classInfo.className}; +import ${packageName}.mapper.${classInfo.className}Mapper; +import ${packageName}.util.ReturnT; +import lombok.extern.slf4j.Slf4j; +import org.apache.commons.lang3.StringUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import org.springframework.web.servlet.ModelAndView; + +import java.util.Date; +import java.util.List; +import java.util.Map; +#if> +/** +* @description ${classInfo.classComment}控制器 +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Slf4j +@RestController +@RequestMapping("/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Autowired + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + /** + * 新增或编辑 + */ + @PostMapping("/save") + public Object save(@RequestBody ${classInfo.className} ${classInfo.className?uncap_first}){ + log.info("${classInfo.className?uncap_first}:"+JSON.toJSONString(${classInfo.className?uncap_first})); + ${classInfo.className} old${classInfo.className} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",${classInfo.className?uncap_first}.get${classInfo.className}Id())); + ${classInfo.className?uncap_first}.setUpdateTime(new Date()); + if(old${classInfo.className}!=null){ + ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); + }else{ + if(${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_name",${classInfo.className?uncap_first}.get${classInfo.className}Name()))!=null){ + return ${returnUtilFailure}("保存失败,名字重复"); + } + ${classInfo.className?uncap_first}.setCreateTime(new Date()); + ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); + } + return ${returnUtilSuccess}("保存成功"); + } + + /** + * 删除 + */ + @PostMapping("/delete") + public Object delete(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + ${classInfo.className?uncap_first}Mapper.deleteById(id); + return ${returnUtilSuccess}("删除成功"); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 查询 + */ + @PostMapping("/find") + public Object find(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + return ${returnUtilSuccess}(${classInfo.className?uncap_first}); + }else{ + return ${returnUtilFailure}("没有找到该对象"); + } + } + + /** + * 自动分页查询 + */ + @PostMapping("/list") + public Object list(String searchParams, + @RequestParam(required = false, defaultValue = "0") int page, + @RequestParam(required = false, defaultValue = "10") int limit) { + log.info("page:"+page+"-limit:"+limit+"-json:"+ JSON.toJSONString(searchParams)); + //分页构造器 + Page<${classInfo.className}> buildPage = new Page<${classInfo.className}>(page,limit); + //条件构造器 + QueryWrapper<${classInfo.className}> queryWrapper = new QueryWrapper<${classInfo.className}>(); + if(StringUtils.isNotEmpty(searchParams)&&JSON.isValid(searchParams)) { + ${classInfo.className} ${classInfo.className?uncap_first} = JSON.parseObject(searchParams, ${classInfo.className}.class); + queryWrapper.eq(StringUtils.isNoneEmpty(${classInfo.className?uncap_first}.get${classInfo.className}Name()), "${classInfo.className?uncap_first}_name", ${classInfo.className?uncap_first}.get${classInfo.className}Name()); + } + //执行分页 + IPage<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.selectPage(buildPage, queryWrapper); + //返回结果 + return ${returnUtil}.PAGE(pageList.getRecords(),pageList.getTotal()); + } + /** + * 手工分页查询(按需使用) + */ + /*@PostMapping("/list2") + public Object list2(String searchParams, + @RequestParam(required = false, defaultValue = "0") int page, + @RequestParam(required = false, defaultValue = "10") int limit) { + log.info("searchParams:"+ JSON.toJSONString(searchParams)); + //通用模式 + ${classInfo.className} queryParamDTO = JSON.parseObject(searchParams, ${classInfo.className}.class); + //专用DTO模式 + //QueryParamDTO queryParamDTO = JSON.parseObject(searchParams, QueryParamDTO.class); + //queryParamDTO.setPage((page - 1)* limit); + //queryParamDTO.setLimit(limit); + //(page - 1) * limit, limit + List<${classInfo.className}> itemList = ${classInfo.className?uncap_first}Mapper.pageAll(queryParamDTO,(page - 1)* limit,limit); + Integer itemCount = ${classInfo.className?uncap_first}Mapper.countAll(queryParamDTO); + //返回结果 + return ${returnUtilSuccess}.PAGE(itemList,itemCount); + }*/ + @GetMapping("/list") + public ModelAndView listPage(){ + return new ModelAndView("${classInfo.className?uncap_first}-list"); + } + + @GetMapping("/edit") + public ModelAndView editPage(int id){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + return new ModelAndView("${classInfo.className?uncap_first}-edit","${classInfo.className?uncap_first}",${classInfo.className?uncap_first}); + } + + /** + * 发布/暂停(如不需要请屏蔽) + */ + @PostMapping("/publish") + public Object publish(int id,Integer status){ + ${classInfo.className} ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Mapper.selectOne(new QueryWrapper<${classInfo.className}>().eq("${classInfo.className?uncap_first}_id",id)); + if(${classInfo.className?uncap_first}!=null){ + ${classInfo.className?uncap_first}.setUpdateTime(new Date()); + ${classInfo.className?uncap_first}.setStatus(status); + ${classInfo.className?uncap_first}Mapper.updateById(${classInfo.className?uncap_first}); + return ${returnUtilSuccess}((status==1)?"已发布":"已暂停"); + }else if(status.equals(${classInfo.className?uncap_first}.getStatus())){ + return ${returnUtilFailure}("状态不正确"); + }else{ + return ${returnUtilFailure}(); + } + } + + /** + * 执行(如不需要请屏蔽) + */ + @PostMapping("/execute") + public Object execute(){ + return ${returnUtilSuccess}; + } +} +} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl new file mode 100644 index 000000000..52134edbb --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusentity.ftl @@ -0,0 +1,46 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.entity;#if> + +<#if isAutoImport?exists && isAutoImport==true> +<#if isLombok?exists && isLombok==true>import lombok.Data;#if> +import java.util.Date; +import java.util.List; +import java.io.Serializable; +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +<#if isSwagger?exists && isSwagger==true> +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty;#if> +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +<#if isLombok?exists && isLombok==true>@Data#if><#if isSwagger?exists && isSwagger==true> +@ApiModel("${classInfo.classComment}")#if> +public class ${classInfo.className} implements Serializable { + + private static final long serialVersionUID = 1L; + + @TableId(type = IdType.AUTO) +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if><#if isSwagger?exists && isSwagger==true> + @ApiModelProperty("${fieldItem.fieldComment}")#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +<#if isLombok?exists && isLombok==false> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } +#if> +#list> +#if> + public ${classInfo.className}() {} +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl new file mode 100644 index 000000000..438b514fd --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusmapper.ftl @@ -0,0 +1,38 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; +import ${packageName}.entity.${classInfo.className}; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +public interface ${classInfo.className}Mapper extends BaseMapper<${classInfo.className}> { + + @Select( + "") + List<${classInfo.className}> pageAll(${classInfo.className} queryParamDTO,int page,int limit); + + @Select("") + int countAll(${classInfo.className} queryParamDTO); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl new file mode 100644 index 000000000..4672e01a1 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis-plus/plusservice.ftl @@ -0,0 +1,16 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.IService; +#if> +/** + * @description ${classInfo.classComment}服务层 + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public interface ${classInfo.className}Service extends IService<${classInfo.className}> { + + + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis.ftl new file mode 100644 index 000000000..0e1a7560e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis.ftl @@ -0,0 +1,82 @@ + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + #list> + #if> + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + `${fieldItem.columnName}`<#if fieldItem_has_next>,#if> + #list> + #if> + + + + INSERT INTO ${classInfo.tableName} ( + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" > + `${fieldItem.columnName}`<#if fieldItem_has_next>,#if> + #if> + #list> + #if> + ) + VALUES( + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" > + <#if fieldItem.columnName="AddTime" || fieldItem.columnName="UpdateTime" > + NOW()<#if fieldItem_has_next>,#if> + <#else> + ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>,#if> + #if> + #if> + #list> + #if> + ) + + + + DELETE FROM ${classInfo.tableName} + WHERE `id` = ${r"#{id}"} + + + + UPDATE ${classInfo.tableName} + SET + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "Id" && fieldItem.columnName != "AddTime" && fieldItem.columnName != "UpdateTime" > + ${fieldItem.columnName} = ${r"#{"}${classInfo.className?uncap_first}.${fieldItem.fieldName}${r"}"}, + #if> + #list> + UpdateTime = NOW() + WHERE `id` = ${r"#{"}${classInfo.className?uncap_first}.id${r"}"} + + + + + SELECT + FROM ${classInfo.tableName} + WHERE `id` = ${r"#{id}"} + + + + SELECT + FROM ${classInfo.tableName} + LIMIT ${r"#{offset}"}, ${r"#{pagesize}"} + + + + SELECT count(1) + FROM ${classInfo.tableName} + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/controller.ftl new file mode 100644 index 000000000..69697c732 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/controller.ftl @@ -0,0 +1,76 @@ +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Map; +#if> + +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@RestController +@RequestMapping(value = "/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + + @Resource + private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + + /** + * 新增 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + @RequestMapping("/insert") + public Object insert(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.insert(${classInfo.className?uncap_first}); + } + + /** + * 刪除 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + @RequestMapping("/delete") + public ReturnT delete(int id){ + return ${classInfo.className?uncap_first}Service.delete(id); + } + + /** + * 更新 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + @RequestMapping("/update") + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}){ + return ${classInfo.className?uncap_first}Service.update(${classInfo.className?uncap_first}); + } + + /** + * 查询 根据主键 id 查询 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + @RequestMapping("/load") + public Object load(int id){ + return ${classInfo.className?uncap_first}Service.load(id); + } + + /** + * 查询 分页查询 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + @RequestMapping("/pageList") + public Map pageList(@RequestParam(required = false, defaultValue = "0") int offset, + @RequestParam(required = false, defaultValue = "10") int pagesize) { + return ${classInfo.className?uncap_first}Service.pageList(offset, pagesize); + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper.ftl new file mode 100644 index 000000000..e7dc9ef57 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper.ftl @@ -0,0 +1,59 @@ +<#if isAutoImport?exists && isAutoImport==true> +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Mapper; +import org.springframework.stereotype.Repository; +import java.util.List; +#if> + +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +@Repository +public interface ${classInfo.className}Mapper { + + /** + * 新增 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + int insert(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 刪除 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + int delete(int id); + + /** + * 更新 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + int update(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 查询 根据主键 id 查询 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + ${classInfo.className} load(int id); + + /** + * 查询 分页查询 + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + List<${classInfo.className}> pageList(int offset,int pagesize); + + /** + * 查询 分页查询 count + * @author ${authorName} + * @date ${.now?string('yyyy/MM/dd')} + **/ + int pageListCount(int offset,int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper2.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper2.ftl new file mode 100644 index 000000000..ee0b5e0a6 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mapper2.ftl @@ -0,0 +1,56 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.apache.ibatis.annotations.*; +import org.springframework.stereotype.Repository; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment}Mapper + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Mapper +@Repository +public interface ${classInfo.className}Mapper { + + @Select("select * from ${classInfo.tableName} where ${classInfo.tableName}_id=井{id}") + public ${classInfo.className} getById(Integer id); + + @Options(useGeneratedKeys=true,keyProperty="${classInfo.className?uncap_first}Id") + @Insert("insert into ${classInfo.tableName}" + + " (<#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>,#if>#list>)" + + " values(<#list classInfo.fieldList as fieldItem >${fieldItem.fieldName}<#if fieldItem_has_next>,<#else>)#if>#list>") + public Integer insert(${classInfo.className} ${classInfo.className?uncap_first}); + + @Delete(value = "delete from ${classInfo.tableName} where ${classInfo.tableName}_id=井{${classInfo.className?uncap_first}Id}") + boolean delete(Integer id); + + @Update(value = "update ${classInfo.tableName} set " + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "id">+" ${fieldItem.columnName}=井{${fieldItem.fieldName}}<#if fieldItem_has_next>,#if>"#if> + #list> + +" where ${classInfo.tableName}_id=井{${classInfo.className?uncap_first}Id} ") + boolean update(${classInfo.className} ${classInfo.className?uncap_first}); + + + @Results(value = { + <#list classInfo.fieldList as fieldItem > + @Result(property = "${fieldItem.fieldName}", column = "${fieldItem.columnName}")<#if fieldItem_has_next>,#if> + #list> + }) + @Select(value = "select * from ${classInfo.tableName} where ${classInfo.tableName}_id=井{queryParam}") + ${classInfo.className} selectOne(String queryParam); + + @Results(value = { + <#list classInfo.fieldList as fieldItem > + @Result(property = "${fieldItem.fieldName}", column = "${fieldItem.columnName}")<#if fieldItem_has_next>,#if> + #list> + }) + @Select(value = "select * from ${classInfo.tableName} where " + <#list classInfo.fieldList as fieldItem > + +" ${fieldItem.columnName}=井{${fieldItem.fieldName}}<#if fieldItem_has_next> or #if>" + #list> + ) + List<${classInfo.className}> selectList(${classInfo.className} ${classInfo.className?uncap_first}); + +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/model.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/model.ftl new file mode 100644 index 000000000..3e94df707 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/model.ftl @@ -0,0 +1,40 @@ +<#if isAutoImport?exists && isAutoImport==true> +import java.io.Serializable; +import java.util.Date; +import java.util.List; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public class ${classInfo.className} implements Serializable { + + private static final long serialVersionUID = 1L; + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem > + <#if isComment?exists && isComment==true>/** + * ${fieldItem.fieldComment} + */#if> + private ${fieldItem.fieldClass} ${fieldItem.fieldName}; + +#list> +#if> + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + public ${classInfo.className}() { + } + +<#list classInfo.fieldList as fieldItem> + public ${fieldItem.fieldClass} get${fieldItem.fieldName?cap_first}() { + return ${fieldItem.fieldName}; + } + + public void set${fieldItem.fieldName?cap_first}(${fieldItem.fieldClass} ${fieldItem.fieldName}) { + this.${fieldItem.fieldName} = ${fieldItem.fieldName}; + } + +#list> +#if> +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mybatis.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mybatis.ftl new file mode 100644 index 000000000..24bfb858b --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/mybatis.ftl @@ -0,0 +1,89 @@ + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + #list> + #if> + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + ${fieldItem.columnName}<#if fieldItem_has_next>,#if> + #list> + #if> + + + + INSERT INTO ${classInfo.tableName} + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "id" > + + ${fieldItem.columnName}<#if fieldItem_has_next>,#if> + ${r""} + #if> + #list> + #if> + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "id" > + <#--<#if fieldItem.columnName="addtime" || fieldItem.columnName="updatetime" > + ${r""} + NOW()<#if fieldItem_has_next>,#if> + ${r""} + <#else>--> + + ${r"#{"}${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>,#if> + ${r""} + <#--#if>--> + #if> + #list> + #if> + + + + + DELETE FROM ${classInfo.tableName} + WHERE id = ${r"#{id}"} + + + + UPDATE ${classInfo.tableName} + + <#list classInfo.fieldList as fieldItem > + <#if fieldItem.columnName != "id" && fieldItem.columnName != "AddTime" && fieldItem.columnName != "UpdateTime" > + ${fieldItem.columnName} = ${r"#{"}${fieldItem.fieldName}${r"}"}<#if fieldItem_has_next>,#if>${r""} + #if> + #list> + + WHERE id = ${r"#{"}id${r"}"} + + + + + SELECT + FROM ${classInfo.tableName} + WHERE id = ${r"#{id}"} + + + + SELECT + FROM ${classInfo.tableName} + LIMIT ${r"#{offset}"}, ${r"#{pageSize}"} + + + + SELECT count(1) + FROM ${classInfo.tableName} + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service.ftl new file mode 100644 index 000000000..c31f30b0f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service.ftl @@ -0,0 +1,36 @@ +<#if isAutoImport?exists && isAutoImport==true> +import java.util.Map; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +public interface ${classInfo.className}Service { + + /** + * 新增 + */ + public Object insert(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 删除 + */ + public Object delete(int id); + + /** + * 更新 + */ + public Object update(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 根据主键 id 查询 + */ + public ${classInfo.className} load(int id); + + /** + * 分页查询 + */ + public Map pageList(int offset, int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service_impl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service_impl.ftl new file mode 100644 index 000000000..3a8345de8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/mybatis/service_impl.ftl @@ -0,0 +1,68 @@ +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +#if> +/** + * @description ${classInfo.classComment} + * @author ${authorName} + * @date ${.now?string('yyyy-MM-dd')} + */ +@Service +public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { + + @Resource + private ${classInfo.className}Mapper ${classInfo.className?uncap_first}Mapper; + + + @Override + public Object insert(${classInfo.className} ${classInfo.className?uncap_first}) { + + // valid + if (${classInfo.className?uncap_first} == null) { + return ${returnUtilFailure}("必要参数缺失"); + } + + ${classInfo.className?uncap_first}Mapper.insert(${classInfo.className?uncap_first}); + return ${returnUtilSuccess}(); + } + + + @Override + public Object delete(int id) { + int ret = ${classInfo.className?uncap_first}Mapper.delete(id); + return ret>0?${returnUtilSuccess}():${returnUtilFailure}(); + } + + + @Override + public Object update(${classInfo.className} ${classInfo.className?uncap_first}) { + int ret = ${classInfo.className?uncap_first}Mapper.update(${classInfo.className?uncap_first}); + return ret>0?${returnUtilSuccess}():${returnUtilFailure}(); + } + + + @Override + public ${classInfo.className} load(int id) { + return ${classInfo.className?uncap_first}Mapper.load(id); + } + + + @Override + public Map pageList(int offset, int pagesize) { + + List<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Mapper.pageList(offset, pagesize); + int totalCount = ${classInfo.className?uncap_first}Mapper.pageListCount(offset, pagesize); + + // result + Map result = new HashMap(); + result.put("pageList", pageList); + result.put("totalCount", totalCount); + + return result; + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl new file mode 100644 index 000000000..2b3193a3f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/menu-sql.ftl @@ -0,0 +1,17 @@ +-- 菜单SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +VALUES ('1', '${classInfo.classComment}', 'generator/${classInfo.className?uncap_first}', NULL, '1', 'config', '6'); + +-- 按钮父菜单ID +set @parentId = @@identity; + +-- 菜单对应按钮SQL +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '查看', null, 'generator:${classInfo.className?uncap_first}:list,generator:${classInfo.className?uncap_first}:info', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '新增', null, 'generator:${classInfo.className?uncap_first}:save', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '修改', null, 'generator:${classInfo.className?uncap_first}:update', '2', null, '6'; +INSERT INTO `sys_menu` (`parent_id`, `name`, `url`, `perms`, `type`, `icon`, `order_num`) +SELECT @parentId, '删除', null, 'generator:${classInfo.className?uncap_first}:delete', '2', null, '6'; + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl new file mode 100644 index 000000000..31a1c39f9 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-controller.ftl @@ -0,0 +1,89 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.controller;#if> +<#if isAutoImport?exists && isAutoImport==true> +import java.util.Arrays; +import java.util.Map; + +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import ${packageName}.entity.${classInfo.className}Entity; +import ${packageName}.service.${classInfo.className}Service; +import ${packageName}.common.utils.PageUtils; +import ${packageName}.common.utils.R; +#if> + + +/** +* @description ${classInfo.classComment}控制器 +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@RestController +@RequestMapping("generator/${classInfo.className?uncap_first}") +public class ${classInfo.className}Controller { + +@Autowired +private ${classInfo.className}Service ${classInfo.className?uncap_first}Service; + +/** +* 列表 +*/ +@RequestMapping("/list") +@RequiresPermissions("generator:${classInfo.className?uncap_first}:list") +public R list(@RequestParam Map params){ + PageUtils page = ${classInfo.className?uncap_first}Service.queryPage(params); + + return R.ok().put("page", page); +} + + +/** +* 信息 +*/ +@RequestMapping("/info/{${classInfo.className?uncap_first}Id}") +@RequiresPermissions("generator:${classInfo.className?uncap_first}:info") +public R info(@PathVariable("${classInfo.className?uncap_first}Id") int ${classInfo.className?uncap_first}Id){ + ${classInfo.className}Entity ${classInfo.className?uncap_first} = ${classInfo.className?uncap_first}Service.getById(${classInfo.className?uncap_first}Id); + + return R.ok().put("${classInfo.className?uncap_first}", ${classInfo.className?uncap_first}); +} + +/** +* 保存 +*/ +@RequestMapping("/save") +@RequiresPermissions("generator:${classInfo.className?uncap_first}:save") +public R save(@RequestBody ${classInfo.className}Entity ${classInfo.className?uncap_first}){ + ${classInfo.className?uncap_first}Service.save(${classInfo.className?uncap_first}); + + return R.ok(); +} + +/** +* 修改 +*/ +@RequestMapping("/update") +@RequiresPermissions("generator:${classInfo.className?uncap_first}:update") +public R update(@RequestBody ${classInfo.className}Entity ${classInfo.className?uncap_first}){ + ${classInfo.className?uncap_first}Service.updateById(${classInfo.className?uncap_first}); + + return R.ok(); +} + +/** +* 删除 +*/ +@RequestMapping("/delete") +@RequiresPermissions("generator:${classInfo.className?uncap_first}:delete") +public R delete(@RequestBody int[] ${classInfo.className?uncap_first}Ids){ + ${classInfo.className?uncap_first}Service.removeByIds(Arrays.asList(${classInfo.className?uncap_first}Ids)); + + return R.ok(); +} + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl new file mode 100644 index 000000000..15f7e9643 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-dao.ftl @@ -0,0 +1,15 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.mapper;#if> +<#if isAutoImport?exists && isAutoImport==true> +import ${packageName}.entity.${classInfo.className}Entity; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +#if> +/** +* @description ${classInfo.classComment}Mapper +* @author ${authorName} +* @date ${.now?string('yyyy-MM-dd')} +*/ +@Mapper +public interface ${classInfo.className}Dao extends BaseMapper<${classInfo.className}Entity> { + +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl new file mode 100644 index 000000000..c4656036e --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-daoxml.ftl @@ -0,0 +1,15 @@ + + + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + #list> + #if> + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-entity.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-entity.ftl new file mode 100644 index 000000000..e69de29bb diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl new file mode 100644 index 000000000..719246d22 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/rr-service.ftl @@ -0,0 +1,28 @@ +<#if isWithPackage?exists && isWithPackage==true>package ${packageName}.service;#if> +<#if isAutoImport?exists && isAutoImport==true> +import org.springframework.stereotype.Service; +import java.util.Map; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import ${packageName}.common.utils.PageUtils; +import ${packageName}.common.utils.Query; + +import ${packageName}.dao.${classInfo.className}Dao; +import ${packageName}.entity.${classInfo.className}Entity; +#if> + +@Service("${classInfo.className?uncap_first}Service") +public class ${classInfo.className}Service extends ServiceImpl<${classInfo.className}Dao, ${classInfo.className}Entity> { + + @Override + public PageUtils queryPage(Map params) { + IPage<${classInfo.className}Entity> page = this.page( + new Query<${classInfo.className}Entity>().getPage(params), + new QueryWrapper<${classInfo.className}Entity>() + ); + + return new PageUtils(page); + } + +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl new file mode 100644 index 000000000..6f5835baf --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-edit.ftl @@ -0,0 +1,101 @@ + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + + + #list> + #if> + + + 取消 + 确定 + + + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl new file mode 100644 index 000000000..969d7d808 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/renren-fast/vue-list.ftl @@ -0,0 +1,162 @@ + + + + + + + + 查询 + 新增 + 批量删除 + + + + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + + #list> + #if> + + + + 修改 + 删除 + + + + + + + + + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service.ftl new file mode 100644 index 000000000..b3295ddab --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service.ftl @@ -0,0 +1,39 @@ +package ${packageService}; +import java.util.Map; + +import ${packageModel}.${classInfo.className}; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +public interface ${classInfo.className}Service { + + /** + * 新增 + */ + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * 删除 + */ + public ReturnT delete(int id); + + /** + * 更新 + */ + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}); + + /** + * Load查询 + */ + public ${classInfo.className} load(int id); + + /** + * 分页查询 + */ + public Map pageList(int offset, int pagesize); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service_impl.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service_impl.ftl new file mode 100644 index 000000000..44ca00df8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/service_impl.ftl @@ -0,0 +1,85 @@ +package ${packageServiceImpl}; + +import org.springframework.stereotype.Service; + +import com.jun.plugin.biz.dao.${classInfo.className}Dao; +import ${packageModel}.${classInfo.className}; +import ${packageService}.${classInfo.className}Service; +import com.jun.plugin.codegenerator.admin.model.ReturnT; + +import javax.annotation.Resource; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** +* ${classInfo.classComment} +* +* Created by wujun on '${.now?string('yyyy-MM-dd HH:mm:ss')}'. +*/ +@Service +public class ${classInfo.className}ServiceImpl implements ${classInfo.className}Service { + + @Resource + private ${classInfo.className}Dao ${classInfo.className?uncap_first}Dao; + + /** + * 新增 + */ + @Override + public ReturnT insert(${classInfo.className} ${classInfo.className?uncap_first}) { + + // valid + if (${classInfo.className?uncap_first} == null) { + return new ReturnT(ReturnT.FAIL_CODE, "必要参数缺失"); + } + + ${classInfo.className?uncap_first}Dao.insert(${classInfo.className?uncap_first}); + return ReturnT.SUCCESS; + } + + /** + * 删除 + */ + @Override + public ReturnT delete(int id) { + int ret = ${classInfo.className?uncap_first}Dao.delete(id); + return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; + } + + /** + * 更新 + */ + @Override + public ReturnT update(${classInfo.className} ${classInfo.className?uncap_first}) { + int ret = ${classInfo.className?uncap_first}Dao.update(${classInfo.className?uncap_first}); + return ret>0?ReturnT.SUCCESS:ReturnT.FAIL; + } + + /** + * Load查询 + */ + @Override + public ${classInfo.className} load(int id) { + return ${classInfo.className?uncap_first}Dao.load(id); + } + + /** + * 分页查询 + */ + @Override + public Map pageList(int offset, int pagesize) { + + List<${classInfo.className}> pageList = ${classInfo.className?uncap_first}Dao.pageList(offset, pagesize); + int totalCount = ${classInfo.className?uncap_first}Dao.pageListCount(offset, pagesize); + + // result + Map result = new HashMap(); + result.put("pageList", pageList); + result.put("totalCount", totalCount); + + return result; + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl new file mode 100644 index 000000000..eaefd4312 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/bootstrap-ui.ftl @@ -0,0 +1,13 @@ + + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + ${fieldItem.fieldComment} + + + #list> + #if> + + 保存 + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/element-ui.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/element-ui.ftl new file mode 100644 index 000000000..9f9e224d2 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/element-ui.ftl @@ -0,0 +1,16 @@ + + + + ${classInfo.classComment} + 提交 + 返回 + + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + + + #list> + #if> + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-edit.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-edit.ftl new file mode 100644 index 000000000..6299a1b24 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-edit.ftl @@ -0,0 +1,64 @@ + + + + + + + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + + ${fieldItem.fieldComment} + + + <#--${fieldItem.fieldComment}--> + + + #list> +#if> + + + + 确认保存 + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-list.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-list.ftl new file mode 100644 index 000000000..a3de2993c --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/layui-list.ftl @@ -0,0 +1,221 @@ + + + + + + + + 搜索信息 + + + + + ${classInfo.classComment}Id + + + + + + ${classInfo.classComment}名称 + + + + + + 搜 索 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/swagger-ui.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/swagger-ui.ftl new file mode 100644 index 000000000..0e506598d --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/ui/swagger-ui.ftl @@ -0,0 +1,9 @@ +@ApiOperation(value = "${classInfo.classComment}", notes = "${classInfo.classComment}") + @ApiImplicitParams({ + <#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + <#list classInfo.fieldList as fieldItem > + @ApiImplicitParam(name = "${fieldItem.fieldName}", value = "${fieldItem.fieldComment}", required = false, dataType = "${fieldItem.fieldClass}")<#if fieldItem_has_next>,#if> + #list> + #if> + } + ) diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/beanutil.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/beanutil.ftl new file mode 100644 index 000000000..108e27af9 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/beanutil.ftl @@ -0,0 +1,41 @@ +/** +* ${classInfo.classComment}对象Get Set +* @author ${authorName} ${.now?string('yyyy-MM-dd')} +*/ + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +${fieldItem.fieldClass} ${fieldItem.fieldName} = ${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}(); +#list> + +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +${classInfo.className?uncap_first}.set${fieldItem.fieldName?cap_first}(); +#list> + +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +${classInfo.className?uncap_first}.set${fieldItem.fieldName?cap_first}(${classInfo.className?uncap_first}2.get${fieldItem.fieldName?cap_first}()); +#list> + +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +map.put("${fieldItem.fieldName?uncap_first}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); +#list> + +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +map.put("${fieldItem.columnName}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); +#list> + +<#list classInfo.fieldList as fieldItem> +map.put("${fieldItem.fieldComment}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); +#list> + +<#list classInfo.fieldList as fieldItem> +// ${fieldItem.fieldComment} +map.put("${fieldItem.fieldName?uncap_first}",${classInfo.className?uncap_first}.get${fieldItem.fieldName?cap_first}()); +#list> + +#if> diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/json.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/json.ftl new file mode 100644 index 000000000..596cce40f --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/json.ftl @@ -0,0 +1,13 @@ +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +{ +<#list classInfo.fieldList as fieldItem> + "${fieldItem.fieldName}":"${fieldItem.fieldComment}"<#if fieldItem_has_next>,#if> +#list> +} + +{ +<#list classInfo.fieldList as fieldItem> + "${fieldItem.fieldName}":""<#if fieldItem_has_next>,#if> +#list> +} +#if> diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/sql.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/sql.ftl new file mode 100644 index 000000000..126f84dc2 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/sql.ftl @@ -0,0 +1,74 @@ + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> + #SQL横向select + SELECT <#list classInfo.fieldList as fieldItem >t.${fieldItem.columnName}<#if fieldItem_has_next>,#if>#list> + FROM ${classInfo.tableName} t; + + #CSV横向字段名 + <#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>,#if>#list> +#if> + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +#LEFT JOIN + SELECT + * + FROM + ${classInfo.tableName} a + LEFT JOIN ${classInfo.tableName} b + ON a.${classInfo.tableName}_id=b.${classInfo.tableName}_id + WHERE 1=1; +#if> + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +#INSERT INTO + INSERT INTO ${classInfo.tableName} ( <#list classInfo.fieldList as fieldItem >${fieldItem.columnName}<#if fieldItem_has_next>,#if>#list> ) + VALUES + ( + <#list classInfo.fieldList as fieldItem >''<#if fieldItem_has_next>,#if>#list> + ); +#if> + + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +#关联更新 + UPDATE ${classInfo.tableName} a + JOIN ${classInfo.tableName}_join b ON a.${classInfo.tableName}_id = b.${classInfo.tableName}_id + SET <#list classInfo.fieldList as fieldItem > a.${fieldItem.columnName} = b.${fieldItem.columnName}<#if fieldItem_has_next>,#if> #list> + WHERE + b.${classInfo.tableName}_id IS NOT NULL; + + UPDATE ${classInfo.tableName} a,${classInfo.tableName}_join b + SET <#list classInfo.fieldList as fieldItem > a.${fieldItem.columnName} = b.${fieldItem.columnName}<#if fieldItem_has_next>,#if> #list> + WHERE a.${classInfo.tableName}_id = b.${classInfo.tableName}_id; + +#普通update + UPDATE ${classInfo.tableName} + SET + <#list classInfo.fieldList as fieldItem > + ${fieldItem.columnName} = ''<#if fieldItem_has_next>,#if> + #list> + WHERE + <#list classInfo.fieldList as fieldItem > + ${fieldItem.columnName} = ''<#if fieldItem_has_next>,#if> + #list>; +#if> + + + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +#关联删除 + delete a from ${classInfo.tableName}_del as a inner join ${classInfo.tableName} as b + where a.${classInfo.tableName}_id=b.${classInfo.tableName}_id; + +#普通删除 + DELETE + FROM + ${classInfo.tableName} + WHERE + <#list classInfo.fieldList as fieldItem > + ${fieldItem.columnName} = ''<#if fieldItem_has_next>,#if> + #list>; + +#if> + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/swagger-yml.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/swagger-yml.ftl new file mode 100644 index 000000000..ce22aaa50 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/swagger-yml.ftl @@ -0,0 +1,12 @@ + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +${classInfo.className}: + type: "object" + properties: +<#list classInfo.fieldList as fieldItem > + ${fieldItem.fieldName}: + type: ${fieldItem.swaggerClass} + description: <#if isComment?exists && isComment==true>"${fieldItem.fieldComment}"#if> +#list> +#if> + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/xml.ftl b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/xml.ftl new file mode 100644 index 000000000..3959cfcb1 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/code-generator/util/xml.ftl @@ -0,0 +1,11 @@ + +<#if classInfo.fieldList?exists && classInfo.fieldList?size gt 0> +<${classInfo.className}> +<#list classInfo.fieldList as fieldItem> + <${fieldItem.fieldName}>${fieldItem.fieldComment}${fieldItem.fieldName}> +#list> +${classInfo.className}> +#if> diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/Controller.java.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/Controller.java.vm new file mode 100644 index 000000000..1768ee9d8 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/Controller.java.vm @@ -0,0 +1,181 @@ +package ${package}.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +import org.springframework.util.CollectionUtils; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.core.metadata.IPage; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; +import java.util.List; +import com.jun.plugin.system.common.utils.DataResult; +import com.jun.plugin.common.aop.annotation.DataScope; +import com.jun.plugin.module.flow.process.BaseFlowController; + +import ${package}.entity.${className}Entity; +import ${package}.mapper.${className}Mapper; +import ${package}.service.${className}Service; + + + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +@Controller +@RequestMapping("/") +@Slf4j +public class ${className}Controller extends BaseFlowController{ + + @Autowired + private ${className}Service ${classname}Service; + + @Autowired + private ${className}Mapper ${classname}Mapper; + + + /** + * 跳转到页面 + */ + @GetMapping("/index/${classname}") + public String ${classname}() { + return "${classNameLower}/list"; + } + + @ApiOperation(value = "新增") + @PostMapping("${classname}/add") + @RequiresPermissions("${classname}:add") + @ResponseBody + public DataResult add(@RequestBody ${className}Entity ${classname}){ + if(this.checkExists(${classname})) { + return DataResult.fail("同名记录信息已存在!"); + } + ${classname}Service.save(${classname}); + return DataResult.success(); + } + + @ApiOperation(value = "删除") + @DeleteMapping("${classname}/delete") + @RequiresPermissions("${classname}:delete") + @ResponseBody + public DataResult delete(@RequestBody @ApiParam(value = "id集合") List ids){ + ${classname}Service.removeByIds(ids); + return DataResult.success(); + } + + @ApiOperation(value = "更新") + @PutMapping("${classname}/update") + @RequiresPermissions("${classname}:update") + @ResponseBody + public DataResult update(@RequestBody ${className}Entity ${classname}){ + ${classname}Service.updateById(${classname}); + return DataResult.success(); + } + + @ApiOperation(value = "查询分页数据") + @PostMapping("${classname}/listByPage") + @RequiresPermissions("${classname}:list") + @ResponseBody + @DataScope + public DataResult findListByPage(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()==null?"":${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + //关联流程查询待办、处理人、状态 + List<${className}Entity> records = iPage.getRecords(); + records.forEach(item -> { + if((item.getOrderId()!=null && item.getOrderId().length()>0) && (item.getOrderStatus()==null)) { + this.setFlowStatusInfo(item); + System.err.println(item.getOrderStatus()); + if(item.getOrderState()==0) { + if((item.getOrderStatus()==null || item.getOrderStatus()!=0)) { + item.setOrderStatus(item.getOrderState()); + ${classname}Service.updateById(item); + } + } + }else { + item.setOrderState(item.getOrderStatus()); + } + + }); + return DataResult.success(iPage); + } + + + @ApiOperation(value = "查询下拉列表数据") + @PostMapping("${classname}/listBySelect") + @ResponseBody + @DataScope + public DataResult listBySelect(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //查询条件示例 + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + return DataResult.success(iPage); + } + + @ApiOperation(value = "查询单条数据") + @PostMapping("${classname}/findOne") + @ResponseBody + public DataResult findOne(@RequestBody ${className}Entity ${classname}){ + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //queryWrapper.eq(${className}Entity::getId, ${classname}.getId()); + //${className}Entity one = ${classname}Service.getOne(queryWrapper); + ${className}Entity one = ${classname}Service.getById(${classname}.getId()); + return DataResult.success(one); + } + + @ApiOperation(value = "查询下拉框数据") + @PostMapping("${classname}/findListBySelect") + @ResponseBody + @DataScope + public DataResult findListBySelect(@RequestBody ${className}Entity ${classname}){ + Page page = new Page(${classname}.getPage(), ${classname}.getLimit()); + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + //数据权限示例, 需手动添加此条件 begin + if (!CollectionUtils.isEmpty(${classname}.getCreateIds())) { + queryWrapper.in(${className}Entity::getCreateId, ${classname}.getCreateIds()); + } + //数据权限示例, 需手动添加此条件 end + //queryWrapper.like(${className}Entity::getId, ${classname}.getId()); + IPage<${className}Entity> iPage = ${classname}Service.page(page, queryWrapper); + log.info("\n this.${classname}Mapper.selectCountUser()="+this.${classname}Mapper.selectCountUser()); + return DataResult.success(iPage); + } + + @PostMapping("${classname}/checkExists") + @ResponseBody + public Boolean checkExists(@RequestBody ${className}Entity ${classname}){ + LambdaQueryWrapper<${className}Entity> queryWrapper = Wrappers.lambdaQuery(); + queryWrapper.eq(${className}Entity::getId, ${classname}.getId());// 这里换成自己查询的关键条件 + ${className}Entity one = ${classname}Service.getOne(queryWrapper.last("LIMIT 1")); + if(one == null) { + return false; + }else { + return true; + } + } + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.java.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.java.vm new file mode 100644 index 000000000..36a5f4563 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.java.vm @@ -0,0 +1,20 @@ +package ${package}.mapper; + +import ${package}.entity.${className}Entity; +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Select; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +public interface ${className}Mapper extends BaseMapper<${className}Entity> { + + @Select("SELECT count(1) from sys_user") + int selectCountUser(); + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.xml.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.xml.vm new file mode 100644 index 000000000..9b44ded64 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/Dao.xml.vm @@ -0,0 +1,14 @@ + + + + + + + +#foreach($column in $columns) + +#end + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/Entity.java.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/Entity.java.vm new file mode 100644 index 000000000..c51dc91f3 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/Entity.java.vm @@ -0,0 +1,60 @@ +package ${package}.entity; + +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.fasterxml.jackson.annotation.JsonFormat; +import com.jun.plugin.common.entity.BaseFlowEntity; +import org.springframework.data.annotation.Id; + +#if(${hasBigDecimal}) +#end +import java.io.Serializable; + +import lombok.Data; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +@Data +@TableName("${tableName}") +public class ${className}Entity extends BaseFlowEntity implements Serializable { + private static final long serialVersionUID = 1L; + +##循环,遍历字段信息 +#foreach ($column in $columns) + /** + * $column.comments + */ +##判断是否主键1 +#if($column.columnName == $pk.columnName) + @Id + @TableId("$column.columnName") + private $column.attrType $column.attrname; +#end +##判断是否主键 +#if($column.columnName != $pk.columnName) +##循环列,新增字段描述备注 + @TableField(value = "$column.columnName" ## +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted")) +, fill = FieldFill.INSERT ## +#elseif($column.columnName.toString().contains("update")) +, fill = FieldFill.INSERT_UPDATE ## +#end ) +##循环列,新增字段描述备注dataType +#if($column.dataType == 'datetime') + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") +#elseif($column.dataType == 'date') + @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8") +#end + private $column.attrType $column.attrname; +#end +##循环,结束 +#end + +} diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/Service.java.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/Service.java.vm new file mode 100644 index 000000000..847833676 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/Service.java.vm @@ -0,0 +1,16 @@ +package ${package}.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import ${package}.entity.${className}Entity; + +/** + * ${comments} + * + * @author ${author} + * @email ${email} + * @date ${datetime} + */ +public interface ${className}Service extends IService<${className}Entity> { + +} + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/ServiceImpl.java.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/ServiceImpl.java.vm new file mode 100644 index 000000000..8d8891f2d --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/ServiceImpl.java.vm @@ -0,0 +1,15 @@ +package ${package}.service.impl; + +import org.springframework.stereotype.Service; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; + +import ${package}.mapper.${className}Mapper; +import ${package}.entity.${className}Entity; +import ${package}.service.${className}Service; + + +@Service("${classname}Service") +public class ${className}ServiceImpl extends ServiceImpl<${className}Mapper, ${className}Entity> implements ${className}Service { + + +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/controller.java.ftl b/jun_api_online/jun_generator/src/main/resources/templates/vm/controller.java.ftl new file mode 100644 index 000000000..b2429b779 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/controller.java.ftl @@ -0,0 +1,78 @@ +package ${package.Controller}; + +import cn.hutool.core.collection.CollUtil; +import org.springframework.web.bind.annotation.RequestMapping; +import ${package.Entity}.${entity}; +import ${package.Service}.${table.serviceName}; +<#if restControllerStyle> + import org.springframework.web.bind.annotation.RestController; +<#else> + import org.springframework.stereotype.Controller; +#if> +import com.laker.admin.framework.model.Response; +import com.laker.admin.framework.model.PageResponse; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import io.swagger.annotations.ApiOperation; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; +<#if superControllerClassPackage??> + import ${superControllerClassPackage}; +#if> + +/** +* + * ${table.comment!} 前端控制器 + * +* +* @author ${author} +* @since ${date} +*/ +<#if restControllerStyle> + @RestController +<#else> + @Controller +#if> +@RequestMapping("/${cfg.easyModule}/${cfg.easyMain}") +<#if superControllerClass??> + public class ${table.controllerName} extends ${superControllerClass} { +<#else> + public class ${table.controllerName} { +#if> +@Autowired +${table.serviceName} ${table.serviceName?substring(1)?uncap_first}; + +@GetMapping +@ApiOperation(value = "${table.comment!}分页查询") +public PageResponse pageAll(@RequestParam(required = false, defaultValue = "1") long page, +@RequestParam(required = false, defaultValue = "10") long limit) { +Page roadPage = new Page<>(page, limit); +LambdaQueryWrapper<${table.entityName}> queryWrapper = new QueryWrapper().lambda(); +Page pageList = ${table.serviceName?substring(1)?uncap_first}.page(roadPage, queryWrapper); +return PageResponse.ok(pageList.getRecords(), pageList.getTotal()); +} + +@PostMapping +@ApiOperation(value = "新增或者更新${table.comment!}") +public Response saveOrUpdate(@RequestBody ${table.entityName} param) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.saveOrUpdate(param)); +} + +@GetMapping("/{id}") +@ApiOperation(value = "根据id查询${table.comment!}") +public Response get(@PathVariable Long id) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.getById(id)); +} + +@DeleteMapping("/{id}") +@ApiOperation(value = "根据id删除${table.comment!}") +public Response delete(@PathVariable Long id) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.removeById(id)); +} +@DeleteMapping("/batch/{ids}") +@ApiOperation(value = "根据批量删除ids删除") +public Response batchRemove(@PathVariable Long[] ids) { +return Response.ok(${table.serviceName?substring(1)?uncap_first}.removeByIds(CollUtil.toList(ids))); +} +} \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/list.html.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/list.html.vm new file mode 100644 index 000000000..0bf010994 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/list.html.vm @@ -0,0 +1,604 @@ + + + + + Title + + + + + + + + + + +#* + + 基本信息 + +*# + +###遍历新增修改表单 +#foreach($column in $columns) + #if($column.columnName == $pk.columnName) + + #else +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("creat") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end + + + +#if($column.dataType != 'text') #end + ${column.comments} + +##注解支持,不展示 +#if($column.dataType == 'datetime') + +#elseif($column.columnName.toString().contains("dict")) + + 请选择 + + +#elseif($column.dataType == 'text') + +#else + #if($column.isNull == 'NO') + + #else + + #end +#end + + #if($column.dataType != 'text') #end + + +#end +#end + + + 保存 + 返回 + + + + + + + + + + + + + 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! + + + +###遍历查询条件 +#foreach($column in $columns) +#if($column.columnName != $pk.columnName && $column.isNull == 'NO') +##跳过循环,新增及修改时间字段,注解支持,不展示 +#if($column.columnName.toString().contains("create") || $column.columnName.toString().contains("deleted") || $column.columnName.toString().contains("update")) + #break +#end +#if($column.dataType == 'datetime') + + + +#else + + + +#end +#end +#end + + 查询 + 导出全部 + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/menu.sql.vm b/jun_api_online/jun_generator/src/main/resources/templates/vm/menu.sql.vm new file mode 100644 index 000000000..0f66241e7 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/menu.sql.vm @@ -0,0 +1,26 @@ +-- 默认上级目录菜单为其他 +INSERT INTO sys_permission (id, name, pid, url,target, type,order_num, deleted, status,create_time,update_time) + VALUES ('${identity}', '${comments}' ,'54', '/index/${classname}','_self', '2', '910',1, 1,now(),now()); +-- 菜单对应按钮SQL +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${selectId}', '${identity}', '列表' , '${classname}/listByPage','${classname}:list', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${addId}', '${identity}', '新增' , '${classname}/add','${classname}:add', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${updateId}', '${identity}', '修改' , '${classname}/update','${classname}:update', '3',1, 1,now(),now()); +INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) + VALUES ('${deleteId}', '${identity}', '删除' , '${classname}/delete','${classname}:delete', '3',1, 1,now(),now()); + +-- INSERT INTO sys_permission (id,pid, name, url, perms, type, deleted, status,create_time,update_time) +-- VALUES ('${deleteId}11', '${identity}', '提交' , '${classname}/submit','${classname}:submit', '3',1, 1,now(),now()); + + + +select +#foreach($column in $columns) + ${column.columnName} as ${column.attrname}, +#end + 1 as gen +from + ${tableName} +where id != null ; \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/web/add.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/add.html.ftl new file mode 100644 index 000000000..d95915f7c --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/add.html.ftl @@ -0,0 +1,63 @@ + + + + + Title + + + + + + + + <#list table.fields as field> + <#if !field.keyFlag && field.propertyName != 'enable'> + + ${field.comment} + + + + + #if> + <#if field.propertyName == 'enable'> + + 字典状态 + + + + + + #if> + #list> + + + + + + + 提交 + + + + 重置 + + + + + + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/web/edit.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/edit.html.ftl new file mode 100644 index 000000000..f72341635 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/edit.html.ftl @@ -0,0 +1,74 @@ + + + + + + + + + + + + <#list table.fields as field> + <#if field.keyFlag > + + + id + + + + + #if> + + <#if !field.keyFlag && field.propertyName != 'enable'> + + ${field.comment} + + + + + #if> + <#if field.propertyName == 'enable'> + + 字典状态 + + + + + + #if> + #list> + + + + + + + + 提交 + + + + 重置 + + + + + + + + + + + diff --git a/jun_api_online/jun_generator/src/main/resources/templates/vm/web/main.html.ftl b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/main.html.ftl new file mode 100644 index 000000000..a69beae59 --- /dev/null +++ b/jun_api_online/jun_generator/src/main/resources/templates/vm/web/main.html.ftl @@ -0,0 +1,113 @@ + + + + + ${table.comment} + + + + + + + + 关键字 + + + + + + 查询 + + + + 重置 + + + + + + + + + + + + + + + + + + + + + diff --git a/jun_api_online/jun_generator/src/test/java/com/jun/plugin/CodeGeneratorMain.java b/jun_api_online/jun_generator/src/test/java/com/jun/plugin/CodeGeneratorMain.java new file mode 100644 index 000000000..cbf72ddaf --- /dev/null +++ b/jun_api_online/jun_generator/src/test/java/com/jun/plugin/CodeGeneratorMain.java @@ -0,0 +1,53 @@ +package com.jun.plugin; + +import com.alibaba.druid.pool.DruidDataSource; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.jun.plugin.common.generator.GeneratorUtil; +import com.jun.plugin.common.generator.GeneratorUtil; + +import java.util.List; +import java.util.Map; + +/** + * 代码生成器,根据DatabaseMetaData及数据表名称生成对应的Model、Mapper、Service、Controller简化基础代码逻辑开发。 + * @author Wujun + */ +public class CodeGeneratorMain { + + public static void main(String[] args) throws Exception { +// String tables = "res_basc,res_basc_arg,api_config"; +// String tables = "git_user"; +// String tables = "app_infoenvt,app_member,app_datasource,app_git_config,git_user,app_deploy_config"; + Map config = Maps.newHashMap(); + config.put("packageName","com.bjc.lcp.app1234"); +// config.put("project_path","D:/workspace/github/jun_code_generator/jun_code_freemarker/"); + config.put("output_path","D:\\workspace\\github\\jun_api_service\\jun_api_service_online\\plugins\\generator\\"); + config.put("template_path","D:\\workspace\\github\\jun_api_service\\jun_api_service_online\\plugins\\generator\\src\\main\\resources\\templates"); + config.put("userDefaultTemplate","false"); + DruidDataSource ds = new DruidDataSource(); + ds.setUrl("jdbc:mysql://localhost:3306/db_qixing_bk?useUnicode=true&characterEncoding=UTF-8&useSSL=true&serverTimezone=UTC&useInformationSchema=true"); + ds.setDriverClassName("com.mysql.cj.jdbc.Driver"); + ds.setUsername("root"); + ds.setPassword(""); + GeneratorUtil.setDataSource(ds); + GeneratorUtil.setTemplates(getTemplates()); + GeneratorUtil.initConfig(config); + GeneratorUtil.genCode("ext_salgrade"); +// GeneratorUtil.genCode(Arrays.asList(tables.split(",")),getTemplates());; + } + + public static List getTemplates() { + List templates = Lists.newArrayList(); + // ************************************************************************************ + templates.add("code-generator/mybatis-plus-single-v2/controller.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/entity.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/mapper.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/service.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/dto.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/vo.java.ftl"); + templates.add("code-generator/mybatis-plus-single-v2/service.impl.java.ftl"); + return templates; + } + +} diff --git a/jun_api_online/jun_plugin/pom.xml b/jun_api_online/jun_plugin/pom.xml new file mode 100644 index 000000000..a3ea5cad9 --- /dev/null +++ b/jun_api_online/jun_plugin/pom.xml @@ -0,0 +1,17 @@ + + + 4.0.0 + + com.jun.plugin + jun_plugin + pom + 1.0 + 组件模块 + + + + + + \ No newline at end of file diff --git a/jun_api_online/jun_plugins/aoplog/pom.xml b/jun_api_online/jun_plugins/aoplog/pom.xml new file mode 100644 index 000000000..de41612ac --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/pom.xml @@ -0,0 +1,65 @@ + + + 4.0.0 + + com.jun.plugin + aoplog + jar + 1.0 + 日志组件 + + + + UTF-8 + UTF-8 + 1.8 + 1.8 + 1.8 + 3.5.3.1 + true + + + + + + com.jun.plugin + common + 1.0 + + + org.springframework.boot + spring-boot-starter-aop + + + + org.apache.shiro + shiro-spring + 1.4.0 + + + com.baomidou + mybatis-plus-extension + 3.5.3.2 + compile + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + \ No newline at end of file diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/annotation/LogAnnotation.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/annotation/LogAnnotation.java new file mode 100644 index 000000000..a56ffaed5 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/annotation/LogAnnotation.java @@ -0,0 +1,25 @@ +package com.jun.plugin.aoplog.annotation; + +import java.lang.annotation.*; + +/** + * LogAnnotation + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface LogAnnotation { + /** + * 模块 + */ + String title() default ""; + + /** + * 功能 + */ + String action() default ""; +} diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/config/LogAutoConfig.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/config/LogAutoConfig.java new file mode 100644 index 000000000..078e9cad8 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/config/LogAutoConfig.java @@ -0,0 +1,17 @@ +package com.jun.plugin.aoplog.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.aoplog") +@MapperScan(basePackages = "com.jun.plugin.aoplog.mapper") +@ServletComponentScan(basePackages = {"com.jun.plugin.aoplog.compoent"}) +public class LogAutoConfig { +} diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/controller/SysLogController.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/controller/SysLogController.java new file mode 100644 index 000000000..4ed3ab34f --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/controller/SysLogController.java @@ -0,0 +1,59 @@ +package com.jun.plugin.aoplog.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.jun.plugin.aoplog.entity.SysLog; +import com.jun.plugin.aoplog.service.LogService; +import com.jun.plugin.common.Result; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.util.List; + +/** + * 系统操作日志 + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +@RequestMapping("/sys") +@Api(tags = "系统模块-系统操作日志管理") +@RestController +public class SysLogController { + @Resource + private LogService logService; + + @PostMapping("/logs") + @ApiOperation(value = "分页查询系统操作日志接口") + @RequiresPermissions("sys:log:list") + public Result pageInfo(@RequestBody SysLog vo) { + LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); + if (!StringUtils.isEmpty(vo.getUsername())) { + queryWrapper.like(SysLog::getUsername, vo.getUsername()); + } + if (!StringUtils.isEmpty(vo.getOperation())) { + queryWrapper.like(SysLog::getOperation, vo.getOperation()); + } + if (!StringUtils.isEmpty(vo.getStartTime())) { + queryWrapper.gt(SysLog::getCreateTime, vo.getStartTime()); + } + if (!StringUtils.isEmpty(vo.getEndTime())) { + queryWrapper.lt(SysLog::getCreateTime, vo.getEndTime()); + } + queryWrapper.orderByDesc(SysLog::getCreateTime); + return Result.success(logService.page(vo.getQueryPage(), queryWrapper)); + } + + @DeleteMapping("/logs") + @ApiOperation(value = "删除日志接口") + @RequiresPermissions("sys:log:deleted") + public Result deleted(@RequestBody List logIds) { + logService.removeByIds(logIds); + return Result.success(); + } +} diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/entity/SysLog.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/entity/SysLog.java new file mode 100644 index 000000000..a4557bb61 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/entity/SysLog.java @@ -0,0 +1,55 @@ +package com.jun.plugin.aoplog.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.Date; + +/** + * 操作日志 + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +@EqualsAndHashCode(callSuper = true) +@Data +public class SysLog extends BaseEntity implements Serializable { + @TableId + private String id; + + private String userId; + + private String username; + + private String operation; + + private Integer time; + + private String method; + + private String params; + + private String ip; + + @TableField(fill = FieldFill.INSERT) + private Date createTime; + + @TableField(exist = false) + private String startTime; + + @TableField(exist = false) + private String endTime; + + public Page getQueryPage(){ + Page page = new Page(getPage(), getLimit()); + return page; + } + +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/mapper/SysLogMapper.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/mapper/SysLogMapper.java new file mode 100644 index 000000000..8a6f27f6c --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/mapper/SysLogMapper.java @@ -0,0 +1,14 @@ +package com.jun.plugin.aoplog.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.jun.plugin.aoplog.entity.SysLog; + +/** + * 操作日志 Mapper + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysLogMapper extends BaseMapper { +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/LogService.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/LogService.java new file mode 100644 index 000000000..1ab6493a2 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/LogService.java @@ -0,0 +1,14 @@ +package com.jun.plugin.aoplog.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.jun.plugin.aoplog.entity.SysLog; + +/** + * 系统日志 + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +public interface LogService extends IService { +} diff --git a/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/impl/LogServiceImpl.java b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/impl/LogServiceImpl.java new file mode 100644 index 000000000..14792e637 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/java/com/jun/plugin/aoplog/service/impl/LogServiceImpl.java @@ -0,0 +1,18 @@ +package com.jun.plugin.aoplog.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.jun.plugin.aoplog.entity.SysLog; +import com.jun.plugin.aoplog.mapper.SysLogMapper; +import com.jun.plugin.aoplog.service.LogService; +import org.springframework.stereotype.Service; + +/** + * 系统日志 + * + * @author wenbin + * @version V1.0 + * @date 2020年3月18日 + */ +@Service +public class LogServiceImpl extends ServiceImpl implements LogService { +} diff --git a/jun_api_online/jun_plugins/aoplog/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_plugins/aoplog/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..906a48344 --- /dev/null +++ b/jun_api_online/jun_plugins/aoplog/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.aoplog.config.LogAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_plugins/fileservice/pom.xml b/jun_api_online/jun_plugins/fileservice/pom.xml new file mode 100644 index 000000000..5ead35996 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/pom.xml @@ -0,0 +1,158 @@ + + + 4.0.0 + + com.jun.plugin + fileservice + 1.0 + jar + 文件服务 + + + + com.jun.plugin + jun_common + 1.0 + + + + + com.tencentcloudapi + tencentcloud-sdk-java-common + 3.1.838 + + + com.qiniu + qiniu-java-sdk + [7.7.0, 7.7.99] + + + + + + com.qiniu + happy-dns-java + 0.1.6 + test + + + junit + junit + 4.12 + test + + + + com.aliyun.oss + aliyun-sdk-oss + 3.17.1 + + + com.qcloud + cos_api + 4.4 + + + org.slf4j + slf4j-log4j12 + + + junit + junit + + + + + com.google.zxing + javase + 3.2.1 + + + + + com.deepoove + poi-tl + 1.9.1 + + + + com.alibaba + easyexcel + 3.0.5 + + + org.springframework.boot + spring-boot-starter-freemarker + + + + org.springframework.boot + spring-boot-configuration-processor + + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileAutoConfig.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileAutoConfig.java new file mode 100644 index 000000000..0d6997883 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileAutoConfig.java @@ -0,0 +1,15 @@ +package com.jun.plugin.file.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.file") +@MapperScan(basePackages = "com.jun.plugin.file.mapper") +public class FileAutoConfig { +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileProperties.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileProperties.java new file mode 100644 index 000000000..7d296a361 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/FileProperties.java @@ -0,0 +1,55 @@ +package com.jun.plugin.file.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Primary; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * 文件上传参数配置类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Primary +@Component +@Data +@ConfigurationProperties(prefix = "file") +public class FileProperties { + + + + private String path; + private String url; + private String accessUrl; + + private String qiniuAccessKey; + private String qiniuBucketName; + private String qiniuDomain; + private String qiniuPrefix; + private String qiniuSecretKey; + private String type; + + + + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + + this.url = url; + + //set accessUrl + if (StringUtils.isEmpty(url)) { + this.accessUrl = null; + } + this.accessUrl = url.substring(url.lastIndexOf("/")) + "/**"; + System.out.println("accessUrl=" + accessUrl); + } + + +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/ResourcesConfig.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/ResourcesConfig.java new file mode 100644 index 000000000..a10af84c8 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/config/ResourcesConfig.java @@ -0,0 +1,63 @@ +//package com.jun.plugin.file.config; +// +//import com.jun.plugin.common.constant.Constants; +//import com.jun.plugin.file.common.comfig.FileUploadProperties; +//import lombok.extern.slf4j.Slf4j; +//import org.springframework.context.annotation.Configuration; +//import org.springframework.web.servlet.config.annotation.*; +// +//import javax.annotation.Resource; +// +///** +// * 通用配置 +// * +// */ +//@Slf4j +//@Configuration +////@EnableConfigurationProperties(FileUploadProperties.class) +//public class ResourcesConfig implements WebMvcConfigurer { +// +// @Resource +// private FileUploadProperties fileUploadProperties; +// +// @Override +// public void addCorsMappings(CorsRegistry registry) { +// WebMvcConfigurer.super.addCorsMappings(registry); +// registry.addMapping("/**").allowedHeaders("*").allowedMethods("POST", "GET", "PUT", "DELETE") +// .allowedOrigins("*"); +// } +// +// /** +// * 默认首页的设置,当输入域名是可以自动跳转到默认指定的网页 +// */ +// @Override +// public void addViewControllers(ViewControllerRegistry registry) { +//// registry.addViewController("/").setViewName("forward:" + indexUrl); +// registry.addViewController("/").setViewName("forward:" + "login.html"); +// } +// +// /** +// * 发现如果继承了WebMvcConfigurationSupport,则在yml中配置的相关内容会失效。 需要重新指定静态资源 +// */ +// +// +// /** +// * @description: 访问静态文件 +// * @date: 2021/4/15 +// */ +// @Override +// public void addResourceHandlers(ResourceHandlerRegistry registry) { +// /** 本地文件上传路径 */ +// registry.addResourceHandler("/files/**").addResourceLocations("file:" + fileUploadProperties.getPath() + "/"); +// +// /** 文件下载映射配置,同下 */ +// registry.addResourceHandler(fileUploadProperties.getAccessUrl()).addResourceLocations("file:" + fileUploadProperties.getPath()); +// +// log.debug("System.getProperty(\"user.dir\")"); +// // 访问路径 +// registry.addResourceHandler("/api/upload/**") +// // 映射真实路径 +// .addResourceLocations("file:" + System.getProperty("user.dir") + "/");// 必须加"/",不然映射不到 +// } +// +//} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/FileControl.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/FileControl.java new file mode 100644 index 000000000..db427aa3b --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/FileControl.java @@ -0,0 +1,129 @@ +package com.jun.plugin.file.controller; + + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.Map; + +import javax.servlet.ServletOutputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.jun.plugin.file.service.FileService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.ResponseBody; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.google.zxing.BarcodeFormat; +import com.google.zxing.EncodeHintType; +import com.google.zxing.MultiFormatWriter; +import com.google.zxing.WriterException; +import com.google.zxing.client.j2se.MatrixToImageWriter; +import com.google.zxing.common.BitMatrix; +import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; + +@Controller +@RequestMapping(value = "/file") +public class FileControl { + @Autowired + private FileService fileService; + + @RequestMapping(value = "/Login") + public String index() { + return "login"; + } + + //http://localhost:8080/public//Qrcode?url=baidu.com&name=wujun + @RequestMapping(value = "/Qrcode") + public void test(HttpServletResponse response,HttpServletRequest request) throws IOException, WriterException { + //生成二维码 + int width = 150; + int height = 150; + String url = request.getParameter("url"); + String name = request.getParameter("name"); + System.out.println(url+"&name="+name); + String format = "png"; + String content = url+"&name="+name; + ServletOutputStream out = response.getOutputStream(); + Map config = new HashMap<>(); + config.put(EncodeHintType.CHARACTER_SET,"UTF-8"); + config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); + config.put(EncodeHintType.MARGIN, 0); + BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,config); + MatrixToImageWriter.writeToStream(bitMatrix,format,out); + System.out.println("二维码生成完毕,已经输出到页面中。"); + } + +// @RequestMapping(value = "/register") +// @ResponseBody +// public String register(HttpServletRequest request) { +//// 获取账号密码 +// String name = request.getParameter("name"); +// String pass = request.getParameter("pass"); +// //创建一个用户对象 +// User user = new User(name, pass); +// String s = registerService.addOne(user); +// return s; +// } + +// @RequestMapping(value = "/login") +// @ResponseBody +// public String login(HttpServletRequest request) { +// // 获取账号密码 +// String name = request.getParameter("name"); +// String pass = request.getParameter("pass"); +// User user = new User(name, pass); +// String s = loginService.loginService(user); +// return s; +// } + + + //文件上传 + @RequestMapping(value = "/upload") + @ResponseBody + public String upload(HttpServletRequest request, HttpServletResponse response) { + String s = fileService.uploadFile(request); + HashMap map = new HashMap<>(); + map.put("result", s); + //转为json + JSONObject jsonObject = new JSONObject(map); + String res = jsonObject.toString(); + return res; + } + + //文件列表 + @RequestMapping(value = "/filedir") + @ResponseBody + public JSONObject filedir(HttpServletRequest request) { + String res = fileService.fileList(request); + JSONObject jsonObject = JSON.parseObject(res); + jsonObject.remove("message"); + return jsonObject; + } + @RequestMapping(value = "/filelist") + @ResponseBody + public JSONObject filelist(HttpServletRequest request) { + String res = fileService.fileList(request); + JSONObject jsonObject = JSON.parseObject(res); + jsonObject.remove("message"); + return jsonObject; + } +// 文件下载 + @RequestMapping(value = "/filedown") + public void filedown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { + fileService.fileDown(request, response); + } + //文件删除 + @RequestMapping(value = "/filedel") + @ResponseBody + public String filedel(HttpServletRequest request,HttpServletResponse response){ + String msg = ""; + msg = fileService.fileDel(request,response); + return msg; + + } +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/QiniuController.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/QiniuController.java new file mode 100644 index 000000000..a68198e87 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/QiniuController.java @@ -0,0 +1,71 @@ +package com.jun.plugin.file.controller; + +import java.io.File; + +import javax.security.auth.message.AuthException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.jun.plugin.file.utils.FileUtils; +import com.jun.plugin.file.utils.QiniuUtils; +import com.jun.plugin.file.utils.ExecuteResult; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; + +@Controller +@RequestMapping(value = "") +public class QiniuController { + + private static Logger logger = LoggerFactory.getLogger(QiniuController.class); + + + @RequestMapping("qiniuCommon") + private String qiniuCommon(HttpServletRequest request){ + return "qiniuCommon"; + } + + + /** + * @param request + * @param multipartFile + * @return + */ + @RequestMapping(value = "/qiniuUpload", method = RequestMethod.POST) + @ResponseBody + public String qiniuUpload(HttpServletRequest request, HttpServletResponse response, @RequestParam("imagefile") MultipartFile multipartFile) { + ExecuteResult executeResult = new ExecuteResult(); + + QiniuUtils QiniuUtils = new QiniuUtils(); + try { + /** + * 上传文件扩展名 + */ + String filenameExtension = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."), multipartFile.getOriginalFilename().length()); + + /** + * MultipartFile 转 file 类型 + */ + File file = FileUtils.multipartToFile(multipartFile); + + /** + * 七牛云文件上传 服务 file文件 以及 文件扩展名 + */ + executeResult = QiniuUtils.uploadFile2(file, filenameExtension); + if (!executeResult.isSuccess()) { + return "失败" + executeResult.getErrorMessages(); + } + + } catch (AuthException e) { + logger.error("AuthException", e); + } + + return executeResult.getResult(); + } + +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/SysFilesController.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/SysFilesController.java new file mode 100644 index 000000000..7e093dbca --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/controller/SysFilesController.java @@ -0,0 +1,279 @@ +package com.jun.plugin.file.controller; + +import com.alibaba.fastjson2.JSON; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.deepoove.poi.XWPFTemplate; +import com.deepoove.poi.data.PictureRenderData; +import com.jun.plugin.common.Result; +import com.jun.plugin.file.config.FileProperties; +import com.jun.plugin.file.utils.FileUtils; +import com.jun.plugin.file.entity.SysFilesEntity; +import com.jun.plugin.file.service.SysFilesService; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +import lombok.extern.slf4j.Slf4j; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.io.DefaultResourceLoader; +import org.springframework.core.io.ResourceLoader; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.multipart.MultipartFile; + +import javax.annotation.Resource; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * 文件上传 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@RestController +@RequestMapping("/sysFiles") +@Api(tags = "文件管理") +@Slf4j +public class SysFilesController { + @Resource + private SysFilesService sysFilesService; + + + @Autowired + FileProperties fileUploadProperties; + + @ApiOperation(value = "新增") + @PostMapping("/upload") + //@RequiresPermissions(value = { "sysFiles:add", "sysContent:update", "sysContent:add" }, logical = Logical.OR) + public Result add(@RequestParam(value = "file") MultipartFile file, @RequestParam(value = "bizid",required = false) String bizid, + @RequestParam(value = "biztype",required = false) String biztype) { + log.info(biztype); + log.info(bizid); + // 判断文件是否空 + if (file == null || file.getOriginalFilename() == null + || "".equalsIgnoreCase(file.getOriginalFilename().trim())) { + return Result.fail("文件为空"); + } + return sysFilesService.saveFile(file, biztype, bizid); + } + + @ApiOperation(value = "删除") + @DeleteMapping("/delete") + //@RequiresPermissions("sysFiles:delete") + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { + sysFilesService.removeByIdsAndFiles(ids); + return Result.success(); + } + +// @ApiOperation(value = "查询分页数据") +// @PostMapping("/listByPage") +// //@RequiresPermissions("sysFiles:list") +// public Result findListByPage(@RequestBody SysFilesEntity sysFiles) { +// Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); +// IPage iPage = sysFilesService.page(page, +// Wrappers.lambdaQuery().orderByDesc(SysFilesEntity::getCreateDate)); +// return Result.success(iPage); +// } + +// @SuppressWarnings({ "rawtypes", "unchecked" }) +// @ApiOperation(value = "查询分页数据") +// @PostMapping("/listByPageUser") +// //@RequiresPermissions("sysFiles:list") +// public Result listByPageUser(@RequestBody SysFilesEntity sysFiles) { +// Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); +// IPage iPage = sysFilesService.page(page, +// Wrappers.lambdaQuery() +// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) +// .eq(SysFilesEntity::getDictBiztype, sysFiles.getDictBiztype()) +// .orderByDesc(SysFilesEntity::getCreateDate)); +// return Result.success(iPage); +// } + + + + + @ApiOperation(value = "生成简历") + @PostMapping("/genResume") +// @RequiresPermissions(value = { "sysFiles:add", "sysContent:update", "sysContent:add" }, logical = Logical.OR) + public Result genResume(@RequestParam(value = "bizid",required = false) String bizid, + @RequestParam(value = "username",required = false) String username, + @RequestParam(value = "realName",required = false) String realName, + @RequestParam(value = "deptName",required = false) String deptName, + @RequestParam(value = "biztype",required = false) String biztype) throws IOException { + Map resume = new HashMap<>(); + Map data = new HashMap<>(); + ResourceLoader resourceLoader = new DefaultResourceLoader(); + org.springframework.core.io.Resource resource1 = resourceLoader.getResource("classpath:files/"+"logo_resume.jpg"); + data.put("pictures", new PictureRenderData(100, 120, resource1.getFile().getAbsolutePath())); + //SysUser user = userMapper.getUserByName(username); + Map m = null;//JSON.parseObject(JSON.toJSONString(user), Map.class); + data.putAll(m); + List> list11=new ArrayList<>(); + System.err.println(JSON.toJSON(data)); + list11.add(data); + resume.put("resume",list11); + org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:files/"+"简历模板2.docx"); + InputStream inputStream =resource.getInputStream() ; + XWPFTemplate template = XWPFTemplate.compile(inputStream).render( resume); + String newFile = fileUploadProperties.getPath()+realName+"简历"+username+".docx"; + File file = new File(newFile); + FileUtils.createFile(file); + template.writeAndClose(new FileOutputStream(newFile)); + log.info(bizid); + // 判断文件是否空 + if (file == null) { + return Result.fail("文件为空"); + } + return sysFilesService.saveFile(file, biztype, bizid); + } + + + + @SuppressWarnings("unchecked") + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPage") +// @RequiresPermissions("sysFiles:list") + public Result findListByPage(@RequestBody SysFilesEntity sysFiles) { + Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); + IPage iPage = sysFilesService.page(page, + Wrappers.lambdaQuery().orderByDesc(SysFilesEntity::getCreateDate)); + List records = iPage.getRecords(); + String userid = "sessionService.getCurrentUsername()"; + records.forEach(item -> { + if(userid.equalsIgnoreCase(item.getCreator())) { + item.setIsOwner(1); + } + }); + return Result.success(iPage); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPageUser") +// @RequiresPermissions("sysFiles:list") + public Result listByPageUser(@RequestBody SysFilesEntity sysFiles) { + Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); + IPage iPage = sysFilesService.page(page, + Wrappers.lambdaQuery() + .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) +// .eq(SysFilesEntity::getDictBiztype, sysFiles.getDictBiztype()) + .orderByDesc(SysFilesEntity::getCreateDate)); + List records = iPage.getRecords(); + String userid = "sessionService.getCurrentUsername()"; + records.forEach(item -> { + if(userid.equalsIgnoreCase(item.getCreator())) { + item.setIsOwner(1); + } + }); + return Result.success(iPage); + } + + @SuppressWarnings({ "rawtypes", "unchecked" }) + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPageUserProjectID") + public Result listByPageUserProjectID(@RequestBody SysFilesEntity sysFiles) { + String pid = sysFiles.getRefBizid(); + Page page = new Page(sysFiles.getPage(), sysFiles.getLimit()); + String tmpSQL = getProjectFilesRefIDS(pid); + IPage iPage = sysFilesService.page(page, + Wrappers.lambdaQuery() +// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) + .inSql(true, SysFilesEntity::getRefBizid, tmpSQL ) +// .eq(SysFilesEntity::getRefBizid, sysFiles.getRefBizid()) + .orderByDesc(SysFilesEntity::getCreateDate)); + List records = iPage.getRecords(); + String userid = "sessionService.getCurrentUsername()"; + records.forEach(item -> { + if(userid.equalsIgnoreCase(item.getCreator())) { + item.setIsOwner(1); + } + }); + return Result.success(iPage); + } + + @ApiOperation(value = "查询userLogo") + @PostMapping("/getImgByBizid") + public Result getImgByBizid(@RequestBody SysFilesEntity sysFiles) { + LambdaQueryWrapper queryWrapper = new LambdaQueryWrapper<>(); + queryWrapper.eq(SysFilesEntity::getDictBiztype,sysFiles.getDictBiztype()); + queryWrapper.eq(SysFilesEntity::getRefBizid,sysFiles.getRefBizid()); + queryWrapper.orderByDesc(SysFilesEntity::getCreateDate); + queryWrapper.last(" limit 1 "); + List list = sysFilesService.list(queryWrapper); + String userid = "sessionService.getCurrentUsername()"; + if(list.size()>0){ + return Result.success(list.get(0)); + }else{ + return Result.success(); + } + } + + + private String getProjectFilesRefIDS(String pid) { + String tmpSQL = " select pjc.id -- ,pjc.*\r\n" + + " from pj_project t\r\n" + + " left join pj_contract pjc on t.project_code=pjc.refid_project_code_hide\r\n" + + " where t.id='"+pid+"' \r\n" + + "\r\n union SELECT '"+pid+"' from pj_project" + + " union \r\n" + + " select pjp.id -- ,pjp.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_plan pjp on t.project_code=pjp.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + "\r\n" + + " union \r\n" + + " select pjd.id -- ,pjd.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_draft pjd on t.project_code=pjd.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + "\r\n" + + " union \r\n" + + " select pjr.id -- ,pjr.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_recheck pjr on t.project_code=pjr.ref_pcode\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pja.id -- ,pja.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_appraise pja on t.project_code=pja.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pji.id -- ,pji.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_invoice pji on t.project_code=pji.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pjm.id -- ,pjm.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_member pjm on t.project_code=pjm.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pjt.id -- ,pjt.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_prodess_task pjt on t.project_code=pjt.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pjr1.id -- ,pjr1.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_report pjr1 on t.project_code=pjr1.ref_project_code\r\n" + + " where t.id='"+pid+"' \r\n" + + " union \r\n" + + " select pjrn.id -- ,pjrn.*\r\n" + + " from pj_project t\r\n" + + " left join pj_project_reportnumber pjrn on t.project_code=pjrn.ref_reportnumber_code\r\n" + + " where t.id='"+pid+"' "; + return tmpSQL; + } + +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/entity/SysFilesEntity.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/entity/SysFilesEntity.java new file mode 100644 index 000000000..1f514d575 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/entity/SysFilesEntity.java @@ -0,0 +1,71 @@ +package com.jun.plugin.file.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; + +import com.jun.plugin.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.Date; + +/** + * 文件上传 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("sys_files") +public class SysFilesEntity extends BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 主键 + */ + @TableId("id") + private String id; + + /** + * URL地址 + */ + @TableField("url") + private String url; + + /** + * 创建时间 + */ + @TableField(value = "create_date", fill = FieldFill.INSERT) + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") + private Date createDate; + + @TableField("file_name") + private String fileName; + + @TableField("file_path") + private String filePath; + + @TableField("dict_biztype") + private String dictBiztype; + + @TableField("ref_bizid") + private String refBizid; + + /** + * 创建人 + */ + @TableField(value = "creator", fill = FieldFill.INSERT) + private String creator; + + @TableField("file_size") + private String fileSize; + + + +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/mapper/SysFilesMapper.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/mapper/SysFilesMapper.java new file mode 100644 index 000000000..f48c07782 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/mapper/SysFilesMapper.java @@ -0,0 +1,15 @@ +package com.jun.plugin.file.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.jun.plugin.file.entity.SysFilesEntity; + +/** + * 文件上传 Mapper + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysFilesMapper extends BaseMapper { + +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/FileService.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/FileService.java new file mode 100644 index 000000000..be9f576b9 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/FileService.java @@ -0,0 +1,12 @@ +package com.jun.plugin.file.service; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.io.UnsupportedEncodingException; + +public interface FileService { + String uploadFile(HttpServletRequest request); + String fileList(HttpServletRequest request); + void fileDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException; + String fileDel(HttpServletRequest request,HttpServletResponse response); +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/SysFilesService.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/SysFilesService.java new file mode 100644 index 000000000..4fcc5f9a5 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/SysFilesService.java @@ -0,0 +1,37 @@ +package com.jun.plugin.file.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.jun.plugin.common.Result; +import com.jun.plugin.file.entity.SysFilesEntity; + +import org.springframework.web.multipart.MultipartFile; + +import java.io.File; +import java.util.List; + +/** + * 文件上传 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysFilesService extends IService { + + Result saveFile(MultipartFile file); + + void removeByIdsAndFiles(List ids); + + Result saveFile(MultipartFile file, String biztype, String bizid); + + Result saveOssFile(MultipartFile file); + + + + Result saveFile(File file, String biztype, String bizid); + + + Result saveFile(File file); + +} + diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/FileServiceImpl.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/FileServiceImpl.java new file mode 100644 index 000000000..843a72973 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/FileServiceImpl.java @@ -0,0 +1,363 @@ +package com.jun.plugin.file.service.impl; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.HashMap; + +import javax.annotation.Resource; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.jun.plugin.common.utils.DateUtils; +import com.jun.plugin.file.config.FileProperties; +import com.jun.plugin.file.entity.SysFilesEntity; +import com.jun.plugin.file.mapper.SysFilesMapper; +import com.jun.plugin.file.service.FileService; +import com.jun.plugin.file.utils.QiniuUtils; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.MultipartHttpServletRequest; +import org.springframework.web.util.WebUtils; + +import com.alibaba.fastjson2.JSONObject; + +import lombok.extern.slf4j.Slf4j; + + +@Slf4j +@Service +public class FileServiceImpl implements FileService { + +// @Value("${filepath}") + @Value("${file.path}") + private String file_root; + + @Resource + private FileProperties fileUploadProperties; + + @Resource + SysFilesMapper sysFilesMapper; + + + @Override + public String uploadFile(HttpServletRequest request) { + String messagee = ""; + MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class); + MultipartFile file = multipartRequest.getFile("file"); + String filename = multipartRequest.getFile("file").getOriginalFilename(); + String username = multipartRequest.getParameter("name"); + if(!username.equals("")){ + //完整的文件路径 + File file1 = new File(file_root + username); + //文件路径不存在则刷新页面创建路径 + if(!file1.exists()){ + if(!file1.exists()){ + file1.mkdirs(); + log.info("用户:{}创建了文件夹{}",username,file); + } + // messagee="请刷新再上传"; + + } + //文件是否存在 + File file2 = new File(file_root + username+File.separator, filename); + if(file2.exists()){ + messagee = "文件已存在,无需上传"; + }else { + try{ + file.transferTo(file2); + log.info("用户:{}上传文件{}成功",username,filename); + messagee = "上传成功"; + } catch (IOException e) { + messagee = "上传失败"; + log.info("用户:{}上传文件{}失败",username,filename); + e.printStackTrace(); + } + } + }else { + Cookie[] cookies = request.getCookies(); + String username1 = ""; + if(cookies != null){ + //找到cookie,作为文件上传路径 + for (int i = 0; i <= cookies.length-1; i++) { + if(cookies[i].getName().equals("Junior_file")){ + username1 = cookies[i].getValue(); + break; + }else { + continue; + } + } + File file1 = new File(file_root + username1); + if(!file1.exists()){ + messagee = "请刷新再上传"; + }else { + File file2 = new File(file_root + username1+File.separator, filename); + if(file2.exists()){ + messagee = "文件已存在,无需上传"; + }else { + try { + file.transferTo(file2); + + saveSysFile(file2, filename, file2.getAbsolutePath(),username,"user",username); + messagee = "上传成功"; + log.info("临时用户上传文件{}成功",filename); + } catch (IOException e) { + messagee = "上传失败"; + log.info("临时用户上传文件{}失败",filename); + e.printStackTrace(); + } + } + } + }else { + messagee = "请刷新再上传"; + } + } + return messagee; + } + + private void saveSysFile(File file,String originalFilename,String newFilePathName, String username,String biztype,String bizid) throws IOException { + String createTime = DateUtils.dateTimeNow(); + String newPath = fileUploadProperties.getPath() + createTime + File.separator; + File uploadDirectory = new File(newPath); + if (uploadDirectory.exists()) { + if (!uploadDirectory.isDirectory()) { + uploadDirectory.delete(); + } + } else { + uploadDirectory.mkdir(); + } + String fileName = originalFilename; + String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); + // QiniuUtils.uploadFile(file, fileNameNew); + String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); + String URL = QiniuUtils.domain + "/" + fileName; + String url = fileUploadProperties.getUrl() + "/" + createTime + "/" + fileNameNew; + String filesize = QiniuUtils.FormetFileSize(file.length()); + this.saveFilesEntity(originalFilename, file.getAbsolutePath(),url,filesize,biztype, bizid); + } + + private void saveFilesEntity(String fileName, String newFilePathName, String url,String filesize, String biztype, String bizid) { + SysFilesEntity entity = new SysFilesEntity(); + entity.setFileName(fileName); + entity.setFilePath(newFilePathName); + entity.setUrl(url); + entity.setFileSize(filesize); + entity.setDictBiztype(biztype); + entity.setRefBizid(bizid); + sysFilesMapper.insert(entity); + } + + + //文件下载 + @Override + public void fileDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException { + String msg = ""; + //获得文件名 + String filename = request.getParameter("filename"); +// 获得文件路径 + String filepath = request.getParameter("name"); + if(!filepath.equals("")){ + File file = new File(file_root + filepath + File.separator+filename); + msg = fileDown(file, response, filename,filepath); + }else { + String filepath1 = getMyCookie(request); + File file = new File(file_root + filepath1 + File.separator + filename); + msg = fileDown(file, response, filename,filepath1); + } + + System.out.println(msg); + } + + //文件删除 + @Override + public String fileDel(HttpServletRequest request,HttpServletResponse response) { + String msg = ""; + String filename = request.getParameter("filename"); + String path = request.getParameter("name"); + if(!path.equals("")){ + File file = new File(file_root + path + File.separator + filename); + msg = fileDelOpt(file); + log.info("用户{}删除文件{}成功",path,filename); + }else { + String path1 = getMyCookie(request); + File file = new File(file_root + path1 + File.separator + filename); + msg = fileDelOpt(file); + log.info("临时用户删除文件{}成功",path,filename); + } + return msg; + } + + @Override + public String fileList(HttpServletRequest request) { + String message = ""; + ArrayList list = new ArrayList<>(); + String username = request.getParameter("name"); + if(!username.equals("")){ + //完整的文件路径 + File file1 = new File(file_root + username); + //文件路径不存在则刷新页面创建路径 + if(!file1.exists()){ + message="文件错误"; + }else { + File[] files = file1.listFiles(); + for (int i = 0; i <=files.length-1; i++) { + HashMap map = new HashMap<>(); + map.put("filename",files[i].getName()); + map.put("filetime",getModifiedTime(files[i])); + map.put("filesize",String.valueOf((((float)Math.round((getFileSize(files[i])/1048576)*100))/100))+" MB"); + list.add(map); + } + message = "文件存在"; + } + }else { + Cookie[] cookies = request.getCookies(); + String username1 = ""; + if(cookies != null){ + //找到cookie,作为文件上传路径 + for (int i = 0; i <= cookies.length-1; i++) { + if(cookies[i].getName().equals("Junior_file")){ + username1 = cookies[i].getValue(); + break; + }else { + continue; + } + } + File file = new File(file_root + username1); + if(!file.exists()){ + message="文件错误"; + }else { + File[] files = file.listFiles(); + for (int i = 0; i <=files.length-1; i++) { + HashMap map = new HashMap<>(); + map.put("filename",files[i].getName()); + map.put("filetime",getModifiedTime(files[i])); + map.put("filesize",String.valueOf((((float)Math.round((getFileSize(files[i])/1048576)*100))/100))+" MB"); + list.add(map); + } + message = "文件存在"; + } + }else { + message="文件错误"; + } + } + JSONObject jsonObject = new JSONObject(); + jsonObject.put("message",message); + if(message == "文件存在"){ + jsonObject.put("code",0); + }else { + jsonObject.put("code",404); + } + jsonObject.put("data",list); + String res = jsonObject.toJSONString(); + return res; + } + + //获取文件大小 + private static float getFileSize(File f) { + InputStream fis = null; + try { + fis = new FileInputStream(f); + return fis.available(); + } catch (Exception e) { + e.printStackTrace(); + } finally { + if (fis != null) { + try { + fis.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + return 0; + } + + //获取文件创建时间 + public static String getModifiedTime(File f){ + Calendar cal = Calendar.getInstance(); + long time = f.lastModified(); + SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + cal.setTimeInMillis(time); + //输出:修改时间[2] 2009-08-17 10:32:38 + return formatter.format(cal.getTime()); + } + + //获取cookie + public static String getMyCookie(HttpServletRequest request) { + String cookie = ""; + Cookie[] cookies = request.getCookies(); + if (cookies != null) { + //找到cookie,作为文件上传路径 + for (int i = 0; i <= cookies.length - 1; i++) { + if (cookies[i].getName().equals("Junior_file")) { + cookie = cookies[i].getValue(); + break; + } else { + continue; + } + } + } + return cookie; + } + + //文件下载操作 + public static String fileDown(File file,HttpServletResponse response,String filename,String filepath) throws UnsupportedEncodingException { + String msg = ""; + if(file.exists()){ + //设置响应体,响应头 + response.setContentType("application/force-download;charset=UTF-8"); + //文件中含有逗号等,需要将文件名用引号包起来 + response.addHeader("Content-Disposition", "attachment;fileName=" + "\""+ URLEncoder.encode(filename,"utf-8") +"\""); + +// 通过文件流下载 + byte[] buffer = new byte[1024]; + try (FileInputStream fis = new FileInputStream(file); + BufferedInputStream bis = new BufferedInputStream(fis)) { + OutputStream os = response.getOutputStream(); + int i = bis.read(buffer); + while (i != -1) { + os.write(buffer, 0, i); + i = bis.read(buffer); + } + log.info("用户:{}下载文件{}成功",filepath,filename); + msg = "下载成功"; + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + }else { + log.info("临时用户下载文件{}失败",filename); + msg = "下载失败"; + } + return msg; + } + + //文件删除操作 + public static String fileDelOpt(File file){ + String msg = ""; + if(file.exists()){ + try { + file.delete(); + msg = "文件删除成功"; + }catch (Exception e){ + e.printStackTrace(); + msg = "文件删除错误"; + } + }else { + msg = "文件删除错误"; + } + return msg; + } +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/SysFilesServiceImpl.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/SysFilesServiceImpl.java new file mode 100644 index 000000000..23e634a38 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/service/impl/SysFilesServiceImpl.java @@ -0,0 +1,250 @@ +package com.jun.plugin.file.service.impl; + +import java.io.File; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.annotation.Resource; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import com.jun.plugin.common.Result; +import com.jun.plugin.common.exception.BusinessException; +import com.jun.plugin.common.utils.DateUtils; +import com.jun.plugin.file.entity.SysFilesEntity; +import com.jun.plugin.file.mapper.SysFilesMapper; +import com.jun.plugin.file.utils.QiniuUtils; +import org.apache.commons.io.FileUtils; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.stereotype.Service; +import org.springframework.web.multipart.MultipartFile; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.jun.plugin.file.config.FileProperties; +import com.jun.plugin.file.service.SysFilesService; + +/** + * 文件上传 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@EnableConfigurationProperties(FileProperties.class) +@Service("sysFilesService") +public class SysFilesServiceImpl extends ServiceImpl implements SysFilesService { + @Resource + private FileProperties fileUploadProperties; + + @Resource + private SysFilesMapper sysFilesMapper; + + private static final ThreadLocal> mapTmp = new ThreadLocal(); + + @Override + public Result saveFile(MultipartFile file) { + //存储文件夹 +// String createTime = DateUtils.format(new Date(), DateUtils.DATEPATTERN); + String createTime = DateUtils.dateTimeNow(); + String newPath = fileUploadProperties.getPath() + createTime + File.separator; + File uploadDirectory = new File(newPath); + if (uploadDirectory.exists()) { + if (!uploadDirectory.isDirectory()) { + uploadDirectory.delete(); + } + } else { + uploadDirectory.mkdir(); + } + try { + String fileName = file.getOriginalFilename(); + //id与filename保持一直,删除文件 + String fileNameNew = UUID.randomUUID().toString().replace("-", "") + getFileType(fileName); + String newFilePathName = newPath + fileNameNew; + String url = fileUploadProperties.getUrl() + "/" + createTime + "/" + fileNameNew; + //创建输出文件对象 + File outFile = new File(newFilePathName); + //拷贝文件到输出文件对象 + FileUtils.copyInputStreamToFile(file.getInputStream(), outFile); + //保存文件记录 + saveFilesEntity(fileName, newFilePathName, url, "filemanager", "",""); + Map resultMap = new HashMap<>(); + resultMap.put("src", url); + return Result.success(resultMap); + } catch (Exception e) { + throw new BusinessException("上传文件失败"); + } + } + + + private void saveFilesEntity(String fileName, String newFilePathName, String url,String filesize, String biztype, String bizid) { + SysFilesEntity entity = new SysFilesEntity(); + entity.setFileName(fileName); + entity.setFilePath(newFilePathName); + entity.setUrl(url); + entity.setFileSize(filesize); + entity.setDictBiztype(biztype); + entity.setRefBizid(bizid); + this.save(entity); + } + + + + + + + +// /** +// * 获取文件后缀名 +// * +// * @param fileName 文件名 +// * @return 后缀名 +// */ +// private String getFileType(String fileName) { +// if (fileName != null && fileName.contains(".")) { +// return fileName.substring(fileName.lastIndexOf(".")); +// } +// return ""; +// } + + @Override + public Result saveFile(MultipartFile file, String biztype, String bizid) { + Map map = Maps.newHashMap(); + map.put("biztype",biztype); + map.put("bizid", bizid); + mapTmp.set(map); + this.saveOssFile(file); + return this.saveFile(file); + } + +// @Override +// public Result saveFile(MultipartFile file, String biztype, String bizid) { +// mapTmp.set(ImmutableMap.builder().put("biztype",biztype).put("bizid", bizid).build()); +//// this.saveOssFile(file); +// return this.saveOssFile(file); +// } + + + + + +// private static final ThreadLocal> mapTmp = new ThreadLocal(); + + + + +// @Override +// @Deprecated +// public Result saveOssFile(MultipartFile file) { +// try { +// String fileName = file.getOriginalFilename(); +// String fileNameNew = QiniuUtils.getFileNameByDate(fileName); +// QiniuUtils.uploadFile(file, fileNameNew); +// String URL = QiniuUtils.domain + "/" + fileName; +// String downUrl = QiniuUtils.downloadURL(fileNameNew);; +// //保存文件记录 +// saveFilesEntity(fileNameNew, URL, downUrl, "filemanager", ""); +// Map resultMap = new HashMap<>(); +// resultMap.put("src", URL); +// return Result.success(resultMap); +// } catch (Exception e) { +// throw new BusinessException("上传文件失败"); +// } +// } + + + @Override + public Result saveOssFile(MultipartFile file) { + try { + String username = "sessionService.getCurrentUsername()"; + String fileName = file.getOriginalFilename(); + String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); +// QiniuUtils.uploadFile(file, fileNameNew); + String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); + String URL = QiniuUtils.domain + "/" + fileName; +// String downUrl = QiniuUtils.download(fileNameNew);; + //保存文件记录 + saveFilesEntity(fileNameNew, downUrl, "filemanager", QiniuUtils.FormetFileSize(file.getSize()),"",""); + Map resultMap = new HashMap<>(); + resultMap.put("src", downUrl); + return Result.success(resultMap); + } catch (Exception e) { + e.printStackTrace(); + throw new BusinessException("上传文件失败"); + } + } + @Override + public Result saveFile(File file) { + try { + String username = "sessionService.getCurrentUsername()"; + String fileName = file.getName(); + String fileNameNew = QiniuUtils.getFileNameByDate(username,fileName); +// QiniuUtils.uploadFile(file, fileNameNew); + String downUrl = QiniuUtils.uploadFileV2(file, fileNameNew); + String URL = QiniuUtils.domain + "/" + fileName; +// String downUrl = QiniuUtils.download(fileNameNew);; + //保存文件记录 + saveFilesEntity(fileNameNew, downUrl, "filemanager", QiniuUtils.FormetFileSize(FileUtils.sizeOfAsBigInteger(file).longValue()),"",""); + Map resultMap = new HashMap<>(); + resultMap.put("src", downUrl); + return Result.success(resultMap); + } catch (Exception e) { + e.printStackTrace(); + throw new BusinessException("上传文件失败"); + } + } + + + @Override + public void removeByIdsAndFiles(List ids) { + List list = this.listByIds(ids); + list.forEach(entity -> { + QiniuUtils.deleteFileFromQiniu(entity.getFileName()); + //如果之前的文件存在,删除 + File file = new File(entity.getFilePath()); + if (file.exists()) { + file.delete(); + } + }); + this.removeByIds(ids); + + } + +// @Override +// public void removeByIdsAndFiles(List ids) { +// List list = this.listByIds(ids); +// list.forEach(entity -> { +// //如果之前的文件存在,删除 +// File file = new File(entity.getFilePath()); +// if (file.exists()) { +// file.delete(); +// } +// }); +// this.removeByIds(ids); +// +// } + + /** + * 获取文件后缀名 + * + * @param fileName 文件名 + * @return 后缀名 + */ + private String getFileType(String fileName) { + if (fileName != null && fileName.contains(".")) { + return fileName.substring(fileName.lastIndexOf(".")); + } + return ""; + } + + + + @Override + public Result saveFile(File file, String biztype, String bizid) { + mapTmp.set(ImmutableMap.builder().put("biztype",biztype).put("bizid", bizid).build()); +// this.saveOssFile(file); + return this.saveFile(file); + } + +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/ExecuteResult.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/ExecuteResult.java new file mode 100644 index 000000000..e48d186d3 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/ExecuteResult.java @@ -0,0 +1,97 @@ +package com.jun.plugin.file.utils; + + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by kzyuan on 2017/4/5. + * 业务类执行结果包装类 + * @param + */ +public class ExecuteResult implements Serializable { + private static final long serialVersionUID = 7365417829056921958L; + /** + * 返回结果数据 + */ + private T result; + /** + * 成功提示消息 + */ + private String successMessage; + /** + * 普通的错误信息 + */ + private List errorMessages = new ArrayList(); + /** + * 字段错误信息-以key-value的形式出现 + */ + private Map fieldErrors = new HashMap(); + /** + * 警告信息 + */ + private List warningMessages = new ArrayList(); + + public String getSuccessMessage() { + return successMessage; + } + public void setSuccessMessage(String successMessage) { + this.successMessage = successMessage; + } + /** + * 判断当前执行结果是否正确,如果errorMessages和fieldErrors都为空,则无错 + * @return + */ + public boolean isSuccess() { + return errorMessages.isEmpty() && fieldErrors.isEmpty(); + } + public T getResult() { + return result; + } + public void setResult(T result) { + this.result = result; + } + public List getErrorMessages() { + return errorMessages; + } + public void setErrorMessages(List errorMessages) { + this.errorMessages = errorMessages; + } + public Map getFieldErrors() { + return fieldErrors; + } + public void setFieldErrors(Map fieldErrors) { + this.fieldErrors = fieldErrors; + } + public List getWarningMessages() { + return warningMessages; + } + public void setWarningMessages(List warningMessages) { + this.warningMessages = warningMessages; + } + /** + * 添加一条错误消息到列表中 + * @param errorMessage + */ + public void addErrorMessage(String errorMessage) { + this.errorMessages.add(errorMessage); + } + /** + * 添加一条字段错误信息到列表中 + * @param field 字段名称-key + * @param errorMessage 该字段对应的错误信息-value + */ + public void addFieldError(String field, String errorMessage) { + this.fieldErrors.put(field, errorMessage); + } + /** + * 添加一条警告信息到列表中 + * @param warningMessage + */ + public void addWarningMessage(String warningMessage) { + this.warningMessages.add(warningMessage); + } +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/FileUtils.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/FileUtils.java new file mode 100644 index 000000000..a82384081 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/FileUtils.java @@ -0,0 +1,125 @@ +package com.jun.plugin.file.utils; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.OutputStream; + +import org.apache.commons.fileupload.FileItem; +import org.apache.commons.fileupload.FileItemFactory; +import org.apache.commons.fileupload.disk.DiskFileItem; +import org.apache.commons.fileupload.disk.DiskFileItemFactory; +import org.apache.commons.io.FilenameUtils; +import org.springframework.web.multipart.MultipartFile; +import org.springframework.web.multipart.commons.CommonsMultipartFile; + +public class FileUtils { + + /** + * 判断文件是否存在,不存在就创建 + * @param file + */ + public static void createFile(File file) { + if (file.exists()) { + System.out.println("File exists"); + } else { + System.out.println("File not exists, create it ..."); + //getParentFile() 获取上级目录(包含文件名时无法直接创建目录的) + if (!file.getParentFile().exists()) { + System.out.println("not exists"); + //创建上级目录 + file.getParentFile().mkdirs(); + } + try { + //在上级目录里创建文件 + file.createNewFile(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + //file 转换为 MultipartFile + private MultipartFile getMulFileByFile(File file) + { + FileItemFactory factory = new DiskFileItemFactory(16, null); + String textFieldName = "textField"; + int num = file.getAbsolutePath().lastIndexOf("."); + String extFile =FilenameUtils.getExtension(file.getAbsolutePath());// filePath.substring(num); + FileItem item = factory.createItem(textFieldName, "text/plain", true, + "MyFileName" + extFile); + File newfile = file; + int bytesRead = 0; + byte[] buffer = new byte[8192]; + try + { + FileInputStream fis = new FileInputStream(newfile); + OutputStream os = item.getOutputStream(); + while ((bytesRead = fis.read(buffer, 0, 8192)) + != -1) + { + os.write(buffer, 0, bytesRead); + } + os.close(); + fis.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + MultipartFile mfile = new CommonsMultipartFile(item); + return mfile; + + } + + //file 转换为 MultipartFile + private MultipartFile getMulFileByPath(String filePath) + { + FileItemFactory factory = new DiskFileItemFactory(16, null); + String textFieldName = "textField"; + int num = filePath.lastIndexOf("."); + String extFile = filePath.substring(num); + FileItem item = factory.createItem(textFieldName, "text/plain", true, + "MyFileName" + extFile); + File newfile = new File(filePath); + int bytesRead = 0; + byte[] buffer = new byte[8192]; + try + { + FileInputStream fis = new FileInputStream(newfile); + OutputStream os = item.getOutputStream(); + while ((bytesRead = fis.read(buffer, 0, 8192)) + != -1) + { + os.write(buffer, 0, bytesRead); + } + os.close(); + fis.close(); + } + catch (IOException e) + { + e.printStackTrace(); + } + + MultipartFile mfile = new CommonsMultipartFile(item); + return mfile; + + } + + + /** + * MultipartFile 转换成File + * + * @param multfile 原文件类型 + * @return File + * @throws IOException + */ + public static File multipartToFile(MultipartFile multfile) { + + CommonsMultipartFile cf = (CommonsMultipartFile)multfile; + //这个myfile是MultipartFile的 + DiskFileItem fi = (DiskFileItem) cf.getFileItem(); + File file = fi.getStoreLocation(); + return file; + } +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/QiniuUtils.java b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/QiniuUtils.java new file mode 100644 index 000000000..7c3ece854 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/java/com/jun/plugin/file/utils/QiniuUtils.java @@ -0,0 +1,466 @@ +package com.jun.plugin.file.utils; + +import java.io.*; +import java.text.DecimalFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.UUID; + +import org.apache.commons.io.IOUtils; +import org.json.JSONException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +import com.qiniu.common.QiniuException; +import com.qiniu.common.Zone; +import com.qiniu.http.Response; +import com.qiniu.storage.BucketManager; +import com.qiniu.storage.Configuration; +import com.qiniu.storage.UploadManager; +import com.qiniu.util.Auth; + +import lombok.extern.slf4j.Slf4j; + +import javax.security.auth.message.AuthException; + +@Component +@Slf4j +public class QiniuUtils { + + public static final String ACCESS_KEY = "ts0n9OF16ekFkDkZTTlpmyPI-tP3HKQDyw_GR4o2"; // 你的access_key + public static final String SECRET_KEY = "c-OjjwV3ZgzCQwxc6W_bsTFKuDg8qeyqohyJU0RL"; // 你的secret_key + public static final String BUCKET_NAME = "qixing-files"; // 你的bucket_name + public static final String domain = "http://qiniu.hbqxcpa.cn"; // 你的bucket_name + public static final long TOKEN_TIME = 3600 * 24 * 365 * 5; // 你的bucket_name + + public static void uploadFile(String filePath, String fileName) throws QiniuException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); + Response r = uploadManager.put(filePath, fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 + + } + + public static void uploadFile(File file, String fileName) throws QiniuException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); + Response r = uploadManager.put(file, fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 + + } + + public static void uploadFile(InputStream ins, String fileName) throws QiniuException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); + Response r = uploadManager.put(chanageInputStream2byte(ins), fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 + } + + public static void uploadFile(MultipartFile file, String fileName) throws IOException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); +// try { + Response r = uploadManager.put(file.getBytes(), fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 +// } catch (IOException e) { +// e.printStackTrace(); +// } + } + + public static String uploadFileV2(MultipartFile file, String fileName) throws IOException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); + Response r = uploadManager.put(file.getBytes(), fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 + String URL = QiniuUtils.domain + "/" + fileName; + String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); + log.info("下载文件路径:" + downloadRUL); + return downloadRUL; + } + public static String uploadFileV2(File file, String fileName) throws IOException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(QiniuUtils.ACCESS_KEY, QiniuUtils.SECRET_KEY); + String token = auth.uploadToken(QiniuUtils.BUCKET_NAME); + FileInputStream input = new FileInputStream(file); + Response r = uploadManager.put(IOUtils.toByteArray(input), fileName, token); + if (r.isOK()) { + log.info("上传成功!"); + log.info("上传文件路径:" + domain + r.url()); + } else { + log.info("上传失败!"); + } + System.out.println(token); // 输出上传凭证 + System.out.println(r.isOK()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); // 输出上传到七牛云之后的文件名称 + System.out.println(r.url()); // 输出上传到七牛云之后的文件名称 + String URL = QiniuUtils.domain + "/" + fileName; + String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); + log.info("下载文件路径:" + downloadRUL); + return downloadRUL; + } + + public static String downloadURL(String fileName) { + // 密钥配置 + Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); + // 构造私有空间的需要生成的下载的链接 + String URL = QiniuUtils.domain + "/" + fileName; + log.info("下载原始文件路径:" + URL); + // 调用privateDownloadUrl方法生成下载链接,第二个参数可以设置Token的过期时间 + String downloadRUL = auth.privateDownloadUrl(URL, TOKEN_TIME); + log.info("下载文件路径:" + downloadRUL); + System.out.println(downloadRUL); + return downloadRUL; + } + + public static byte[] chanageInputStream2byte(InputStream fis) { + byte[] buffer = null; + try { + // FileInputStream fis = new FileInputStream(tradeFile); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + return buffer; + } + + public static String FormetFileSize(Long fileLength) { + String fileSizeString = ""; + DecimalFormat df = new DecimalFormat("#.00"); + if (fileLength != null) { + if (fileLength < 1024) { + fileSizeString = df.format((double) fileLength) + "B"; + } else if (fileLength < 1048576) { + fileSizeString = df.format((double) fileLength / 1024) + "K"; + } else if (fileLength < 1073741824) { + fileSizeString = df.format((double) fileLength / 1048576) + "M"; + } else { + fileSizeString = df.format((double) fileLength / 1073741824) + "G"; + } + } + return fileSizeString; + } + + public static String getFileNameByDate(String filename) { + String filenameExtension = ""; + String filenamePre = ""; + if (filename.contains(".")) { + filenameExtension = filename.substring(filename.indexOf(".") + 1, filename.length()); + filenamePre = filename.substring(0, filename.indexOf(".")); + } else { + filenamePre = filename; + } + SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss"); + String filenameNew = filenamePre + "-" + time.format(new Date()) + "." + filenameExtension; + log.info(filenameNew); + return filenameNew; + + } + + public static String getFileNameByDate(String username , String filename) { + String filenameExtension = ""; + String filenamePre = ""; + if (filename.contains(".")) { + filenameExtension = filename.substring(filename.indexOf(".") + 1, filename.length()); + filenamePre = filename.substring(0, filename.indexOf(".")); + } else { + filenamePre = filename; + } + SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss"); + String filenameNew =username+"/" + filenamePre + "-" + time.format(new Date()) +"-"+ username+ "." + filenameExtension; + log.info(filenameNew); + return filenameNew; + + } + + // 删除文件 + public static int deleteFileFromQiniu(String fileName) { + // 构造一个带指定Zone对象的配置类 + @SuppressWarnings("deprecation") + Configuration cfg = new Configuration(Zone.zone0()); + String key = fileName; + Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY); + BucketManager bucketManager = new BucketManager(auth, cfg); + try { + Response delete = bucketManager.delete(BUCKET_NAME, key); + return delete.statusCode; + } catch (QiniuException ex) { + // 如果遇到异常,说明删除失败 + ex.printStackTrace(); + System.err.println(ex.code()); + System.err.println(ex.response.toString()); + } + return -1; + } + + + public static void main(String[] args) { + try { +// uploadFile("D:\\11111108599.zip", "11111108599.zip"); +// uploadFile(new File("D:\\quickstart-master.tar.gz"), "quickstart-master.tar.gz"); +// download("11111108599.zip"); +// getFileNameByDate("11111108599.tar.gz"); + } catch (Exception e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + + // ***************************************************************************************************************** + // ***************************************************************************************************************** + // ***************************************************************************************************************** + + private static Logger logger = LoggerFactory.getLogger(QiniuUtils.class); + String bucketName = "bucketName"; +// private String bucketName = propertyUtil.getProperty("bucketName"); +// private String domain = propertyUtil.getProperty("domain"); +// private String ACCESS_KEY = propertyUtil.getProperty("ACCESS_KEY"); +// private String SECRET_KEY = propertyUtil.getProperty("SECRET_KEY"); + + //通过文件路径上传文件 + public ExecuteResult uploadFile(String localFile) throws AuthException, JSONException { + File file = new File(localFile); + /** + * 文件后缀名 文件扩展名 + */ + String filenameExtension = localFile.substring(localFile.lastIndexOf("."), localFile.length()); + return uploadFile2(file, filenameExtension); + } + + //通过File上传 + public ExecuteResult uploadFile2(File file, String filename) throws AuthException, JSONException { + ExecuteResult executeResult = new ExecuteResult(); +// String uptoken = getUpToken(); + // 可选的上传选项,具体说明请参见使用手册。 +// PutExtra extra = new PutExtra(); +// PutRet ret = IoApi.putFile(uptoken,filename , extra); + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); + String token = auth.uploadToken(bucketName); + Response r; + try { + r = uploadManager.put(file, filename, token); + System.out.println(token); //输出上传凭证 + System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 + if (r.isOK()) { + executeResult.setSuccessMessage("上传成功!"); + executeResult.setResult(domain+r.url()); + } else { + executeResult.addErrorMessage("上传失败"); + } + } catch (QiniuException e) { + e.printStackTrace(); + } + + + return executeResult; + } + public String getFileNameByDateAndUUID(String filenameExtension) { + SimpleDateFormat time = new SimpleDateFormat("yyyy/MM/dd"); + String filename = time.format(new Date()) + "/" + UUID.randomUUID() + filenameExtension; + return filename; + + } + + /** + * 从 inputstream 中写入七牛 + * + * @param content 要写入的内容 + * @return + * @throws AuthException + * @throws JSONException + */ + public boolean uploadFile2(String content ,String fileName) throws AuthException, JSONException { + // 读取的时候按的二进制,所以这里要同一 + ByteArrayInputStream inputStream = new ByteArrayInputStream(content.getBytes()); + // 可选的上传选项,具体说明请参见使用手册。 + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); + String token = auth.uploadToken(bucketName); + + Response r; + try { + r = uploadManager.put(QiniuUtils.chanageInputStream2byte(inputStream), fileName, token); +// Response r = uploadManager.put(inputStream, key, token); + System.out.println(token); //输出上传凭证 + System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 + if (r.isOK()) { + return true; + } else { + return false; + } + } catch (QiniuException e) { + e.printStackTrace(); + } + return false; + } + public boolean uploadFile2(InputStream ins,String fileName) throws AuthException, JSONException { + com.qiniu.storage.Configuration cfg = new Configuration(); + UploadManager uploadManager = new UploadManager(cfg); + Auth auth = Auth.create(ACCESS_KEY,SECRET_KEY); + String token = auth.uploadToken(bucketName); + Response r; + try { + r = uploadManager.put(QiniuUtils.chanageInputStream2byte(ins), fileName, token); + //Response r = uploadManager.put(inputStream, key, token); + System.out.println(token); //输出上传凭证 + System.out.println(r.isOK()); //输出上传到七牛云之后的文件名称 + System.out.println(r.toString()); //输出上传到七牛云之后的文件名称 + if (r.isOK()) { + return true; + } else { + return false; + } + } catch (QiniuException e) { + e.printStackTrace(); + } + return false; + } + + public static byte[] chanageInputStream2byte2(InputStream fis){ + byte[] buffer = null; + try + { +// FileInputStream fis = new FileInputStream(tradeFile); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int n; + while ((n = fis.read(b)) != -1) + { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + }catch (FileNotFoundException e){ + e.printStackTrace(); + }catch (IOException e){ + e.printStackTrace(); + } + return buffer; + } + public static byte[] File2byte(File tradeFile){ + byte[] buffer = null; + try + { + FileInputStream fis = new FileInputStream(tradeFile); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int n; + while ((n = fis.read(b)) != -1) + { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + }catch (FileNotFoundException e){ + e.printStackTrace(); + }catch (IOException e){ + e.printStackTrace(); + } + return buffer; + } + + //获得下载地址 +// public String getDownloadFileUrl(String filename) throws Exception { +// Mac mac = getMac(); +// String baseUrl = URLUtils.makeBaseUrl(domain, filename); +// GetPolicy getPolicy = new GetPolicy(); +// String downloadUrl = getPolicy.makeRequest(baseUrl, mac); +// return downloadUrl; +// } +// +// //删除文件 +// public void deleteFile(String filename) { +// Mac mac = getMac(); +// RSClient client = new RSClient(mac); +// client.delete(domain, filename); +// } +// +// //获取凭证 +// private String getUpToken() throws AuthException, JSONException { +// Mac mac = getMac(); +// PutPolicy putPolicy = new PutPolicy(bucketName); +// String uptoken = putPolicy.token(mac); +// return uptoken; +// } +// +// private Mac getMac() { +// Mac mac = new Mac(ACCESS_KEY, SECRET_KEY); +// return mac; +// } + +} diff --git a/jun_api_online/jun_plugins/fileservice/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_plugins/fileservice/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..e6c14c4e2 --- /dev/null +++ b/jun_api_online/jun_plugins/fileservice/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.file.config.FileAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_plugins/pom.xml b/jun_api_online/jun_plugins/pom.xml new file mode 100644 index 000000000..06c8e1e45 --- /dev/null +++ b/jun_api_online/jun_plugins/pom.xml @@ -0,0 +1,22 @@ + + + 4.0.0 + + com.jun.plugin + jun_plugins + pom + 1.0 + 组件模块 + + + aoplog + fileservice + snakerflow + quartz + sms + shiro + + + \ No newline at end of file diff --git a/jun_api_online/jun_plugins/quartz/pom.xml b/jun_api_online/jun_plugins/quartz/pom.xml new file mode 100644 index 000000000..f59965a64 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/pom.xml @@ -0,0 +1,84 @@ + + + 4.0.0 + + com.jun.plugin + quartz + 1.0 + jar + + 定时任务 + + + + org.quartz-scheduler + quartz + 2.3.2 + + + com.mchange + c3p0 + + + com.zaxxer + HikariCP-java6 + + + + + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + com.jun.plugin + jun_common + 1.0 + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/config/QuartzAutoConfig.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/config/QuartzAutoConfig.java new file mode 100644 index 000000000..14313e27d --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/config/QuartzAutoConfig.java @@ -0,0 +1,15 @@ +package com.jun.plugin.quartz.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.quartz") +@MapperScan(basePackages = "com.jun.plugin.quartz.mapper") +public class QuartzAutoConfig { +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobController.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobController.java new file mode 100644 index 000000000..fdb4d7f5c --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobController.java @@ -0,0 +1,166 @@ +package com.jun.plugin.quartz.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.common.Result; +import com.jun.plugin.common.exception.code.BaseResponseCode; +import com.jun.plugin.quartz.utils.ScheduleJob; +import com.jun.plugin.quartz.entity.SysJobEntity; +import com.jun.plugin.quartz.service.SysJobService; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import io.swagger.annotations.ApiParam; +//import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.quartz.TriggerUtils; +import org.quartz.impl.triggers.CronTriggerImpl; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + + +/** + * 定时任务 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Api(tags = "定时任务") +@RestController +@RequestMapping("/sysJob") +public class SysJobController { + @Resource + private SysJobService sysJobService; + + @ApiOperation(value = "新增") + @PostMapping("/add") + //@RequiresPermissions("sysJob:add") + public Result add(@RequestBody SysJobEntity sysJob) { + if (isValidExpression(sysJob.getCronExpression())) { + return Result.fail("cron表达式有误"); + } + Result result = ScheduleJob.judgeBean(sysJob.getBeanName()); + sysJobService.saveJob(sysJob); + return Result.success(result); + } + + @ApiOperation(value = "删除") + @DeleteMapping("/delete") + //@RequiresPermissions("sysJob:delete") + public Result delete(@RequestBody @ApiParam(value = "id集合") List ids) { + sysJobService.delete(ids); + return Result.success(); + } + + @ApiOperation(value = "更新") + @PutMapping("/update") + //@RequiresPermissions("sysJob:update") + public Result update(@RequestBody SysJobEntity sysJob) { + if (isValidExpression(sysJob.getCronExpression())) { + return Result.fail("cron表达式有误"); + } + Result result = ScheduleJob.judgeBean(sysJob.getBeanName()); + sysJobService.updateJobById(sysJob); + return Result.success(result); + } + + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPage") + //@RequiresPermissions("sysJob:list") + public Result findListByPage(@RequestBody SysJobEntity sysJob) { + Page page = new Page(sysJob.getPage(), sysJob.getLimit()); + LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + if (!StringUtils.isEmpty(sysJob.getBeanName())) { + queryWrapper.like(SysJobEntity::getBeanName, sysJob.getBeanName()); + } + IPage iPage = sysJobService.page(page, queryWrapper); + return Result.success(iPage); + } + + + /** + * 立即执行任务 + */ + @ApiOperation(value = "立即执行任务") + @PostMapping("/run") + //@RequiresPermissions("sysJob:run") + public Result run(@RequestBody List ids) { + sysJobService.run(ids); + + return Result.success(); + } + + /** + * 暂停定时任务 + */ + @ApiOperation(value = "暂停定时任务") + @PostMapping("/pause") + //@RequiresPermissions("sysJob:pause") + public Result pause(@RequestBody List ids) { + sysJobService.pause(ids); + + return Result.success(); + } + + /** + * 恢复定时任务 + */ + @ApiOperation(value = "恢复定时任务") + @PostMapping("/resume") + //@RequiresPermissions("sysJob:resume") + public Result resume(@RequestBody List ids) { + sysJobService.resume(ids); + return Result.success(); + } + + /** + * 判断cron表达式 + * + * @param cronExpression cron表达式 + * @return 是否有误 + */ + public static boolean isValidExpression(String cronExpression) { + CronTriggerImpl trigger = new CronTriggerImpl(); + try { + trigger.setCronExpression(cronExpression); + Date date = trigger.computeFirstFireTime(null); + return date == null || !date.after(new Date()); + } catch (Exception e) { + return true; + } + } + + + @ApiOperation(value = "获取运行时间") + @PostMapping("/getRecentTriggerTime") + //@RequiresPermissions("sysJob:add") + public Result getRecentTriggerTime(String cron) { + List list = new ArrayList<>(); + try { + CronTriggerImpl cronTriggerImpl = new CronTriggerImpl(); + cronTriggerImpl.setCronExpression(cron); + // 这个是重点,一行代码搞定 + List dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, 5); + SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + for (Date date : dates) { + list.add(dateFormat.format(date)); + } + + } catch (ParseException e) { + e.printStackTrace(); + } + return Result.success(list); + } + + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobLogController.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobLogController.java new file mode 100644 index 000000000..f4761591a --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/controller/SysJobLogController.java @@ -0,0 +1,57 @@ +package com.jun.plugin.quartz.controller; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.metadata.IPage; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.jun.plugin.common.Result; +import com.jun.plugin.quartz.service.SysJobLogService; +import com.jun.plugin.quartz.entity.SysJobLogEntity; + +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +//import org.apache.shiro.authz.annotation.RequiresPermissions; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.*; + +import javax.annotation.Resource; + + +/** + * 定时任务日志 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Api(tags = "定时任务日志") +@RestController +@RequestMapping("/sysJobLog") +public class SysJobLogController { + @Resource + private SysJobLogService sysJobLogService; + + @ApiOperation(value = "查询分页数据") + @PostMapping("/listByPage") + //@RequiresPermissions("sysJob:list") + public Result findListByPage(@RequestBody SysJobLogEntity sysJobLog) { + Page page = new Page(sysJobLog.getPage(), sysJobLog.getLimit()); + LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); + //查询条件示例 + if (!StringUtils.isEmpty(sysJobLog.getJobId())) { + queryWrapper.like(SysJobLogEntity::getJobId, sysJobLog.getJobId()); + } + queryWrapper.orderByDesc(SysJobLogEntity::getCreateTime); + IPage iPage = sysJobLogService.page(page, queryWrapper); + return Result.success(iPage); + } + + @ApiOperation(value = "清空定时任务日志") + @DeleteMapping("/delete") + //@RequiresPermissions("sysJob:delete") + public Result delete() { + sysJobLogService.remove(Wrappers.emptyWrapper()); + return Result.success(); + } + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobEntity.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobEntity.java new file mode 100644 index 000000000..27b7f6eee --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobEntity.java @@ -0,0 +1,76 @@ +package com.jun.plugin.quartz.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; + +import com.jun.plugin.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.Date; + +/** + * 定时任务 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("sys_job") +public class SysJobEntity extends BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + /** + * 任务调度参数key + */ + public static final String JOB_PARAM_KEY = "JOB_PARAM_KEY"; + /** + * 任务id + */ + @TableId("id") + private String id; + + /** + * spring bean名称 + */ + @TableField("bean_name") + private String beanName; + + /** + * 参数 + */ + @TableField("params") + private String params; + + /** + * cron表达式 + */ + @TableField("cron_expression") + private String cronExpression; + + /** + * 任务状态 0:正常 1:暂停 + */ + @TableField("status") + private Integer status; + + /** + * 备注 + */ + @TableField("remark") + private String remark; + + /** + * 创建时间 + */ + @TableField(value = "create_time", fill = FieldFill.INSERT) + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") + private Date createTime; + + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobLogEntity.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobLogEntity.java new file mode 100644 index 000000000..f98815024 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/entity/SysJobLogEntity.java @@ -0,0 +1,79 @@ +package com.jun.plugin.quartz.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.fasterxml.jackson.annotation.JsonFormat; + +import com.jun.plugin.common.entity.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +import java.io.Serializable; +import java.util.Date; + +/** + * 定时任务日志 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@EqualsAndHashCode(callSuper = true) +@Data +@TableName("sys_job_log") +public class SysJobLogEntity extends BaseEntity implements Serializable { + private static final long serialVersionUID = 1L; + + /** + * 任务日志id + */ + @TableId("id") + private String id; + + /** + * 任务id + */ + @TableField("job_id") + private String jobId; + + /** + * spring bean名称 + */ + @TableField("bean_name") + private String beanName; + + /** + * 参数 + */ + @TableField("params") + private String params; + + /** + * 任务状态 0:成功 1:失败 + */ + @TableField("status") + private Integer status; + + /** + * 失败信息 + */ + @TableField("error") + private String error; + + /** + * 耗时(单位:毫秒) + */ + @TableField("times") + private Integer times; + + /** + * 创建时间 + */ + @TableField(value = "create_time", fill = FieldFill.INSERT) + @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") + private Date createTime; + + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobLogMapper.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobLogMapper.java new file mode 100644 index 000000000..49823ce35 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobLogMapper.java @@ -0,0 +1,15 @@ +package com.jun.plugin.quartz.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.jun.plugin.quartz.entity.SysJobLogEntity; + +/** + * 定时任务日志、 Mapper + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysJobLogMapper extends BaseMapper { + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobMapper.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobMapper.java new file mode 100644 index 000000000..3206015eb --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/mapper/SysJobMapper.java @@ -0,0 +1,15 @@ +package com.jun.plugin.quartz.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.jun.plugin.quartz.entity.SysJobEntity; + +/** + * 定时任务 Mapper + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysJobMapper extends BaseMapper { + +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobLogService.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobLogService.java new file mode 100644 index 000000000..69c881d40 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobLogService.java @@ -0,0 +1,16 @@ +package com.jun.plugin.quartz.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.jun.plugin.quartz.entity.SysJobLogEntity; + +/** + * 定时任务 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysJobLogService extends IService { + +} + diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobService.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobService.java new file mode 100644 index 000000000..cddb8576f --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/SysJobService.java @@ -0,0 +1,67 @@ +package com.jun.plugin.quartz.service; + +import com.baomidou.mybatisplus.extension.service.IService; +import com.jun.plugin.quartz.entity.SysJobEntity; + +import java.util.List; + +/** + * 定时任务 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public interface SysJobService extends IService { + + /** + * 保存job + * + * @param sysJob sysJob + */ + void saveJob(SysJobEntity sysJob); + + /** + * 更新job + * + * @param sysJob sysJob + */ + void updateJobById(SysJobEntity sysJob); + + /** + * 删除job + * + * @param ids ids + */ + void delete(List ids); + + /** + * 运行一次job + * + * @param ids ids + */ + void run(List ids); + + /** + * 暂停job + * + * @param ids ids + */ + void pause(List ids); + + /** + * 恢复job + * + * @param ids ids + */ + void resume(List ids); + + /** + * 批量更新状态 + * + * @param ids ids + * @param status status + */ + void updateBatch(List ids, int status); +} + diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobLogServiceImpl.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobLogServiceImpl.java new file mode 100644 index 000000000..cef77c514 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobLogServiceImpl.java @@ -0,0 +1,21 @@ +package com.jun.plugin.quartz.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.jun.plugin.quartz.service.SysJobLogService; +import com.jun.plugin.quartz.entity.SysJobLogEntity; +import com.jun.plugin.quartz.mapper.SysJobLogMapper; + +import org.springframework.stereotype.Service; + +/** + * 定时任务 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Service("sysJobLogService") +public class SysJobLogServiceImpl extends ServiceImpl implements SysJobLogService { + + +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobServiceImpl.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobServiceImpl.java new file mode 100644 index 000000000..0e484ead1 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/service/impl/SysJobServiceImpl.java @@ -0,0 +1,116 @@ +package com.jun.plugin.quartz.service.impl; + +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.jun.plugin.common.constant.Constant; +import com.jun.plugin.common.exception.BusinessException; +import com.jun.plugin.quartz.utils.ScheduleUtils; +import com.jun.plugin.quartz.entity.SysJobEntity; +import com.jun.plugin.quartz.mapper.SysJobMapper; +import com.jun.plugin.quartz.service.SysJobService; + +import org.quartz.CronTrigger; +import org.quartz.Scheduler; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import javax.annotation.PostConstruct; +import javax.annotation.Resource; +import java.util.List; + +/** + * 定时任务 服务类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Service("sysJobService") +public class SysJobServiceImpl extends ServiceImpl implements SysJobService { + @Resource + private Scheduler scheduler; + @Resource + private SysJobMapper sysJobMapper; + + /** + * 项目启动时,初始化定时器 + */ + @PostConstruct + public void init() { + List scheduleJobList = this.list(); + for (SysJobEntity scheduleJob : scheduleJobList) { + CronTrigger cronTrigger = ScheduleUtils.getCronTrigger(scheduler, scheduleJob.getId()); + //如果不存在,则创建 + if (cronTrigger == null) { + ScheduleUtils.createScheduleJob(scheduler, scheduleJob); + } else { + ScheduleUtils.updateScheduleJob(scheduler, scheduleJob); + } + } + } + + @Override + public void saveJob(SysJobEntity sysJob) { + sysJob.setStatus(Constant.SCHEDULER_STATUS_NORMAL); + this.save(sysJob); + + ScheduleUtils.createScheduleJob(scheduler, sysJob); + } + + @Override + public void updateJobById(SysJobEntity sysJob) { + SysJobEntity sysJobEntity = this.getById(sysJob.getId()); + if (sysJobEntity == null) { + throw new BusinessException("获取定时任务异常"); + } + sysJob.setStatus(sysJobEntity.getStatus()); + ScheduleUtils.updateScheduleJob(scheduler, sysJob); + + this.updateById(sysJob); + } + + @Override + public void delete(List ids) { + for (String jobId : ids) { + ScheduleUtils.deleteScheduleJob(scheduler, jobId); + } + sysJobMapper.deleteBatchIds(ids); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void run(List ids) { + for (String jobId : ids) { + ScheduleUtils.run(scheduler, this.getById(jobId)); + } + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void pause(List ids) { + for (String jobId : ids) { + ScheduleUtils.pauseJob(scheduler, jobId); + } + + updateBatch(ids, Constant.SCHEDULER_STATUS_PAUSE); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void resume(List ids) { + for (String jobId : ids) { + ScheduleUtils.resumeJob(scheduler, jobId); + } + + updateBatch(ids, Constant.SCHEDULER_STATUS_NORMAL); + } + + @Override + public void updateBatch(List ids, int status) { + ids.parallelStream().forEach(id -> { + SysJobEntity sysJobEntity = new SysJobEntity(); + sysJobEntity.setId(id); + sysJobEntity.setStatus(status); + baseMapper.updateById(sysJobEntity); + }); + } +} \ No newline at end of file diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/task/TestTask11.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/task/TestTask11.java new file mode 100644 index 000000000..f7b91780c --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/task/TestTask11.java @@ -0,0 +1,23 @@ +package com.jun.plugin.quartz.task; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.stereotype.Component; + +/** + * Queartz JOB 测试定时任务(演示Demo,可删除) + * testTask为spring bean的名称, 方法名称必须是run + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Component("testTask11") +public class TestTask11 { + private Logger logger = LoggerFactory.getLogger(getClass()); + + public void run(String params){ + //@TODO,新增定时任务,更新项目管理功能的当前处理人跟当前处理流程节点; + logger.debug("TestTask 111111111111111 定时任务正在执行,每分钟执行一次,参数为:{}", params); + } +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleJob.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleJob.java new file mode 100644 index 000000000..db2b8b796 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleJob.java @@ -0,0 +1,110 @@ +package com.jun.plugin.quartz.utils; + +import com.jun.plugin.common.Result; +import com.jun.plugin.common.util.SpringContextUtil; +import com.jun.plugin.quartz.entity.SysJobEntity; +import com.jun.plugin.quartz.entity.SysJobLogEntity; +import com.jun.plugin.quartz.service.SysJobLogService; +import org.apache.commons.lang3.StringUtils; +import org.quartz.JobExecutionContext; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.scheduling.quartz.QuartzJobBean; + +import java.lang.reflect.Method; + + +/** + * 定时任务 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public class ScheduleJob extends QuartzJobBean { + private Logger logger = LoggerFactory.getLogger(getClass()); + + final SysJobLogService sysJobLogService; + + public ScheduleJob(SysJobLogService sysJobLogService) { + this.sysJobLogService = sysJobLogService; + } + + @Override + protected void executeInternal(JobExecutionContext context) { + SysJobEntity scheduleJob = (SysJobEntity) context.getMergedJobDataMap() + .get(SysJobEntity.JOB_PARAM_KEY); + + //获取spring bean + SysJobLogService scheduleJobLogService = (SysJobLogService) SpringContextUtil.getBean("sysJobLogService"); + + //数据库保存执行记录 + SysJobLogEntity log = new SysJobLogEntity(); + log.setJobId(scheduleJob.getId()); + log.setBeanName(scheduleJob.getBeanName()); + log.setParams(scheduleJob.getParams()); + + //任务开始时间 + long startTime = System.currentTimeMillis(); + + try { + //执行任务 + logger.debug("任务准备执行,任务ID:" + scheduleJob.getId()); + + Object target = SpringContextUtil.getBean(scheduleJob.getBeanName()); + assert target != null; + Method method = target.getClass().getDeclaredMethod("run", String.class); + method.invoke(target, scheduleJob.getParams()); + + //任务执行总时长 + long times = System.currentTimeMillis() - startTime; + log.setTimes((int) times); + //任务状态 0:成功 1:失败 + log.setStatus(0); + + logger.debug("任务执行完毕,任务ID:" + scheduleJob.getId() + " 总共耗时:" + times + "毫秒"); + } catch (Exception e) { + logger.error("任务执行失败,任务ID:" + scheduleJob.getId(), e); + + //任务执行总时长 + long times = System.currentTimeMillis() - startTime; + log.setTimes((int) times); + + //任务状态 0:成功 1:失败 + log.setStatus(1); + log.setError(StringUtils.substring(e.toString(), 0, 2000)); + } finally { + assert scheduleJobLogService != null; + scheduleJobLogService.save(log); + } + } + + /** + * 判断bean是否有效 + * + * @param beanName beanName + * @return 返回信息 + */ + public static Result judgeBean(String beanName) { + + if (org.springframework.util.StringUtils.isEmpty(beanName)) { + return Result.fail("spring bean名称不能为空"); + } + + Object target = SpringContextUtil.getBean(beanName); + if (target == null) { + return Result.fail("spring bean不存在,请检查"); + } + Method method; + try { + method = target.getClass().getDeclaredMethod("run", String.class); + } catch (Exception e) { + return Result.fail("spring bean中的run方法不存在,请检查"); + } + if (method == null) { + return Result.fail("spring bean中的run方法不存在,请检查"); + } + + return Result.success(); + } +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleUtils.java b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleUtils.java new file mode 100644 index 000000000..dda2988da --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/java/com/jun/plugin/quartz/utils/ScheduleUtils.java @@ -0,0 +1,151 @@ +package com.jun.plugin.quartz.utils; + +import com.jun.plugin.common.constant.Constant; +import com.jun.plugin.common.exception.BusinessException; +import org.quartz.*; + +import com.jun.plugin.quartz.entity.SysJobEntity; + +/** + * 定时任务工具类 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +public class ScheduleUtils { + private final static String JOB_NAME = "TASK_"; + + /** + * 获取触发器key + */ + public static TriggerKey getTriggerKey(String jobId) { + return TriggerKey.triggerKey(JOB_NAME + jobId); + } + + /** + * 获取jobKey + */ + public static JobKey getJobKey(String jobId) { + return JobKey.jobKey(JOB_NAME + jobId); + } + + /** + * 获取表达式触发器 + */ + public static CronTrigger getCronTrigger(Scheduler scheduler, String jobId) { + try { + return (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId)); + } catch (SchedulerException e) { + throw new BusinessException("获取定时任务CronTrigger出现异常"); + } + } + + /** + * 创建定时任务 + */ + public static void createScheduleJob(Scheduler scheduler, SysJobEntity scheduleJob) { + try { + //构建job信息 + JobDetail jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(scheduleJob.getId())).build(); + + //表达式调度构建器 + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) + .withMisfireHandlingInstructionDoNothing(); + + //按新的cronExpression表达式构建一个新的trigger + CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(scheduleJob.getId())).withSchedule(scheduleBuilder).build(); + + //放入参数,运行时的方法可以获取 + jobDetail.getJobDataMap().put(SysJobEntity.JOB_PARAM_KEY, scheduleJob); + + scheduler.scheduleJob(jobDetail, trigger); + + //暂停任务 + if (Constant.SCHEDULER_STATUS_PAUSE.equals(scheduleJob.getStatus())) { + pauseJob(scheduler, scheduleJob.getId()); + } + } catch (SchedulerException e) { + throw new BusinessException("创建定时任务失败"); + } + } + + /** + * 更新定时任务 + */ + public static void updateScheduleJob(Scheduler scheduler, SysJobEntity scheduleJob) { + try { + TriggerKey triggerKey = getTriggerKey(scheduleJob.getId()); + + //表达式调度构建器 + CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCronExpression()) + .withMisfireHandlingInstructionDoNothing(); + + CronTrigger trigger = getCronTrigger(scheduler, scheduleJob.getId()); + + //按新的cronExpression表达式重新构建trigger + trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build(); + + //参数 + trigger.getJobDataMap().put(SysJobEntity.JOB_PARAM_KEY, scheduleJob); + + scheduler.rescheduleJob(triggerKey, trigger); + + //暂停任务 + if (Constant.SCHEDULER_STATUS_PAUSE.equals(scheduleJob.getStatus())) { + pauseJob(scheduler, scheduleJob.getId()); + } + + } catch (SchedulerException e) { + throw new BusinessException("更新定时任务失败"); + } + } + + /** + * 立即执行任务 + */ + public static void run(Scheduler scheduler, SysJobEntity scheduleJob) { + try { + //参数 + JobDataMap dataMap = new JobDataMap(); + dataMap.put(SysJobEntity.JOB_PARAM_KEY, scheduleJob); + + scheduler.triggerJob(getJobKey(scheduleJob.getId()), dataMap); + } catch (SchedulerException e) { + throw new BusinessException("立即执行定时任务失败"); + } + } + + /** + * 暂停任务 + */ + public static void pauseJob(Scheduler scheduler, String jobId) { + try { + scheduler.pauseJob(getJobKey(jobId)); + } catch (SchedulerException e) { + throw new BusinessException("暂停定时任务失败"); + } + } + + /** + * 恢复任务 + */ + public static void resumeJob(Scheduler scheduler, String jobId) { + try { + scheduler.resumeJob(getJobKey(jobId)); + } catch (SchedulerException e) { + throw new BusinessException("暂停定时任务失败"); + } + } + + /** + * 删除定时任务 + */ + public static void deleteScheduleJob(Scheduler scheduler, String jobId) { + try { + scheduler.deleteJob(getJobKey(jobId)); + } catch (SchedulerException e) { + throw new BusinessException("删除定时任务失败"); + } + } +} diff --git a/jun_api_online/jun_plugins/quartz/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_plugins/quartz/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..6ff9d6880 --- /dev/null +++ b/jun_api_online/jun_plugins/quartz/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.quartz.config.QuartzAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_plugins/shiro/pom.xml b/jun_api_online/jun_plugins/shiro/pom.xml new file mode 100644 index 000000000..04726ce2b --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/pom.xml @@ -0,0 +1,73 @@ + + + 4.0.0 + + com.jun.plugin + shiro + 1.0 + jar + Shiro组件 + + + + com.jun.plugin + jun_common + 1.0 + + + + org.apache.shiro + shiro-spring + 1.4.0 + + + com.github.theborakompanioni + thymeleaf-extras-shiro + 2.0.0 + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomHashedCredentialsMatcher.java b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomHashedCredentialsMatcher.java new file mode 100644 index 000000000..c59bb6c58 --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomHashedCredentialsMatcher.java @@ -0,0 +1,46 @@ +package com.jun.plugin.shiro; + +import com.jun.plugin.common.exception.BusinessException; +import com.jun.plugin.common.exception.code.BaseResponseCode; +import com.jun.plugin.common.service.RedisService; +import org.apache.shiro.SecurityUtils; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.credential.SimpleCredentialsMatcher; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; + +import lombok.extern.slf4j.Slf4j; + +/** + * 认证 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Slf4j +public class CustomHashedCredentialsMatcher extends SimpleCredentialsMatcher { + + @Lazy + @Autowired + private RedisService redisDb; + @Value("${spring.redis.key.prefix.userToken}") + private String userTokenPrefix; + + @Override + public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) { + String accessToken = (String) token.getPrincipal(); + if (!redisDb.exists(userTokenPrefix + accessToken)) { + log.error("-------------------------------------------------------------------------------"); + log.error("userTokenPrefix + accessToken:"+userTokenPrefix + accessToken); + log.error("userTokenPrefix :"+userTokenPrefix ); + log.error("accessToken:"+ accessToken); + log.error("-------------------------------------------------------------------------------"); + SecurityUtils.getSubject().logout(); + throw new BusinessException(BaseResponseCode.TOKEN_ERROR); + } + return true; + } +} diff --git a/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomRealm.java b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomRealm.java new file mode 100644 index 000000000..c9b7f2166 --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/CustomRealm.java @@ -0,0 +1,89 @@ +package com.jun.plugin.shiro; + +import com.alibaba.fastjson2.JSON; +import com.alibaba.fastjson2.JSONObject; +import com.jun.plugin.common.constant.Constant; +import com.jun.plugin.common.exception.BusinessException; +import com.jun.plugin.common.exception.code.BaseResponseCode; +import com.jun.plugin.common.service.RedisService; +//import com.jun.plugin.system.service.PermissionService; +//import com.jun.plugin.system.service.RoleService; + +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.AuthenticationInfo; +import org.apache.shiro.authc.AuthenticationToken; +import org.apache.shiro.authc.SimpleAuthenticationInfo; +import org.apache.shiro.authz.AuthorizationInfo; +import org.apache.shiro.authz.SimpleAuthorizationInfo; +import org.apache.shiro.realm.AuthorizingRealm; +import org.apache.shiro.subject.PrincipalCollection; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Lazy; +import org.springframework.util.StringUtils; + +import java.util.Collection; + +/** + * 授权 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Slf4j +public class CustomRealm extends AuthorizingRealm { +// @Lazy +// @Autowired +// private PermissionService permissionService; +// @Lazy +// @Autowired +// private RoleService roleService; + @Lazy + @Autowired + private RedisService redisService; + @Value("${spring.redis.key.prefix.permissionRefresh}") + private String redisPermissionRefreshKey; + @Value("${spring.redis.key.prefix.userToken}") + private String userTokenPrefix; + @Lazy + @Autowired + private RedisService redisDb; + + + /** + * 执行授权逻辑 + */ + @Override + @SuppressWarnings("unchecked") + protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { + SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo(); + + String sessionInfoStr = redisDb.get(userTokenPrefix + principalCollection.getPrimaryPrincipal()); + if (StringUtils.isEmpty(sessionInfoStr)) { + throw new BusinessException(BaseResponseCode.TOKEN_ERROR); + } + JSONObject redisSession = JSON.parseObject(sessionInfoStr); + if (redisSession == null) { + throw new BusinessException(BaseResponseCode.TOKEN_ERROR); + } + + if (redisSession.get(Constant.ROLES_KEY) != null) { + authorizationInfo.addRoles((Collection) redisSession.get(Constant.ROLES_KEY)); + } + if (redisSession.get(Constant.PERMISSIONS_KEY) != null) { + authorizationInfo.addStringPermissions((Collection) redisSession.get(Constant.PERMISSIONS_KEY)); + } + return authorizationInfo; + } + + + /** + * 执行认证逻辑 + */ + @Override + protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException { + return new SimpleAuthenticationInfo(authenticationToken.getPrincipal(), authenticationToken.getPrincipal(), getName()); + } +} diff --git a/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroAutoConfig.java b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroAutoConfig.java new file mode 100644 index 000000000..9a3e0bfa1 --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroAutoConfig.java @@ -0,0 +1,17 @@ +package com.jun.plugin.shiro; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.shiro") +@MapperScan(basePackages = "com.jun.plugin.shiro.mapper") +@ServletComponentScan(basePackages = {"com.jun.plugin.shiro.compoent"}) +public class ShiroAutoConfig { +} diff --git a/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroConfig.java b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroConfig.java new file mode 100644 index 000000000..1dfcd8a15 --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/ShiroConfig.java @@ -0,0 +1,150 @@ +package com.jun.plugin.shiro; + +import com.jun.plugin.shiro.compoent.CustomAccessControlFilter; +import org.apache.shiro.mgt.SecurityManager; +import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor; +import org.apache.shiro.spring.web.ShiroFilterFactoryBean; +import org.apache.shiro.web.mgt.DefaultWebSecurityManager; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +//import com.jun.plugin.system.common.comfig.FileUploadProperties; + +import at.pollux.thymeleaf.shiro.dialect.ShiroDialect; + +import javax.servlet.Filter; +import java.util.LinkedHashMap; +import java.util.Map; + +/** + * ShiroConfig + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Configuration +//@EnableConfigurationProperties(FileUploadProperties.class) +public class ShiroConfig { + +// @Resource +// private FileUploadProperties fileUploadProperties; + + @Value("${shiro.enable}") + private boolean shiroEnable; + + @Bean(name = "shiroDialect") + public ShiroDialect shiroDialect() { + return new ShiroDialect(); + } + + @Bean + public CustomHashedCredentialsMatcher customHashedCredentialsMatcher() { + return new CustomHashedCredentialsMatcher(); + } + + /** + * 创建realm + */ + @Bean + public CustomRealm customRealm() { + CustomRealm customRealm = new CustomRealm(); + customRealm.setCredentialsMatcher(customHashedCredentialsMatcher()); + return customRealm; + } + + @Bean + public SecurityManager securityManager() { + DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); + //关联realm + securityManager.setRealm(customRealm()); + return securityManager; + } + + + @Bean + public ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { + + //整个shiro执行过程: 过滤器、认证、授权 + + ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean(); + shiroFilterFactoryBean.setSecurityManager(securityManager); + if(shiroEnable){ + //设置安全管理器 + LinkedHashMap filtersMap = new LinkedHashMap<>(); + //用来校验token + filtersMap.put("token", new CustomAccessControlFilter()); + //filtersMap.put("jwt", new JwtFilter()); // TODO JWT认证,Wujun 添加自己的过滤器并且取名为jwt + shiroFilterFactoryBean.setFilters(filtersMap); + + Map filterRuleMap = new LinkedHashMap<>(); + // 配置不会被拦截的链接 顺序判断 + filterRuleMap.put("/*.html", "anon"); + filterRuleMap.put("/sys/user/token", "anon"); + filterRuleMap.put("/sys/user/login", "anon"); + filterRuleMap.put("/sys/getVerify", "anon"); + filterRuleMap.put("/sys/checkVerify", "anon"); + filterRuleMap.put("/sysDict/getType/*", "anon"); + filterRuleMap.put("/sms/sendCode", "anon"); + filterRuleMap.put("/index/**", "anon"); + filterRuleMap.put("/admin/**", "anon"); + filterRuleMap.put("/flow/**", "anon"); + filterRuleMap.put("/ext/**", "anon"); + filterRuleMap.put("/configInfo/**", "anon"); + filterRuleMap.put("/pages/*.html", "anon"); + filterRuleMap.put("/**/*.ttf", "anon"); + filterRuleMap.put("/**/*.wottf", "anon"); + filterRuleMap.put("/assets/**", "anon"); + filterRuleMap.put("/prj/**", "anon"); + filterRuleMap.put("/**/*.html", "anon"); + filterRuleMap.put("/**/*.js", "anon"); + filterRuleMap.put("/**/*.css", "anon"); + filterRuleMap.put("/**/*.json", "anon"); + filterRuleMap.put("/static/**", "anon"); + filterRuleMap.put("/rest/**", "anon"); + filterRuleMap.put("/doc.html", "anon"); + filterRuleMap.put("/swagger-resources/**", "anon"); + filterRuleMap.put("/v2/api-docs", "anon"); + filterRuleMap.put("/v2/api-docs-ext", "anon"); + filterRuleMap.put("/webjars/**", "anon"); + filterRuleMap.put("/druid/**", "anon"); + filterRuleMap.put("/favicon.ico", "anon"); + filterRuleMap.put("/captcha.jpg", "anon"); + filterRuleMap.put("/csrf", "anon"); + filterRuleMap.put("/public/**", "anon"); + //文件上传可直接访问 +// filterRuleMap.put(fileUploadProperties.getAccessUrl(), "anon"); + filterRuleMap.put("/images/**", "anon"); + filterRuleMap.put("/js/**", "anon"); + filterRuleMap.put("/layui/**", "anon"); + filterRuleMap.put("/css/**", "anon"); + filterRuleMap.put("/layui-ext/**", "anon"); + filterRuleMap.put("/api/**", "anon"); + filterRuleMap.put("/lib/**", "anon"); + filterRuleMap.put("/component/**", "anon"); + filterRuleMap.put("/**", "token,authc");// TODO 所有请求通过我们自己的JWT Filter + //filterRuleMap.put("/**", "token,authc,jwt");// TODO 所有请求通过我们自己的JWT Filter + shiroFilterFactoryBean.setLoginUrl("/login.html"); + shiroFilterFactoryBean.setUnauthorizedUrl("/401"); // 可设置无需鉴权的路径 + shiroFilterFactoryBean.setFilterChainDefinitionMap(filterRuleMap); + } + return shiroFilterFactoryBean; + } + + /** + * 开启shiro aop注解支持. + * 使用代理方式;所以需要开启代码支持; + * + * @return org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor + */ + @Bean + public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) { + AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor(); + authorizationAttributeSourceAdvisor.setSecurityManager(securityManager); + return authorizationAttributeSourceAdvisor; + } + + +} + diff --git a/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/compoent/CustomAccessControlFilter.java b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/compoent/CustomAccessControlFilter.java new file mode 100644 index 000000000..319fc12c0 --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/java/com/jun/plugin/shiro/compoent/CustomAccessControlFilter.java @@ -0,0 +1,149 @@ +package com.jun.plugin.shiro.compoent; + +import com.alibaba.fastjson2.JSON; + +import com.jun.plugin.common.Result; +import com.jun.plugin.common.constant.Constant; +import com.jun.plugin.common.exception.BusinessException; +import com.jun.plugin.common.exception.code.BaseResponseCode; +import com.jun.plugin.common.util.HttpRequestUtil; +import lombok.extern.slf4j.Slf4j; +import org.apache.shiro.authc.AuthenticationException; +import org.apache.shiro.authc.UsernamePasswordToken; +import org.apache.shiro.subject.Subject; +import org.apache.shiro.web.filter.AccessControlFilter; +import org.springframework.util.CollectionUtils; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.util.UriComponentsBuilder; + +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.util.HashMap; +import java.util.Map; + + +/** + * 自定义过滤器 + * + * @author wujun + * @version V1.0 + * @date 2020年3月18日 + */ +@Slf4j +public class CustomAccessControlFilter extends AccessControlFilter { + + + @Override + protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) { + return false; + } + + @Override + protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException, ServletException { + HttpServletRequest request = (HttpServletRequest) servletRequest; + StringBuffer url = request.getRequestURL(); + String uri = request.getRequestURI(); + if(url.toString().endsWith(".js") || url.toString().endsWith(".css")){ + return true; + } + if(uri.equals("/")){ + return true; + } + try { + Subject subject = getSubject(servletRequest, servletResponse); + System.out.println(subject.isAuthenticated() + ""); + System.out.println(HttpRequestUtil.isAjaxRequest(request)); + log.info(request.getMethod()); + log.info(request.getRequestURL().toString()); + //从header中获取token + String token = request.getHeader(Constant.ACCESS_TOKEN); + //如果header中不存在token,则从参数中获取token + if (StringUtils.isEmpty(token)) { + token = request.getParameter(Constant.ACCESS_TOKEN); + if (StringUtils.isEmpty(token)) { + Map urlPara = getParam(request); + token = urlPara.get(Constant.ACCESS_TOKEN)==null?null:urlPara.get(Constant.ACCESS_TOKEN).toString(); + } + } + if (StringUtils.isEmpty(token)) { + throw new BusinessException(BaseResponseCode.TOKEN_ERROR); + } + UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(token, token); + getSubject(servletRequest, servletResponse).login(usernamePasswordToken); + } catch (BusinessException exception) { + if (HttpRequestUtil.isAjaxRequest(request)) { + customResponse(exception.getMessageCode(), exception.getDetailMessage(), servletResponse); + } else if (exception.getMessageCode() == BaseResponseCode.TOKEN_ERROR.getCode()) { + servletRequest.getRequestDispatcher("/login.html").forward(servletRequest, servletResponse); + } else if (exception.getMessageCode() == BaseResponseCode.UNAUTHORIZED_ERROR.getCode()) { + servletRequest.getRequestDispatcher("/index/403").forward(servletRequest, servletResponse); + } else { + servletRequest.getRequestDispatcher("/index/500").forward(servletRequest, servletResponse); + } + return false; + } catch (AuthenticationException e) { + if (HttpRequestUtil.isAjaxRequest(request)) { + if (e.getCause() instanceof BusinessException) { + BusinessException exception = (BusinessException) e.getCause(); + customResponse(exception.getMessageCode(), exception.getDetailMessage(), servletResponse); + } else { + customResponse(BaseResponseCode.SYSTEM_BUSY.getCode(), BaseResponseCode.SYSTEM_BUSY.getMsg(), servletResponse); + } + } else { + servletRequest.getRequestDispatcher("/index/403").forward(servletRequest, servletResponse); + } + return false; + } catch (Exception e) { + if (HttpRequestUtil.isAjaxRequest(request)) { + if (e.getCause() instanceof BusinessException) { + BusinessException exception = (BusinessException) e.getCause(); + customResponse(exception.getMessageCode(), exception.getDetailMessage(), servletResponse); + } else { + customResponse(BaseResponseCode.SYSTEM_BUSY.getCode(), BaseResponseCode.SYSTEM_BUSY.getMsg(), servletResponse); + } + } else { + servletRequest.getRequestDispatcher("/index/500").forward(servletRequest, servletResponse); + } + return false; + } + return true; + } + + private static Map getParam(HttpServletRequest request) { + StringBuffer url = request.getRequestURL(); + if (request.getQueryString() != null) { + url.append("?"); + url.append(request.getQueryString()); + } + Map result = new HashMap<>(); + MultiValueMap urlMvp = UriComponentsBuilder.fromHttpUrl(url.toString()).build().getQueryParams(); + urlMvp.forEach((key, value) -> { + String firstValue = CollectionUtils.isEmpty(value) ? null : value.get(0); + result.put(key, firstValue); + }); + return result; + } + + private void customResponse(int code, String msg, ServletResponse response) { + try { + Result result = Result.getResult(code, msg); + + response.setContentType("application/json; charset=utf-8"); + response.setCharacterEncoding("UTF-8"); + + String userJson = JSON.toJSONString(result); + OutputStream out = response.getOutputStream(); + out.write(userJson.getBytes(StandardCharsets.UTF_8)); + out.flush(); + } catch (IOException e) { + log.error("error={}", e, e); + } + } + +} diff --git a/jun_api_online/jun_plugins/shiro/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_plugins/shiro/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..8b1ab0e1e --- /dev/null +++ b/jun_api_online/jun_plugins/shiro/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.shiro.ShiroAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_plugins/sms/pom.xml b/jun_api_online/jun_plugins/sms/pom.xml new file mode 100644 index 000000000..cc60aa91c --- /dev/null +++ b/jun_api_online/jun_plugins/sms/pom.xml @@ -0,0 +1,140 @@ + + + 4.0.0 + + com.jun.plugin + sms + 1.0 + jar + 短信组件 + + + + com.jun.plugin + jun_common + 1.0 + + + com.jun.plugin + jun_system + 1.0 + + + + + + com.tencentcloudapi + tencentcloud-sdk-java + 3.1.841 + + + + com.qiniu + qiniu-java-sdk + [7.7.0, 7.7.99] + + + + + + com.qiniu + happy-dns-java + 0.1.6 + test + + + com.aliyun.oss + aliyun-sdk-oss + 3.17.1 + + + com.qcloud + cos_api + 4.4 + + + org.slf4j + slf4j-log4j12 + + + junit + junit + + + + + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + 1.8 + 1.8 + + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/config/SmsAutoConfig.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/config/SmsAutoConfig.java new file mode 100644 index 000000000..13c7532d3 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/config/SmsAutoConfig.java @@ -0,0 +1,17 @@ +package com.jun.plugin.sms.config; + +import org.mybatis.spring.annotation.MapperScan; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.context.annotation.Configuration; + +/** + * @author wujun + * @date 2021/3/19 + */ +@Configuration +@ComponentScan(basePackages = "com.jun.plugin.sms") +@MapperScan(basePackages = "com.jun.plugin.sms.mapper") +@ServletComponentScan(basePackages = {"com.jun.plugin.sms.compoent"}) +public class SmsAutoConfig { +} diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/controller/SmsApiController.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/controller/SmsApiController.java new file mode 100644 index 000000000..8166d6447 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/controller/SmsApiController.java @@ -0,0 +1,134 @@ +package com.jun.plugin.sms.controller; + + +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.jun.plugin.common.Result; +import com.jun.plugin.common.service.HttpSessionService; +import com.jun.plugin.common.service.RedisService; +import com.jun.plugin.common.util.PasswordUtils; +import com.jun.plugin.sms.service.SendSmsImpl; +import com.jun.plugin.system.entity.SysUser; +import com.jun.plugin.system.mapper.SysUserMapper; +import com.jun.plugin.system.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Lazy; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.annotation.Resource; +import java.util.Random; + +@RestController +@RequestMapping("/sms") +//@CrossOrigin +public class SmsApiController { + @Autowired + public SendSmsImpl sendSms; + +// @Autowired +// public RedisTemplate redisTemplate; + + @Lazy + @Resource + private RedisService redisService; + @Resource + private SysUserMapper sysUserMapper; + @Resource + private UserService userService; + @Resource + private HttpSessionService httpSessionService; + + + public Random random = new Random(); + + @RequestMapping("/sendCode") + public Result sendCode(@RequestParam(value = "phone",required = true) String phone) { + //调用发送的方法即可 + + //1、连接Redis,查找手机验证码是否存在 + //String code = (String)redisTemplate.opsForValue().get(phone); + //String code = redisService.getRedisTemplate().opsForValue().get(phone); + String code = redisService.get(phone); + //==================================================== + // 1、1如果存在的话,说明在5分钟内已经发送过验证码了,不能再发了 + if (!StringUtils.isEmpty(code)) { + System.out.println("已存在,还没有过期,不能再次发送"); + return new Result(401, phone+":"+code+" 已存在,还没有过期"); + } + //===================================================== + + //1。2 如果不存在的话,那么redis创建键值对生成验证码并存储,设置过期时间 + String newCode = ""; + // 生成6位随机验证码 + for (int i = 0; i < 4; i++) { + newCode += random.nextInt(10); + } + String param[]= {newCode,"5"}; + // 将6位随机验证码对手机号进行发送 + boolean idSend = sendSms.send(phone,"1621170",param); + + //===================================================== + + // 因为有短信轰炸的情况,短信服务对每次发送限制次数,所以有发送不成功的情况,要考虑 + + if(idSend){//如果发送成功将验证码存储到redis中 + //redisTemplate.opsForValue().set(phone, newCode, 300,TimeUnit.SECONDS); + redisService.setAndExpire(phone, newCode, 300); + //redisService.getRedisTemplate().expire(phone, 60*5, TimeUnit.SECONDS); + System.out.println("发送成功!"); + return new Result(0, phone+":"+newCode+" 发送成功!"); + }else{ + System.out.println("发送失败!"); + return new Result(500, phone+":"+newCode+ "发送失败!"); + } + } + + + @RequestMapping("/verifyUser") + public Result verifyUser(@RequestParam(value = "username",required = true) String username, + @RequestParam(value = "phone",required = true) String phone, + @RequestParam(value = "captcha",required = true) String captcha) { + SysUser sysUserOne = sysUserMapper.selectOne(Wrappers.lambdaQuery().eq(SysUser::getUsername, username).eq(SysUser::getPhone, phone)); + if (sysUserOne == null) { + return new Result(500, "用户名不存在或者手机号不存在或者用户名与手机号不匹配(请联系管理员处理)!"); + }else{ + return new Result(0, "请重置密码!"); + } + } + + @RequestMapping("/resetPassword") + public Result resetPassword(@RequestParam(value = "username",required = true) String username, + @RequestParam(value = "phone",required = true) String phone, + @RequestParam(value = "captcha",required = true) String captcha, + @RequestParam(value = "passwd",required = true) String passwd, + @RequestParam(value = "comPassword",required = true) String comPassword) { + SysUser sysUser = sysUserMapper.selectOne(Wrappers.lambdaQuery().eq(SysUser::getUsername, username).eq(SysUser::getPhone, phone)); + if (sysUser == null) { + return new Result(500, "用户名不存在或者手机号不存在或者用户名与手机号不匹配(请联系管理员处理)!"); + }else{ + } + if(passwd.equals(comPassword)) { + String userId = httpSessionService.getCurrentUserId(); + String code = redisService.get(phone); + if (StringUtils.isEmpty(code)) { + return new Result(500, phone+":"+code+" 验证码不存在,验证码已过期"); + } + if (sysUser.getPassword().equals(PasswordUtils.encode(passwd, sysUser.getSalt()))) { + new Result(500, "新密码不能与旧密码相同"); + } + sysUser.setPassword(PasswordUtils.encode(passwd, sysUser.getSalt())); + sysUserMapper.updateById(sysUser); + //退出用户 + httpSessionService.abortAllUserByToken(); + return new Result(0, "密码重置成功!"); + //return new Result(500, "密码重置失败!"); + }else { + return new Result(500, "两次输入密码不一致!"); + } + + } +} + + diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSms.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSms.java new file mode 100644 index 000000000..a2a07e3e4 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSms.java @@ -0,0 +1,12 @@ +package com.jun.plugin.sms.service; + +public interface SendSms { /** + * + * @param phoneNum 短信发送的手机号 + * @param templateCode 使用的短信模板id + * @param code 发送的手机验证码 + * @return 返回是否发送成功 + */ + public boolean send(String phoneNum,String templateCode, String[] param); + } + diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSmsImpl.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSmsImpl.java new file mode 100644 index 000000000..a5db6ece1 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/service/SendSmsImpl.java @@ -0,0 +1,118 @@ +package com.jun.plugin.sms.service; + + +import org.springframework.stereotype.Service; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; +//导入可选配置类 +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; +// 导入对应SMS模块的client +import com.tencentcloudapi.sms.v20210111.SmsClient; +// 导入要请求接口对应的request response类 +import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest; +import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse; +@Service +public class SendSmsImpl implements SendSms{ + + /** + * @param phoneNum 短信发送的手机号 + * @param templateCode 使用的短信模板id + * @return 返回是否发送成功 + */ + + @Override + public boolean send(String phoneNum, String templateCode, String[] param) { + + try { + /* 必要步骤: + * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 + * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + * 以免泄露密钥对危及你的财产安全。 + * SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi */ + Credential cred = new Credential("AKIDb4KMAkBTZTAbmiQu98sOjpgHfokS2XzO", "NfpspgP1YzJYghbP6hAXnx1yrgJkxvd5"); + + // 实例化一个http选项,可选,没有特殊需求可以跳过 + HttpProfile httpProfile = new HttpProfile(); + // 设置代理(无需要直接忽略) + // httpProfile.setProxyHost("真实代理ip"); + // httpProfile.setProxyPort(真实代理端口); + /* SDK默认使用POST方法。 + * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */ + httpProfile.setReqMethod("POST"); + /* SDK有默认的超时时间,非必要请不要进行调整 + * 如有需要请在代码中查阅以获取最新的默认值 */ + httpProfile.setConnTimeout(60); + /* 指定接入地域域名,默认就近地域接入域名为 sms.tencentcloudapi.com ,也支持指定地域域名访问,例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */ + httpProfile.setEndpoint("sms.tencentcloudapi.com"); + + /* 非必要步骤: + * 实例化一个客户端配置对象,可以指定超时时间等配置 */ + ClientProfile clientProfile = new ClientProfile(); + /* SDK默认用TC3-HMAC-SHA256进行签名 + * 非必要请不要修改这个字段 */ + clientProfile.setSignMethod("HmacSHA256"); + clientProfile.setHttpProfile(httpProfile); + /* 实例化要请求产品(以sms为例)的client对象 + * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */ + SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile); + /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + * 你可以直接查询SDK源码确定接口有哪些属性可以设置 + * 属性可能是基本类型,也可能引用了另一个数据结构 + * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */ + SendSmsRequest req = new SendSmsRequest(); + + /* 填充请求参数,这里request对象的成员变量即对应接口的入参 + * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义 + * 基本类型的设置: + * 帮助链接: + * 短信控制台: https://console.cloud.tencent.com/smsv2 + * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */ + + /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */ + // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看 + String sdkAppId = "1400595817"; + req.setSmsSdkAppId(sdkAppId); + + /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名 */ + // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看 + String signName = "新博技术"; + req.setSignName(signName); + + /* 模板 ID: 必须填写已审核通过的模板 ID */ + // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看 + String templateId = templateCode; + req.setTemplateId(templateId); + + /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,若无模板参数,则设置为空 */ + String[] templateParamSet = param; + req.setTemplateParamSet(templateParamSet); + + /* 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号] + * 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号 */ + String[] phoneNumberSet = {"+86"+phoneNum}; + req.setPhoneNumberSet(phoneNumberSet); + + + + /* 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的 + * 返回的 res 是一个 SendSmsResponse 类的实例,与请求对象对应 */ + SendSmsResponse res = client.SendSms(req); + + // 输出json格式的字符串回包 + System.out.println(SendSmsResponse.toJsonString(res)); + return true; + + // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义 + // System.out.println(res.getRequestId()); + + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + } + return false; + } + +} + diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/AddSmsTemplate.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/AddSmsTemplate.java new file mode 100644 index 000000000..c29bc1049 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/AddSmsTemplate.java @@ -0,0 +1,90 @@ +package com.jun.plugin.sms.utils; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; +//导入可选配置类 +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; +// 导入 SMS 模块的 client +import com.tencentcloudapi.sms.v20210111.SmsClient; +// 导入要请求接口对应的 request response 类 +import com.tencentcloudapi.sms.v20210111.models.AddSmsTemplateRequest; +import com.tencentcloudapi.sms.v20210111.models.AddSmsTemplateResponse; +/** +* Tencent Cloud Sms AddSmsTemplate +* +*/ +public class AddSmsTemplate +{ + public static void main( String[] args ) + { + try { + /* 必要步骤: + * 实例化一个认证对象,入参需要传入腾讯云账户密钥对 secretId 和 secretKey + * 本示例采用从环境变量读取的方式,需要预先在环境变量中设置这两个值 + * 您也可以直接在代码中写入密钥对,但需谨防泄露,不要将代码复制、上传或者分享给他人 + * CAM 密钥查询:https://console.cloud.tencent.com/cam/capi + */ + Credential cred = new Credential("secretId", "secretKey"); + // 实例化一个 http 选项,可选,无特殊需求时可以跳过 + HttpProfile httpProfile = new HttpProfile(); + // 设置代理 + // httpProfile.setProxyHost("真实代理ip"); + // httpProfile.setProxyPort(真实代理端口); + /* SDK 默认使用 POST 方法 + * 如需使用 GET 方法,可以在此处设置,但 GET 方法无法处理较大的请求 */ + httpProfile.setReqMethod("POST"); + /* SDK 有默认的超时时间,非必要请不要进行调整 + * 如有需要请在代码中查阅以获取最新的默认值 */ + httpProfile.setConnTimeout(60); + /* SDK 会自动指定域名,通常无需指定域名,但访问金融区的服务时必须手动指定域名 + * 例如 SMS 的上海金融区域名为 sms.ap-shanghai-fsi.tencentcloudapi.com */ + httpProfile.setEndpoint("sms.tencentcloudapi.com"); + /* 非必要步骤: + * 实例化一个客户端配置对象,可以指定超时时间等配置 */ + ClientProfile clientProfile = new ClientProfile(); + /* SDK 默认使用 TC3-HMAC-SHA256 进行签名 + * 非必要请不要修改该字段 */ + clientProfile.setSignMethod("HmacSHA256"); + clientProfile.setHttpProfile(httpProfile); + /* 实例化 SMS 的 client 对象 + * 第二个参数是地域信息,可以直接填写字符串 ap-guangzhou,或者引用预设的常量 */ + SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile); + /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + * 您可以直接查询 SDK 源码确定接口有哪些属性可以设置 + * 属性可能是基本类型,也可能引用了另一个数据结构 + * 推荐使用 IDE 进行开发,可以方便地跳转查阅各个接口和数据结构的文档说明 */ + AddSmsTemplateRequest req = new AddSmsTemplateRequest(); + /* 填充请求参数,这里 request 对象的成员变量即对应接口的入参 + * 您可以通过官网接口文档或跳转到 request 对象的定义处查看请求参数的定义 + * 基本类型的设置: + * 帮助链接: + * 短信控制台:https://console.cloud.tencent.com/smsv2 + * sms helper:https://cloud.tencent.com/document/product/382/3773 */ + /* 模板名称*/ + String templatename = "腾讯云"; + req.setTemplateName(templatename); + /* 模板内容 */ + String templatecontent = "{1}为您的登录验证码,请于{2}分钟内填写,如非本人操作,请忽略本短信。"; + req.setTemplateContent(templatecontent); + /* 短信类型:0表示普通短信, 1表示营销短信 */ + long smstype = 0; + req.setSmsType(smstype); + /* 是否国际/港澳台短信:0:表示国内短信,1:表示国际/港澳台短信。 */ + long international = 0; + req.setInternational(international); + /* 模板备注:例如申请原因,使用场景等 */ + String remark = "xxx"; + req.setRemark(remark); + /* 通过 client 对象调用 AddSmsTemplate 方法发起请求。注意请求方法名与请求对象是对应的 + * 返回的 res 是一个 AddSmsTemplateResponse 类的实例,与请求对象对应 */ + AddSmsTemplateResponse res = client.AddSmsTemplate(req); + // 输出 JSON 格式的字符串回包 + System.out.println(AddSmsTemplateResponse.toJsonString(res)); + // 可以取出单个值,您可以通过官网接口文档或跳转到 response 对象的定义处查看返回字段的定义 + System.out.println(res.getRequestId()); + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + } + } +} diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/PullSmsSendStatus.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/PullSmsSendStatus.java new file mode 100644 index 000000000..e91750c48 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/PullSmsSendStatus.java @@ -0,0 +1,93 @@ +package com.jun.plugin.sms.utils; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; + +//导入可选配置类 +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; + +// 导入对应SMS模块的client +import com.tencentcloudapi.sms.v20210111.SmsClient; + +// 导入要请求接口对应的request response类 +import com.tencentcloudapi.sms.v20210111.models.PullSmsReplyStatusRequest; +import com.tencentcloudapi.sms.v20210111.models.PullSmsReplyStatusResponse; +import com.tencentcloudapi.sms.v20210111.models.PullSmsSendStatusRequest; +import com.tencentcloudapi.sms.v20210111.models.PullSmsSendStatusResponse; + +/** + * Tencent Cloud Sms PullSmsSendStatus + * + */ +public class PullSmsSendStatus { + public static void main(String[] args) { + try { + /* 必要步骤: + * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 + * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + * 以免泄露密钥对危及你的财产安全。 + * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/ + Credential cred = new Credential("secretId", "secretKey"); + + // 实例化一个http选项,可选,没有特殊需求可以跳过 + HttpProfile httpProfile = new HttpProfile(); + // 设置代理 + // httpProfile.setProxyHost("真实代理ip"); + // httpProfile.setProxyPort(真实代理端口); + /* SDK默认使用POST方法。 + * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */ + httpProfile.setReqMethod("POST"); + /* SDK有默认的超时时间,非必要请不要进行调整 + * 如有需要请在代码中查阅以获取最新的默认值 */ + httpProfile.setConnTimeout(60); + /* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务 + * 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */ + httpProfile.setEndpoint("sms.tencentcloudapi.com"); + + /* 非必要步骤: + * 实例化一个客户端配置对象,可以指定超时时间等配置 */ + ClientProfile clientProfile = new ClientProfile(); + /* SDK默认用TC3-HMAC-SHA256进行签名 + * 非必要请不要修改这个字段 */ + clientProfile.setSignMethod("HmacSHA256"); + clientProfile.setHttpProfile(httpProfile); + + /* 实例化要请求产品(以sms为例)的client对象 + * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */ + SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile); + + /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + * 你可以直接查询SDK源码确定接口有哪些属性可以设置 + * 属性可能是基本类型,也可能引用了另一个数据结构 + * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */ + PullSmsSendStatusRequest req = new PullSmsSendStatusRequest(); + + /* 填充请求参数,这里request对象的成员变量即对应接口的入参 + * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义 + * 基本类型的设置: + * 帮助链接: + * 短信控制台: https://console.cloud.tencent.com/smsv2 + * sms helper: https://cloud.tencent.com/document/product/382/3773 */ + + /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */ + String sdkAppId = "1400009099"; + req.setSmsSdkAppId(sdkAppId); + + // 设置拉取最大条数,最多100条 + Long limit = 5L; + req.setLimit(limit); + + /* 通过 client 对象调用 PullSmsSendStatus 方法发起请求。注意请求方法名与请求对象是对应的 + * 返回的 res 是一个 PullSmsSendStatusResponse 类的实例,与请求对象对应 */ + PullSmsSendStatusResponse res = client.PullSmsSendStatus(req); + + // 输出json格式的字符串回包 + System.out.println(PullSmsSendStatusResponse.toJsonString(res)); + + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + } + } +} diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendSms.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendSms.java new file mode 100644 index 000000000..9c9478fbf --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendSms.java @@ -0,0 +1,156 @@ +package com.jun.plugin.sms.utils; + +import javax.annotation.Resource; + +import com.jun.plugin.common.service.HttpSessionService; +import org.springframework.stereotype.Component; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; +//导入可选配置类 +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; +// 导入对应SMS模块的client +import com.tencentcloudapi.sms.v20210111.SmsClient; +// 导入要请求接口对应的request response类 +import com.tencentcloudapi.sms.v20210111.models.SendSmsRequest; +import com.tencentcloudapi.sms.v20210111.models.SendSmsResponse; + +/** + * Tencent Cloud Sms Sendsms + * + */ +@Component +public class SendSms { + @Resource + private HttpSessionService httpSessionService; + + public static void main(String[] args) { + // 验证码V1 + Sms smsv1 = new Sms(); + smsv1.setSdkAppId("1400595817"); + smsv1.setSignName("新博技术"); + smsv1.setSessionContext("session01"); + smsv1.setTemplateId("1199339"); + smsv1.setPhoneNumberSet(new String[]{"18572807207"});; + smsv1.setTemplateParamSet(new String[]{"3456","5"}); + + // 流程审批提醒 + Sms smsflow = new Sms(); + smsflow.setSdkAppId("1400595817"); + smsflow.setSignName("新博技术"); + smsflow.setSessionContext("session01"); + smsflow.setTemplateId("1199343"); + smsflow.setPhoneNumberSet(new String[]{"18572807207"});; + smsflow.setTemplateParamSet(null); + SendSms.send(smsflow); + } + + public static void send(Sms sms) { + try { + /* + * 必要步骤: 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + * 以免泄露密钥对危及你的财产安全。 CAM密匙查询: https://console.cloud.tencent.com/cam/capi + */ + //密匙已禁用,后续抽到配置文件prod里面,不提交 + Credential cred = new Credential("AKIDb4KMAkBTZTAbmiQu98sOjpgHfokS2XzO", + "NfpspgP1YzJYghbP6hAXnx1yrgJkxvd5"); + + // 实例化一个http选项,可选,没有特殊需求可以跳过 + HttpProfile httpProfile = new HttpProfile(); + // 设置代理 + // httpProfile.setProxyHost("真实代理ip"); + // httpProfile.setProxyPort(真实代理端口); + /* + * SDK默认使用POST方法。 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 + */ + httpProfile.setReqMethod("POST"); + /* + * SDK有默认的超时时间,非必要请不要进行调整 如有需要请在代码中查阅以获取最新的默认值 + */ + httpProfile.setConnTimeout(60); + /* + * SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务 则必须手动指定域名,例如sms的上海金融区域名: + * sms.ap-shanghai-fsi.tencentcloudapi.com + */ + httpProfile.setEndpoint("sms.tencentcloudapi.com"); + + /* + * 非必要步骤: 实例化一个客户端配置对象,可以指定超时时间等配置 + */ + ClientProfile clientProfile = new ClientProfile(); + /* + * SDK默认用TC3-HMAC-SHA256进行签名 非必要请不要修改这个字段 + */ + clientProfile.setSignMethod("HmacSHA256"); + clientProfile.setHttpProfile(httpProfile); + /* + * 实例化要请求产品(以sms为例)的client对象 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 + */ + SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile); + /* + * 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 你可以直接查询SDK源码确定接口有哪些属性可以设置 + * 属性可能是基本类型,也可能引用了另一个数据结构 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 + */ + SendSmsRequest req = new SendSmsRequest(); + + /* + * 填充请求参数,这里request对象的成员变量即对应接口的入参 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义 + * 基本类型的设置: 帮助链接: 短信控制台: https://console.cloud.tencent.com/smsv2 sms helper: + * https://cloud.tencent.com/document/product/382/3773 + */ + + /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */ + String sdkAppId = sms.getSdkAppId();//""; + req.setSmsSdkAppId(sdkAppId); + + /* 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名,签名信息可登录 [短信控制台] 查看 */ + String signName = sms.getSignName(); + req.setSignName(signName); + + /* 国际/港澳台短信 SenderId: 国内短信填空,默认未开通,如需开通请联系 [sms helper] */ + String senderid = ""; + req.setSenderId(senderid); + + /* 用户的 session 内容: 可以携带用户侧 ID 等上下文信息,server 会原样返回 */ + String sessionContext = sms.getSessionContext(); + req.setSessionContext(sessionContext); + + /* 短信号码扩展号: 默认未开通,如需开通请联系 [sms helper] */ + String extendCode = ""; + req.setExtendCode(extendCode); + + /* 模板 ID: 必须填写已审核通过的模板 ID。模板ID可登录 [短信控制台] 查看 */ + String templateId = sms.getTemplateId(); + req.setTemplateId(templateId); + + /* + * 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号] 示例如:+8613711112222, 其中前面有一个+号 + * ,86为国家码,13711112222为手机号,最多不要超过200个手机号 + */ + String[] phoneNumberSet = sms.getPhoneNumberSet(); + req.setPhoneNumberSet(phoneNumberSet); + + /* 模板参数: 若无模板参数,则设置为空 */ + String[] templateParamSet = sms.getTemplateParamSet(); + req.setTemplateParamSet(templateParamSet); + + /* + * 通过 client 对象调用 SendSms 方法发起请求。注意请求方法名与请求对象是对应的 返回的 res 是一个 SendSmsResponse + * 类的实例,与请求对象对应 + */ + System.out.println("短信发送入参:"+SendSmsResponse.toJsonString(req)); + SendSmsResponse res = client.SendSms(req); + + // 输出json格式的字符串回包 + System.out.println("短信返回参数:"+SendSmsResponse.toJsonString(res)); + + // 也可以取出单个值,你可以通过官网接口文档或跳转到response对象的定义处查看返回字段的定义 + System.out.println(res.getRequestId()); + + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + } + } +} diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendStatusStatistics.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendStatusStatistics.java new file mode 100644 index 000000000..5ee0e5b37 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/SendStatusStatistics.java @@ -0,0 +1,101 @@ +package com.jun.plugin.sms.utils; + +import com.tencentcloudapi.common.Credential; +import com.tencentcloudapi.common.exception.TencentCloudSDKException; + +//导入可选配置类 +import com.tencentcloudapi.common.profile.ClientProfile; +import com.tencentcloudapi.common.profile.HttpProfile; + +// 导入对应SMS模块的client +import com.tencentcloudapi.sms.v20210111.SmsClient; + +// 导入要请求接口对应的request response类 +import com.tencentcloudapi.sms.v20210111.models.SendStatusStatisticsRequest; +import com.tencentcloudapi.sms.v20210111.models.SendStatusStatisticsResponse; + +/** + * Tencent Cloud Sms SendStatusStatistics + * + */ +public class SendStatusStatistics { + public static void main(String[] args) { + try { + /* 必要步骤: + * 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。 + * 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。 + * 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人, + * 以免泄露密钥对危及你的财产安全。 + * CAM密匙查询: https://console.cloud.tencent.com/cam/capi*/ + Credential cred = new Credential("secretId", "secretKey"); + + // 实例化一个http选项,可选,没有特殊需求可以跳过 + HttpProfile httpProfile = new HttpProfile(); + // 设置代理 + // httpProfile.setProxyHost("真实代理ip"); + // httpProfile.setProxyPort(真实代理端口); + /* SDK默认使用POST方法。 + * 如果你一定要使用GET方法,可以在这里设置。GET方法无法处理一些较大的请求 */ + httpProfile.setReqMethod("POST"); + /* SDK有默认的超时时间,非必要请不要进行调整 + * 如有需要请在代码中查阅以获取最新的默认值 */ + httpProfile.setConnTimeout(60); + /* SDK会自动指定域名。通常是不需要特地指定域名的,但是如果你访问的是金融区的服务 + * 则必须手动指定域名,例如sms的上海金融区域名: sms.ap-shanghai-fsi.tencentcloudapi.com */ + httpProfile.setEndpoint("sms.tencentcloudapi.com"); + + /* 非必要步骤: + * 实例化一个客户端配置对象,可以指定超时时间等配置 */ + ClientProfile clientProfile = new ClientProfile(); + /* SDK默认用TC3-HMAC-SHA256进行签名 + * 非必要请不要修改这个字段 */ + clientProfile.setSignMethod("HmacSHA256"); + clientProfile.setHttpProfile(httpProfile); + + /* 实例化要请求产品(以sms为例)的client对象 + * 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,或者引用预设的常量 */ + SmsClient client = new SmsClient(cred, "ap-guangzhou",clientProfile); + + /* 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数 + * 你可以直接查询SDK源码确定接口有哪些属性可以设置 + * 属性可能是基本类型,也可能引用了另一个数据结构 + * 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明 */ + SendStatusStatisticsRequest req = new SendStatusStatisticsRequest(); + + /* 填充请求参数,这里request对象的成员变量即对应接口的入参 + * 你可以通过官网接口文档或跳转到request对象的定义处查看请求参数的定义 + * 基本类型的设置: + * 帮助链接: + * 短信控制台: https://console.cloud.tencent.com/smsv2 + * sms helper: https://cloud.tencent.com/document/product/382/3773 */ + + /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666 */ + String sdkAppId = "1400009099"; + req.setSmsSdkAppId(sdkAppId); + + // 设置拉取最大条数,最多100条 + Long limit = 5L; + req.setLimit(limit); + /* 偏移量 注:目前固定设置为0 */ + Long offset = 0L; + req.setOffset(offset); + /* 开始时间,yyyymmddhh 需要拉取的起始时间,精确到小时 */ + String beginTime = "2019071100"; + req.setBeginTime(beginTime); + /* 结束时间,yyyymmddhh 需要拉取的截止时间,精确到小时 + * 注:EndTime 必须大于 beginTime */ + String endTime = "2019071123"; + req.setEndTime(endTime); + + /* 通过 client 对象调用 SendStatusStatistics 方法发起请求。注意请求方法名与请求对象是对应的 + * 返回的 res 是一个 SendStatusStatisticsResponse 类的实例,与请求对象对应 */ + SendStatusStatisticsResponse res = client.SendStatusStatistics(req); + + // 输出json格式的字符串回包 + System.out.println(SendStatusStatisticsResponse.toJsonString(res)); + + } catch (TencentCloudSDKException e) { + e.printStackTrace(); + } + } +} diff --git a/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/Sms.java b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/Sms.java new file mode 100644 index 000000000..afd812e26 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/java/com/jun/plugin/sms/utils/Sms.java @@ -0,0 +1,14 @@ +package com.jun.plugin.sms.utils; + +import lombok.Data; + +@Data +public class Sms { + private String sdkAppId; + private String signName; + private String sessionContext; + private String templateId; + private String[] phoneNumberSet; + private String[] templateParamSet; + +} diff --git a/jun_api_online/jun_plugins/sms/src/main/resources/META-INF/spring.factories b/jun_api_online/jun_plugins/sms/src/main/resources/META-INF/spring.factories new file mode 100644 index 000000000..84d8aecd2 --- /dev/null +++ b/jun_api_online/jun_plugins/sms/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.jun.plugin.sms.config.SmsAutoConfig \ No newline at end of file diff --git a/jun_api_online/jun_plugins/snakerflow/pom.xml b/jun_api_online/jun_plugins/snakerflow/pom.xml new file mode 100644 index 000000000..c27363efc --- /dev/null +++ b/jun_api_online/jun_plugins/snakerflow/pom.xml @@ -0,0 +1,83 @@ + + + 4.0.0 + + com.jun.plugin + snakerflow + 1.0 + jar + Snaker工作流 + + + + com.jun.plugin + jun_common + 1.0 + + + + + + com.github.snakerflow-starter + snakerflow-spring-boot-starter + 1.0.8 + + + mybatis-plus-boot-starter + com.baomidou + + + + + com.baomidou + mybatis-plus-boot-starter + 3.5.3.2 + + + + + + + + + + + org.springframework.boot + spring-boot-dependencies + + + + 2.5.14 + pom + import + + + + + + + + + aliyun-repos + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + + + + aliyun-plugin + http://maven.aliyun.com/nexus/content/groups/public/ + + false + + + + diff --git a/jun_api_online/jun_plugins/snakerflow/src/main/java/com/jun/plugin/snakerflow/SnakerflowFacetsController.java b/jun_api_online/jun_plugins/snakerflow/src/main/java/com/jun/plugin/snakerflow/SnakerflowFacetsController.java new file mode 100644 index 000000000..4343dc3d1 --- /dev/null +++ b/jun_api_online/jun_plugins/snakerflow/src/main/java/com/jun/plugin/snakerflow/SnakerflowFacetsController.java @@ -0,0 +1,551 @@ +package com.jun.plugin.snakerflow; + +import static org.snaker.engine.access.QueryFilter.DESC; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import javax.annotation.Resource; +import javax.servlet.http.HttpServletResponse; + +//import com.jun.plugin.bizservice.service.BizCommonService; +import com.jun.plugin.snakerflow.ext.mapper.ExtLogMapper; +import com.jun.plugin.snakerflow.module.PageResponse; +import com.jun.plugin.snakerflow.module.Response; +import com.jun.plugin.snakerflow.process.SnakerEngineFacets; +import com.jun.plugin.snakerflow.process.SnakerHelper; +import org.apache.commons.lang.StringUtils; +import org.snaker.engine.SnakerEngine; +import org.snaker.engine.access.Page; +import org.snaker.engine.access.QueryFilter; +import org.snaker.engine.entity.HistoryOrder; +import org.snaker.engine.entity.HistoryTask; +import org.snaker.engine.entity.Order; +import org.snaker.engine.entity.Process; +import org.snaker.engine.entity.Task; +import org.snaker.engine.entity.WorkItem; +import org.snaker.engine.helper.AssertHelper; +import org.snaker.engine.helper.StreamHelper; +import org.snaker.engine.helper.StringHelper; +import org.snaker.engine.model.ProcessModel; +import org.snaker.engine.model.TaskModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.*; + +//import com.jun.plugin.system.entity.SysUser; +//import com.jun.plugin.system.mapper.SysUserMapper; +//import com.jun.plugin.system.service.HttpSessionService; +//import com.laker.admin.framework.aop.Metrics; +//import com.laker.admin.module.flow.SnakerflowFacetsController; +//import com.laker.admin.module.sys.entity.SysUser; +//import com.laker.admin.module.sys.service.ISysUserService; +//import com.jun.plugin.system.service.UserService; + +//import cn.dev33.satoken.annotation.SaCheckPermission; +//import cn.dev33.satoken.stp.StpUtil; +//import cn.dev33.satoken.annotation.SaCheckPermission; +//import cn.dev33.satoken.stp.StpUtil; +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.lang.Dict; +import cn.hutool.core.map.MapUtil; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +//import com.laker.admin.framework.aop.Metrics; +//import com.laker.admin.framework.model.PageResponse; +//import com.laker.admin.framework.model.Response; +//import com.laker.admin.module.flow.process.SnakerEngineFacets; +//import com.laker.admin.module.flow.process.SnakerHelper; +//import com.laker.admin.module.sys.entity.SysUser; +//import com.laker.admin.module.sys.service.ISysUserService; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +@RestController +@RequestMapping("/flow") +@Slf4j +public class SnakerflowFacetsController { + +// @Resource +// HttpSessionService sessionService; + + @Autowired + private SnakerEngineFacets snakerEngineFacets; + +// @Resource +// private UserService sysUserService; + +// @Autowired +// private SysUserMapper sysuer; + + @Autowired + private ExtLogMapper bizCommonMapper; +// @Autowired +// private BizCommonService bizCommonService; + + /** + * ---------------------------------------------流程定义-------------------------------------------- + */ + /** + * 根据流程文件名称,在线部署流程 http://qixing.vip321.vip/flow/process/deploy/leave.snaker + * http://localhost:8081/flow/process/deploy/leave.snaker + * + * @return + */ + @ApiOperation(value = "根据流程文件名称,在线部署流程", tags = "流程引擎-流程部署") + @RequestMapping(value = "/process/deploy/{filename}", method = RequestMethod.GET) + // @Metrics + public Response processdeploy(@PathVariable("filename") String filename) { + snakerEngineFacets.initFlowsByName(filename); + return Response.ok(); + } + + /** + * 获取流程定义,获取流程定义的XML,根据流程ID + */ + @GetMapping("/getXml") + public Response processEdit(String id) { + Process process = snakerEngineFacets.getEngine().process().getProcessById(id); + if (process.getDBContent() != null) { + try { + return Response.ok(new String(process.getDBContent(), "UTF-8")); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + return Response.error("500", "xml异常"); + } + + /** + * 获取流程定义JOSN,根据流程定义的名称 + * + * @param processId + * @return + */ + @GetMapping(value = "/process/modelJson"/*, produces = "application/json;charset=UTF-8"*/) +// @GetMapping(value = "/process/modelJson", produces = "text/plain;charset=UTF-8") + @ApiOperation(value = "根据流程定义名称获取流程定义json", tags = "流程引擎-流程") + // @Metrics + public void getProcess(@RequestParam(required = false) String processId) throws IOException { + HttpServletResponse response = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse(); + assert response != null; + String json = ""; + if (StrUtil.isBlank(processId)) { + json = ""; + } + Process process = snakerEngineFacets.getEngine().process().getProcessById(processId); + AssertHelper.notNull(process); + ProcessModel processModel = process.getModel(); + if (processModel != null) { + json = SnakerHelper.getModelJson(processModel); + +// return json; + } + response.setStatus(200); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().print(json); +// return null; + } + + /** + * 流程定义清单,查询列表 + */ + @ApiOperation(value = "根据给定的参数列表args分页查询process", tags = "流程引擎-流程") + @RequestMapping(value = "/process/list", method = RequestMethod.GET) + public Response processList(Page page, String displayName, String limit) { + QueryFilter filter = new QueryFilter(); + if (StringHelper.isNotEmpty(displayName)) { + filter.setDisplayName(displayName); + } + if (StringHelper.isNotEmpty(limit)) { + page.setPageSize(Integer.valueOf(limit)); + } + filter.orderBy("create_Time").order(DESC); + snakerEngineFacets.getEngine().process().getProcesss(page, filter); + return PageResponse.ok(JSONUtil.parse(page.getResult()), page.getTotalCount()); + } + + /** + * 根据流程定义ID,删除流程定义 + * + * @param id + * @return + */ + @ApiOperation(value = "根据流程定义ID,删除流程定义", tags = "流程引擎-流程") + @RequestMapping(value = "/process/delete/{id}", method = RequestMethod.GET) + // @Metrics + // @SaCheckPermission("flow.delete") + public Response processDelete(@PathVariable("id") String id) { + snakerEngineFacets.getEngine().process().undeploy(id); + return Response.ok(); + } + + /** + * 保存流程定义[web流程设计器] + * + * @param model + * @return + */ + @ApiOperation(value = "保存流程定义[web流程设计器]", tags = "流程引擎-流程") + @RequestMapping(value = "/process/deployXml", method = RequestMethod.POST) + // @SaCheckPermission("flow.update") + public boolean processDeploy(String model, String id, + @RequestParam(required = false, defaultValue = "false") boolean xmlHearder) { + InputStream input = null; + try { + String xml = ""; + if (!xmlHearder) { + xml = "\n"; + } + xml = xml + SnakerHelper.convertXml(model); + System.out.println("model xml=\n" + xml); + input = StreamHelper.getStreamFromString(xml); + if (StringUtils.isNotEmpty(id)) { + snakerEngineFacets.getEngine().process().redeploy(id, input); + } else { + snakerEngineFacets.getEngine().process().deploy(input); + } + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally { + if (input != null) { + try { + input.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return true; + } + + /** + * + * @param processId + * @param orderId + * @return + */ + @ApiOperation(value = "流程定义+流程状态", tags = "流程引擎-流程") + @RequestMapping(value = "/process/json", method = RequestMethod.GET) + // @Metrics + public Object json(String processId, String orderId) { + if (StrUtil.isBlank(processId)) { + processId = snakerEngineFacets.getEngine().query().getHistOrder(orderId).getProcessId(); + } + Process process = snakerEngineFacets.getEngine().process().getProcessById(processId); + AssertHelper.notNull(process); + ProcessModel model = process.getModel(); + Map jsonMap = new HashMap(); + if (model != null) { + jsonMap.put("process", SnakerHelper.getModelJson(model)); + } + + if (StringUtils.isNotEmpty(orderId)) { + List tasks = snakerEngineFacets.getEngine().query() + .getActiveTasks(new QueryFilter().setOrderId(orderId)); + List historyTasks = snakerEngineFacets.getEngine().query() + .getHistoryTasks(new QueryFilter().setOrderId(orderId)); + jsonMap.put("state", SnakerHelper.getStateJson(model, tasks, historyTasks)); + } + log.info(jsonMap.get("state")); + // {"historyRects":{"rects":[{"paths":["TO 任务1"],"name":"开始"},{"paths":["TO + // 分支"],"name":"任务1"},{"paths":["TO 任务3","TO 任务4","TO 任务2"],"name":"分支"}]}} + return jsonMap; + } + + /** + * --------------------------------------------- 任务相关 + * --------------------------------------------- + */ + /** + * 根据当前用户查询待办任务列表 + */ + @GetMapping("/task/todoList") + @ApiOperation(value = "根据当前用户查询待办任务列表", tags = "流程引擎-任务") + public PageResponse userTaskTodoList(String username) { + if (org.springframework.util.StringUtils.isEmpty(username)) { + username = "sessionService.getCurrentUsername()"; + } + String usercode = "sessionService.getCurrentUsername()"; + Page page = new Page<>(30); + snakerEngineFacets.getEngine().query().getWorkItems(page, new QueryFilter().setOperator(username)); + return PageResponse.ok(page.getResult(), page.getTotalCount()); + } + + /** + * 根据当前用户查询待办任务列表 + */ + @GetMapping("/task/doneList") + @ApiOperation(value = "根据当前用户查询已办任务列表", tags = "流程引擎-任务") + public PageResponse userTaskdoneList() { + Page page = new Page<>(30); + snakerEngineFacets.getEngine().query().getHistoryWorkItems(page, + new QueryFilter().setOperator("sessionService.getCurrentUsername()")); + List items = page.getResult(); + return PageResponse.ok(page.getResult(), page.getTotalCount()); + } + + @GetMapping("/task/actor/add") + @ApiOperation(value = "根据流程实例id和任务名称,增加任务参与者", tags = "流程引擎-任务") + public Response addTaskActor(@RequestParam("orderId") String orderId, @RequestParam("taskName") String taskName, + @RequestParam("operator") String operator) { + List tasks = snakerEngineFacets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId)); + for (Task task : tasks) { + if (task.getTaskName().equalsIgnoreCase(taskName) && StringUtils.isNotEmpty(operator)) { + snakerEngineFacets.getEngine().task().addTaskActor(task.getId(), operator); + } + } + return Response.ok(); + } + + @GetMapping("/task/tip") + @ApiOperation(value = "根据流程实例id和任务名称,查找当前任务的到达时间和待执行人", tags = "流程引擎-任务") + public Response taskTip(String orderId, String taskName) { + List tasks = snakerEngineFacets.getEngine().query().getActiveTasks(new QueryFilter().setOrderId(orderId)); + StringBuilder builder = new StringBuilder(); + String createTime = ""; + String finishTime = ""; + String taskOperatorFlag = ""; + String taskOperatorMsg = ""; + boolean find = false; + for (Task task : tasks) { + if (task.getTaskName().equalsIgnoreCase(taskName)) { + String[] actors = snakerEngineFacets.getEngine().query().getTaskActorsByTaskId(task.getId()); + String.join(",",actors); + for (String actor : actors) { +// SysUser sysUser = sysuer.getUserByName(actor); +// if (sysUser!=null) { +// String name = sysUser.getRealName(); +// if (!builder.toString().contains(name)) { +// builder.append(name).append(","); +// } +// }else{ +// //builder.append("用户【"+actor+"】不存在 ").append(","); +// +// } + find = true; + } + createTime = task.getCreateTime(); + taskOperatorFlag = String.valueOf(task.getVariableMap().get("taskOperatorFlag")); + taskOperatorMsg = String.valueOf(task.getVariableMap().get("taskOperatorMsg")); + } + } + if (!find) { + List historyTasks = snakerEngineFacets.getEngine().query() + .getHistoryTasks(new QueryFilter().setOrderId(orderId)); + for (HistoryTask task : historyTasks) { + if (task.getTaskName().equalsIgnoreCase(taskName)) { + String[] actors = snakerEngineFacets.getEngine().query().getHistoryTaskActorsByTaskId(task.getId()); + for (String actor : actors) { +// // SysUser sysUser = sysUserService.getById(String.valueOf(actor)); +// SysUser sysUser = sysuer.getUserByName(actor); +// if (sysUser != null) { +// String nickName = sysUser.getRealName(); +// if (!builder.toString().contains(nickName)) { +// builder.append(nickName).append(","); +// } +// } + } + createTime = task.getCreateTime(); + finishTime = task.getFinishTime(); + taskOperatorFlag = String.valueOf(task.getVariableMap().get("taskOperatorFlag")); + taskOperatorMsg = String.valueOf(task.getVariableMap().get("taskOperatorMsg")); + } + } + } + if (builder.length() > 0) { + builder.deleteCharAt(builder.length() - 1); + } + Map data = new HashMap(); + data.put("actors", builder.toString()); + data.put("createTime", createTime); + data.put("finishTime", finishTime); + data.put("taskOperatorFlag", taskOperatorFlag); + data.put("taskOperatorMsg", taskOperatorMsg); + return Response.ok(data); + } + + /** + * 活动任务的驳回 + */ + @GetMapping("/task/reject") + @ApiOperation(value = "\t 【审批任务】驳回,根据任务主键ID,操作人ID,参数列表执行任务,并且根据nodeName跳转到任意节点\n" + + "\t 1、nodeName为null时,则跳转至上一步处理\n" + "\t 2、nodeName不为null时,则任意跳转,即动态创建转移", tags = "流程引擎-任务") + public Response activeTaskReject(String taskId, String nodeName, String reason) { + Dict rejectReason = Dict.create() + // 拒绝原因,建议单独搞个 审核表 审核的comment file单独存储 + .set("rejectReason", reason); + Map args = new HashMap(8); + args.put("taskOperator", "sessionService.getCurrentUsername()"); + args.put("taskOperatorMsg", "驳回原因,填写有问题,不能XXX,需要XXX!"); + args.put("taskOperatorFlag", "处理结果:驳回"); + snakerEngineFacets.executeAndJump(taskId, "sessionService.getCurrentUsername()", args, nodeName); + return Response.ok(); + } + + /** + * 活动任务的驳回-驳回到发起人 + */ + @SuppressWarnings({ "unchecked", "rawtypes" }) + @GetMapping("/task/rejectToCreate") + @ApiOperation(value = "【任务驳回】驳回到发起人", tags = "流程引擎-任务") + public Response activeTaskReject(String taskId, String taskOperatorFlag, String taskOperatorMsg, + String operatorNextid, String operatorNext) { + List workItems = snakerEngineFacets.getEngine().query().getWorkItems(null, + new QueryFilter().setTaskId(taskId)); + if (CollUtil.isEmpty(workItems)) { + Response.error("500", "不存在任务喽"); + } + WorkItem workItem = workItems.get(0); + Process process = snakerEngineFacets.getEngine().process().getProcessById(workItem.getProcessId()); + ProcessModel model = process.getModel(); + // 获取开始节点下面的第一个节点 + String name = model.getStart().getOutputs().get(0).getTarget().getName(); + Map args = new HashMap(8); + args.put("taskOperator", "sessionService.getCurrentUsername()"); + args.put("taskOperatorName", operatorNext); + args.put("taskOperatorMsg", taskOperatorMsg); + args.put("taskOperatorFlag", taskOperatorFlag); + snakerEngineFacets.executeAndJump(taskId, "sessionService.getCurrentUsername()", args, name); + return Response.ok(); + } + + @SuppressWarnings({ "unchecked", "rawtypes" }) + @RequestMapping(value = "/task/approval", method = RequestMethod.GET) + @ApiOperation(value = "【审批任务】同意", tags = "流程引擎-任务") + public Response doApproval(String taskId, String flag, String taskOperatorFlag, String taskOperatorMsg, + String operatorNextid, String operatorNext, String processName, String processId) { + Task task1 = snakerEngineFacets.getEngine().query().getTask(taskId);// 查询当前任务节点信息 + String orderId = task1.getOrderId(); + String taskName = task1.getTaskName(); + String processNameEn = String.valueOf(task1.getVariableMap().get("processName"));// 获取流程名称 + String businessId = String.valueOf(task1.getVariableMap().get("businessId"));// 获取流程名称 + Process process = snakerEngineFacets.getEngine().process().getProcessByName(processNameEn);// 获取流程实例信息 + List
+ * ${table.comment!} 前端控制器 + *
+ 在此你可以对${comments}进行编辑!若有操作及使用问题及常见“问题”:请查看操作手册! +