From da30366a02176746f704c81e1837f1365927387a Mon Sep 17 00:00:00 2001 From: "20932067@zju.edu.cn" Date: Tue, 23 Feb 2021 17:29:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E7=94=9F=E6=88=90=E9=83=A8?= =?UTF-8?q?=E5=88=86=E5=88=86=E7=A6=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- hchyun/hchyun-generator/pom.xml | 139 ++- .../java/com/hchyun/generator/aop/Excel.java | 139 +++ .../java/com/hchyun/generator/aop/Excels.java | 17 + .../java/com/hchyun/generator/aop/Log.java | 36 + .../com/hchyun/generator/config/Config.java | 34 + .../generator/controller/AjaxResult.java | 153 ++++ .../controller/ApiclassController.java | 89 +- .../controller/AssociatedController.java | 38 +- .../generator/controller/GenController.java | 41 +- .../controller/InterTableController.java | 112 ++- .../controller/ModuleController.java | 89 +- .../generator/controller/QueryController.java | 61 +- .../controller/RegularController.java | 79 +- .../controller/UniQueryController.java | 79 +- .../com/hchyun/generator/dao/QueryDao.java | 6 +- .../com/hchyun/generator/entity/Apiclass.java | 6 +- .../generator/entity/GenBaseEntity.java | 145 +++ .../com/hchyun/generator/entity/GenTable.java | 17 +- .../generator/entity/GenTableColumn.java | 34 +- .../hchyun/generator/entity/InterTable.java | 3 +- .../com/hchyun/generator/entity/Module.java | 5 +- .../com/hchyun/generator/entity/Regular.java | 5 +- .../com/hchyun/generator/entity/UniCon.java | 3 - .../com/hchyun/generator/entity/UniQuery.java | 3 +- .../generator/enums/GenBusinessType.java | 58 ++ .../generator/enums/GenOperatorType.java | 23 + .../generator/service/ApiclassService.java | 14 +- .../generator/service/AssociatedService.java | 8 +- .../generator/service/GenTableService.java | 4 +- .../generator/service/InterTableService.java | 23 +- .../generator/service/ModuleService.java | 14 +- .../generator/service/QueryService.java | 11 +- .../generator/service/RegularService.java | 14 +- .../generator/service/UniQueryService.java | 14 +- .../service/impl/ApiclassServiceImpl.java | 58 +- .../service/impl/AssociatedServiceImpl.java | 24 +- .../impl/GenTableColumnServiceImpl.java | 15 +- .../service/impl/GenTableServiceImpl.java | 92 +- .../service/impl/InterTableServiceImpl.java | 116 ++- .../service/impl/ModuleServiceImpl.java | 58 +- .../service/impl/QueryServiceImpl.java | 53 +- .../service/impl/RegularServiceImpl.java | 57 +- .../service/impl/UniQueryServiceImpl.java | 58 +- .../{util => utils}/AssociatedUtils.java | 18 +- .../generator/utils/GenBaseController.java | 90 ++ .../hchyun/generator/utils/GenDateUtils.java | 144 +++ .../hchyun/generator/utils/GenDictUtils.java | 148 +++ .../hchyun/generator/utils/GenHttpStatus.java | 93 ++ .../GenInterApiUtils.java} | 5 +- .../GenInterTableUtils.java} | 14 +- .../generator/utils/GenMapExcelUtil.java | 295 ++++++ .../generator/utils/GenMessageUtils.java | 24 + .../generator/utils/GenReturnConstants.java | 29 + .../generator/utils/GenSecurityUtils.java | 34 + .../generator/utils/GenServerResult.java | 88 ++ .../generator/utils/GenServletUtils.java | 119 +++ .../generator/utils/GenStringUtils.java | 411 +++++++++ .../generator/{util => utils}/GenUtils.java | 41 +- .../{util => utils}/VelocityInitializer.java | 4 +- .../{util => utils}/VelocityUtils.java | 81 +- .../generator/utils/constant/Constants.java | 128 +++ .../utils/constant/GenConstants.java | 195 ++++ .../utils/constant/GenHttpStatus.java | 93 ++ .../utils/constant/GenUserConstants.java | 89 ++ .../generator/utils/entity/GenDictData.java | 175 ++++ .../generator/utils/entity/GenMenu.java | 263 ++++++ .../utils/exception/GenBaseException.java | 84 ++ .../utils/exception/GenCustomException.java | 37 + .../generator/utils/page/GenPageDomain.java | 70 ++ .../utils/page/GenTableDataInfo.java | 82 ++ .../generator/utils/page/GenTableSupport.java | 47 + .../generator/utils/poi/GenExcelUtil.java | 811 +++++++++++++++++ .../generator/utils/redis/GenRedisCache.java | 210 +++++ .../generator/utils/reflect/ReflectUtils.java | 322 +++++++ .../utils/spring/GenSpringUtils.java | 131 +++ .../generator/utils/sql/GenSqlUtil.java | 33 + .../generator/utils/text/CharsetKit.java | 92 ++ .../hchyun/generator/utils/text/Convert.java | 851 ++++++++++++++++++ .../generator/utils/text/StrFormatter.java | 77 ++ .../main/resources/vm/java/controller.java.vm | 44 +- 80 files changed, 6731 insertions(+), 788 deletions(-) create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excel.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excels.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Log.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/config/Config.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AjaxResult.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenBaseEntity.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenBusinessType.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenOperatorType.java rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util => utils}/AssociatedUtils.java (80%) create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenBaseController.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDateUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDictUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenHttpStatus.java rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util/InterApiUtils.java => utils/GenInterApiUtils.java} (67%) rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util/InterTableUtils.java => utils/GenInterTableUtils.java} (92%) create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMapExcelUtil.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMessageUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenReturnConstants.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenSecurityUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServerResult.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServletUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenStringUtils.java rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util => utils}/GenUtils.java (81%) rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util => utils}/VelocityInitializer.java (90%) rename hchyun/hchyun-generator/src/main/java/com/hchyun/generator/{util => utils}/VelocityUtils.java (75%) create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/Constants.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenConstants.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenHttpStatus.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenUserConstants.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenDictData.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenMenu.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenBaseException.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenCustomException.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenPageDomain.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableDataInfo.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableSupport.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/poi/GenExcelUtil.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/redis/GenRedisCache.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/reflect/ReflectUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/spring/GenSpringUtils.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/sql/GenSqlUtil.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/CharsetKit.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/Convert.java create mode 100644 hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/StrFormatter.java diff --git a/hchyun/hchyun-generator/pom.xml b/hchyun/hchyun-generator/pom.xml index 45e4082..13cf53f 100644 --- a/hchyun/hchyun-generator/pom.xml +++ b/hchyun/hchyun-generator/pom.xml @@ -21,13 +21,144 @@ org.apache.velocity velocity - - + - com.hchyun - hchyun-common + commons-net + commons-net + 3.7 + + + org.springframework + spring-context-support + + + + + org.springframework + spring-web + + + + + org.springframework.boot + spring-boot-starter-security + + + + + com.github.pagehelper + pagehelper-spring-boot-starter + + + + + javax.validation + validation-api + + + + + org.apache.commons + commons-lang3 + + + + + com.fasterxml.jackson.core + jackson-databind + + + + + com.alibaba + fastjson + + + + + commons-io + commons-io + + + + + commons-fileupload + commons-fileupload + + + + + org.apache.poi + poi-ooxml + + + + + org.yaml + snakeyaml + + + + + io.jsonwebtoken + jjwt + + + + + org.springframework.boot + spring-boot-starter-data-redis + + + + + org.apache.commons + commons-pool2 + + + + + eu.bitwalker + UserAgentUtils + + + + + javax.servlet + javax.servlet-api + + + + io.springfox + springfox-swagger2 + + + + + io.swagger + swagger-annotations + 1.5.21 + + + + io.swagger + swagger-models + 1.5.21 + + + + + io.springfox + springfox-swagger-ui + + + + + + + \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excel.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excel.java new file mode 100644 index 0000000..9344046 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excel.java @@ -0,0 +1,139 @@ +package com.hchyun.generator.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.math.BigDecimal; + +/** + * 自定义导出Excel数据注解 + * + * @author hchyun + */ +@Retention(RetentionPolicy.RUNTIME) +@Target(ElementType.FIELD) +public @interface Excel { + /** + * 导出时在excel中排序 + */ +// public int sort() default Integer.MAX_VALUE; + public int sort() default 1; + + /** + * 导出到Excel中的名字. + */ + public String name() default ""; + + /** + * 日期格式, 如: yyyy-MM-dd + */ + public String dateFormat() default ""; + + /** + * 如果是字典类型,请设置字典的type值 (如: sys_user_sex) + */ + public String dictType() default ""; + + /** + * 读取内容转表达式 (如: 0=男,1=女,2=未知) + */ + public String readConverterExp() default ""; + + /** + * 分隔符,读取字符串组内容 + */ + public String separator() default ","; + + /** + * BigDecimal 精度 默认:-1(默认不开启BigDecimal格式化) + */ + public int scale() default -1; + + /** + * BigDecimal 舍入规则 默认:BigDecimal.ROUND_HALF_EVEN + */ + public int roundingMode() default BigDecimal.ROUND_HALF_EVEN; + + /** + * 导出类型(0数字 1字符串) + */ + public ColumnType cellType() default ColumnType.STRING; + + /** + * 导出时在excel中每个列的高度 单位为字符 + */ + public double height() default 14; + + /** + * 导出时在excel中每个列的宽 单位为字符 + */ + public double width() default 16; + + /** + * 文字后缀,如% 90 变成90% + */ + public String suffix() default ""; + + /** + * 当值为空时,字段的默认值 + */ + public String defaultValue() default ""; + + /** + * 提示信息 + */ + public String prompt() default ""; + + /** + * 设置只能选择不能输入的列内容. + */ + public String[] combo() default {}; + + /** + * 是否导出数据,应对需求:有时我们需要导出一份模板,这是标题需要但内容需要用户手工填写. + */ + public boolean isExport() default true; + + /** + * 另一个类中的属性名称,支持多级获取,以小数点隔开 + */ + public String targetAttr() default ""; + + /** + * 是否自动统计数据,在最后追加一行统计数据总和 + */ + public boolean isStatistics() default false; + + + /** + * 字段类型(0:导出导入;1:仅导出;2:仅导入) + */ + Type type() default Type.ALL; + + public enum Type { + ALL(0), EXPORT(1), IMPORT(2); + private final int value; + + Type(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } + + public enum ColumnType { + NUMERIC(0), STRING(1); + private final int value; + + ColumnType(int value) { + this.value = value; + } + + public int value() { + return this.value; + } + } +} \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excels.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excels.java new file mode 100644 index 0000000..e8b862b --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Excels.java @@ -0,0 +1,17 @@ +package com.hchyun.generator.aop; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Excel注解集 + * + * @author hchyun + */ +@Target(ElementType.FIELD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Excels { + Excel[] value(); +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Log.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Log.java new file mode 100644 index 0000000..b2ddd50 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/aop/Log.java @@ -0,0 +1,36 @@ +package com.hchyun.generator.aop; + +import com.hchyun.generator.enums.GenBusinessType; +import com.hchyun.generator.enums.GenOperatorType; + +import java.lang.annotation.*; + +/** + * 自定义操作日志记录注解 + * + * @author hchyun + */ +@Target({ElementType.PARAMETER, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface Log { + /** + * 模块 + */ + public String title() default ""; + + /** + * 功能 + */ + public GenBusinessType businessType() default GenBusinessType.OTHER; + + /** + * 操作人类别 + */ + public GenOperatorType operatorType() default GenOperatorType.MANAGE; + + /** + * 是否保存请求的参数 + */ + public boolean isSaveRequestData() default true; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/config/Config.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/config/Config.java new file mode 100644 index 0000000..16d7862 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/config/Config.java @@ -0,0 +1,34 @@ +package com.hchyun.generator.config; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +/** + * @Author 18209 + * @Date 2021/2/23 15:48 + * @Version 1.0 + */ + +@Component +@ConfigurationProperties(prefix = "hchyun") +public class Config { + + + + /** + * 上传路径 + */ + private static String profile; + + + public static String getProfile() { + return profile; + } + + /** + * 获取下载路径 + */ + public static String getDownloadPath() { + return getProfile() + "/download/"; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AjaxResult.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AjaxResult.java new file mode 100644 index 0000000..c173e25 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AjaxResult.java @@ -0,0 +1,153 @@ +package com.hchyun.generator.controller; + + +import com.hchyun.generator.utils.GenHttpStatus; +import com.hchyun.generator.utils.GenStringUtils; + +import java.util.HashMap; + +/** + * 操作消息提醒 + * + * @author hchyun + */ +public class AjaxResult extends HashMap { + + + /** + * 状态码 + */ + public static final String CODE_TAG = "code"; + + /** + * 返回内容 + */ + public static final String MSG_TAG = "msg"; + + /** + * 数据对象 + */ + public static final String DATA_TAG = "data"; + + /** + * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。 + */ + public AjaxResult() { + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param code 状态码 + * @param msg 返回内容 + */ + public AjaxResult(int code, String msg) { + super.put(CODE_TAG, code); + super.put(MSG_TAG, msg); + } + + /** + * 初始化一个新创建的 AjaxResult 对象 + * + * @param code 状态码 + * @param msg 返回内容 + * @param data 数据对象 + */ + public AjaxResult(int code, String msg, Object data) { + super.put(CODE_TAG, code); + super.put(MSG_TAG, msg); + if (GenStringUtils.isNotNull(data)) { + super.put(DATA_TAG, data); + } + } + + /** + * 返回成功消息 + * + * @return 成功消息 + */ + public static AjaxResult success() { + return AjaxResult.success("操作成功"); + } + + /** + * 返回成功数据 + * + * @return 成功消息 + */ + public static AjaxResult success(Object data) { + return AjaxResult.success("操作成功", data); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @return 成功消息 + */ + public static AjaxResult success(String msg) { + return AjaxResult.success(msg, null); + } + + /** + * 返回成功消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 成功消息 + */ + public static AjaxResult success(String msg, Object data) { + return new AjaxResult(GenHttpStatus.SUCCESS, msg, data); + } + + /** + * 返回错误消息 + * + * @return + */ + public static AjaxResult error() { + return AjaxResult.error("操作失败"); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult error(String msg) { + return AjaxResult.error(msg, null); + } + + /** + * 返回错误消息 + * + * @param msg 返回内容 + * @param data 数据对象 + * @return 警告消息 + */ + public static AjaxResult error(String msg, Object data) { + return new AjaxResult(GenHttpStatus.ERROR, msg, data); + } + + /** + * 返回错误消息 + * + * @param code 状态码 + * @param msg 返回内容 + * @return 警告消息 + */ + public static AjaxResult error(int code, String msg) { + return new AjaxResult(code, msg, null); + } + + /** + * 返回提示信息 + * + * @param msg 返回内容 + * @return 提示消息 + */ + public static AjaxResult info(String msg) { + return new AjaxResult(GenHttpStatus.NO_DATA, msg, null); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ApiclassController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ApiclassController.java index 6889f06..9b8f641 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ApiclassController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ApiclassController.java @@ -3,9 +3,12 @@ package com.hchyun.generator.controller; import java.io.Serializable; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.controller.HcyBaseController; -import com.hchyun.common.utils.ServerResult; +import com.hchyun.generator.aop.Log; +import com.hchyun.generator.enums.GenBusinessType; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.poi.GenExcelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; @@ -18,12 +21,8 @@ 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.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.enums.BusinessType; import com.hchyun.generator.entity.Apiclass; import com.hchyun.generator.service.ApiclassService; -import com.hchyun.common.utils.poi.ExcelUtil; /** * 接口类名Controller @@ -33,7 +32,7 @@ import com.hchyun.common.utils.poi.ExcelUtil; */ @RestController @RequestMapping("/tool/apiclass") -public class ApiclassController extends HcyBaseController { +public class ApiclassController extends GenBaseController { protected final Logger logger = LoggerFactory.getLogger(ApiclassController.class); @Autowired @@ -49,15 +48,15 @@ public class ApiclassController extends HcyBaseController { @GetMapping("querylist") public AjaxResult queryList() { try { - ServerResult> serverResult = apiclassService.selectApiclassList(new Apiclass()); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = apiclassService.selectApiclassList(new Apiclass()); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -69,15 +68,15 @@ public class ApiclassController extends HcyBaseController { public Serializable list(Apiclass apiclass) { try { startPage(); - ServerResult> serverResult = apiclassService.selectApiclassList(apiclass); - if (serverResult.isStart()) { - return getDataTable(serverResult.getData()); + GenServerResult> genServerResult = apiclassService.selectApiclassList(apiclass); + if (genServerResult.isStart()) { + return getDataTable(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -85,20 +84,20 @@ public class ApiclassController extends HcyBaseController { * 导出接口类名列表 */ @PreAuthorize("@hchyun.hasPermi('tool:apiclass:export')") - @Log(title = "接口类名", businessType = BusinessType.EXPORT) + @Log(title = "接口类名", businessType = GenBusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(Apiclass apiclass) { try { - ServerResult> serverResult = apiclassService.selectApiclassList(apiclass); - ExcelUtil util = new ExcelUtil(Apiclass.class); - if (serverResult.isStart()) { - return util.exportExcel(serverResult.getData(), "apiclass"); + GenServerResult> genServerResult = apiclassService.selectApiclassList(apiclass); + GenExcelUtil util = new GenExcelUtil(Apiclass.class); + if (genServerResult.isStart()) { + return util.exportExcel(genServerResult.getData(), "apiclass"); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -109,15 +108,15 @@ public class ApiclassController extends HcyBaseController { @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { try { - ServerResult serverResult = apiclassService.selectApiclassById(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult genServerResult = apiclassService.selectApiclassById(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -125,7 +124,7 @@ public class ApiclassController extends HcyBaseController { * 新增接口类名 */ @PreAuthorize("@hchyun.hasPermi('tool:apiclass:add')") - @Log(title = "接口类名", businessType = BusinessType.INSERT) + @Log(title = "接口类名", businessType = GenBusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody Apiclass apiclass) { if (apiclass.getmId() == null || apiclass.getmId() < 0) { @@ -138,15 +137,15 @@ public class ApiclassController extends HcyBaseController { return AjaxResult.error("类描述不能为空!"); } try { - ServerResult serverResult = apiclassService.insertApiclass(apiclass); - if (serverResult.isStart()) { + GenServerResult genServerResult = apiclassService.insertApiclass(apiclass); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -154,7 +153,7 @@ public class ApiclassController extends HcyBaseController { * 修改接口类名 */ @PreAuthorize("@hchyun.hasPermi('tool:apiclass:edit')") - @Log(title = "接口类名", businessType = BusinessType.UPDATE) + @Log(title = "接口类名", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody Apiclass apiclass) { try { @@ -168,15 +167,15 @@ public class ApiclassController extends HcyBaseController { if (apiclass.getcDescribe() == null || apiclass.getcDescribe().equals("")) { return AjaxResult.error("类描述不能为空!"); } - ServerResult serverResult = apiclassService.updateApiclass(apiclass); - if (serverResult.isStart()) { + GenServerResult genServerResult = apiclassService.updateApiclass(apiclass); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -184,22 +183,22 @@ public class ApiclassController extends HcyBaseController { * 删除接口类名 */ @PreAuthorize("@hchyun.hasPermi('tool:apiclass:remove')") - @Log(title = "接口类名", businessType = BusinessType.DELETE) + @Log(title = "接口类名", businessType = GenBusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { try { if (ids.length < 0) { return AjaxResult.error("id不能为空!"); } - ServerResult serverResult = apiclassService.deleteApiclassByIds(ids); - if (serverResult.isStart()) { + GenServerResult genServerResult = apiclassService.deleteApiclassByIds(ids); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AssociatedController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AssociatedController.java index 4230619..3028369 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AssociatedController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/AssociatedController.java @@ -1,12 +1,9 @@ package com.hchyun.generator.controller; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.AssColumn; import com.hchyun.generator.service.AssociatedService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -34,15 +31,14 @@ public class AssociatedController { private AssociatedService associatedService; - @ApiOperation("tableid") @GetMapping("/{tableId}") private AjaxResult assColumnsByTable(@PathVariable("tableId") Long tableId) { try { - ServerResult> serverResult = associatedService.assColumnsByTable(tableId); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = associatedService.assColumnsByTable(tableId); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -50,35 +46,33 @@ public class AssociatedController { } } - @ApiOperation("获取表信息") @GetMapping("/tableinfos") public AjaxResult tableInfos() { try { - ServerResult>> serverResult = associatedService.tableInfos(); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult>> genServerResult = associatedService.tableInfos(); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } - @ApiOperation("关联表字段") @GetMapping("/{tableName}/{tableId}") public AjaxResult assColumns(@PathVariable("tableName") String tableName, @PathVariable("tableId") Long tableId) { try { - ServerResult> serverResult = associatedService.assColumns(tableName, tableId); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = associatedService.assColumns(tableName, tableId); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/GenController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/GenController.java index c7125a0..4ccafde 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/GenController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/GenController.java @@ -7,8 +7,13 @@ import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.ServerResult; +import com.hchyun.generator.aop.Log; +import com.hchyun.generator.enums.GenBusinessType; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.page.GenTableDataInfo; +import com.hchyun.generator.utils.text.Convert; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,12 +28,6 @@ import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.controller.BaseController; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.core.page.TableDataInfo; -import com.hchyun.common.core.text.Convert; -import com.hchyun.common.enums.BusinessType; import com.hchyun.generator.entity.GenTable; import com.hchyun.generator.entity.GenTableColumn; import com.hchyun.generator.service.GenTableColumnService; @@ -41,7 +40,7 @@ import com.hchyun.generator.service.GenTableService; */ @RestController @RequestMapping("/tool/gen") -public class GenController extends BaseController { +public class GenController extends GenBaseController { private Logger logger = LoggerFactory.getLogger(GenController.class); @Autowired @@ -94,7 +93,7 @@ public class GenController extends BaseController { @PreAuthorize("@hchyun.hasPermi('tool:gen:list')") @GetMapping(value = "/column/{talbleId}") public Serializable columnList(Long tableId) { - TableDataInfo dataInfo = new TableDataInfo(); + GenTableDataInfo dataInfo = new GenTableDataInfo(); List list = genTableColumnService.selectGenTableColumnListByTableId(tableId); dataInfo.setRows(list); dataInfo.setTotal(list.size()); @@ -105,7 +104,7 @@ public class GenController extends BaseController { * 导入表结构(保存) */ @PreAuthorize("@hchyun.hasPermi('tool:gen:list')") - @Log(title = "代码生成", businessType = BusinessType.IMPORT) + @Log(title = "代码生成", businessType = GenBusinessType.IMPORT) @PostMapping("/importTable") public AjaxResult importTableSave(String tables) { String[] tableNames = Convert.toStrArray(tables); @@ -120,7 +119,7 @@ public class GenController extends BaseController { * 修改保存代码生成业务 */ @PreAuthorize("@hchyun.hasPermi('tool:gen:edit')") - @Log(title = "代码生成", businessType = BusinessType.UPDATE) + @Log(title = "代码生成", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult editSave(@Validated @RequestBody GenTable genTable) { genTableService.validateEdit(genTable); @@ -132,19 +131,19 @@ public class GenController extends BaseController { * 删除代码生成 */ @PreAuthorize("@hchyun.hasPermi('tool:gen:remove')") - @Log(title = "代码生成", businessType = BusinessType.DELETE) + @Log(title = "代码生成", businessType = GenBusinessType.DELETE) @DeleteMapping("/{tableIds}") public AjaxResult remove(@PathVariable Long[] tableIds) { try { - ServerResult serverResult = genTableService.deleteGenTableByIds(tableIds); - if (serverResult.isStart()) { + GenServerResult genServerResult = genTableService.deleteGenTableByIds(tableIds); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -162,7 +161,7 @@ public class GenController extends BaseController { * 生成代码(下载方式) */ @PreAuthorize("@hchyun.hasPermi('tool:gen:code')") - @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @GetMapping("/download/{tableName}") public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { byte[] data = genTableService.downloadCode(tableName); @@ -173,7 +172,7 @@ public class GenController extends BaseController { * 生成代码(自定义路径) */ @PreAuthorize("@hchyun.hasPermi('tool:gen:code')") - @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @GetMapping("/genCode/{tableName}") public AjaxResult genCode(@PathVariable("tableName") String tableName) { boolean start = genTableService.generatorCode(tableName); @@ -188,7 +187,7 @@ public class GenController extends BaseController { * 同步数据库 */ @PreAuthorize("@hchyun.hasPermi('tool:gen:edit')") - @Log(title = "代码生成", businessType = BusinessType.UPDATE) + @Log(title = "代码生成", businessType = GenBusinessType.UPDATE) @GetMapping("/synchDb/{tableName}") public AjaxResult synchDb(@PathVariable("tableName") String tableName) { genTableService.synchDb(tableName); @@ -199,7 +198,7 @@ public class GenController extends BaseController { * 批量生成代码 */ @PreAuthorize("@hchyun.hasPermi('tool:gen:code')") - @Log(title = "代码生成", businessType = BusinessType.GENCODE) + @Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @GetMapping("/batchGenCode") public void batchGenCode(HttpServletResponse response, String tables) throws IOException { String[] tableNames = Convert.toStrArray(tables); diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/InterTableController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/InterTableController.java index 8cf1e6a..9eaea90 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/InterTableController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/InterTableController.java @@ -5,14 +5,12 @@ import java.io.Serializable; import java.util.Map; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.controller.HcyBaseController; -import com.hchyun.common.utils.ServerResult; +import com.hchyun.generator.aop.Log; import com.hchyun.generator.dto.InterTableDto; -import com.hchyun.generator.entity.Apiclass; -import com.hchyun.generator.service.ApiclassService; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import com.hchyun.generator.enums.GenBusinessType; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; import org.apache.commons.io.IOUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -20,19 +18,13 @@ import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; -import org.springframework.web.bind.annotation.DeleteMapping; 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.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.enums.BusinessType; import com.hchyun.generator.entity.InterTable; import com.hchyun.generator.service.InterTableService; -import com.hchyun.common.utils.poi.ExcelUtil; import javax.servlet.http.HttpServletResponse; @@ -45,7 +37,7 @@ import javax.servlet.http.HttpServletResponse; @RestController @RequestMapping("/generator/intertable") -public class InterTableController extends HcyBaseController { +public class InterTableController extends GenBaseController { protected final Logger logger = LoggerFactory.getLogger(InterTableController.class); @Autowired @@ -58,15 +50,15 @@ public class InterTableController extends HcyBaseController { @GetMapping("/list") public Serializable list(InterTable interTable) { try { - ServerResult> serverResult = interTableService.selectInterTableList(interTable); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = interTableService.selectInterTableList(interTable); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -75,19 +67,19 @@ public class InterTableController extends HcyBaseController { */ @PreAuthorize("@hchyun.hasPermi('generator:intertable:classpreview')") - @Log(title = "预览代码(工作流)", businessType = BusinessType.GENCODE) + @Log(title = "预览代码(工作流)", businessType = GenBusinessType.GENCODE) @GetMapping("/classpreview/{id}") public AjaxResult classPreview(@PathVariable("id") Long id) { try { - ServerResult> serverResult = interTableService.previewCodeCalss(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = interTableService.previewCodeCalss(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -95,19 +87,19 @@ public class InterTableController extends HcyBaseController { * 预览代码(工作台) */ @PreAuthorize("@hchyun.hasPermi('generator:intertable:modulepreview')") - @Log(title = "预览代码(工作台)", businessType = BusinessType.GENCODE) + @Log(title = "预览代码(工作台)", businessType = GenBusinessType.GENCODE) @GetMapping("/modulepreview/{id}") public AjaxResult modulePreview(@PathVariable("id") Long id) { try { - ServerResult> serverResult = interTableService.previewCodeMoudle(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = interTableService.previewCodeMoudle(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -119,20 +111,20 @@ public class InterTableController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('generator:intertable:classgen')") - @Log(title = "生成代码(工作流)", businessType = BusinessType.GENCODE) + @Log(title = "生成代码(工作流)", businessType = GenBusinessType.GENCODE) @GetMapping("/classgen/{id}") public AjaxResult classGenerator(@PathVariable("id") Long id, HttpServletResponse response) { try { - ServerResult serverResult = interTableService.generatorCodeClass(id); - if (serverResult.isStart()) { - genCode(response, serverResult.getData()); + GenServerResult genServerResult = interTableService.generatorCodeClass(id); + if (genServerResult.isStart()) { + genCode(response, genServerResult.getData()); return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException | IOException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -144,20 +136,20 @@ public class InterTableController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('generator:intertable:moudlegen')") - @Log(title = "生成代码(工作台)", businessType = BusinessType.GENCODE) + @Log(title = "生成代码(工作台)", businessType = GenBusinessType.GENCODE) @GetMapping("/moudlegen/{id}") public AjaxResult moudleGenerator(@PathVariable("id") Long id, HttpServletResponse response) { try { - ServerResult serverResult = interTableService.generatorCodeMoudle(id); - if (serverResult.isStart()) { - genCode(response, serverResult.getData()); + GenServerResult genServerResult = interTableService.generatorCodeMoudle(id); + if (genServerResult.isStart()) { + genCode(response, genServerResult.getData()); return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException | IOException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -166,19 +158,19 @@ public class InterTableController extends HcyBaseController { * 修改接口信息 */ @PreAuthorize("@hchyun.hasPermi('generator:intertable:edit')") - @Log(title = "接口信息", businessType = BusinessType.UPDATE) + @Log(title = "接口信息", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult edit(@Validated @RequestBody InterTableDto interTableDto) { try { - ServerResult serverResult = interTableService.updateInterTable(interTableDto); - if (serverResult.isStart()) { + GenServerResult genServerResult = interTableService.updateInterTable(interTableDto); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -200,12 +192,12 @@ public class InterTableController extends HcyBaseController { // * 导出接口信息列表 // */ // @PreAuthorize("@hchyun.hasPermi('generator:intertable:export')") -// @Log(title = "接口信息", businessType = BusinessType.EXPORT) +// @Log(title = "接口信息", businessType = GenBusinessType.EXPORT) // @GetMapping("/export") // public GenResult export(InterTable interTable) { // try { -// ServerResult> serverResult = interTableService.selectInterTableList(interTable); -// ExcelUtil util = new ExcelUtil(InterTable. class); +// GenServerResult> serverResult = interTableService.selectInterTableList(interTable); +// GenExcelUtil util = new GenExcelUtil(InterTable. class); // if (serverResult.isStart()) { // return util.exportExcel(serverResult.getData(), "intertable"); // } else { @@ -213,7 +205,7 @@ public class InterTableController extends HcyBaseController { // } // } catch (RuntimeException e) { // logger.error(e.getMessage()); -// return GenResult.error(ReturnConstants.SYS_ERROR); +// return GenResult.error(GenReturnConstants.SYS_ERROR); // } // } @@ -224,7 +216,7 @@ public class InterTableController extends HcyBaseController { // @GetMapping(value = "/{id}") // public GenResult Info(@PathVariable("id") Long id) { // try { -// ServerResult serverResult = interTableService.selectInterTableById(id); +// GenServerResult serverResult = interTableService.selectInterTableById(id); // if (serverResult.isStart()) { // return GenResult.success(serverResult.getData()); // } else { @@ -232,7 +224,7 @@ public class InterTableController extends HcyBaseController { // } // } catch (RuntimeException e) { // logger.error(e.getMessage()); -// return GenResult.error(ReturnConstants.SYS_ERROR); +// return GenResult.error(GenReturnConstants.SYS_ERROR); // } // } // @@ -240,11 +232,11 @@ public class InterTableController extends HcyBaseController { // * 新增接口信息 // */ // @PreAuthorize("@hchyun.hasPermi('generator:intertable:add')") -// @Log(title = "接口信息", businessType = BusinessType.INSERT) +// @Log(title = "接口信息", businessType = GenBusinessType.INSERT) // @PostMapping // public GenResult add(@RequestBody InterTable interTable) { // try { -// ServerResult serverResult = interTableService.insertInterTable(interTable); +// GenServerResult serverResult = interTableService.insertInterTable(interTable); // if (serverResult.isStart()) { // return GenResult.success(); // } else { @@ -252,7 +244,7 @@ public class InterTableController extends HcyBaseController { // } // } catch (RuntimeException e) { // logger.error(e.getMessage()); -// return GenResult.error(ReturnConstants.SYS_ERROR); +// return GenResult.error(GenReturnConstants.SYS_ERROR); // } // } // @@ -260,14 +252,14 @@ public class InterTableController extends HcyBaseController { // * 删除接口信息 // */ // @PreAuthorize("@hchyun.hasPermi('generator:intertable:remove')") -// @Log(title = "接口信息", businessType = BusinessType.DELETE) +// @Log(title = "接口信息", businessType = GenBusinessType.DELETE) // @DeleteMapping("/{ids}") // public GenResult remove(@PathVariable Long[] ids) { // try { // if (ids.length<0){ // return GenResult.error("id不能为空!"); // } -// ServerResult serverResult = interTableService.deleteInterTableByIds(ids); +// GenServerResult serverResult = interTableService.deleteInterTableByIds(ids); // if (serverResult.isStart()) { // return GenResult.success(); // } else { @@ -275,7 +267,7 @@ public class InterTableController extends HcyBaseController { // } // }catch (RuntimeException e){ // logger.error(e.getMessage()); -// return GenResult.error(ReturnConstants.SYS_ERROR); +// return GenResult.error(GenReturnConstants.SYS_ERROR); // } // } } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ModuleController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ModuleController.java index c6acf0f..b0a4f02 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ModuleController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/ModuleController.java @@ -4,9 +4,12 @@ import java.io.Serializable; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.controller.HcyBaseController; -import com.hchyun.common.utils.ServerResult; +import com.hchyun.generator.aop.Log; +import com.hchyun.generator.enums.GenBusinessType; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.poi.GenExcelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; @@ -19,12 +22,8 @@ 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.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.enums.BusinessType; import com.hchyun.generator.entity.Module; import com.hchyun.generator.service.ModuleService; -import com.hchyun.common.utils.poi.ExcelUtil; /** * 模块管理Controller @@ -34,7 +33,7 @@ import com.hchyun.common.utils.poi.ExcelUtil; */ @RestController @RequestMapping("/tool/module") -public class ModuleController extends HcyBaseController { +public class ModuleController extends GenBaseController { protected final Logger logger = LoggerFactory.getLogger(ModuleController.class); @Autowired @@ -50,15 +49,15 @@ public class ModuleController extends HcyBaseController { @GetMapping("querylist") public AjaxResult queryList() { try { - ServerResult> serverResult = moduleService.selectModuleList(new Module()); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult> genServerResult = moduleService.selectModuleList(new Module()); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -71,15 +70,15 @@ public class ModuleController extends HcyBaseController { public Serializable list(Module module) { try { startPage(); - ServerResult> serverResult = moduleService.selectModuleList(module); - if (serverResult.isStart()) { - return getDataTable(serverResult.getData()); + GenServerResult> genServerResult = moduleService.selectModuleList(module); + if (genServerResult.isStart()) { + return getDataTable(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -87,20 +86,20 @@ public class ModuleController extends HcyBaseController { * 导出模块管理列表 */ @PreAuthorize("@hchyun.hasPermi('tool:module:export')") - @Log(title = "模块管理", businessType = BusinessType.EXPORT) + @Log(title = "模块管理", businessType = GenBusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(Module module) { try { - ServerResult> serverResult = moduleService.selectModuleList(module); - ExcelUtil util = new ExcelUtil(Module.class); - if (serverResult.isStart()) { - return util.exportExcel(serverResult.getData(), "module"); + GenServerResult> genServerResult = moduleService.selectModuleList(module); + GenExcelUtil util = new GenExcelUtil(Module.class); + if (genServerResult.isStart()) { + return util.exportExcel(genServerResult.getData(), "module"); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -111,15 +110,15 @@ public class ModuleController extends HcyBaseController { @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { try { - ServerResult serverResult = moduleService.selectModuleById(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult genServerResult = moduleService.selectModuleById(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -127,7 +126,7 @@ public class ModuleController extends HcyBaseController { * 新增模块管理 */ @PreAuthorize("@hchyun.hasPermi('tool:module:add')") - @Log(title = "模块管理", businessType = BusinessType.INSERT) + @Log(title = "模块管理", businessType = GenBusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody Module module) { if (module.getmName() == null || module.getmName().equals("")) { @@ -137,15 +136,15 @@ public class ModuleController extends HcyBaseController { return AjaxResult.error("模块描述不能为空!"); } try { - ServerResult serverResult = moduleService.insertModule(module); - if (serverResult.isStart()) { + GenServerResult genServerResult = moduleService.insertModule(module); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -153,7 +152,7 @@ public class ModuleController extends HcyBaseController { * 修改模块管理 */ @PreAuthorize("@hchyun.hasPermi('tool:module:edit')") - @Log(title = "模块管理", businessType = BusinessType.UPDATE) + @Log(title = "模块管理", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody Module module) { try { @@ -164,15 +163,15 @@ public class ModuleController extends HcyBaseController { if (module.getmDescribe() == null || module.getmDescribe().equals("")) { return AjaxResult.error("模块描述不能为空!"); } - ServerResult serverResult = moduleService.updateModule(module); - if (serverResult.isStart()) { + GenServerResult genServerResult = moduleService.updateModule(module); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -180,22 +179,22 @@ public class ModuleController extends HcyBaseController { * 删除模块管理 */ @PreAuthorize("@hchyun.hasPermi('tool:module:remove')") - @Log(title = "模块管理", businessType = BusinessType.DELETE) + @Log(title = "模块管理", businessType = GenBusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { try { if (ids.length < 0) { return AjaxResult.error("id不能为空!"); } - ServerResult serverResult = moduleService.deleteModuleByIds(ids); - if (serverResult.isStart()) { + GenServerResult genServerResult = moduleService.deleteModuleByIds(ids); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/QueryController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/QueryController.java index f52e098..a497ea0 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/QueryController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/QueryController.java @@ -1,16 +1,11 @@ package com.hchyun.generator.controller; import com.github.pagehelper.PageHelper; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.controller.BaseController; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.utils.ServerResult; -import com.hchyun.common.utils.StringUtils; -import com.hchyun.common.utils.sql.SqlUtil; import com.hchyun.generator.entity.UniCon; import com.hchyun.generator.entity.UniQuery; import com.hchyun.generator.service.QueryService; -import com.hchyun.common.utils.MapExcelUtil; +import com.hchyun.generator.utils.*; +import com.hchyun.generator.utils.sql.GenSqlUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -31,7 +26,7 @@ import java.util.Map; */ @RestController @RequestMapping("/query") -public class QueryController extends BaseController { +public class QueryController extends GenBaseController { private Logger logger = LoggerFactory.getLogger(QueryController.class); @@ -47,9 +42,9 @@ public class QueryController extends BaseController { @GetMapping("/{id}") public AjaxResult Info(@PathVariable("id") Long id) { try { - ServerResult serverResult = queryService.selectQueryById(id); - if (serverResult.isStart()) { - UniQuery uniQuery = serverResult.getData(); + GenServerResult genServerResult = queryService.selectQueryById(id); + if (genServerResult.isStart()) { + UniQuery uniQuery = genServerResult.getData(); Map modeMap = new HashMap<>(); List uniCons = uniQuery.getUniCons(); uniQuery.setUniCons(null); @@ -57,11 +52,11 @@ public class QueryController extends BaseController { modeMap.put("list", uniCons); return AjaxResult.success(modeMap); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -74,15 +69,15 @@ public class QueryController extends BaseController { @PutMapping public AjaxResult edit(@Validated @RequestBody UniQuery uniQuery) { try { - ServerResult serverResult = queryService.updateQueryInfo(uniQuery); - if (serverResult.isStart()) { + GenServerResult genServerResult = queryService.updateQueryInfo(uniQuery); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -95,15 +90,15 @@ public class QueryController extends BaseController { @PutMapping("export") public AjaxResult export(@Validated @RequestBody UniQuery uniQuery) { try { - ServerResult>> serverResult = queryService.previewQuery(uniQuery); - if (serverResult.isStart()) { - return new MapExcelUtil().exportExcel(serverResult.getData(), uniQuery.getUqName()); + GenServerResult>> genServerResult = queryService.previewQuery(uniQuery); + if (genServerResult.isStart()) { + return new GenMapExcelUtil().exportExcel(genServerResult.getData(), uniQuery.getUqName()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -117,15 +112,15 @@ public class QueryController extends BaseController { public Serializable Preview(@Validated @RequestBody UniQuery uniQuery) { try { startPage(uniQuery); - ServerResult>> serverResult = queryService.previewQuery(uniQuery); - if (serverResult.isStart()) { - return getDataTable(serverResult.getData()); + GenServerResult>> genServerResult = queryService.previewQuery(uniQuery); + if (genServerResult.isStart()) { + return getDataTable(genServerResult.getData()); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -142,11 +137,11 @@ public class QueryController extends BaseController { return AjaxResult.error("id不能为空!"); } else { if (uniQuery.getIsRelease() == 1 || uniQuery.getIsRelease() == 2) { - ServerResult serverResult = queryService.Release(uniQuery); - if (serverResult.isStart()) { + GenServerResult genServerResult = queryService.Release(uniQuery); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } else { return AjaxResult.error("状态输入错误!"); @@ -154,7 +149,7 @@ public class QueryController extends BaseController { } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -164,8 +159,8 @@ public class QueryController extends BaseController { protected void startPage(UniQuery uniQuery) { Integer pageNum = uniQuery.getPageNum(); Integer pageSize = uniQuery.getPageSize(); - if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) { - String orderBy = SqlUtil.escapeOrderBySql(""); + if (GenStringUtils.isNotNull(pageNum) && GenStringUtils.isNotNull(pageSize)) { + String orderBy = GenSqlUtil.escapeOrderBySql(""); PageHelper.startPage(pageNum, pageSize, orderBy); } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/RegularController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/RegularController.java index 2cb2008..886f3a0 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/RegularController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/RegularController.java @@ -4,11 +4,14 @@ import java.io.Serializable; import java.util.List; import java.util.regex.Pattern; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.ServerResult; -import com.hchyun.common.utils.poi.ExcelUtil; +import com.hchyun.generator.aop.Log; import com.hchyun.generator.entity.Regular; +import com.hchyun.generator.enums.GenBusinessType; import com.hchyun.generator.service.RegularService; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.poi.GenExcelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; @@ -21,10 +24,6 @@ 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.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.controller.HcyBaseController; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.enums.BusinessType; /** * 校验规则Controller @@ -34,7 +33,7 @@ import com.hchyun.common.enums.BusinessType; */ @RestController @RequestMapping("/tool/regular") -public class RegularController extends HcyBaseController { +public class RegularController extends GenBaseController { protected final Logger logger = LoggerFactory.getLogger(RegularController.class); @Autowired @@ -51,15 +50,15 @@ public class RegularController extends HcyBaseController { public Serializable list(Regular regular) { try { startPage(); - ServerResult> serverResult = regularService.selectRegularList(regular); - if (serverResult.isStart()) { - return getDataTable(serverResult.getData()); + GenServerResult> genServerResult = regularService.selectRegularList(regular); + if (genServerResult.isStart()) { + return getDataTable(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -70,20 +69,20 @@ public class RegularController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('tool:regular:export')") - @Log(title = "校验规则", businessType = BusinessType.EXPORT) + @Log(title = "校验规则", businessType = GenBusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(Regular regular) { try { - ServerResult> serverResult = regularService.selectRegularList(regular); - ExcelUtil util = new ExcelUtil(Regular.class); - if (serverResult.isStart()) { - return util.exportExcel(serverResult.getData(), "regular"); + GenServerResult> genServerResult = regularService.selectRegularList(regular); + GenExcelUtil util = new GenExcelUtil(Regular.class); + if (genServerResult.isStart()) { + return util.exportExcel(genServerResult.getData(), "regular"); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -97,15 +96,15 @@ public class RegularController extends HcyBaseController { @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { try { - ServerResult serverResult = regularService.selectRegularById(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult genServerResult = regularService.selectRegularById(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -116,7 +115,7 @@ public class RegularController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('tool:regular:add')") - @Log(title = "校验规则", businessType = BusinessType.INSERT) + @Log(title = "校验规则", businessType = GenBusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody Regular regular) { try { @@ -132,15 +131,15 @@ public class RegularController extends HcyBaseController { if (!verifyRegular(regular)) { return AjaxResult.error("正则表达式校验不通过!"); } - ServerResult serverResult = regularService.insertRegular(regular); - if (serverResult.isStart()) { + GenServerResult genServerResult = regularService.insertRegular(regular); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -151,7 +150,7 @@ public class RegularController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('tool:regular:edit')") - @Log(title = "校验规则", businessType = BusinessType.UPDATE) + @Log(title = "校验规则", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody Regular regular) { try { @@ -167,15 +166,15 @@ public class RegularController extends HcyBaseController { if (!verifyRegular(regular)) { return AjaxResult.error("正则表达式校验不通过!"); } - ServerResult serverResult = regularService.updateRegular(regular); - if (serverResult.isStart()) { + GenServerResult genServerResult = regularService.updateRegular(regular); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -186,22 +185,22 @@ public class RegularController extends HcyBaseController { * @return */ @PreAuthorize("@hchyun.hasPermi('tool:regular:remove')") - @Log(title = "校验规则", businessType = BusinessType.DELETE) + @Log(title = "校验规则", businessType = GenBusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { try { if (ids.length == 0) { return AjaxResult.error("需要删除id数不能为空!"); } - ServerResult serverResult = regularService.deleteRegularByIds(ids); - if (serverResult.isStart()) { + GenServerResult genServerResult = regularService.deleteRegularByIds(ids); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/UniQueryController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/UniQueryController.java index 93f7c45..fd10821 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/UniQueryController.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/controller/UniQueryController.java @@ -4,12 +4,14 @@ import java.io.Serializable; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.controller.BaseController; -import com.hchyun.common.utils.ServerResult; -import com.hchyun.common.utils.poi.ExcelUtil; +import com.hchyun.generator.aop.Log; import com.hchyun.generator.entity.UniQuery; +import com.hchyun.generator.enums.GenBusinessType; import com.hchyun.generator.service.UniQueryService; +import com.hchyun.generator.utils.GenBaseController; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.poi.GenExcelUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.prepost.PreAuthorize; @@ -22,9 +24,6 @@ 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.RestController; -import com.hchyun.common.annotation.Log; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.enums.BusinessType; /** * 万能查询Controller @@ -34,7 +33,7 @@ import com.hchyun.common.enums.BusinessType; */ @RestController @RequestMapping("/tool/query") -public class UniQueryController extends BaseController { +public class UniQueryController extends GenBaseController { protected final Logger logger = LoggerFactory.getLogger(UniQueryController.class); @Autowired @@ -48,15 +47,15 @@ public class UniQueryController extends BaseController { public Serializable list(UniQuery uniQuery) { try { startPage(); - ServerResult> serverResult = uniQueryService.selectUniQueryList(uniQuery); - if (serverResult.isStart()) { - return getDataTable(serverResult.getData()); + GenServerResult> genServerResult = uniQueryService.selectUniQueryList(uniQuery); + if (genServerResult.isStart()) { + return getDataTable(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -64,20 +63,20 @@ public class UniQueryController extends BaseController { * 导出万能查询列表 */ @PreAuthorize("@hchyun.hasPermi('tool:query:export')") - @Log(title = "万能查询", businessType = BusinessType.EXPORT) + @Log(title = "万能查询", businessType = GenBusinessType.EXPORT) @GetMapping("/export") public AjaxResult export(UniQuery uniQuery) { try { - ServerResult> serverResult = uniQueryService.selectUniQueryList(uniQuery); - ExcelUtil util = new ExcelUtil(UniQuery.class); - if (serverResult.isStart()) { - return util.exportExcel(serverResult.getData(), "query"); + GenServerResult> genServerResult = uniQueryService.selectUniQueryList(uniQuery); + GenExcelUtil util = new GenExcelUtil(UniQuery.class); + if (genServerResult.isStart()) { + return util.exportExcel(genServerResult.getData(), "query"); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -88,15 +87,15 @@ public class UniQueryController extends BaseController { @GetMapping(value = "/{id}") public AjaxResult getInfo(@PathVariable("id") Long id) { try { - ServerResult serverResult = uniQueryService.selectUniQueryById(id); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + GenServerResult genServerResult = uniQueryService.selectUniQueryById(id); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -104,7 +103,7 @@ public class UniQueryController extends BaseController { * 新增万能查询 */ @PreAuthorize("@hchyun.hasPermi('tool:query:add')") - @Log(title = "万能查询", businessType = BusinessType.INSERT) + @Log(title = "万能查询", businessType = GenBusinessType.INSERT) @PostMapping public AjaxResult add(@RequestBody UniQuery uniQuery) { if (uniQuery.getUqName() == null || uniQuery.getUqName().equals("")) { @@ -114,15 +113,15 @@ public class UniQueryController extends BaseController { return AjaxResult.error("描述不能为空!"); } try { - ServerResult serverResult = uniQueryService.insertUniQuery(uniQuery); - if (serverResult.isStart()) { + GenServerResult genServerResult = uniQueryService.insertUniQuery(uniQuery); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -130,7 +129,7 @@ public class UniQueryController extends BaseController { * 简单修改万能能查询 */ @PreAuthorize("@hchyun.hasPermi('tool:query:edit')") - @Log(title = "万能查询", businessType = BusinessType.UPDATE) + @Log(title = "万能查询", businessType = GenBusinessType.UPDATE) @PutMapping public AjaxResult edit(@RequestBody UniQuery uniQuery) { try { @@ -141,15 +140,15 @@ public class UniQueryController extends BaseController { if (uniQuery.getUqDescribe() == null || uniQuery.getUqDescribe().equals("")) { return AjaxResult.error("描述不能为空!"); } - ServerResult serverResult = uniQueryService.updateUniQuery(uniQuery); - if (serverResult.isStart()) { + GenServerResult genServerResult = uniQueryService.updateUniQuery(uniQuery); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } @@ -157,22 +156,22 @@ public class UniQueryController extends BaseController { * 删除万能查询 */ @PreAuthorize("@hchyun.hasPermi('tool:query:remove')") - @Log(title = "万能查询", businessType = BusinessType.DELETE) + @Log(title = "万能查询", businessType = GenBusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove(@PathVariable Long[] ids) { try { if (ids.length < 0) { return AjaxResult.error("id不能为空!"); } - ServerResult serverResult = uniQueryService.deleteUniQueryByIds(ids); - if (serverResult.isStart()) { + GenServerResult genServerResult = uniQueryService.deleteUniQueryByIds(ids); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return AjaxResult.error(ReturnConstants.SYS_ERROR); + return AjaxResult.error(GenReturnConstants.SYS_ERROR); } } } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/dao/QueryDao.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/dao/QueryDao.java index eb33d4c..c428ffe 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/dao/QueryDao.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/dao/QueryDao.java @@ -1,8 +1,8 @@ package com.hchyun.generator.dao; -import com.hchyun.common.core.entity.entity.Menu; import com.hchyun.generator.entity.UniCon; import com.hchyun.generator.entity.UniQuery; +import com.hchyun.generator.utils.entity.GenMenu; import java.util.List; import java.util.Map; @@ -58,10 +58,10 @@ public interface QueryDao { /** * 插入到菜单 - * @param menu + * @param genMenu * @return */ - Integer insertMenu(Menu menu); + Integer insertMenu(GenMenu genMenu); /** * 删除菜单 diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Apiclass.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Apiclass.java index f5829d3..5c0ca56 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Apiclass.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Apiclass.java @@ -1,8 +1,6 @@ package com.hchyun.generator.entity; -import com.hchyun.common.annotation.Excel; -import com.hchyun.common.core.entity.BaseEntity; -import io.swagger.annotations.ApiModel; +import com.hchyun.generator.aop.Excel; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -15,7 +13,7 @@ import java.util.List; * @author hchyun * @date 2021-01-24 */ -public class Apiclass extends BaseEntity { +public class Apiclass extends GenBaseEntity { /** diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenBaseEntity.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenBaseEntity.java new file mode 100644 index 0000000..c091d73 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenBaseEntity.java @@ -0,0 +1,145 @@ +package com.hchyun.generator.entity; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.hchyun.generator.aop.Excel; + +import java.io.Serializable; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +/** + * Entity基类 + * + * @author hchyun + */ +public class GenBaseEntity implements Serializable { + + + /** + * 搜索值 + */ + private String searchValue; + + /** + * 创建者 + */ + private Long createBy; + + /** + * 创建时间 + */ + @Excel(name = "创建时间", dateFormat = "yyyy-MM-dd HH:mm:ss", sort = Integer.MAX_VALUE - 1) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date createTime; + + /** + * 更新者 + */ + private Long updateBy; + + /** + * 更新时间 + */ + @Excel(name = "更新时间", dateFormat = "yyyy-MM-dd HH:mm:ss", sort = Integer.MAX_VALUE) + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss") + private Date updateTime; + + /** + * 备注 + */ + private String remark; + + /** + * 开始时间 + */ + @JsonIgnore + private String beginTime; + + /** + * 结束时间 + */ + @JsonIgnore + private String endTime; + + /** + * 请求参数 + */ + private Map params; + + public String getSearchValue() { + return searchValue; + } + + public void setSearchValue(String searchValue) { + this.searchValue = searchValue; + } + + public Date getCreateTime() { + return createTime; + } + + public Long getCreateBy() { + return createBy; + } + + public void setCreateBy(Long createBy) { + this.createBy = createBy; + } + + public Long getUpdateBy() { + return updateBy; + } + + public void setUpdateBy(Long updateBy) { + this.updateBy = updateBy; + } + + public void setCreateTime(Date createTime) { + this.createTime = createTime; + } + + public Date getUpdateTime() { + return updateTime; + } + + public void setUpdateTime(Date updateTime) { + this.updateTime = updateTime; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } + + public String getBeginTime() { + return beginTime; + } + + public void setBeginTime(String beginTime) { + this.beginTime = beginTime; + } + + public String getEndTime() { + return endTime; + } + + public void setEndTime(String endTime) { + this.endTime = endTime; + } + + public Map getParams() { + if (params == null) { + params = new HashMap<>(); + } + return params; + } + + public void setParams(Map params) { + this.params = params; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTable.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTable.java index 6f866b5..837250b 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTable.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTable.java @@ -4,17 +4,16 @@ import java.util.List; import javax.validation.Valid; import javax.validation.constraints.NotBlank; +import com.hchyun.generator.utils.GenStringUtils; +import com.hchyun.generator.utils.constant.GenConstants; import org.apache.commons.lang3.ArrayUtils; -import com.hchyun.common.constant.GenConstants; -import com.hchyun.common.core.entity.BaseEntity; -import com.hchyun.common.utils.StringUtils; /** * 业务表 gen_table * * @author hchyun */ -public class GenTable extends BaseEntity { +public class GenTable extends GenBaseEntity { /** @@ -393,7 +392,7 @@ public class GenTable extends BaseEntity { } public static boolean isSub(String tplCategory) { - return tplCategory != null && StringUtils.equals(GenConstants.TPL_SUB, tplCategory); + return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_SUB, tplCategory); } public boolean isTree() { @@ -401,7 +400,7 @@ public class GenTable extends BaseEntity { } public static boolean isTree(String tplCategory) { - return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory); + return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_TREE, tplCategory); } public boolean isCrud() { @@ -409,7 +408,7 @@ public class GenTable extends BaseEntity { } public static boolean isCrud(String tplCategory) { - return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory); + return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_CRUD, tplCategory); } public boolean isSuperColumn(String javaField) { @@ -418,9 +417,9 @@ public class GenTable extends BaseEntity { public static boolean isSuperColumn(String tplCategory, String javaField) { if (isTree(tplCategory)) { - return StringUtils.equalsAnyIgnoreCase(javaField, + return GenStringUtils.equalsAnyIgnoreCase(javaField, ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY)); } - return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); + return GenStringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); } } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTableColumn.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTableColumn.java index 00aa745..fe91762 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTableColumn.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/GenTableColumn.java @@ -1,16 +1,16 @@ package com.hchyun.generator.entity; +import com.hchyun.generator.utils.GenStringUtils; + import javax.validation.constraints.NotBlank; -import com.hchyun.common.core.entity.BaseEntity; -import com.hchyun.common.utils.StringUtils; /** * 代码生成业务字段表 gen_table_column * * @author hchyun */ -public class GenTableColumn extends BaseEntity { +public class GenTableColumn extends GenBaseEntity { /** @@ -188,7 +188,7 @@ public class GenTableColumn extends BaseEntity { } public String getCapJavaField() { - return StringUtils.capitalize(javaField); + return GenStringUtils.capitalize(javaField); } public void setIsPk(String isPk) { @@ -204,7 +204,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isPk(String isPk) { - return isPk != null && StringUtils.equals("1", isPk); + return isPk != null && GenStringUtils.equals("1", isPk); } public String getIsIncrement() { @@ -220,7 +220,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isIncrement(String isIncrement) { - return isIncrement != null && StringUtils.equals("1", isIncrement); + return isIncrement != null && GenStringUtils.equals("1", isIncrement); } public void setIsRequired(String isRequired) { @@ -236,7 +236,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isRequired(String isRequired) { - return isRequired != null && StringUtils.equals("1", isRequired); + return isRequired != null && GenStringUtils.equals("1", isRequired); } public void setIsInsert(String isInsert) { @@ -252,7 +252,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isInsert(String isInsert) { - return isInsert != null && StringUtils.equals("1", isInsert); + return isInsert != null && GenStringUtils.equals("1", isInsert); } public void setIsEdit(String isEdit) { @@ -268,7 +268,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isEdit(String isEdit) { - return isEdit != null && StringUtils.equals("1", isEdit); + return isEdit != null && GenStringUtils.equals("1", isEdit); } public void setIsList(String isList) { @@ -284,7 +284,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isList(String isList) { - return isList != null && StringUtils.equals("1", isList); + return isList != null && GenStringUtils.equals("1", isList); } public void setIsQuery(String isQuery) { @@ -300,7 +300,7 @@ public class GenTableColumn extends BaseEntity { } public boolean isQuery(String isQuery) { - return isQuery != null && StringUtils.equals("1", isQuery); + return isQuery != null && GenStringUtils.equals("1", isQuery); } public void setQueryType(String queryType) { @@ -340,8 +340,8 @@ public class GenTableColumn extends BaseEntity { } public static boolean isSuperColumn(String javaField) { - return StringUtils.equalsAnyIgnoreCase(javaField, - // BaseEntity + return GenStringUtils.equalsAnyIgnoreCase(javaField, + // GenBaseEntity "createBy", "createTime", "updateBy", "updateTime", "remark", // TreeEntity "parentName", "parentId", "orderNum", "ancestors"); @@ -353,15 +353,15 @@ public class GenTableColumn extends BaseEntity { public static boolean isUsableColumn(String javaField) { // isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单 - return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark"); + return GenStringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark"); } public String readConverterExp() { - String remarks = StringUtils.substringBetween(this.columnComment, "(", ")"); + String remarks = GenStringUtils.substringBetween(this.columnComment, "(", ")"); StringBuffer sb = new StringBuffer(); - if (StringUtils.isNotEmpty(remarks)) { + if (GenStringUtils.isNotEmpty(remarks)) { for (String value : remarks.split(" ")) { - if (StringUtils.isNotEmpty(value)) { + if (GenStringUtils.isNotEmpty(value)) { Object startStr = value.subSequence(0, 1); String endStr = value.substring(1); sb.append("").append(startStr).append("=").append(endStr).append(","); diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/InterTable.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/InterTable.java index 0089c04..11a32f5 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/InterTable.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/InterTable.java @@ -1,8 +1,7 @@ package com.hchyun.generator.entity; import com.fasterxml.jackson.annotation.JsonFormat; -import com.hchyun.common.annotation.Excel; -import com.hchyun.common.core.entity.BaseEntity; +import com.hchyun.generator.aop.Excel; import io.swagger.annotations.ApiModel; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Module.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Module.java index f5586de..7b81034 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Module.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Module.java @@ -1,7 +1,6 @@ package com.hchyun.generator.entity; -import com.hchyun.common.annotation.Excel; -import com.hchyun.common.core.entity.BaseEntity; +import com.hchyun.generator.aop.Excel; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -13,7 +12,7 @@ import java.util.List; * @author hchyun * @date 2021-01-24 */ -public class Module extends BaseEntity { +public class Module extends GenBaseEntity { /** diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Regular.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Regular.java index c216327..1b4b6fb 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Regular.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/Regular.java @@ -1,7 +1,6 @@ package com.hchyun.generator.entity; -import com.hchyun.common.annotation.Excel; -import com.hchyun.common.core.entity.BaseEntity; +import com.hchyun.generator.aop.Excel; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -11,7 +10,7 @@ import org.apache.commons.lang3.builder.ToStringStyle; * @author hchyun * @date 2021-01-18 */ -public class Regular extends BaseEntity { +public class Regular extends GenBaseEntity { /** diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniCon.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniCon.java index 278458f..bce9695 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniCon.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniCon.java @@ -1,8 +1,5 @@ package com.hchyun.generator.entity; -import com.hchyun.common.core.entity.BaseEntity; -import org.apache.commons.lang3.builder.ToStringBuilder; -import org.apache.commons.lang3.builder.ToStringStyle; /** * 万能查询条件对象 sys_uni_con diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniQuery.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniQuery.java index bc7b7ad..3dd3a7d 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniQuery.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/entity/UniQuery.java @@ -1,6 +1,5 @@ package com.hchyun.generator.entity; -import com.hchyun.common.core.entity.BaseEntity; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; @@ -13,7 +12,7 @@ import java.util.List; * @author hchyun * @date 2021-01-30 */ -public class UniQuery extends BaseEntity { +public class UniQuery extends GenBaseEntity { /** * id diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenBusinessType.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenBusinessType.java new file mode 100644 index 0000000..eabda08 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenBusinessType.java @@ -0,0 +1,58 @@ +package com.hchyun.generator.enums; + +/** + * 业务操作类型 + * + * @author hchyun + */ +public enum GenBusinessType { + /** + * 其它 + */ + OTHER, + + /** + * 新增 + */ + INSERT, + + /** + * 修改 + */ + UPDATE, + + /** + * 删除 + */ + DELETE, + + /** + * 授权 + */ + GRANT, + + /** + * 导出 + */ + EXPORT, + + /** + * 导入 + */ + IMPORT, + + /** + * 强退 + */ + FORCE, + + /** + * 生成代码 + */ + GENCODE, + + /** + * 清空数据 + */ + CLEAN, +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenOperatorType.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenOperatorType.java new file mode 100644 index 0000000..338a5e9 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/enums/GenOperatorType.java @@ -0,0 +1,23 @@ +package com.hchyun.generator.enums; + +/** + * 操作人类别 + * + * @author hchyun + */ +public enum GenOperatorType { + /** + * 其它 + */ + OTHER, + + /** + * 后台用户 + */ + MANAGE, + + /** + * 手机端用户 + */ + MOBILE +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ApiclassService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ApiclassService.java index 8251d0b..df44449 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ApiclassService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ApiclassService.java @@ -2,8 +2,8 @@ package com.hchyun.generator.service; import java.util.List; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.Apiclass; +import com.hchyun.generator.utils.GenServerResult; /** * 接口类名Service接口 @@ -18,7 +18,7 @@ public interface ApiclassService { * @param id 接口类名ID * @return 接口类名 */ - ServerResult selectApiclassById(Long id); + GenServerResult selectApiclassById(Long id); /** * 查询接口类名列表 @@ -26,7 +26,7 @@ public interface ApiclassService { * @param apiclass 接口类名 * @return 接口类名集合 */ - ServerResult> selectApiclassList(Apiclass apiclass); + GenServerResult> selectApiclassList(Apiclass apiclass); /** * 新增接口类名 @@ -34,7 +34,7 @@ public interface ApiclassService { * @param apiclass 接口类名 * @return 结果 */ - ServerResult insertApiclass(Apiclass apiclass); + GenServerResult insertApiclass(Apiclass apiclass); /** * 修改接口类名 @@ -42,7 +42,7 @@ public interface ApiclassService { * @param apiclass 接口类名 * @return 结果 */ - ServerResult updateApiclass(Apiclass apiclass); + GenServerResult updateApiclass(Apiclass apiclass); /** * 批量删除接口类名 @@ -50,7 +50,7 @@ public interface ApiclassService { * @param ids 需要删除的接口类名ID * @return 结果 */ - ServerResult deleteApiclassByIds(Long[] ids); + GenServerResult deleteApiclassByIds(Long[] ids); /** * 删除接口类名信息 @@ -58,5 +58,5 @@ public interface ApiclassService { * @param id 接口类名ID * @return 结果 */ - ServerResult deleteApiclassById(Long id); + GenServerResult deleteApiclassById(Long id); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/AssociatedService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/AssociatedService.java index 681c71a..de92258 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/AssociatedService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/AssociatedService.java @@ -1,7 +1,7 @@ package com.hchyun.generator.service; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.AssColumn; +import com.hchyun.generator.utils.GenServerResult; import java.util.List; import java.util.Map; @@ -17,7 +17,7 @@ public interface AssociatedService { * * @return */ - ServerResult>> tableInfos(); + GenServerResult>> tableInfos(); /** * 获取到关联边字段信息 @@ -26,7 +26,7 @@ public interface AssociatedService { * @param tableId 关联关系id * @return */ - ServerResult> assColumns(String tableName, Long tableId); + GenServerResult> assColumns(String tableName, Long tableId); /** * 通过table获取到关联信息 @@ -34,7 +34,7 @@ public interface AssociatedService { * @param tableId * @return */ - ServerResult> assColumnsByTable(Long tableId); + GenServerResult> assColumnsByTable(Long tableId); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/GenTableService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/GenTableService.java index 1191f1f..e02b231 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/GenTableService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/GenTableService.java @@ -3,8 +3,8 @@ package com.hchyun.generator.service; import java.util.List; import java.util.Map; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.GenTable; +import com.hchyun.generator.utils.GenServerResult; /** * 业务 服务层 @@ -65,7 +65,7 @@ public interface GenTableService { * @param tableIds 需要删除的表数据ID * @return 结果 */ - public ServerResult deleteGenTableByIds(Long[] tableIds); + public GenServerResult deleteGenTableByIds(Long[] tableIds); /** * 导入表结构 diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/InterTableService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/InterTableService.java index 4ebe80f..1e13f00 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/InterTableService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/InterTableService.java @@ -1,11 +1,10 @@ package com.hchyun.generator.service; import java.util.Map; -import java.util.zip.ZipOutputStream; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dto.InterTableDto; import com.hchyun.generator.entity.InterTable; +import com.hchyun.generator.utils.GenServerResult; /** * 接口信息Service接口 @@ -20,7 +19,7 @@ public interface InterTableService { * @param id 接口信息ID * @return 接口信息 */ - ServerResult selectInterTableById(Long id); + GenServerResult selectInterTableById(Long id); /** * 查询接口信息列表 @@ -28,7 +27,7 @@ public interface InterTableService { * @param interTable 接口信息 * @return 接口信息集合 */ - ServerResult> selectInterTableList(InterTable interTable); + GenServerResult> selectInterTableList(InterTable interTable); /** * 新增接口信息 @@ -36,7 +35,7 @@ public interface InterTableService { * @param interTable 接口信息 * @return 结果 */ - ServerResult insertInterTable(InterTable interTable); + GenServerResult insertInterTable(InterTable interTable); /** * 修改接口信息 @@ -44,7 +43,7 @@ public interface InterTableService { * @param interTableDto 接口信息 * @return 结果 */ - ServerResult updateInterTable(InterTableDto interTableDto); + GenServerResult updateInterTable(InterTableDto interTableDto); /** * 批量删除接口信息 @@ -52,7 +51,7 @@ public interface InterTableService { * @param ids 需要删除的接口信息ID * @return 结果 */ - ServerResult deleteInterTableByIds(Long[] ids); + GenServerResult deleteInterTableByIds(Long[] ids); /** * 删除接口信息信息 @@ -60,7 +59,7 @@ public interface InterTableService { * @param id 接口信息ID * @return 结果 */ - ServerResult deleteInterTableById(Long id); + GenServerResult deleteInterTableById(Long id); /** * 预览代码(工作流) @@ -68,7 +67,7 @@ public interface InterTableService { * @param cid * @return */ - ServerResult> previewCodeCalss(Long cid); + GenServerResult> previewCodeCalss(Long cid); /** * 预览代码()工作台 @@ -76,7 +75,7 @@ public interface InterTableService { * @param mid * @return */ - ServerResult> previewCodeMoudle(Long mid); + GenServerResult> previewCodeMoudle(Long mid); /** * 生成代码(工作流) @@ -84,7 +83,7 @@ public interface InterTableService { * @param cid * @return */ - ServerResult generatorCodeClass(Long cid); + GenServerResult generatorCodeClass(Long cid); /** * 生成代码(工作台) @@ -92,6 +91,6 @@ public interface InterTableService { * @param mid * @return */ - ServerResult generatorCodeMoudle(Long mid); + GenServerResult generatorCodeMoudle(Long mid); } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ModuleService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ModuleService.java index bc352f2..d7c4171 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ModuleService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/ModuleService.java @@ -1,8 +1,8 @@ package com.hchyun.generator.service; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.Module; +import com.hchyun.generator.utils.GenServerResult; import java.util.List; @@ -19,7 +19,7 @@ public interface ModuleService { * @param id 模块管理ID * @return 模块管理 */ - ServerResult selectModuleById(Long id); + GenServerResult selectModuleById(Long id); /** * 查询模块管理列表 @@ -27,7 +27,7 @@ public interface ModuleService { * @param module 模块管理 * @return 模块管理集合 */ - ServerResult> selectModuleList(Module module); + GenServerResult> selectModuleList(Module module); /** * 新增模块管理 @@ -35,7 +35,7 @@ public interface ModuleService { * @param module 模块管理 * @return 结果 */ - ServerResult insertModule(Module module); + GenServerResult insertModule(Module module); /** * 修改模块管理 @@ -43,7 +43,7 @@ public interface ModuleService { * @param module 模块管理 * @return 结果 */ - ServerResult updateModule(Module module); + GenServerResult updateModule(Module module); /** * 批量删除模块管理 @@ -51,7 +51,7 @@ public interface ModuleService { * @param ids 需要删除的模块管理ID * @return 结果 */ - ServerResult deleteModuleByIds(Long[] ids); + GenServerResult deleteModuleByIds(Long[] ids); /** * 删除模块管理信息 @@ -59,5 +59,5 @@ public interface ModuleService { * @param id 模块管理ID * @return 结果 */ - ServerResult deleteModuleById(Long id); + GenServerResult deleteModuleById(Long id); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/QueryService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/QueryService.java index b9b1883..dd8ea81 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/QueryService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/QueryService.java @@ -1,8 +1,7 @@ package com.hchyun.generator.service; -import com.hchyun.common.utils.ServerResult; -import com.hchyun.generator.entity.UniCon; import com.hchyun.generator.entity.UniQuery; +import com.hchyun.generator.utils.GenServerResult; import java.util.List; import java.util.Map; @@ -19,7 +18,7 @@ public interface QueryService { * @param id * @return */ - ServerResult selectQueryById(Long id); + GenServerResult selectQueryById(Long id); /** * 修改基础信息 @@ -27,7 +26,7 @@ public interface QueryService { * @param uniQuery * @return */ - ServerResult updateQueryInfo(UniQuery uniQuery); + GenServerResult updateQueryInfo(UniQuery uniQuery); /** * 预览万能查询数据 @@ -35,11 +34,11 @@ public interface QueryService { * @param uniQuery * @return */ - ServerResult>> previewQuery(UniQuery uniQuery); + GenServerResult>> previewQuery(UniQuery uniQuery); /** * @param uniQuery * @return */ - ServerResult Release(UniQuery uniQuery); + GenServerResult Release(UniQuery uniQuery); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/RegularService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/RegularService.java index aa95c4f..a9a4c27 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/RegularService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/RegularService.java @@ -1,7 +1,7 @@ package com.hchyun.generator.service; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.Regular; +import com.hchyun.generator.utils.GenServerResult; import java.util.List; @@ -18,7 +18,7 @@ public interface RegularService { * @param id 校验规则ID * @return 校验规则 */ - ServerResult selectRegularById(Long id); + GenServerResult selectRegularById(Long id); /** * 查询校验规则列表 @@ -26,7 +26,7 @@ public interface RegularService { * @param regular 校验规则 * @return 校验规则集合 */ - ServerResult> selectRegularList(Regular regular); + GenServerResult> selectRegularList(Regular regular); /** * 新增校验规则 @@ -34,7 +34,7 @@ public interface RegularService { * @param regular 校验规则 * @return 结果 */ - ServerResult insertRegular(Regular regular); + GenServerResult insertRegular(Regular regular); /** * 修改校验规则 @@ -42,7 +42,7 @@ public interface RegularService { * @param regular 校验规则 * @return 结果 */ - ServerResult updateRegular(Regular regular); + GenServerResult updateRegular(Regular regular); /** * 批量删除校验规则 @@ -50,7 +50,7 @@ public interface RegularService { * @param ids 需要删除的校验规则ID * @return 结果 */ - ServerResult deleteRegularByIds(Long[] ids); + GenServerResult deleteRegularByIds(Long[] ids); /** * 删除校验规则信息 @@ -58,5 +58,5 @@ public interface RegularService { * @param id 校验规则ID * @return 结果 */ - ServerResult deleteRegularById(Long id); + GenServerResult deleteRegularById(Long id); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/UniQueryService.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/UniQueryService.java index eb206b3..9404fa6 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/UniQueryService.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/UniQueryService.java @@ -2,8 +2,8 @@ package com.hchyun.generator.service; import java.util.List; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.entity.UniQuery; +import com.hchyun.generator.utils.GenServerResult; /** * 万能查询Service接口 @@ -18,7 +18,7 @@ public interface UniQueryService { * @param id 万能查询ID * @return 万能查询 */ - ServerResult selectUniQueryById(Long id); + GenServerResult selectUniQueryById(Long id); /** * 查询万能查询列表 @@ -26,7 +26,7 @@ public interface UniQueryService { * @param uniQuery 万能查询 * @return 万能查询集合 */ - ServerResult> selectUniQueryList(UniQuery uniQuery); + GenServerResult> selectUniQueryList(UniQuery uniQuery); /** * 新增万能查询 @@ -34,7 +34,7 @@ public interface UniQueryService { * @param uniQuery 万能查询 * @return 结果 */ - ServerResult insertUniQuery(UniQuery uniQuery); + GenServerResult insertUniQuery(UniQuery uniQuery); /** * 修改万能查询 @@ -42,7 +42,7 @@ public interface UniQueryService { * @param uniQuery 万能查询 * @return 结果 */ - ServerResult updateUniQuery(UniQuery uniQuery); + GenServerResult updateUniQuery(UniQuery uniQuery); /** * 批量删除万能查询 @@ -50,7 +50,7 @@ public interface UniQueryService { * @param ids 需要删除的万能查询ID * @return 结果 */ - ServerResult deleteUniQueryByIds(Long[] ids); + GenServerResult deleteUniQueryByIds(Long[] ids); /** * 删除万能查询信息 @@ -58,5 +58,5 @@ public interface UniQueryService { * @param id 万能查询ID * @return 结果 */ - ServerResult deleteUniQueryById(Long id); + GenServerResult deleteUniQueryById(Long id); } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ApiclassServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ApiclassServiceImpl.java index 809147f..4d0ed08 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ApiclassServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ApiclassServiceImpl.java @@ -2,12 +2,12 @@ package com.hchyun.generator.service.impl; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.ApiclassDao; import com.hchyun.generator.entity.Apiclass; import com.hchyun.generator.service.ApiclassService; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenSecurityUtils; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -33,17 +33,17 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 接口类名 */ @Override - public ServerResult selectApiclassById(Long id) { + public GenServerResult selectApiclassById(Long id) { try { Apiclass apiclass = apiclassDao.selectApiclassById(id); if (apiclass != null) { - return new ServerResult(true, apiclass); + return new GenServerResult(true, apiclass); } else { - return new ServerResult(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -54,17 +54,17 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 接口类名 */ @Override - public ServerResult> selectApiclassList(Apiclass apiclass) { + public GenServerResult> selectApiclassList(Apiclass apiclass) { try { List apiclassList = apiclassDao.selectApiclassList(apiclass); if (apiclassList.size() > 0) { - return new ServerResult>(true, apiclassList); + return new GenServerResult>(true, apiclassList); } else { - return new ServerResult>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @@ -75,18 +75,18 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 结果 */ @Override - public ServerResult insertApiclass(Apiclass apiclass) { + public GenServerResult insertApiclass(Apiclass apiclass) { try { - apiclass.setCreateBy(SecurityUtils.getUserId()); + apiclass.setCreateBy(GenSecurityUtils.getUserId()); Integer renewal = apiclassDao.insertApiclass(apiclass); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -97,18 +97,18 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 结果 */ @Override - public ServerResult updateApiclass(Apiclass apiclass) { + public GenServerResult updateApiclass(Apiclass apiclass) { try { - apiclass.setUpdateBy(SecurityUtils.getUserId()); + apiclass.setUpdateBy(GenSecurityUtils.getUserId()); Integer renewal = apiclassDao.updateApiclass(apiclass); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -119,17 +119,17 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 结果 */ @Override - public ServerResult deleteApiclassByIds(Long[] ids) { + public GenServerResult deleteApiclassByIds(Long[] ids) { try { Integer renewal = apiclassDao.deleteApiclassByIds(ids); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -140,17 +140,17 @@ public class ApiclassServiceImpl implements ApiclassService { * @return 结果 */ @Override - public ServerResult deleteApiclassById(Long id) { + public GenServerResult deleteApiclassById(Long id) { try { Integer renewal = apiclassDao.deleteApiclassById(id); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/AssociatedServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/AssociatedServiceImpl.java index a6cfbda..dab1ab6 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/AssociatedServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/AssociatedServiceImpl.java @@ -1,11 +1,11 @@ package com.hchyun.generator.service.impl; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.AssociatedDao; import com.hchyun.generator.entity.AssColumn; import com.hchyun.generator.service.AssociatedService; -import com.hchyun.generator.util.AssociatedUtils; +import com.hchyun.generator.utils.AssociatedUtils; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -27,38 +27,38 @@ public class AssociatedServiceImpl implements AssociatedService { private AssociatedDao associatedDao; @Override - public ServerResult> assColumnsByTable(Long tableId) { + public GenServerResult> assColumnsByTable(Long tableId) { try { List assColumns = associatedDao.selectTableColumnByTableId(tableId); - return new ServerResult<>(true, assColumns); + return new GenServerResult<>(true, assColumns); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @Override - public ServerResult>> tableInfos() { + public GenServerResult>> tableInfos() { try { List> dataMap = associatedDao.tableInfos(); - return new ServerResult<>(true, dataMap); + return new GenServerResult<>(true, dataMap); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @Override - public ServerResult> assColumns(String tableName, Long tableId) { + public GenServerResult> assColumns(String tableName, Long tableId) { try { List assColumns = associatedDao.selectTableColumn(tableName); for (AssColumn assColumn : assColumns) { AssociatedUtils.initAssColumn(assColumn, tableId); } - return new ServerResult<>(true, assColumns); + return new GenServerResult<>(true, assColumns); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableColumnServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableColumnServiceImpl.java index 30305e6..66aa0f3 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableColumnServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableColumnServiceImpl.java @@ -3,15 +3,14 @@ package com.hchyun.generator.service.impl; import java.util.ArrayList; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.entity.AjaxResult; -import com.hchyun.common.exception.CustomException; import com.hchyun.generator.service.GenTableColumnService; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.exception.GenCustomException; +import com.hchyun.generator.utils.text.Convert; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import com.hchyun.common.core.text.Convert; import com.hchyun.generator.entity.GenTableColumn; import com.hchyun.generator.dao.GenTableColumnDao; @@ -39,7 +38,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService { return genTableColumnDao.selectGenTableColumnListByTableId(tableId); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -55,7 +54,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService { return genTableColumnDao.insertGenTableColumn(genTableColumn); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -73,7 +72,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService { return genTableColumnDao.updateGenTableColumn(genTableColumns); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -89,7 +88,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService { return genTableColumnDao.deleteGenTableColumnByIds(Convert.toLongArray(ids)); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableServiceImpl.java index 1360592..d25c58d 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/GenTableServiceImpl.java @@ -11,11 +11,15 @@ import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.AssociatedDao; import com.hchyun.generator.entity.AssColumn; import com.hchyun.generator.service.GenTableService; +import com.hchyun.generator.utils.*; +import com.hchyun.generator.utils.constant.Constants; +import com.hchyun.generator.utils.constant.GenConstants; +import com.hchyun.generator.utils.exception.GenCustomException; +import com.hchyun.generator.utils.text.CharsetKit; +import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; @@ -27,20 +31,10 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.hchyun.common.constant.Constants; -import com.hchyun.common.constant.GenConstants; -import com.hchyun.common.core.text.CharsetKit; -import com.hchyun.common.exception.CustomException; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.StringUtils; -import com.hchyun.common.utils.file.FileUtils; import com.hchyun.generator.entity.GenTable; import com.hchyun.generator.entity.GenTableColumn; import com.hchyun.generator.dao.GenTableColumnDao; import com.hchyun.generator.dao.GenTableDao; -import com.hchyun.generator.util.GenUtils; -import com.hchyun.generator.util.VelocityInitializer; -import com.hchyun.generator.util.VelocityUtils; import org.springframework.transaction.interceptor.TransactionAspectSupport; /** @@ -75,7 +69,7 @@ public class GenTableServiceImpl implements GenTableService { return genTable; }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -91,7 +85,7 @@ public class GenTableServiceImpl implements GenTableService { return genTableDao.selectGenTableList(genTable); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -107,7 +101,7 @@ public class GenTableServiceImpl implements GenTableService { return genTableDao.selectDbTableList(genTable); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -123,7 +117,7 @@ public class GenTableServiceImpl implements GenTableService { return genTableDao.selectDbTableListByNames(tableNames); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -138,7 +132,7 @@ public class GenTableServiceImpl implements GenTableService { return genTableDao.selectGenTableAll(); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -163,10 +157,10 @@ public class GenTableServiceImpl implements GenTableService { associatedDao.insertColumns(assColumns); } } - } catch (CustomException e) { + } catch (GenCustomException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - throw new CustomException(ReturnConstants.DB_EX); + throw new GenCustomException(GenReturnConstants.DB_EX); } } @@ -178,15 +172,15 @@ public class GenTableServiceImpl implements GenTableService { */ @Override @Transactional - public ServerResult deleteGenTableByIds(Long[] tableIds) { + public GenServerResult deleteGenTableByIds(Long[] tableIds) { try { genTableDao.deleteGenTableByIds(tableIds); genTableColumnDao.deleteGenTableColumnByIds(tableIds); - return new ServerResult<>(true); + return new GenServerResult<>(true); } catch (RuntimeException e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -198,7 +192,7 @@ public class GenTableServiceImpl implements GenTableService { @Override @Transactional public void importGenTable(List tableList) { - Long operName = SecurityUtils.getUserId(); + Long operName = GenSecurityUtils.getUserId(); try { for (GenTable table : tableList) { String tableName = table.getTableName(); @@ -214,7 +208,7 @@ public class GenTableServiceImpl implements GenTableService { } } } catch (Exception e) { - throw new CustomException("导入失败:" + e.getMessage()); + throw new GenCustomException("导入失败:" + e.getMessage()); } } @@ -255,7 +249,7 @@ public class GenTableServiceImpl implements GenTableService { return dataMap; }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(e.getMessage()); } } @@ -275,7 +269,7 @@ public class GenTableServiceImpl implements GenTableService { return outputStream.toByteArray(); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -302,7 +296,7 @@ public class GenTableServiceImpl implements GenTableService { // 获取模板列表 List templates = VelocityUtils.getTemplateList(table.getTplCategory()); for (String template : templates) { - if (!StringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { + if (!GenStringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { // 渲染模板 StringWriter sw = new StringWriter(); Template tpl = Velocity.getTemplate(template, Constants.UTF8); @@ -326,7 +320,7 @@ public class GenTableServiceImpl implements GenTableService { return true; }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -344,8 +338,8 @@ public class GenTableServiceImpl implements GenTableService { List tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); List dbTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName); - if (StringUtils.isEmpty(dbTableColumns)) { - throw new CustomException("同步数据失败,原表结构不存在"); + if (GenStringUtils.isEmpty(dbTableColumns)) { + throw new GenCustomException("同步数据失败,原表结构不存在"); } List dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); @@ -357,12 +351,12 @@ public class GenTableServiceImpl implements GenTableService { }); List delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList()); - if (StringUtils.isNotEmpty(delColumns)) { + if (GenStringUtils.isNotEmpty(delColumns)) { genTableColumnDao.deleteGenTableColumns(delColumns); } }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -388,7 +382,7 @@ public class GenTableServiceImpl implements GenTableService { return outputStream.toByteArray(); }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } } @@ -417,7 +411,7 @@ public class GenTableServiceImpl implements GenTableService { }catch (RuntimeException e){ logger.error(e.getMessage()); - throw new CustomException(ReturnConstants.OP_ERROR); + throw new GenCustomException(GenReturnConstants.OP_ERROR); } // 查询表信息 GenTable table = genTableDao.selectGenTableByName(tableName); @@ -471,17 +465,17 @@ public class GenTableServiceImpl implements GenTableService { if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) { String options = JSON.toJSONString(genTable.getParams()); JSONObject paramsObj = JSONObject.parseObject(options); - if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) { - throw new CustomException("树编码字段不能为空"); - } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) { - throw new CustomException("树父编码字段不能为空"); - } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) { - throw new CustomException("树名称字段不能为空"); + if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) { + throw new GenCustomException("树编码字段不能为空"); + } else if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) { + throw new GenCustomException("树父编码字段不能为空"); + } else if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) { + throw new GenCustomException("树名称字段不能为空"); } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) { - if (StringUtils.isEmpty(genTable.getSubTableName())) { - throw new CustomException("关联子表的表名不能为空"); - } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) { - throw new CustomException("子表关联的外键名不能为空"); + if (GenStringUtils.isEmpty(genTable.getSubTableName())) { + throw new GenCustomException("关联子表的表名不能为空"); + } else if (GenStringUtils.isEmpty(genTable.getSubTableFkName())) { + throw new GenCustomException("子表关联的外键名不能为空"); } } else if (GenConstants.TPL_ASS.equals(genTable.getTplCategory())) { // todo 规则校验 @@ -501,7 +495,7 @@ public class GenTableServiceImpl implements GenTableService { break; } } - if (StringUtils.isNull(table.getPkColumn())) { + if (GenStringUtils.isNull(table.getPkColumn())) { table.setPkColumn(table.getColumns().get(0)); } if (GenConstants.TPL_SUB.equals(table.getTplCategory())) { @@ -511,7 +505,7 @@ public class GenTableServiceImpl implements GenTableService { break; } } - if (StringUtils.isNull(table.getSubTable().getPkColumn())) { + if (GenStringUtils.isNull(table.getSubTable().getPkColumn())) { table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0)); } } @@ -524,7 +518,7 @@ public class GenTableServiceImpl implements GenTableService { */ public void setSubTable(GenTable table) { String subTableName = table.getSubTableName(); - if (StringUtils.isNotEmpty(subTableName)) { + if (GenStringUtils.isNotEmpty(subTableName)) { table.setSubTable(genTableDao.selectGenTableByName(subTableName)); } } @@ -536,7 +530,7 @@ public class GenTableServiceImpl implements GenTableService { */ public void setTableFromOptions(GenTable genTable) { JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions()); - if (StringUtils.isNotNull(paramsObj)) { + if (GenStringUtils.isNotNull(paramsObj)) { String treeCode = paramsObj.getString(GenConstants.TREE_CODE); String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE); String treeName = paramsObj.getString(GenConstants.TREE_NAME); @@ -560,7 +554,7 @@ public class GenTableServiceImpl implements GenTableService { */ public static String getGenPath(GenTable table, String template) { String genPath = table.getGenPath(); - if (StringUtils.equals(genPath, "/")) { + if (GenStringUtils.equals(genPath, "/")) { return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table); } return genPath + File.separator + VelocityUtils.getFileName(template, table); diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/InterTableServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/InterTableServiceImpl.java index 28dafc4..8a3a953 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/InterTableServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/InterTableServiceImpl.java @@ -10,18 +10,14 @@ import java.util.Map; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import com.hchyun.common.constant.Constants; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.ApiclassDao; import com.hchyun.generator.dao.GenTableDao; import com.hchyun.generator.dao.ModuleDao; import com.hchyun.generator.dto.InterTableDto; import com.hchyun.generator.entity.Apiclass; import com.hchyun.generator.entity.Module; -import com.hchyun.generator.util.InterTableUtils; -import com.hchyun.generator.util.VelocityInitializer; +import com.hchyun.generator.utils.*; +import com.hchyun.generator.utils.constant.Constants; import org.apache.commons.io.IOUtils; import org.apache.velocity.Template; import org.apache.velocity.VelocityContext; @@ -62,17 +58,17 @@ public class InterTableServiceImpl implements InterTableService { * @return 接口信息 */ @Override - public ServerResult selectInterTableById(Long id) { + public GenServerResult selectInterTableById(Long id) { try { InterTable interTable = interTableDao.selectInterTableById(id); if (interTable != null) { - return new ServerResult(true, interTable); + return new GenServerResult(true, interTable); } else { - return new ServerResult(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -83,7 +79,7 @@ public class InterTableServiceImpl implements InterTableService { * @return 接口信息 */ @Override - public ServerResult> selectInterTableList(InterTable interTable) { + public GenServerResult> selectInterTableList(InterTable interTable) { try { Map modeMap = new HashMap(); if (interTable.getType() == 1) { @@ -95,10 +91,10 @@ public class InterTableServiceImpl implements InterTableService { } List interTableList = interTableDao.selectInterTableList(interTable); modeMap.put("rows", interTableList); - return new ServerResult>(true, modeMap); + return new GenServerResult>(true, modeMap); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @@ -109,18 +105,18 @@ public class InterTableServiceImpl implements InterTableService { * @return 结果 */ @Override - public ServerResult insertInterTable(InterTable interTable) { + public GenServerResult insertInterTable(InterTable interTable) { try { - interTable.setCreateBy(SecurityUtils.getUserId()); + interTable.setCreateBy(GenSecurityUtils.getUserId()); Integer renewal = interTableDao.insertInterTable(interTable); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -132,7 +128,7 @@ public class InterTableServiceImpl implements InterTableService { */ @Override @Transactional - public ServerResult updateInterTable(InterTableDto interTableDto) { + public GenServerResult updateInterTable(InterTableDto interTableDto) { try { List interTables = interTableDto.getInterTables(); Integer renewal = 0; @@ -148,19 +144,19 @@ public class InterTableServiceImpl implements InterTableService { Integer renewalTables = 0; if (interTables.size() > 0) { for (int i = 0; i < interTables.size(); i++) { - interTables.get(i).setCreateBy(SecurityUtils.getUserId()); + interTables.get(i).setCreateBy(GenSecurityUtils.getUserId()); } renewalTables = interTableDao.insertInterTables(interTables); } if (renewalTables > 0 || renewal > 0) { - return new ServerResult(true, renewalTables); + return new GenServerResult(true, renewalTables); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -171,17 +167,17 @@ public class InterTableServiceImpl implements InterTableService { * @return 结果 */ @Override - public ServerResult deleteInterTableByIds(Long[] ids) { + public GenServerResult deleteInterTableByIds(Long[] ids) { try { Integer renewal = interTableDao.deleteInterTableByIds(ids); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -192,31 +188,31 @@ public class InterTableServiceImpl implements InterTableService { * @return 结果 */ @Override - public ServerResult deleteInterTableById(Long id) { + public GenServerResult deleteInterTableById(Long id) { try { Integer renewal = interTableDao.deleteInterTableById(id); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @Override - public ServerResult> previewCodeCalss(Long cid) { + public GenServerResult> previewCodeCalss(Long cid) { try { Map dataMap = new LinkedHashMap(); Apiclass apiclass = interTableDao.selectInterTableClass(cid); if (apiclass == null) { - return new ServerResult>(false, ReturnConstants.INTER_NULL); + return new GenServerResult>(false, GenReturnConstants.INTER_NULL); } VelocityInitializer.initVelocity(); - VelocityContext context = InterTableUtils.prepareClassContext(apiclass); - Map templates = InterTableUtils.getTemplateList(2); + VelocityContext context = GenInterTableUtils.prepareClassContext(apiclass); + Map templates = GenInterTableUtils.getTemplateList(2); StringWriter sw = new StringWriter(); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); template.merge(context, sw); @@ -226,24 +222,24 @@ public class InterTableServiceImpl implements InterTableService { template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); template.merge(context, sw); dataMap.put(getSqlName(apiclass.getcName()), sw.toString()); - return new ServerResult>(true, dataMap); + return new GenServerResult>(true, dataMap); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @Override - public ServerResult> previewCodeMoudle(Long mid) { + public GenServerResult> previewCodeMoudle(Long mid) { try { Map dataMap = new LinkedHashMap(); List interTableList = interTableDao.selectInterTableModule(mid); if (interTableList.size() == 0) { - return new ServerResult>(false, "该模块下接口为空,请先创建接口!"); + return new GenServerResult>(false, "该模块下接口为空,请先创建接口!"); } VelocityInitializer.initVelocity(); - List contextList = InterTableUtils.prepareMoudleContext(interTableList); - Map templates = InterTableUtils.getTemplateList(2); + List contextList = GenInterTableUtils.prepareMoudleContext(interTableList); + Map templates = GenInterTableUtils.getTemplateList(2); StringWriter sqlsw = new StringWriter(); Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); for (VelocityContext context : contextList) { @@ -254,29 +250,29 @@ public class InterTableServiceImpl implements InterTableService { dataMap.put(getJavaClassName((String) context.get("ClassName")), sw.toString()); } dataMap.put(getSqlName("module"), sqlsw.toString()); - return new ServerResult>(true, dataMap); + return new GenServerResult>(true, dataMap); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @Override @Transactional - public ServerResult generatorCodeClass(Long cid) { + public GenServerResult generatorCodeClass(Long cid) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream); Apiclass apiclass = interTableDao.selectInterTableClass(cid); VelocityInitializer.initVelocity(); - VelocityContext context = InterTableUtils.prepareClassContext(apiclass); - Map templates = InterTableUtils.getTemplateList(2); + VelocityContext context = GenInterTableUtils.prepareClassContext(apiclass); + Map templates = GenInterTableUtils.getTemplateList(2); StringWriter sw = new StringWriter(); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); template.merge(context, sw); zip = genCode(getJavaClassName(apiclass.getcName()), zip, sw); if (zip == null) { - return new ServerResult(false, "代码生成失败!"); + return new GenServerResult(false, "代码生成失败!"); } sw = new StringWriter(); template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); @@ -284,35 +280,35 @@ public class InterTableServiceImpl implements InterTableService { zip = genCode(getSqlName(apiclass.getcName()), zip, sw); if (zip == null) { - return new ServerResult(false, "代码生成失败!"); + return new GenServerResult(false, "代码生成失败!"); } int start = genTableDao.insertMenu(sw.toString()); if (!(start > 0)) { - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } IOUtils.closeQuietly(zip); - return new ServerResult(true, outputStream.toByteArray()); + return new GenServerResult(true, outputStream.toByteArray()); } catch (RuntimeException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult(false, "代码生成失败!"); + return new GenServerResult(false, "代码生成失败!"); } } @Override @Transactional - public ServerResult generatorCodeMoudle(Long mid) { + public GenServerResult generatorCodeMoudle(Long mid) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ZipOutputStream zip = new ZipOutputStream(outputStream); List interTableList = interTableDao.selectInterTableModule(mid); if (interTableList.size() == 0) { - return new ServerResult(false, "该模块下接口为空,请先创建接口!"); + return new GenServerResult(false, "该模块下接口为空,请先创建接口!"); } VelocityInitializer.initVelocity(); - List contextList = InterTableUtils.prepareMoudleContext(interTableList); - Map templates = InterTableUtils.getTemplateList(2); + List contextList = GenInterTableUtils.prepareMoudleContext(interTableList); + Map templates = GenInterTableUtils.getTemplateList(2); StringWriter sqlsw = new StringWriter(); Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); for (VelocityContext context : contextList) { @@ -326,15 +322,15 @@ public class InterTableServiceImpl implements InterTableService { if (zip != null) { int start = genTableDao.insertMenu(sqlsw.toString()); if (!(start > 0)) { - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } IOUtils.closeQuietly(zip); - return new ServerResult(true, outputStream.toByteArray()); + return new GenServerResult(true, outputStream.toByteArray()); } catch (RuntimeException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult(false, "代码生成失败!"); + return new GenServerResult(false, "代码生成失败!"); } } @@ -355,10 +351,10 @@ public class InterTableServiceImpl implements InterTableService { public String getJavaClassName(String cName) { - return InterTableUtils.getUpperCase(cName) + "Controller.java"; + return GenInterTableUtils.getUpperCase(cName) + "Controller.java"; } public String getSqlName(String cName) { - return InterTableUtils.getUpperCase(cName) + ".sql"; + return GenInterTableUtils.getUpperCase(cName) + ".sql"; } } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ModuleServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ModuleServiceImpl.java index 22a81da..2d850e9 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ModuleServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/ModuleServiceImpl.java @@ -2,12 +2,12 @@ package com.hchyun.generator.service.impl; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.ModuleDao; import com.hchyun.generator.entity.Module; import com.hchyun.generator.service.ModuleService; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenSecurityUtils; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -33,17 +33,17 @@ public class ModuleServiceImpl implements ModuleService { * @return 模块管理 */ @Override - public ServerResult selectModuleById(Long id) { + public GenServerResult selectModuleById(Long id) { try { Module module = moduleDao.selectModuleById(id); if (module != null) { - return new ServerResult(true, module); + return new GenServerResult(true, module); } else { - return new ServerResult(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -54,17 +54,17 @@ public class ModuleServiceImpl implements ModuleService { * @return 模块管理 */ @Override - public ServerResult> selectModuleList(Module module) { + public GenServerResult> selectModuleList(Module module) { try { List moduleList = moduleDao.selectModuleList(module); if (moduleList.size() > 0) { - return new ServerResult>(true, moduleList); + return new GenServerResult>(true, moduleList); } else { - return new ServerResult>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @@ -75,18 +75,18 @@ public class ModuleServiceImpl implements ModuleService { * @return 结果 */ @Override - public ServerResult insertModule(Module module) { + public GenServerResult insertModule(Module module) { try { - module.setCreateBy(SecurityUtils.getUserId()); + module.setCreateBy(GenSecurityUtils.getUserId()); Integer renewal = moduleDao.insertModule(module); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -97,18 +97,18 @@ public class ModuleServiceImpl implements ModuleService { * @return 结果 */ @Override - public ServerResult updateModule(Module module) { + public GenServerResult updateModule(Module module) { try { - module.setUpdateBy(SecurityUtils.getUserId()); + module.setUpdateBy(GenSecurityUtils.getUserId()); Integer renewal = moduleDao.updateModule(module); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -119,17 +119,17 @@ public class ModuleServiceImpl implements ModuleService { * @return 结果 */ @Override - public ServerResult deleteModuleByIds(Long[] ids) { + public GenServerResult deleteModuleByIds(Long[] ids) { try { Integer renewal = moduleDao.deleteModuleByIds(ids); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -140,17 +140,17 @@ public class ModuleServiceImpl implements ModuleService { * @return 结果 */ @Override - public ServerResult deleteModuleById(Long id) { + public GenServerResult deleteModuleById(Long id) { try { Integer renewal = moduleDao.deleteModuleById(id); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/QueryServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/QueryServiceImpl.java index 0c91162..76c5634 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/QueryServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/QueryServiceImpl.java @@ -1,15 +1,15 @@ package com.hchyun.generator.service.impl; import com.alibaba.fastjson.JSONObject; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.core.entity.entity.Menu; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.QueryDao; import com.hchyun.generator.dao.UniQueryDao; import com.hchyun.generator.entity.UniCon; import com.hchyun.generator.entity.UniQuery; import com.hchyun.generator.service.QueryService; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenSecurityUtils; +import com.hchyun.generator.utils.GenServerResult; +import com.hchyun.generator.utils.entity.GenMenu; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -17,7 +17,6 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.interceptor.TransactionAspectSupport; -import java.util.ArrayList; import java.util.List; import java.util.Map; @@ -41,55 +40,55 @@ public class QueryServiceImpl implements QueryService { * 查询万能查询的基本信息和条件信息 */ @Override - public ServerResult selectQueryById(Long id) { + public GenServerResult selectQueryById(Long id) { try { UniQuery uniQuery = queryDao.selectQueryInfo(id); if (uniQuery != null) { - return new ServerResult<>(true, uniQuery); + return new GenServerResult<>(true, uniQuery); } else { - return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.SYS_FAILL); + return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); } } @Override @Transactional - public ServerResult Release(UniQuery uniQuery) { + public GenServerResult Release(UniQuery uniQuery) { try { Integer isRelease = queryDao.Release(uniQuery.getId()); if ((isRelease == 1 && uniQuery.getIsRelease() == 2) || (isRelease == 2 && uniQuery.getIsRelease() == 1)) { if (uniQuery.getIsRelease() == 1) { UniQuery query = uniQueryDao.selectUniQueryById(uniQuery.getId()); - Menu menu = new Menu(query.getId(), query.getUqName(), SecurityUtils.getUserId()); - Integer insermenu = queryDao.insertMenu(menu); + GenMenu genMenu = new GenMenu(query.getId(), query.getUqName(), GenSecurityUtils.getUserId()); + Integer insermenu = queryDao.insertMenu(genMenu); if (insermenu == 0) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.OP_ERROR); + return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); } } else { Integer deleteMenu = queryDao.deleteMenu("data/" + uniQuery.getId()); if (deleteMenu == 0) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.OP_ERROR); + return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); } } Integer release = queryDao.changeRelease(uniQuery); if (release > 0) { - return new ServerResult<>(true); + return new GenServerResult<>(true); } else { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.OP_ERROR); + return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); } } else { - return new ServerResult<>(false, ReturnConstants.STATE_ERROR); + return new GenServerResult<>(false, GenReturnConstants.STATE_ERROR); } } catch (RuntimeException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.SYS_FAILL); + return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); } } @@ -98,7 +97,7 @@ public class QueryServiceImpl implements QueryService { */ @Override @Transactional - public ServerResult updateQueryInfo(UniQuery uniQuery) { + public GenServerResult updateQueryInfo(UniQuery uniQuery) { try { int uqrenewal = uniQueryDao.updateUniQuery(uniQuery); if (uqrenewal > 0) { @@ -106,26 +105,26 @@ public class QueryServiceImpl implements QueryService { queryDao.deleteUniCon(uniQuery.getId()); Integer ucrenewal = queryDao.insertUniCon(uniQuery.getUniCons()); if (ucrenewal == 0) { - return new ServerResult<>(false, ReturnConstants.OP_ERROR); + return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); } } - return new ServerResult<>(true); + return new GenServerResult<>(true); } - return new ServerResult<>(false, ReturnConstants.OP_ERROR); + return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); } catch (RuntimeException e) { logger.error(e.getMessage()); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.SYS_FAILL); + return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); } } @Override - public ServerResult>> previewQuery(UniQuery uniQuery) { + public GenServerResult>> previewQuery(UniQuery uniQuery) { try { StringBuilder sql = new StringBuilder(uniQuery.getUqSql().toLowerCase()); List uniConList = uniQuery.getUniCons(); if (sql.toString().contains("insert") || sql.toString().contains("delete ") || sql.toString().contains("update ") || sql.toString().contains("drop ") || sql.toString().contains("database ") || sql.toString().contains("create ") || sql.toString().contains("view ") || sql.toString().contains("alter ")) { - return new ServerResult<>(false, "sql语句含有insert,delete,update,drop,database,view,alter等特殊字符!"); + return new GenServerResult<>(false, "sql语句含有insert,delete,update,drop,database,view,alter等特殊字符!"); } if (uniConList.size() > 0) { @@ -135,10 +134,10 @@ public class QueryServiceImpl implements QueryService { } } List> dataMap = queryDao.UniQuery(sql.toString()); - return new ServerResult<>(true, dataMap); + return new GenServerResult<>(true, dataMap); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, e.getMessage()); + return new GenServerResult<>(false, e.getMessage()); } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/RegularServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/RegularServiceImpl.java index 484391d..599f8fd 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/RegularServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/RegularServiceImpl.java @@ -2,14 +2,13 @@ package com.hchyun.generator.service.impl; import java.util.List; -import com.hchyun.common.utils.DateUtils; - -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; import com.hchyun.generator.dao.RegularDao; import com.hchyun.generator.entity.Regular; import com.hchyun.generator.service.RegularService; +import com.hchyun.generator.utils.GenDateUtils; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenSecurityUtils; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -35,17 +34,17 @@ public class RegularServiceImpl implements RegularService { * @return 校验规则 */ @Override - public ServerResult selectRegularById(Long id) { + public GenServerResult selectRegularById(Long id) { try { Regular regular = regularDao.selectRegularById(id); if (regular != null) { - return new ServerResult<>(true, regular); + return new GenServerResult<>(true, regular); } else { - return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -56,17 +55,17 @@ public class RegularServiceImpl implements RegularService { * @return 校验规则 */ @Override - public ServerResult> selectRegularList(Regular regular) { + public GenServerResult> selectRegularList(Regular regular) { try { List regulars = regularDao.selectRegularList(regular); if (regulars.size() > 0) { - return new ServerResult<>(true, regulars); + return new GenServerResult<>(true, regulars); } else { - return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -77,15 +76,15 @@ public class RegularServiceImpl implements RegularService { * @return 结果 */ @Override - public ServerResult insertRegular(Regular regular) { + public GenServerResult insertRegular(Regular regular) { try { - regular.setCreateTime(DateUtils.getNowDate()); - regular.setCreateBy(SecurityUtils.getUserId()); + regular.setCreateTime(GenDateUtils.getNowDate()); + regular.setCreateBy(GenSecurityUtils.getUserId()); int renewal = regularDao.insertRegular(regular); - return new ServerResult<>(true, renewal); + return new GenServerResult<>(true, renewal); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -96,15 +95,15 @@ public class RegularServiceImpl implements RegularService { * @return 结果 */ @Override - public ServerResult updateRegular(Regular regular) { + public GenServerResult updateRegular(Regular regular) { try { - regular.setUpdateTime(DateUtils.getNowDate()); - regular.setUpdateBy(SecurityUtils.getUserId()); + regular.setUpdateTime(GenDateUtils.getNowDate()); + regular.setUpdateBy(GenSecurityUtils.getUserId()); int renewal = regularDao.updateRegular(regular); - return new ServerResult<>(true, renewal); + return new GenServerResult<>(true, renewal); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -115,13 +114,13 @@ public class RegularServiceImpl implements RegularService { * @return 结果 */ @Override - public ServerResult deleteRegularByIds(Long[] ids) { + public GenServerResult deleteRegularByIds(Long[] ids) { try { Integer renewals = regularDao.deleteRegularByIds(ids); - return new ServerResult<>(true, renewals); + return new GenServerResult<>(true, renewals); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -132,13 +131,13 @@ public class RegularServiceImpl implements RegularService { * @return 结果 */ @Override - public ServerResult deleteRegularById(Long id) { + public GenServerResult deleteRegularById(Long id) { try { Integer renewal = regularDao.deleteRegularById(id); - return new ServerResult<>(true, renewal); + return new GenServerResult<>(true, renewal); } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/UniQueryServiceImpl.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/UniQueryServiceImpl.java index f673ff3..b1a30b4 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/UniQueryServiceImpl.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/service/impl/UniQueryServiceImpl.java @@ -2,9 +2,9 @@ package com.hchyun.generator.service.impl; import java.util.List; -import com.hchyun.common.constant.ReturnConstants; -import com.hchyun.common.utils.SecurityUtils; -import com.hchyun.common.utils.ServerResult; +import com.hchyun.generator.utils.GenReturnConstants; +import com.hchyun.generator.utils.GenSecurityUtils; +import com.hchyun.generator.utils.GenServerResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -35,17 +35,17 @@ public class UniQueryServiceImpl implements UniQueryService { * @return 万能查询 */ @Override - public ServerResult selectUniQueryById(Long id) { + public GenServerResult selectUniQueryById(Long id) { try { UniQuery uniQuery = uniQueryDao.selectUniQueryById(id); if (uniQuery != null) { - return new ServerResult(true, uniQuery); + return new GenServerResult(true, uniQuery); } else { - return new ServerResult(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -56,17 +56,17 @@ public class UniQueryServiceImpl implements UniQueryService { * @return 万能查询 */ @Override - public ServerResult> selectUniQueryList(UniQuery uniQuery) { + public GenServerResult> selectUniQueryList(UniQuery uniQuery) { try { List uniQueryList = uniQueryDao.selectUniQueryList(uniQuery); if (uniQueryList.size() > 0) { - return new ServerResult>(true, uniQueryList); + return new GenServerResult>(true, uniQueryList); } else { - return new ServerResult>(false, ReturnConstants.RESULT_EMPTY); + return new GenServerResult>(false, GenReturnConstants.RESULT_EMPTY); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult>(false, ReturnConstants.DB_EX); + return new GenServerResult>(false, GenReturnConstants.DB_EX); } } @@ -77,18 +77,18 @@ public class UniQueryServiceImpl implements UniQueryService { * @return 结果 */ @Override - public ServerResult insertUniQuery(UniQuery uniQuery) { + public GenServerResult insertUniQuery(UniQuery uniQuery) { try { - uniQuery.setCreateBy(SecurityUtils.getUserId()); + uniQuery.setCreateBy(GenSecurityUtils.getUserId()); Integer renewal = uniQueryDao.insertUniQuery(uniQuery); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -99,18 +99,18 @@ public class UniQueryServiceImpl implements UniQueryService { * @return 结果 */ @Override - public ServerResult updateUniQuery(UniQuery uniQuery) { + public GenServerResult updateUniQuery(UniQuery uniQuery) { try { - uniQuery.setUpdateBy(SecurityUtils.getUserId()); + uniQuery.setUpdateBy(GenSecurityUtils.getUserId()); Integer renewal = uniQueryDao.updateUniQuery(uniQuery); if (renewal > 0) { - return new ServerResult(true, renewal); + return new GenServerResult(true, renewal); } else { - return new ServerResult(false, ReturnConstants.SYS_FAILL); + return new GenServerResult(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { logger.error(e.getMessage()); - return new ServerResult(false, ReturnConstants.DB_EX); + return new GenServerResult(false, GenReturnConstants.DB_EX); } } @@ -122,22 +122,22 @@ public class UniQueryServiceImpl implements UniQueryService { */ @Override @Transactional - public ServerResult deleteUniQueryByIds(Long[] ids) { + public GenServerResult deleteUniQueryByIds(Long[] ids) { try { Integer renewal = uniQueryDao.deleteUniQueryByIds(ids); for (Long id : ids) { uniQueryDao.deleteUniQueryByUqId(id); } if (renewal > 0) { - return new ServerResult<>(true, renewal); + return new GenServerResult<>(true, renewal); } else { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - return new ServerResult<>(false, ReturnConstants.SYS_FAILL); + return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } @@ -149,19 +149,19 @@ public class UniQueryServiceImpl implements UniQueryService { */ @Override @Transactional - public ServerResult deleteUniQueryById(Long id) { + public GenServerResult deleteUniQueryById(Long id) { try { Integer renewal = uniQueryDao.deleteUniQueryById(id); uniQueryDao.deleteUniQueryByUqId(id); if (renewal > 0) { - return new ServerResult<>(true, renewal); + return new GenServerResult<>(true, renewal); } else { - return new ServerResult<>(false, ReturnConstants.SYS_FAILL); + return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); } } catch (RuntimeException e) { TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); logger.error(e.getMessage()); - return new ServerResult<>(false, ReturnConstants.DB_EX); + return new GenServerResult<>(false, GenReturnConstants.DB_EX); } } } \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/AssociatedUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/AssociatedUtils.java similarity index 80% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/AssociatedUtils.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/AssociatedUtils.java index e6cd71d..64e2481 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/AssociatedUtils.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/AssociatedUtils.java @@ -1,9 +1,7 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; -import com.hchyun.common.constant.GenConstants; -import com.hchyun.common.utils.StringUtils; import com.hchyun.generator.entity.AssColumn; -import org.apache.commons.lang3.RegExUtils; +import com.hchyun.generator.utils.constant.GenConstants; /** * @Author 18209 @@ -23,7 +21,7 @@ public class AssociatedUtils { //设置创建者id assColumn.setCreateBy(1); //转为设置java字段名称 - assColumn.setJavaField(StringUtils.toCamelCase(columnName)); + assColumn.setJavaField(GenStringUtils.toCamelCase(columnName)); //默认类型 assColumn.setJavaType(GenConstants.TYPE_STRING); //默认查询条件 精确查询 @@ -41,7 +39,7 @@ public class AssociatedUtils { assColumn.setHtmlType(GenConstants.HTML_INPUT); // 如果是浮点型 统一用BigDecimal - String[] str = StringUtils.split(StringUtils.substringBetween(assColumn.getColumnType(), "(", ")"), ","); + String[] str = GenStringUtils.split(GenStringUtils.substringBetween(assColumn.getColumnType(), "(", ")"), ","); if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { assColumn.setJavaType(GenConstants.TYPE_BIGDECIMAL); } @@ -59,16 +57,16 @@ public class AssociatedUtils { // 查询字段 assColumn.setIsQuery(GenConstants.NO_REQUIRE); // 查询字段类型 - if (StringUtils.endsWithIgnoreCase(columnName, "name")) { + if (GenStringUtils.endsWithIgnoreCase(columnName, "name")) { assColumn.setQueryType(GenConstants.QUERY_LIKE); } // 状态字段设置单选框 - if (StringUtils.endsWithIgnoreCase(columnName, "status")) { + if (GenStringUtils.endsWithIgnoreCase(columnName, "status")) { assColumn.setHtmlType(GenConstants.HTML_RADIO); } // 类型&性别字段设置下拉框 - else if (StringUtils.endsWithIgnoreCase(columnName, "type") - || StringUtils.endsWithIgnoreCase(columnName, "sex")) { + else if (GenStringUtils.endsWithIgnoreCase(columnName, "type") + || GenStringUtils.endsWithIgnoreCase(columnName, "sex")) { assColumn.setHtmlType(GenConstants.HTML_SELECT); } } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenBaseController.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenBaseController.java new file mode 100644 index 0000000..e961237 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenBaseController.java @@ -0,0 +1,90 @@ +package com.hchyun.generator.utils; + +import com.github.pagehelper.PageHelper; +import com.github.pagehelper.PageInfo; +import com.hchyun.generator.utils.page.GenPageDomain; +import com.hchyun.generator.utils.page.GenTableDataInfo; +import com.hchyun.generator.utils.page.GenTableSupport; +import com.hchyun.generator.utils.sql.GenSqlUtil; +import org.springframework.web.bind.WebDataBinder; +import org.springframework.web.bind.annotation.InitBinder; + +import java.beans.PropertyEditorSupport; +import java.util.Date; +import java.util.List; +import java.util.Map; + +public class GenBaseController { + + /** + * 将前台传递过来的日期格式的字符串,自动转化为Date类型 + */ + @InitBinder + public void initBinder(WebDataBinder binder) { + // Date 类型转换 + binder.registerCustomEditor(Date.class, new PropertyEditorSupport() { + @Override + public void setAsText(String text) { + setValue(GenDateUtils.parseDate(text)); + } + }); + } + + /** + * 设置请求分页数据 + */ + protected void startPage() { + GenPageDomain genPageDomain = GenTableSupport.buildPageRequest(); + Integer pageNum = genPageDomain.getPageNum(); + Integer pageSize = genPageDomain.getPageSize(); + if (GenStringUtils.isNotNull(pageNum) && GenStringUtils.isNotNull(pageSize)) { + String orderBy = GenSqlUtil.escapeOrderBySql(genPageDomain.getOrderBy()); + PageHelper.startPage(pageNum, pageSize, orderBy); + } + } + + /** + * 设置请求分页数据 + */ + public void startPage(Map map) { + GenPageDomain genPageDomain = GenTableSupport.buildPageRequest(); + Integer pageNum = (Integer) map.get("pageNum"); + Integer pageSize = (Integer) map.get("pageSize"); + if (GenStringUtils.isNotNull(pageNum) && GenStringUtils.isNotNull(pageSize)) { + String orderBy = GenSqlUtil.escapeOrderBySql(genPageDomain.getOrderBy()); + PageHelper.startPage(pageNum, pageSize, orderBy); + } + } + + /** + * 响应请求分页数据 + */ + @SuppressWarnings({"rawtypes", "unchecked"}) + protected GenTableDataInfo getDataTable(List list) { + GenTableDataInfo rspData = new GenTableDataInfo(); + rspData.setCode(GenHttpStatus.SUCCESS); + rspData.setMsg("查询成功"); + rspData.setRows(list); + rspData.setTotal(new PageInfo(list).getTotal()); + return rspData; + } + + +// /** +// * 响应返回结果 +// * +// * @param rows 影响行数 +// * @return 操作结果 +// */ +// protected AjaxResult toAjax(int rows) +// { +// return rows > 0 ? AjaxResult.success() : AjaxResult.error(); +// } + + /** + * 页面跳转 + */ + public String redirect(String url) { + return GenStringUtils.format("redirect:{}", url); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDateUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDateUtils.java new file mode 100644 index 0000000..61c870a --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDateUtils.java @@ -0,0 +1,144 @@ +package com.hchyun.generator.utils; + +import org.apache.commons.lang3.time.DateFormatUtils; + +import java.lang.management.ManagementFactory; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.Date; + +/** + * 时间工具类 + * + * @author hchyun + */ +public class GenDateUtils extends org.apache.commons.lang3.time.DateUtils { + public static String YYYY = "yyyy"; + + public static String YYYY_MM = "yyyy-MM"; + + public static String YYYY_MM_DD = "yyyy-MM-dd"; + + public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss"; + + public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss"; + + private static String[] parsePatterns = { + "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", + "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM", + "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"}; + + /** + * 获取当前Date型日期 + * + * @return Date() 当前日期 + */ + public static Date getNowDate() { + return new Date(); + } + + /** + * 获取当前日期, 默认格式为yyyy-MM-dd + * + * @return String + */ + public static String getDate() { + return dateTimeNow(YYYY_MM_DD); + } + + public static String getDate(String time) { + try { + return new SimpleDateFormat(YYYY_MM_DD).parse(time).toString(); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + + public static final String getTime() { + return dateTimeNow(YYYY_MM_DD_HH_MM_SS); + } + + public static final String dateTimeNow() { + return dateTimeNow(YYYYMMDDHHMMSS); + } + + public static final String dateTimeNow(final String format) { + return parseDateToStr(format, new Date()); + } + + public static final String dateTime(final Date date) { + return parseDateToStr(YYYY_MM_DD, date); + } + + public static final String parseDateToStr(final String format, final Date date) { + return new SimpleDateFormat(format).format(date); + } + + public static final Date dateTime(final String format, final String ts) { + try { + return new SimpleDateFormat(format).parse(ts); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * 日期路径 即年/月/日 如2018/08/08 + */ + public static final String datePath() { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyy/MM/dd"); + } + + /** + * 日期路径 即年/月/日 如20180808 + */ + public static final String dateTime() { + Date now = new Date(); + return DateFormatUtils.format(now, "yyyyMMdd"); + } + + /** + * 日期型字符串转化为日期 格式 + */ + public static Date parseDate(Object str) { + if (str == null) { + return null; + } + try { + return parseDate(str.toString(), parsePatterns); + } catch (ParseException e) { + return null; + } + } + + /** + * 获取服务器启动时间 + */ + public static Date getServerStartDate() { + long time = ManagementFactory.getRuntimeMXBean().getStartTime(); + return new Date(time); + } + + /** + * 计算两个时间差 + */ + public static String getDatePoor(Date endDate, Date nowDate) { + long nd = 1000 * 24 * 60 * 60; + long nh = 1000 * 60 * 60; + long nm = 1000 * 60; + // long ns = 1000; + // 获得两个时间的毫秒时间差异 + long diff = endDate.getTime() - nowDate.getTime(); + // 计算差多少天 + long day = diff / nd; + // 计算差多少小时 + long hour = diff % nd / nh; + // 计算差多少分钟 + long min = diff % nd % nh / nm; + // 计算差多少秒//输出结果 + // long sec = diff % nd % nh % nm / ns; + return day + "天" + hour + "小时" + min + "分钟"; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDictUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDictUtils.java new file mode 100644 index 0000000..9c17a6f --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenDictUtils.java @@ -0,0 +1,148 @@ +package com.hchyun.generator.utils; + +import com.hchyun.generator.utils.constant.Constants; +import com.hchyun.generator.utils.entity.GenDictData; +import com.hchyun.generator.utils.redis.GenRedisCache; +import com.hchyun.generator.utils.spring.GenSpringUtils; + +import java.util.Collection; +import java.util.List; + +/** + * 字典工具类 + * + * @author hchyun + */ +public class GenDictUtils { + /** + * 分隔符 + */ + public static final String SEPARATOR = ","; + + /** + * 设置字典缓存 + * + * @param key 参数键 + * @param genDictData 字典数据列表 + */ + public static void setDictCache(String key, List genDictData) { + GenSpringUtils.getBean(GenRedisCache.class).setCacheObject(getCacheKey(key), genDictData); + } + + /** + * 获取字典缓存 + * + * @param key 参数键 + * @return dictDatas 字典数据列表 + */ + public static List getDictCache(String key) { + Object cacheObj = GenSpringUtils.getBean(GenRedisCache.class).getCacheObject(getCacheKey(key)); + if (GenStringUtils.isNotNull(cacheObj)) { + List genDictData = GenStringUtils.cast(cacheObj); + return genDictData; + } + return null; + } + + /** + * 根据字典类型和字典值获取字典标签 + * + * @param dictType 字典类型 + * @param dictValue 字典值 + * @return 字典标签 + */ + public static String getDictLabel(String dictType, String dictValue) { + return getDictLabel(dictType, dictValue, SEPARATOR); + } + + /** + * 根据字典类型和字典标签获取字典值 + * + * @param dictType 字典类型 + * @param dictLabel 字典标签 + * @return 字典值 + */ + public static String getDictValue(String dictType, String dictLabel) { + return getDictValue(dictType, dictLabel, SEPARATOR); + } + + /** + * 根据字典类型和字典值获取字典标签 + * + * @param dictType 字典类型 + * @param dictValue 字典值 + * @param separator 分隔符 + * @return 字典标签 + */ + public static String getDictLabel(String dictType, String dictValue, String separator) { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + + if (GenStringUtils.containsAny(separator, dictValue) && GenStringUtils.isNotEmpty(datas)) { + for (GenDictData dict : datas) { + for (String value : dictValue.split(separator)) { + if (value.equals(dict.getDictValue())) { + propertyString.append(dict.getDictLabel() + separator); + break; + } + } + } + } else { + for (GenDictData dict : datas) { + if (dictValue.equals(dict.getDictValue())) { + return dict.getDictLabel(); + } + } + } + return GenStringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 根据字典类型和字典标签获取字典值 + * + * @param dictType 字典类型 + * @param dictLabel 字典标签 + * @param separator 分隔符 + * @return 字典值 + */ + public static String getDictValue(String dictType, String dictLabel, String separator) { + StringBuilder propertyString = new StringBuilder(); + List datas = getDictCache(dictType); + + if (GenStringUtils.containsAny(separator, dictLabel) && GenStringUtils.isNotEmpty(datas)) { + for (GenDictData dict : datas) { + for (String label : dictLabel.split(separator)) { + if (label.equals(dict.getDictLabel())) { + propertyString.append(dict.getDictValue() + separator); + break; + } + } + } + } else { + for (GenDictData dict : datas) { + if (dictLabel.equals(dict.getDictLabel())) { + return dict.getDictValue(); + } + } + } + return GenStringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 清空字典缓存 + */ + public static void clearDictCache() { + Collection keys = GenSpringUtils.getBean(GenRedisCache.class).keys(Constants.SYS_DICT_KEY + "*"); + GenSpringUtils.getBean(GenRedisCache.class).deleteObject(keys); + } + + /** + * 设置cache key + * + * @param configKey 参数键 + * @return 缓存键key + */ + public static String getCacheKey(String configKey) { + return Constants.SYS_DICT_KEY + configKey; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenHttpStatus.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenHttpStatus.java new file mode 100644 index 0000000..9de7a24 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenHttpStatus.java @@ -0,0 +1,93 @@ +package com.hchyun.generator.utils; + +/** + * 返回状态码 + * + * @author hchyun + */ +public class GenHttpStatus { + /** + * 操作成功 + */ + public static final int SUCCESS = 200; + + /** + * 操作成功 + */ + public static final int NO_DATA = 199; + + /** + * 对象创建成功 + */ + public static final int CREATED = 201; + + /** + * 请求已经被接受 + */ + public static final int ACCEPTED = 202; + + /** + * 操作已经执行成功,但是没有返回数据 + */ + public static final int NO_CONTENT = 204; + + /** + * 资源已被移除 + */ + public static final int MOVED_PERM = 301; + + /** + * 重定向 + */ + public static final int SEE_OTHER = 303; + + /** + * 资源没有被修改 + */ + public static final int NOT_MODIFIED = 304; + + /** + * 参数列表错误(缺少,格式不匹配) + */ + public static final int BAD_REQUEST = 400; + + /** + * 未授权 + */ + public static final int UNAUTHORIZED = 401; + + /** + * 访问受限,授权过期 + */ + public static final int FORBIDDEN = 403; + + /** + * 资源,服务未找到 + */ + public static final int NOT_FOUND = 404; + + /** + * 不允许的http方法 + */ + public static final int BAD_METHOD = 405; + + /** + * 资源冲突,或者资源被锁 + */ + public static final int CONFLICT = 409; + + /** + * 不支持的数据,媒体类型 + */ + public static final int UNSUPPORTED_TYPE = 415; + + /** + * 系统内部错误 + */ + public static final int ERROR = 500; + + /** + * 接口未实现 + */ + public static final int NOT_IMPLEMENTED = 501; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterApiUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterApiUtils.java similarity index 67% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterApiUtils.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterApiUtils.java index 3a312c0..082182e 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterApiUtils.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterApiUtils.java @@ -1,10 +1,9 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; import com.hchyun.generator.dto.InterTableDto; -import com.hchyun.generator.entity.GenTable; import org.apache.velocity.VelocityContext; -public class InterApiUtils { +public class GenInterApiUtils { public static VelocityContext prepareContext(InterTableDto interTableDto) { diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterTableUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterTableUtils.java similarity index 92% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterTableUtils.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterTableUtils.java index 3da084b..9fe828f 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/InterTableUtils.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenInterTableUtils.java @@ -1,7 +1,5 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; -import com.hchyun.common.utils.DateUtils; -import com.hchyun.common.utils.SecurityUtils; import com.hchyun.generator.entity.Apiclass; import com.hchyun.generator.entity.InterTable; import org.apache.velocity.VelocityContext; @@ -11,7 +9,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -public class InterTableUtils { +public class GenInterTableUtils { public static List prepareMoudleContext(List interTableList) { List apiclassList = new ArrayList(); for (int i = 0; i < interTableList.size(); i++) { @@ -59,7 +57,7 @@ public class InterTableUtils { permission = true; } } - velocityContext.put("createBy", SecurityUtils.getUserId()); + velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("Permission", permission); velocityContext.put("packageName", "com.huhyun." + module); velocityContext.put("prefix", module + ":" + getLowerCase(className)); @@ -69,7 +67,7 @@ public class InterTableUtils { velocityContext.put("functionName", apiclass.getcDescribe()); velocityContext.put("author", apiclass.getAuthor()); velocityContext.put("emali", apiclass.getEmail()); - velocityContext.put("time", DateUtils.getTime()); + velocityContext.put("time", GenDateUtils.getTime()); contextList.add(velocityContext); } @@ -84,7 +82,7 @@ public class InterTableUtils { permission = true; } } - velocityContext.put("createBy", SecurityUtils.getUserId()); + velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("Permission", permission); velocityContext.put("packageName", apiclass.getPackageName()); velocityContext.put("ClassName", getUpperCase(apiclass.getcName())); @@ -94,7 +92,7 @@ public class InterTableUtils { velocityContext.put("functionName", apiclass.getcDescribe()); velocityContext.put("author", apiclass.getAuthor()); velocityContext.put("emali", apiclass.getEmail()); - velocityContext.put("time", DateUtils.getTime()); + velocityContext.put("time", GenDateUtils.getTime()); return velocityContext; } diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMapExcelUtil.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMapExcelUtil.java new file mode 100644 index 0000000..5a8c96c --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMapExcelUtil.java @@ -0,0 +1,295 @@ +package com.hchyun.generator.utils; + +import com.hchyun.generator.config.Config; +import com.hchyun.generator.controller.AjaxResult; +import com.hchyun.generator.utils.exception.GenCustomException; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.util.*; + +/** + * @Author 18209 + * @Date 2021/2/3 21:09 + * @Version 1.0 + */ +public class GenMapExcelUtil { + private Logger logger = LoggerFactory.getLogger(GenMapExcelUtil.class); + + /** + * Excel sheet最大行数,默认65536 + */ + public static final int sheetSize = 65536; + + /** + * 工作表名称 + */ + private String sheetName; + + /** + * 工作薄对象 + */ + private Workbook wb; + + /** + * 工作表对象 + */ + private Sheet sheet; + + /** + * 样式列表 + */ + private Map styles; + + /** + * 导入导出数据列表 + */ + private List> list; + + /** + * 注解列表 + */ + private List herders; + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @param list 导出数据集合 + * @param sheetName 工作表的名称 + * @return 结果 + */ + public AjaxResult exportExcel(List> list, String sheetName) { + this.init(list, sheetName); + return exportExcel(); + } + + + public void init(List> list, String sheetName) { + if (list == null) { + list = new ArrayList>(); + } + this.list = list; + this.sheetName = sheetName; + createExcelField(); + createWorkbook(); + } + + /** + * 创建一个工作簿 + */ + public void createWorkbook() { + this.wb = new SXSSFWorkbook(500); + } + + /** + * 得到所有定义字段 + */ + private void createExcelField() { + this.herders = new ArrayList(); + Map modeMap = this.list.get(0); + for (String key : modeMap.keySet()) { + this.herders.add(key); + } + + + } + + /** + * 创建表格样式 + * + * @param wb 工作薄对象 + * @return 样式列表 + */ + private Map createStyles(Workbook wb) { + // 写入各条记录,每条记录对应excel表中的一行 + Map styles = new HashMap(); + CellStyle style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderTop(BorderStyle.THIN); + style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + Font dataFont = wb.createFont(); + dataFont.setFontName("Arial"); + dataFont.setFontHeightInPoints((short) 10); + style.setFont(dataFont); + styles.put("data", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + Font headerFont = wb.createFont(); + headerFont.setFontName("Arial"); + headerFont.setFontHeightInPoints((short) 10); + headerFont.setBold(true); + headerFont.setColor(IndexedColors.WHITE.getIndex()); + style.setFont(headerFont); + styles.put("header", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + Font totalFont = wb.createFont(); + totalFont.setFontName("Arial"); + totalFont.setFontHeightInPoints((short) 10); + style.setFont(totalFont); + styles.put("total", style); + + return styles; + } + + /** + * 创建工作表 + * + * @param sheetNo sheet数量 + * @param index 序号 + */ + public void createSheet(double sheetNo, int index) { + this.sheet = wb.createSheet(); + this.styles = createStyles(wb); + // 设置工作表的名称. + if (sheetNo == 0) { + wb.setSheetName(index, sheetName); + } else { + wb.setSheetName(index, sheetName + index); + } + } + + /** + * 填充excel数据 + * + * @param index 序号 + * @param row 单元格行 + */ + public void fillExcelData(int index, Row row) { + int startNo = index * sheetSize; + int endNo = Math.min(startNo + sheetSize, list.size()); + for (int i = startNo; i < endNo; i++) { + row = sheet.createRow(i + 1 - startNo); + //获取内容 + int k = 0; + for (String key : herders) { + // 填充单元格的值 + this.addCell(row, key, i, k++); + } + } + } + + /** + * 添加单元格 + */ + public Cell addCell(Row row, String key, int column, Integer k) { + Cell cell = null; + try { + // 设置行高 + row.setHeight((short) 280); + // 创建cell + cell = row.createCell(k); + cell.setCellStyle(styles.get("data")); + Object value = this.list.get(column).get(key); + cell.setCellValue(value.toString()); + } catch (Exception e) { + logger.error("导出Excel失败{}", e); + } + return cell; + } + + /** + * 创建单元格 + */ + public Cell createCell(Row row, String herder, int column) { + // 创建列 + Cell cell = row.createCell(column); + // 写入列信息 + cell.setCellValue(herder); + cell.setCellStyle(styles.get("header")); + return cell; + } + + + /** + * 编码文件名 + */ + public String encodingFilename(String filename) { + filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; + return filename; + } + + /** + * 获取下载路径 + * + * @param filename 文件名称 + */ + public String getAbsoluteFile(String filename) { + String downloadPath = Config.getDownloadPath() + filename; + File desc = new File(downloadPath); + if (!desc.getParentFile().exists()) { + desc.getParentFile().mkdirs(); + } + return downloadPath; + } + + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @return 结果 + */ + public AjaxResult exportExcel() { + OutputStream out = null; + try { + // 取出一共有多少个sheet. + double sheetNo = Math.ceil(list.size() / sheetSize); + for (int index = 0; index <= sheetNo; index++) { + createSheet(sheetNo, index); + + // 产生一行 + Row row = sheet.createRow(0); + int column = 0; + // 写入各个字段的列头名称 + for (String herder : herders) { + //设置列名称 + this.createCell(row, herder, column++); + } + fillExcelData(index, row); + } + String filename = encodingFilename(sheetName); + out = new FileOutputStream(getAbsoluteFile(filename)); + wb.write(out); + return AjaxResult.success(filename); + } catch (Exception e) { + logger.error("导出Excel异常{}", e.getMessage()); + throw new GenCustomException("导出Excel失败,请联系网站管理员!"); + } finally { + if (wb != null) { + try { + wb.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + } + +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMessageUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMessageUtils.java new file mode 100644 index 0000000..c41abac --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenMessageUtils.java @@ -0,0 +1,24 @@ +package com.hchyun.generator.utils; + +import com.hchyun.generator.utils.spring.GenSpringUtils; +import org.springframework.context.MessageSource; +import org.springframework.context.i18n.LocaleContextHolder; + +/** + * 获取i18n资源文件 + * + * @author hchyun + */ +public class GenMessageUtils { + /** + * 根据消息键和参数 获取消息 委托给spring messageSource + * + * @param code 消息键 + * @param args 参数 + * @return 获取国际化翻译值 + */ + public static String message(String code, Object... args) { + MessageSource messageSource = GenSpringUtils.getBean(MessageSource.class); + return messageSource.getMessage(code, args, LocaleContextHolder.getLocale()); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenReturnConstants.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenReturnConstants.java new file mode 100644 index 0000000..a922d51 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenReturnConstants.java @@ -0,0 +1,29 @@ +package com.hchyun.generator.utils; + +public class GenReturnConstants { + /** + * 系统错误 + */ + public static final String SYS_ERROR = "系统错误!"; + + /** + * 查询结果为空 + */ + public static final String RESULT_EMPTY = "查询结果为空!"; + /** + * 数据库异常 + */ + public static final String DB_EX = "数据库异常!"; + /** + * 操作失败 + */ + public static final String SYS_FAILL = "数据库异常!"; + /** + * 接口为空 + */ + public static final String INTER_NULL = "该类下接口数据为空,请先添加接口!"; + + public static final String STATE_ERROR = "状态错错误!"; + + public static final String OP_ERROR = "操作失败!"; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenSecurityUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenSecurityUtils.java new file mode 100644 index 0000000..638e41e --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenSecurityUtils.java @@ -0,0 +1,34 @@ +package com.hchyun.generator.utils; + +import com.alibaba.fastjson.JSONObject; +import com.hchyun.generator.utils.exception.GenCustomException; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; + +/** + * 安全服务工具类 + * + * @author hchyun + */ +public class GenSecurityUtils { + + public static Long getUserId() { + try { + Object object = getAuthentication().getPrincipal(); + JSONObject jsonObject = (JSONObject) JSONObject.toJSON(object); + JSONObject userObject = (JSONObject) jsonObject.get("user"); + return (Long) userObject.get("userId"); + } catch (Exception e) { + System.out.println(e.getMessage()); + throw new GenCustomException("获取用户账户异常", GenHttpStatus.UNAUTHORIZED); + } + } + + /** + * 获取Authentication + */ + public static Authentication getAuthentication() { + return SecurityContextHolder.getContext().getAuthentication(); + } +} + diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServerResult.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServerResult.java new file mode 100644 index 0000000..3adcbca --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServerResult.java @@ -0,0 +1,88 @@ +package com.hchyun.generator.utils; + +/** + * @author clay + * @version 1.0 + * @mail 20932067@zju.edu.cn + * @date 2020/12/15 21:34 + */ +public class GenServerResult { + private T data;// 成功时返回的数据 + private Integer count; + private boolean start; + private String msg; + + private String sheetName; + + public GenServerResult() { + } + + public GenServerResult(boolean start, T data, Integer count) { + this.data = data; + this.count = count; + this.start = start; + this.msg = "操作成功"; + } + + public GenServerResult(boolean start, T data) { + this.data = data; + this.start = start; + this.msg = "操作成功"; + } + + public GenServerResult(boolean start, T data, String sheetName) { + this.data = data; + this.start = start; + this.sheetName = sheetName; + this.msg = "操作成功"; + } + + public GenServerResult(boolean start, String msg) { + this.start = start; + this.msg = msg; + } + + public String getSheetName() { + return sheetName; + } + + public void setSheetName(String sheetName) { + this.sheetName = sheetName; + } + + public GenServerResult(boolean start) { + this.start = start; + } + + public T getData() { + return data; + } + + public void setData(T data) { + this.data = data; + } + + public Integer getCount() { + return count; + } + + public void setCount(Integer count) { + this.count = count; + } + + public boolean isStart() { + return start; + } + + public void setStart(boolean start) { + this.start = start; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServletUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServletUtils.java new file mode 100644 index 0000000..a9ee96d --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenServletUtils.java @@ -0,0 +1,119 @@ +package com.hchyun.generator.utils; + +import com.hchyun.generator.utils.text.Convert; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import javax.servlet.http.HttpSession; +import java.io.IOException; + +/** + * 客户端工具类 + * + * @author hchyun + */ +public class GenServletUtils { + /** + * 获取String参数 + */ + public static String getParameter(String name) { + return getRequest().getParameter(name); + } + + /** + * 获取String参数 + */ + public static String getParameter(String name, String defaultValue) { + return Convert.toStr(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name) { + return Convert.toInt(getRequest().getParameter(name)); + } + + /** + * 获取Integer参数 + */ + public static Integer getParameterToInt(String name, Integer defaultValue) { + return Convert.toInt(getRequest().getParameter(name), defaultValue); + } + + /** + * 获取request + */ + public static HttpServletRequest getRequest() { + return getRequestAttributes().getRequest(); + } + + /** + * 获取response + */ + public static HttpServletResponse getResponse() { + return getRequestAttributes().getResponse(); + } + + /** + * 获取session + */ + public static HttpSession getSession() { + return getRequest().getSession(); + } + + public static ServletRequestAttributes getRequestAttributes() { + RequestAttributes attributes = RequestContextHolder.getRequestAttributes(); + return (ServletRequestAttributes) attributes; + } + + /** + * 将字符串渲染到客户端 + * + * @param response 渲染对象 + * @param string 待渲染的字符串 + * @return null + */ + public static String renderString(HttpServletResponse response, String string) { + try { + response.setStatus(200); + response.setContentType("application/json"); + response.setCharacterEncoding("utf-8"); + response.getWriter().print(string); + } catch (IOException e) { + e.printStackTrace(); + } + return null; + } + + /** + * 是否是Ajax异步请求 + * + * @param request + */ + public static boolean isAjaxRequest(HttpServletRequest request) { + String accept = request.getHeader("accept"); + if (accept != null && accept.indexOf("application/json") != -1) { + return true; + } + + String xRequestedWith = request.getHeader("X-Requested-With"); + if (xRequestedWith != null && xRequestedWith.indexOf("XMLHttpRequest") != -1) { + return true; + } + + String uri = request.getRequestURI(); + if (GenStringUtils.inStringIgnoreCase(uri, ".json", ".xml")) { + return true; + } + + String ajax = request.getParameter("__ajax"); + if (GenStringUtils.inStringIgnoreCase(ajax, "json", "xml")) { + return true; + } + return false; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenStringUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenStringUtils.java new file mode 100644 index 0000000..f45954f --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenStringUtils.java @@ -0,0 +1,411 @@ +package com.hchyun.generator.utils; + + +import com.hchyun.generator.utils.text.StrFormatter; + +import java.util.*; + +/** + * 字符串工具类 + * + * @author hchyun + */ +public class GenStringUtils extends org.apache.commons.lang3.StringUtils { + /** + * 空字符串 + */ + private static final String NULLSTR = ""; + + /** + * 下划线 + */ + private static final char SEPARATOR = '_'; + + /** + * 获取参数不为空值 + * + * @param value defaultValue 要判断的value + * @return value 返回值 + */ + public static T nvl(T value, T defaultValue) { + return value != null ? value : defaultValue; + } + + /** + * * 判断一个Collection是否为空, 包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Collection coll) { + return isNull(coll) || coll.isEmpty(); + } + + /** + * * 判断一个Collection是否非空,包含List,Set,Queue + * + * @param coll 要判断的Collection + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Collection coll) { + return !isEmpty(coll); + } + + /** + * * 判断一个对象数组是否为空 + * + * @param objects 要判断的对象数组 + * * @return true:为空 false:非空 + */ + public static boolean isEmpty(Object[] objects) { + return isNull(objects) || (objects.length == 0); + } + + /** + * * 判断一个对象数组是否非空 + * + * @param objects 要判断的对象数组 + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Object[] objects) { + return !isEmpty(objects); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:为空 false:非空 + */ + public static boolean isEmpty(Map map) { + return isNull(map) || map.isEmpty(); + } + + /** + * * 判断一个Map是否为空 + * + * @param map 要判断的Map + * @return true:非空 false:空 + */ + public static boolean isNotEmpty(Map map) { + return !isEmpty(map); + } + + /** + * * 判断一个字符串是否为空串 + * + * @param str String + * @return true:为空 false:非空 + */ + public static boolean isEmpty(String str) { + return isNull(str) || NULLSTR.equals(str.trim()); + } + + /** + * * 判断一个字符串是否为非空串 + * + * @param str String + * @return true:非空串 false:空串 + */ + public static boolean isNotEmpty(String str) { + return !isEmpty(str); + } + + /** + * * 判断一个对象是否为空 + * + * @param object Object + * @return true:为空 false:非空 + */ + public static boolean isNull(Object object) { + return object == null; + } + + /** + * * 判断一个对象是否非空 + * + * @param object Object + * @return true:非空 false:空 + */ + public static boolean isNotNull(Object object) { + return !isNull(object); + } + + /** + * * 判断一个对象是否是数组类型(Java基本型别的数组) + * + * @param object 对象 + * @return true:是数组 false:不是数组 + */ + public static boolean isArray(Object object) { + return isNotNull(object) && object.getClass().isArray(); + } + + /** + * 去空格 + */ + public static String trim(String str) { + return (str == null ? "" : str.trim()); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @return 结果 + */ + public static String substring(final String str, int start) { + if (str == null) { + return NULLSTR; + } + + if (start < 0) { + start = str.length() + start; + } + + if (start < 0) { + start = 0; + } + if (start > str.length()) { + return NULLSTR; + } + + return str.substring(start); + } + + /** + * 截取字符串 + * + * @param str 字符串 + * @param start 开始 + * @param end 结束 + * @return 结果 + */ + public static String substring(final String str, int start, int end) { + if (str == null) { + return NULLSTR; + } + + if (end < 0) { + end = str.length() + end; + } + if (start < 0) { + start = str.length() + start; + } + + if (end > str.length()) { + end = str.length(); + } + + if (start > end) { + return NULLSTR; + } + + if (start < 0) { + start = 0; + } + if (end < 0) { + end = 0; + } + + return str.substring(start, end); + } + + /** + * 格式化文本, {} 表示占位符
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param template 文本模板,被替换的部分用 {} 表示 + * @param params 参数值 + * @return 格式化后的文本 + */ + public static String format(String template, Object... params) { + if (isEmpty(params) || isEmpty(template)) { + return template; + } + return StrFormatter.format(template, params); + } + + /** + * 字符串转set + * + * @param str 字符串 + * @param sep 分隔符 + * @return set集合 + */ + public static final Set str2Set(String str, String sep) { + return new HashSet(str2List(str, sep, true, false)); + } + + /** + * 字符串转list + * + * @param str 字符串 + * @param sep 分隔符 + * @param filterBlank 过滤纯空白 + * @param trim 去掉首尾空白 + * @return list集合 + */ + public static final List str2List(String str, String sep, boolean filterBlank, boolean trim) { + List list = new ArrayList(); + if (GenStringUtils.isEmpty(str)) { + return list; + } + + // 过滤空白字符串 + if (filterBlank && GenStringUtils.isBlank(str)) { + return list; + } + String[] split = str.split(sep); + for (String string : split) { + if (filterBlank && GenStringUtils.isBlank(string)) { + continue; + } + if (trim) { + string = string.trim(); + } + list.add(string); + } + + return list; + } + + /** + * 下划线转驼峰命名 + */ + public static String toUnderScoreCase(String str) { + if (str == null) { + return null; + } + StringBuilder sb = new StringBuilder(); + // 前置字符是否大写 + boolean preCharIsUpperCase = true; + // 当前字符是否大写 + boolean curreCharIsUpperCase = true; + // 下一字符是否大写 + boolean nexteCharIsUpperCase = true; + for (int i = 0; i < str.length(); i++) { + char c = str.charAt(i); + if (i > 0) { + preCharIsUpperCase = Character.isUpperCase(str.charAt(i - 1)); + } else { + preCharIsUpperCase = false; + } + + curreCharIsUpperCase = Character.isUpperCase(c); + + if (i < (str.length() - 1)) { + nexteCharIsUpperCase = Character.isUpperCase(str.charAt(i + 1)); + } + + if (preCharIsUpperCase && curreCharIsUpperCase && !nexteCharIsUpperCase) { + sb.append(SEPARATOR); + } else if ((i != 0 && !preCharIsUpperCase) && curreCharIsUpperCase) { + sb.append(SEPARATOR); + } + sb.append(Character.toLowerCase(c)); + } + + return sb.toString(); + } + + /** + * 是否包含字符串 + * + * @param str 验证字符串 + * @param strs 字符串组 + * @return 包含返回true + */ + public static boolean inStringIgnoreCase(String str, String... strs) { + if (str != null && strs != null) { + for (String s : strs) { + if (str.equalsIgnoreCase(trim(s))) { + return true; + } + } + } + return false; + } + + /** + * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空,则返回空字符串。 例如:HELLO_WORLD->HelloWorld + * + * @param name 转换前的下划线大写方式命名的字符串 + * @return 转换后的驼峰式命名的字符串 + */ + public static String convertToCamelCase(String name) { + StringBuilder result = new StringBuilder(); + // 快速检查 + if (name == null || name.isEmpty()) { + // 没必要转换 + return ""; + } else if (!name.contains("_")) { + // 不含下划线,仅将首字母大写 + return name.substring(0, 1).toUpperCase() + name.substring(1); + } + // 用下划线将原始字符串分割 + String[] camels = name.split("_"); + for (String camel : camels) { + // 跳过原始字符串中开头、结尾的下换线或双重下划线 + if (camel.isEmpty()) { + continue; + } + // 首字母大写 + result.append(camel.substring(0, 1).toUpperCase()); + result.append(camel.substring(1).toLowerCase()); + } + return result.toString(); + } + + /** + * 驼峰式命名法 例如:user_name->userName + */ + public static String toCamelCase(String s) { + if (s == null) { + return null; + } + s = s.toLowerCase(); + StringBuilder sb = new StringBuilder(s.length()); + boolean upperCase = false; + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + + if (c == SEPARATOR) { + upperCase = true; + } else if (upperCase) { + sb.append(Character.toUpperCase(c)); + upperCase = false; + } else { + sb.append(c); + } + } + return sb.toString(); + } + + /** + * 分割sql字符串 + * + * @param str + * @return + */ + public static String sqlFormat(String str) { + String[] strList = str.split("_"); + String sqlStr = ""; + for (String s : strList) { + sqlStr += s.substring(0, 1); + } + return sqlStr; + } + + @SuppressWarnings("unchecked") + public static T cast(Object obj) { + return (T) obj; + } + +} \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/GenUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenUtils.java similarity index 81% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/GenUtils.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenUtils.java index fb7ef48..644913e 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/GenUtils.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/GenUtils.java @@ -1,10 +1,9 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; import java.util.Arrays; +import com.hchyun.generator.utils.constant.GenConstants; import org.apache.commons.lang3.RegExUtils; -import com.hchyun.common.constant.GenConstants; -import com.hchyun.common.utils.StringUtils; import com.hchyun.generator.config.GenConfig; import com.hchyun.generator.entity.GenTable; import com.hchyun.generator.entity.GenTableColumn; @@ -37,7 +36,7 @@ public class GenUtils { column.setTableId(table.getTableId()); column.setCreateBy(table.getCreateBy()); // 设置java字段名 - column.setJavaField(StringUtils.toCamelCase(columnName)); + column.setJavaField(GenStringUtils.toCamelCase(columnName)); // 设置默认类型 column.setJavaType(GenConstants.TYPE_STRING); @@ -53,7 +52,7 @@ public class GenUtils { column.setHtmlType(GenConstants.HTML_INPUT); // 如果是浮点型 统一用BigDecimal - String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); + String[] str = GenStringUtils.split(GenStringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { column.setJavaType(GenConstants.TYPE_BIGDECIMAL); } @@ -84,28 +83,28 @@ public class GenUtils { } // 查询字段类型 - if (StringUtils.endsWithIgnoreCase(columnName, "name")) { + if (GenStringUtils.endsWithIgnoreCase(columnName, "name")) { column.setQueryType(GenConstants.QUERY_LIKE); } // 状态字段设置单选框 - if (StringUtils.endsWithIgnoreCase(columnName, "status")) { + if (GenStringUtils.endsWithIgnoreCase(columnName, "status")) { column.setHtmlType(GenConstants.HTML_RADIO); } // 类型&性别字段设置下拉框 - else if (StringUtils.endsWithIgnoreCase(columnName, "type") - || StringUtils.endsWithIgnoreCase(columnName, "sex")) { + else if (GenStringUtils.endsWithIgnoreCase(columnName, "type") + || GenStringUtils.endsWithIgnoreCase(columnName, "sex")) { column.setHtmlType(GenConstants.HTML_SELECT); } // 图片字段设置图片上传控件 - else if (StringUtils.endsWithIgnoreCase(columnName, "image")) { + else if (GenStringUtils.endsWithIgnoreCase(columnName, "image")) { column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD); } // 文件字段设置文件上传控件 - else if (StringUtils.endsWithIgnoreCase(columnName, "file")) { + else if (GenStringUtils.endsWithIgnoreCase(columnName, "file")) { column.setHtmlType(GenConstants.HTML_FILE_UPLOAD); } // 内容字段设置富文本控件 - else if (StringUtils.endsWithIgnoreCase(columnName, "content")) { + else if (GenStringUtils.endsWithIgnoreCase(columnName, "content")) { column.setHtmlType(GenConstants.HTML_EDITOR); } } @@ -130,7 +129,7 @@ public class GenUtils { public static String getModuleName(String packageName) { int lastIndex = packageName.lastIndexOf("."); int nameLength = packageName.length(); - String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength); + String moduleName = GenStringUtils.substring(packageName, lastIndex + 1, nameLength); return moduleName; } @@ -143,7 +142,7 @@ public class GenUtils { public static String getBusinessName(String tableName) { int lastIndex = tableName.lastIndexOf("_"); int nameLength = tableName.length(); - String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength); + String businessName = GenStringUtils.substring(tableName, lastIndex + 1, nameLength); return businessName; } @@ -156,11 +155,11 @@ public class GenUtils { public static String convertClassName(String tableName) { boolean autoRemovePre = GenConfig.getAutoRemovePre(); String tablePrefix = GenConfig.getTablePrefix(); - if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) { - String[] searchList = StringUtils.split(tablePrefix, ","); + if (autoRemovePre && GenStringUtils.isNotEmpty(tablePrefix)) { + String[] searchList = GenStringUtils.split(tablePrefix, ","); tableName = replaceFirst(tableName, searchList); } - return StringUtils.convertToCamelCase(tableName); + return GenStringUtils.convertToCamelCase(tableName); } /** @@ -198,8 +197,8 @@ public class GenUtils { * @return 截取后的列类型 */ public static String getDbType(String columnType) { - if (StringUtils.indexOf(columnType, "(") > 0) { - return StringUtils.substringBefore(columnType, "("); + if (GenStringUtils.indexOf(columnType, "(") > 0) { + return GenStringUtils.substringBefore(columnType, "("); } else { return columnType; } @@ -212,8 +211,8 @@ public class GenUtils { * @return 截取后的列类型 */ public static Integer getColumnLength(String columnType) { - if (StringUtils.indexOf(columnType, "(") > 0) { - String length = StringUtils.substringBetween(columnType, "(", ")"); + if (GenStringUtils.indexOf(columnType, "(") > 0) { + String length = GenStringUtils.substringBetween(columnType, "(", ")"); return Integer.valueOf(length); } else { return 0; diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityInitializer.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityInitializer.java similarity index 90% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityInitializer.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityInitializer.java index 5fd7ce0..d680bbc 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityInitializer.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityInitializer.java @@ -1,9 +1,9 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; import java.util.Properties; +import com.hchyun.generator.utils.constant.Constants; import org.apache.velocity.app.Velocity; -import com.hchyun.common.constant.Constants; /** * VelocityEngine工厂 diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityUtils.java similarity index 75% rename from hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityUtils.java rename to hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityUtils.java index f5b91ae..a6644c8 100644 --- a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/util/VelocityUtils.java +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/VelocityUtils.java @@ -1,15 +1,12 @@ -package com.hchyun.generator.util; +package com.hchyun.generator.utils; import java.util.ArrayList; import java.util.HashSet; import java.util.List; -import com.hchyun.common.utils.SecurityUtils; +import com.hchyun.generator.utils.constant.GenConstants; import org.apache.velocity.VelocityContext; import com.alibaba.fastjson.JSONObject; -import com.hchyun.common.constant.GenConstants; -import com.hchyun.common.utils.DateUtils; -import com.hchyun.common.utils.StringUtils; import com.hchyun.generator.entity.GenTable; import com.hchyun.generator.entity.GenTableColumn; @@ -49,17 +46,17 @@ public class VelocityUtils { VelocityContext velocityContext = new VelocityContext(); velocityContext.put("tplCategory", genTable.getTplCategory()); velocityContext.put("tableName", genTable.getTableName()); - velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); + velocityContext.put("functionName", GenStringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("ClassName", genTable.getClassName()); - velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName())); + velocityContext.put("className", GenStringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("moduleName", genTable.getModuleName()); - velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName())); + velocityContext.put("BusinessName", GenStringUtils.capitalize(genTable.getBusinessName())); velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("basePackage", getPackagePrefix(packageName)); velocityContext.put("packageName", packageName); velocityContext.put("author", genTable.getFunctionAuthor()); - velocityContext.put("datetime", DateUtils.getDate()); - velocityContext.put("createBy", SecurityUtils.getUserId()); + velocityContext.put("datetime", GenDateUtils.getDate()); + velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("pkColumn", genTable.getPkColumn()); velocityContext.put("importList", getImportList(genTable)); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); @@ -81,9 +78,9 @@ public class VelocityUtils { public static void setAssVelocityContext(VelocityContext context, GenTable genTable) { String assClassName = GenUtils.convertClassName(genTable.getAssTableName()); context.put("assClassName", assClassName); - context.put("assclassName", StringUtils.uncapitalize(assClassName)); - context.put("tableMapping", StringUtils.sqlFormat(genTable.getTableName())); - context.put("assMapping", StringUtils.sqlFormat(genTable.getAssTableName())); + context.put("assclassName", GenStringUtils.uncapitalize(assClassName)); + context.put("tableMapping", GenStringUtils.sqlFormat(genTable.getTableName())); + context.put("assMapping", GenStringUtils.sqlFormat(genTable.getAssTableName())); } public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { @@ -117,17 +114,17 @@ public class VelocityUtils { String subTableName = genTable.getSubTableName(); String subTableFkName = genTable.getSubTableFkName(); String subClassName = genTable.getSubTable().getClassName(); - String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName); + String subTableFkClassName = GenStringUtils.convertToCamelCase(subTableFkName); - context.put("tableMapping", StringUtils.sqlFormat(genTable.getTableName())); - context.put("subMapping", StringUtils.sqlFormat(subTable.getTableName())); + context.put("tableMapping", GenStringUtils.sqlFormat(genTable.getTableName())); + context.put("subMapping", GenStringUtils.sqlFormat(subTable.getTableName())); context.put("subTable", subTable); context.put("subTableName", subTableName); context.put("subTableFkName", subTableFkName); context.put("subTableFkClassName", subTableFkClassName); - context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName)); + context.put("subTableFkclassName", GenStringUtils.uncapitalize(subTableFkClassName)); context.put("subClassName", subClassName); - context.put("subclassName", StringUtils.uncapitalize(subClassName)); + context.put("subclassName", GenStringUtils.uncapitalize(subClassName)); context.put("subImportList", getImportList(genTable.getSubTable())); } @@ -175,35 +172,35 @@ public class VelocityUtils { // 业务名称 String businessName = genTable.getBusinessName(); - String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/"); + String javaPath = PROJECT_PATH + "/" + GenStringUtils.replace(packageName, ".", "/"); String mybatisPath = MYBATIS_PATH + "/" + moduleName; String vuePath = "vue"; if (template.contains("entity.java.vm")) { - fileName = StringUtils.format("{}/entity/{}.java", javaPath, className); + fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, className); } - if (template.contains("sub-entity.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { - fileName = StringUtils.format("{}/entity/{}.java", javaPath, genTable.getSubTable().getClassName()); + if (template.contains("sub-entity.java.vm") && GenStringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { + fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, genTable.getSubTable().getClassName()); } else if (template.contains("ass-entity.java.vm")) { - fileName = StringUtils.format("{}/entity/{}.java", javaPath, GenUtils.convertClassName(genTable.getAssTableName())); + fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, GenUtils.convertClassName(genTable.getAssTableName())); } else if (template.contains("dao.java.vm")) { - fileName = StringUtils.format("{}/dao/{}Dao.java", javaPath, className); + fileName = GenStringUtils.format("{}/dao/{}Dao.java", javaPath, className); } else if (template.contains("service.java.vm")) { - fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className); + fileName = GenStringUtils.format("{}/service/{}Service.java", javaPath, className); } else if (template.contains("serviceImpl.java.vm")) { - fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); + fileName = GenStringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); } else if (template.contains("controller.java.vm")) { - fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className); + fileName = GenStringUtils.format("{}/controller/{}Controller.java", javaPath, className); } else if (template.contains("mapper.xml.vm")) { - fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className); + fileName = GenStringUtils.format("{}/{}Mapper.xml", mybatisPath, className); } else if (template.contains("table.sql.vm")) { - fileName = businessName + "Menu.sql"; + fileName = businessName + "GenMenu.sql"; } else if (template.contains("api.js.vm")) { - fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); + fileName = GenStringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); } else if (template.contains("index.vue.vm")) { - fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + fileName = GenStringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } else if (template.contains("index-tree.vue.vm")) { - fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); + fileName = GenStringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); } return fileName; } @@ -216,7 +213,7 @@ public class VelocityUtils { */ public static String getPackagePrefix(String packageName) { int lastIndex = packageName.lastIndexOf("."); - String basePackage = StringUtils.substring(packageName, 0, lastIndex); + String basePackage = GenStringUtils.substring(packageName, 0, lastIndex); return basePackage; } @@ -230,7 +227,7 @@ public class VelocityUtils { List columns = genTable.getColumns(); GenTable subGenTable = genTable.getSubTable(); HashSet importList = new HashSet(); - if (StringUtils.isNotNull(subGenTable)) { + if (GenStringUtils.isNotNull(subGenTable)) { importList.add("java.util.List"); } for (GenTableColumn column : columns) { @@ -252,7 +249,7 @@ public class VelocityUtils { * @return 返回权限前缀 */ public static String getPermissionPrefix(String moduleName, String businessName) { - return StringUtils.format("{}:{}", moduleName, businessName); + return GenStringUtils.format("{}:{}", moduleName, businessName); } /** @@ -262,7 +259,7 @@ public class VelocityUtils { * @return 上级菜单ID字段 */ public static String getParentMenuId(JSONObject paramsObj) { - if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) { + if (GenStringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) { return paramsObj.getString(GenConstants.PARENT_MENU_ID); } return DEFAULT_PARENT_MENU_ID; @@ -276,9 +273,9 @@ public class VelocityUtils { */ public static String getTreecode(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_CODE)) { - return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); + return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); } - return StringUtils.EMPTY; + return GenStringUtils.EMPTY; } /** @@ -289,9 +286,9 @@ public class VelocityUtils { */ public static String getTreeParentCode(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { - return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); + return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); } - return StringUtils.EMPTY; + return GenStringUtils.EMPTY; } /** @@ -302,9 +299,9 @@ public class VelocityUtils { */ public static String getTreeName(JSONObject paramsObj) { if (paramsObj.containsKey(GenConstants.TREE_NAME)) { - return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); + return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); } - return StringUtils.EMPTY; + return GenStringUtils.EMPTY; } /** diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/Constants.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/Constants.java new file mode 100644 index 0000000..f39a539 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/Constants.java @@ -0,0 +1,128 @@ +package com.hchyun.generator.utils.constant; + +/** + * 通用常量信息 + * + * @author hchyun + */ +public class Constants { + /** + * UTF-8 字符集 + */ + public static final String UTF8 = "UTF-8"; + + /** + * GBK 字符集 + */ + public static final String GBK = "GBK"; + + /** + * http请求 + */ + public static final String HTTP = "http://"; + + /** + * https请求 + */ + public static final String HTTPS = "https://"; + + /** + * 通用成功标识 + */ + public static final String SUCCESS = "0"; + + /** + * 通用失败标识 + */ + public static final String FAIL = "1"; + + /** + * 登录成功 + */ + public static final String LOGIN_SUCCESS = "Success"; + + /** + * 注销 + */ + public static final String LOGOUT = "Logout"; + + /** + * 登录失败 + */ + public static final String LOGIN_FAIL = "Error"; + + /** + * 验证码 redis key + */ + public static final String CAPTCHA_CODE_KEY = "captcha_codes:"; + + /** + * 登录用户 redis key + */ + public static final String LOGIN_TOKEN_KEY = "login_tokens:"; + + /** + * 防重提交 redis key + */ + public static final String REPEAT_SUBMIT_KEY = "repeat_submit:"; + + /** + * 验证码有效期(分钟) + */ + public static final Integer CAPTCHA_EXPIRATION = 2; + + /** + * 令牌 + */ + public static final String TOKEN = "token"; + + /** + * 令牌前缀 + */ + public static final String TOKEN_PREFIX = "Bearer "; + + /** + * 令牌前缀 + */ + public static final String LOGIN_USER_KEY = "login_user_key"; + + /** + * 用户ID + */ + public static final String JWT_USERID = "userid"; + + /** + * 用户名称 + */ + public static final String JWT_USERNAME = "sub"; + + /** + * 用户头像 + */ + public static final String JWT_AVATAR = "avatar"; + + /** + * 创建时间 + */ + public static final String JWT_CREATED = "created"; + + /** + * 用户权限 + */ + public static final String JWT_AUTHORITIES = "authorities"; + + /** + * 参数管理 cache key + */ + public static final String SYS_CONFIG_KEY = "sys_config:"; + + /** + * 字典管理 cache key + */ + public static final String SYS_DICT_KEY = "sys_dict:"; + + /** + * 资源映射路径 前缀 + */ + public static final String RESOURCE_PREFIX = "/profile"; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenConstants.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenConstants.java new file mode 100644 index 0000000..5539c1b --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenConstants.java @@ -0,0 +1,195 @@ +package com.hchyun.generator.utils.constant; + +/** + * 代码生成通用常量 + * + * @author hchyun + */ +public class GenConstants { + /** + * 单表(增删改查) + */ + public static final String TPL_CRUD = "crud"; + + /** + * 树表(增删改查) + */ + public static final String TPL_TREE = "tree"; + + /** + * 主子表(增删改查) + */ + public static final String TPL_SUB = "sub"; + + /** + * 关联查询(增删改查) + */ + public static final String TPL_ASS = "ass"; + + /** + * 树编码字段 + */ + public static final String TREE_CODE = "treeCode"; + + /** + * 树父编码字段 + */ + public static final String TREE_PARENT_CODE = "treeParentCode"; + + /** + * 树名称字段 + */ + public static final String TREE_NAME = "treeName"; + + /** + * 上级菜单ID字段 + */ + public static final String PARENT_MENU_ID = "parentMenuId"; + + /** + * 上级菜单名称字段 + */ + public static final String PARENT_MENU_NAME = "parentMenuName"; + + /** + * 数据库字符串类型 + */ + public static final String[] COLUMNTYPE_STR = {"char", "varchar", "nvarchar", "varchar2", "tinytext", "text", + "mediumtext", "longtext"}; + + /** + * 数据库文本类型 + */ + public static final String[] COLUMNTYPE_TEXT = {"tinytext", "text", "mediumtext", "longtext"}; + + /** + * 数据库时间类型 + */ + public static final String[] COLUMNTYPE_TIME = {"datetime", "time", "date", "timestamp"}; + + /** + * 数据库数字类型 + */ + public static final String[] COLUMNTYPE_NUMBER = {"tinyint", "smallint", "mediumint", "int", "number", "integer", + "bit", "bigint", "float", "float", "double", "decimal"}; + + /** + * 页面不需要编辑字段 + */ + public static final String[] COLUMNNAME_NOT_EDIT = {"id", "create_by", "create_time", "del_flag"}; + + /** + * 页面不需要显示的列表字段 + */ + public static final String[] COLUMNNAME_NOT_LIST = {"id", "create_by", "create_time", "del_flag", "update_by", + "update_time"}; + + /** + * 页面不需要查询字段 + */ + public static final String[] COLUMNNAME_NOT_QUERY = {"id", "create_by", "create_time", "del_flag", "update_by", + "update_time", "remark"}; + + /** + * Entity基类字段 + */ + public static final String[] BASE_ENTITY = {"createBy", "createTime", "updateBy", "updateTime", "remark"}; + + /** + * Tree基类字段 + */ + public static final String[] TREE_ENTITY = {"parentName", "parentId", "orderNum", "ancestors", "children"}; + + /** + * 文本框 + */ + public static final String HTML_INPUT = "input"; + + /** + * 文本域 + */ + public static final String HTML_TEXTAREA = "textarea"; + + /** + * 下拉框 + */ + public static final String HTML_SELECT = "select"; + + /** + * 单选框 + */ + public static final String HTML_RADIO = "radio"; + + /** + * 复选框 + */ + public static final String HTML_CHECKBOX = "checkbox"; + + /** + * 日期控件 + */ + public static final String HTML_DATETIME = "datetime"; + + /** + * 图片上传控件 + */ + public static final String HTML_IMAGE_UPLOAD = "imageUpload"; + + /** + * 文件上传控件 + */ + public static final String HTML_FILE_UPLOAD = "fileUpload"; + + /** + * 富文本控件 + */ + public static final String HTML_EDITOR = "editor"; + + /** + * 字符串类型 + */ + public static final String TYPE_STRING = "String"; + + /** + * 整型 + */ + public static final String TYPE_INTEGER = "Integer"; + + /** + * 长整型 + */ + public static final String TYPE_LONG = "Long"; + + /** + * 浮点型 + */ + public static final String TYPE_DOUBLE = "Double"; + + /** + * 高精度计算类型 + */ + public static final String TYPE_BIGDECIMAL = "BigDecimal"; + + /** + * 时间类型 + */ + public static final String TYPE_DATE = "Date"; + + /** + * 模糊查询 + */ + public static final String QUERY_LIKE = "LIKE"; + /** + * 精确查询 + */ + public static final String QUERY_EQ = "EQ"; + + /** + * 需要 + */ + public static final String REQUIRE = "1"; + /** + * 不需要 + */ + public static final String NO_REQUIRE = "0"; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenHttpStatus.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenHttpStatus.java new file mode 100644 index 0000000..28b916a --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenHttpStatus.java @@ -0,0 +1,93 @@ +package com.hchyun.generator.utils.constant; + +/** + * 返回状态码 + * + * @author hchyun + */ +public class GenHttpStatus { + /** + * 操作成功 + */ + public static final int SUCCESS = 200; + + /** + * 操作成功 + */ + public static final int NO_DATA = 199; + + /** + * 对象创建成功 + */ + public static final int CREATED = 201; + + /** + * 请求已经被接受 + */ + public static final int ACCEPTED = 202; + + /** + * 操作已经执行成功,但是没有返回数据 + */ + public static final int NO_CONTENT = 204; + + /** + * 资源已被移除 + */ + public static final int MOVED_PERM = 301; + + /** + * 重定向 + */ + public static final int SEE_OTHER = 303; + + /** + * 资源没有被修改 + */ + public static final int NOT_MODIFIED = 304; + + /** + * 参数列表错误(缺少,格式不匹配) + */ + public static final int BAD_REQUEST = 400; + + /** + * 未授权 + */ + public static final int UNAUTHORIZED = 401; + + /** + * 访问受限,授权过期 + */ + public static final int FORBIDDEN = 403; + + /** + * 资源,服务未找到 + */ + public static final int NOT_FOUND = 404; + + /** + * 不允许的http方法 + */ + public static final int BAD_METHOD = 405; + + /** + * 资源冲突,或者资源被锁 + */ + public static final int CONFLICT = 409; + + /** + * 不支持的数据,媒体类型 + */ + public static final int UNSUPPORTED_TYPE = 415; + + /** + * 系统内部错误 + */ + public static final int ERROR = 500; + + /** + * 接口未实现 + */ + public static final int NOT_IMPLEMENTED = 501; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenUserConstants.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenUserConstants.java new file mode 100644 index 0000000..8f760c1 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/constant/GenUserConstants.java @@ -0,0 +1,89 @@ +package com.hchyun.generator.utils.constant; + +/** + * 用户常量信息 + * + * @author hchyun + */ +public class GenUserConstants { + /** + * 平台内系统用户的唯一标志 + */ + public static final String SYS_USER = "SYS_USER"; + + /** + * 正常状态 + */ + public static final String NORMAL = "0"; + + /** + * 异常状态 + */ + public static final String EXCEPTION = "1"; + + /** + * 用户封禁状态 + */ + public static final String USER_DISABLE = "1"; + + /** + * 角色封禁状态 + */ + public static final String ROLE_DISABLE = "1"; + + /** + * 部门正常状态 + */ + public static final String DEPT_NORMAL = "0"; + + /** + * 部门停用状态 + */ + public static final String DEPT_DISABLE = "1"; + + /** + * 字典正常状态 + */ + public static final String DICT_NORMAL = "0"; + + /** + * 是否为系统默认(是) + */ + public static final String YES = "Y"; + + /** + * 是否菜单外链(是) + */ + public static final String YES_FRAME = "0"; + + /** + * 是否菜单外链(否) + */ + public static final String NO_FRAME = "1"; + + /** + * 菜单类型(目录) + */ + public static final String TYPE_DIR = "M"; + + /** + * 菜单类型(菜单) + */ + public static final String TYPE_MENU = "C"; + + /** + * 菜单类型(按钮) + */ + public static final String TYPE_BUTTON = "F"; + + /** + * Layout组件标识 + */ + public final static String LAYOUT = "Layout"; + + /** + * 校验返回结果码 + */ + public final static String UNIQUE = "0"; + public final static String NOT_UNIQUE = "1"; +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenDictData.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenDictData.java new file mode 100644 index 0000000..fe6a2da --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenDictData.java @@ -0,0 +1,175 @@ +package com.hchyun.generator.utils.entity; + +import com.hchyun.generator.aop.Excel; +import com.hchyun.generator.aop.Excel.ColumnType; +import com.hchyun.generator.entity.GenBaseEntity; +import com.hchyun.generator.utils.constant.GenUserConstants; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; + +/** + * 字典数据表 sys_dict_data + * + * @author hchyun + */ +public class GenDictData extends GenBaseEntity { + + + /** + * 字典编码 + */ + @Excel(name = "字典编码", cellType = ColumnType.NUMERIC) + private Long dictCode; + + /** + * 字典排序 + */ + @Excel(name = "字典排序", cellType = ColumnType.NUMERIC) + private Long dictSort; + + /** + * 字典标签 + */ + @Excel(name = "字典标签") + private String dictLabel; + + /** + * 字典键值 + */ + @Excel(name = "字典键值") + private String dictValue; + + /** + * 字典类型 + */ + @Excel(name = "字典类型") + private String dictType; + + /** + * 样式属性(其他样式扩展) + */ + private String cssClass; + + /** + * 表格字典样式 + */ + private String listClass; + + /** + * 是否默认(Y是 N否) + */ + @Excel(name = "是否默认", readConverterExp = "Y=是,N=否") + private String isDefault; + + /** + * 状态(0正常 1停用) + */ + @Excel(name = "状态", readConverterExp = "0=正常,1=停用") + private String status; + + public Long getDictCode() { + return dictCode; + } + + public void setDictCode(Long dictCode) { + this.dictCode = dictCode; + } + + public Long getDictSort() { + return dictSort; + } + + public void setDictSort(Long dictSort) { + this.dictSort = dictSort; + } + + @NotBlank(message = "字典标签不能为空") + @Size(min = 0, max = 100, message = "字典标签长度不能超过100个字符") + public String getDictLabel() { + return dictLabel; + } + + public void setDictLabel(String dictLabel) { + this.dictLabel = dictLabel; + } + + @NotBlank(message = "字典键值不能为空") + @Size(min = 0, max = 100, message = "字典键值长度不能超过100个字符") + public String getDictValue() { + return dictValue; + } + + public void setDictValue(String dictValue) { + this.dictValue = dictValue; + } + + @NotBlank(message = "字典类型不能为空") + @Size(min = 0, max = 100, message = "字典类型长度不能超过100个字符") + public String getDictType() { + return dictType; + } + + public void setDictType(String dictType) { + this.dictType = dictType; + } + + @Size(min = 0, max = 100, message = "样式属性长度不能超过100个字符") + public String getCssClass() { + return cssClass; + } + + public void setCssClass(String cssClass) { + this.cssClass = cssClass; + } + + public String getListClass() { + return listClass; + } + + public void setListClass(String listClass) { + this.listClass = listClass; + } + + public boolean getDefault() { + return GenUserConstants.YES.equals(this.isDefault) ? true : false; + } + + public String getIsDefault() { + return isDefault; + } + + public void setIsDefault(String isDefault) { + this.isDefault = isDefault; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("dictCode", getDictCode()) + .append("dictSort", getDictSort()) + .append("dictLabel", getDictLabel()) + .append("dictValue", getDictValue()) + .append("dictType", getDictType()) + .append("cssClass", getCssClass()) + .append("listClass", getListClass()) + .append("isDefault", getIsDefault()) + .append("status", getStatus()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenMenu.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenMenu.java new file mode 100644 index 0000000..ff9b0a1 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/entity/GenMenu.java @@ -0,0 +1,263 @@ +package com.hchyun.generator.utils.entity; + +import com.hchyun.generator.entity.GenBaseEntity; +import org.apache.commons.lang3.builder.ToStringBuilder; +import org.apache.commons.lang3.builder.ToStringStyle; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Size; +import java.util.ArrayList; +import java.util.List; + +/** + * 菜单权限表 sys_menu + * + * @author hchyun + */ +public class GenMenu extends GenBaseEntity { + + + /** + * 菜单ID + */ + private Long menuId; + + /** + * 菜单名称 + */ + private String menuName; + + /** + * 父菜单名称 + */ + private String parentName; + + /** + * 父菜单ID + */ + private Long parentId; + + /** + * 显示顺序 + */ + private String orderNum; + + /** + * 路由地址 + */ + private String path; + + /** + * 组件路径 + */ + private String component; + + /** + * 是否为外链(0是 1否) + */ + private String isFrame; + + /** + * 是否缓存(0缓存 1不缓存) + */ + private String isCache; + + /** + * 类型(M目录 C菜单 F按钮) + */ + private String menuType; + + /** + * 显示状态(0显示 1隐藏) + */ + private String visible; + + /** + * 菜单状态(0显示 1隐藏) + */ + private String status; + + /** + * 权限字符串 + */ + private String perms; + + /** + * 菜单图标 + */ + private String icon; + + /** + * 子菜单 + */ + private List children = new ArrayList(); + + public GenMenu() { + } + + public GenMenu(Long uqId, String uqName, Long create) { + parentId = 6L; + menuName = uqName; + orderNum = "0"; + path = "data/" + uqId; + component = "system/query/queryDate"; + isFrame = "1"; + isCache = "0"; + menuType = "C"; + visible = "0"; + status = "0"; + icon = "chart"; + setCreateBy(create); + } + + public Long getMenuId() { + return menuId; + } + + public void setMenuId(Long menuId) { + this.menuId = menuId; + } + + @NotBlank(message = "菜单名称不能为空") + @Size(min = 0, max = 50, message = "菜单名称长度不能超过50个字符") + public String getMenuName() { + return menuName; + } + + public void setMenuName(String menuName) { + this.menuName = menuName; + } + + public String getParentName() { + return parentName; + } + + public void setParentName(String parentName) { + this.parentName = parentName; + } + + public Long getParentId() { + return parentId; + } + + public void setParentId(Long parentId) { + this.parentId = parentId; + } + + @NotBlank(message = "显示顺序不能为空") + public String getOrderNum() { + return orderNum; + } + + public void setOrderNum(String orderNum) { + this.orderNum = orderNum; + } + + @Size(min = 0, max = 200, message = "路由地址不能超过200个字符") + public String getPath() { + return path; + } + + public void setPath(String path) { + this.path = path; + } + + @Size(min = 0, max = 200, message = "组件路径不能超过255个字符") + public String getComponent() { + return component; + } + + public void setComponent(String component) { + this.component = component; + } + + public String getIsFrame() { + return isFrame; + } + + public void setIsFrame(String isFrame) { + this.isFrame = isFrame; + } + + public String getIsCache() { + return isCache; + } + + public void setIsCache(String isCache) { + this.isCache = isCache; + } + + @NotBlank(message = "菜单类型不能为空") + public String getMenuType() { + return menuType; + } + + public void setMenuType(String menuType) { + this.menuType = menuType; + } + + public String getVisible() { + return visible; + } + + public void setVisible(String visible) { + this.visible = visible; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Size(min = 0, max = 100, message = "权限标识长度不能超过100个字符") + public String getPerms() { + return perms; + } + + public void setPerms(String perms) { + this.perms = perms; + } + + public String getIcon() { + return icon; + } + + public void setIcon(String icon) { + this.icon = icon; + } + + public List getChildren() { + return children; + } + + public void setChildren(List children) { + this.children = children; + } + + @Override + public String toString() { + return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE) + .append("menuId", getMenuId()) + .append("menuName", getMenuName()) + .append("parentId", getParentId()) + .append("orderNum", getOrderNum()) + .append("path", getPath()) + .append("component", getComponent()) + .append("isFrame", getIsFrame()) + .append("IsCache", getIsCache()) + .append("menuType", getMenuType()) + .append("visible", getVisible()) + .append("status ", getStatus()) + .append("perms", getPerms()) + .append("icon", getIcon()) + .append("createBy", getCreateBy()) + .append("createTime", getCreateTime()) + .append("updateBy", getUpdateBy()) + .append("updateTime", getUpdateTime()) + .append("remark", getRemark()) + .toString(); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenBaseException.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenBaseException.java new file mode 100644 index 0000000..439fc27 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenBaseException.java @@ -0,0 +1,84 @@ +package com.hchyun.generator.utils.exception; + +import com.hchyun.generator.utils.GenMessageUtils; +import com.hchyun.generator.utils.GenStringUtils; + +/** + * 基础异常 + * + * @author hchyun + */ +public class GenBaseException extends RuntimeException { + + + /** + * 所属模块 + */ + private String module; + + /** + * 错误码 + */ + private String code; + + /** + * 错误码对应的参数 + */ + private Object[] args; + + /** + * 错误消息 + */ + private String defaultMessage; + + public GenBaseException(String module, String code, Object[] args, String defaultMessage) { + this.module = module; + this.code = code; + this.args = args; + this.defaultMessage = defaultMessage; + } + + public GenBaseException(String module, String code, Object[] args) { + this(module, code, args, null); + } + + public GenBaseException(String module, String defaultMessage) { + this(module, null, null, defaultMessage); + } + + public GenBaseException(String code, Object[] args) { + this(null, code, args, null); + } + + public GenBaseException(String defaultMessage) { + this(null, null, null, defaultMessage); + } + + @Override + public String getMessage() { + String message = null; + if (!GenStringUtils.isEmpty(code)) { + message = GenMessageUtils.message(code, args); + } + if (message == null) { + message = defaultMessage; + } + return message; + } + + public String getModule() { + return module; + } + + public String getCode() { + return code; + } + + public Object[] getArgs() { + return args; + } + + public String getDefaultMessage() { + return defaultMessage; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenCustomException.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenCustomException.java new file mode 100644 index 0000000..a93d2a3 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/exception/GenCustomException.java @@ -0,0 +1,37 @@ +package com.hchyun.generator.utils.exception; + +/** + * 自定义异常 + * + * @author hchyun + */ +public class GenCustomException extends RuntimeException { + + + private Integer code; + + private String message; + + public GenCustomException(String message) { + this.message = message; + } + + public GenCustomException(String message, Integer code) { + this.message = message; + this.code = code; + } + + public GenCustomException(String message, Throwable e) { + super(message, e); + this.message = message; + } + + @Override + public String getMessage() { + return message; + } + + public Integer getCode() { + return code; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenPageDomain.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenPageDomain.java new file mode 100644 index 0000000..35f5c75 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenPageDomain.java @@ -0,0 +1,70 @@ +package com.hchyun.generator.utils.page; + + +import com.hchyun.generator.utils.GenStringUtils; + +/** + * 分页数据 + * + * @author hchyun + */ +public class GenPageDomain { + /** + * 当前记录起始索引 + */ + private Integer pageNum; + + /** + * 每页显示记录数 + */ + private Integer pageSize; + + /** + * 排序列 + */ + private String orderByColumn; + + /** + * 排序的方向desc或者asc + */ + private String isAsc = "asc"; + + public String getOrderBy() { + if (GenStringUtils.isEmpty(orderByColumn)) { + return ""; + } + return GenStringUtils.toUnderScoreCase(orderByColumn) + " " + isAsc; + } + + public Integer getPageNum() { + return pageNum; + } + + public void setPageNum(Integer pageNum) { + this.pageNum = pageNum; + } + + public Integer getPageSize() { + return pageSize; + } + + public void setPageSize(Integer pageSize) { + this.pageSize = pageSize; + } + + public String getOrderByColumn() { + return orderByColumn; + } + + public void setOrderByColumn(String orderByColumn) { + this.orderByColumn = orderByColumn; + } + + public String getIsAsc() { + return isAsc; + } + + public void setIsAsc(String isAsc) { + this.isAsc = isAsc; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableDataInfo.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableDataInfo.java new file mode 100644 index 0000000..175b192 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableDataInfo.java @@ -0,0 +1,82 @@ +package com.hchyun.generator.utils.page; + +import java.io.Serializable; +import java.util.List; + +/** + * 表格分页数据对象 + * + * @author hchyun + */ +public class GenTableDataInfo implements Serializable { + + + /** + * 总记录数 + */ + private long total; + + /** + * 列表数据 + */ + private List rows; + + /** + * 消息状态码 + */ + private int code; + + /** + * 消息内容 + */ + private String msg; + + /** + * 表格数据对象 + */ + public GenTableDataInfo() { + } + + /** + * 分页 + * + * @param list 列表数据 + * @param total 总记录数 + */ + public GenTableDataInfo(List list, int total) { + this.rows = list; + this.total = total; + } + + public long getTotal() { + return total; + } + + public void setTotal(long total) { + this.total = total; + } + + public List getRows() { + return rows; + } + + public void setRows(List rows) { + this.rows = rows; + } + + public int getCode() { + return code; + } + + public void setCode(int code) { + this.code = code; + } + + public String getMsg() { + return msg; + } + + public void setMsg(String msg) { + this.msg = msg; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableSupport.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableSupport.java new file mode 100644 index 0000000..86d66a1 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/page/GenTableSupport.java @@ -0,0 +1,47 @@ +package com.hchyun.generator.utils.page; + + +import com.hchyun.generator.utils.GenServletUtils; + +/** + * 表格数据处理 + * + * @author hchyun + */ +public class GenTableSupport { + /** + * 当前记录起始索引 + */ + public static final String PAGE_NUM = "pageNum"; + + /** + * 每页显示记录数 + */ + public static final String PAGE_SIZE = "pageSize"; + + /** + * 排序列 + */ + public static final String ORDER_BY_COLUMN = "orderByColumn"; + + /** + * 排序的方向 "desc" 或者 "asc". + */ + public static final String IS_ASC = "isAsc"; + + /** + * 封装分页对象 + */ + public static GenPageDomain getPageDomain() { + GenPageDomain genPageDomain = new GenPageDomain(); + genPageDomain.setPageNum(GenServletUtils.getParameterToInt(PAGE_NUM)); + genPageDomain.setPageSize(GenServletUtils.getParameterToInt(PAGE_SIZE)); + genPageDomain.setOrderByColumn(GenServletUtils.getParameter(ORDER_BY_COLUMN)); + genPageDomain.setIsAsc(GenServletUtils.getParameter(IS_ASC)); + return genPageDomain; + } + + public static GenPageDomain buildPageRequest() { + return getPageDomain(); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/poi/GenExcelUtil.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/poi/GenExcelUtil.java new file mode 100644 index 0000000..8b714d0 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/poi/GenExcelUtil.java @@ -0,0 +1,811 @@ +package com.hchyun.generator.utils.poi; + +import com.hchyun.generator.aop.Excels; +import com.hchyun.generator.config.Config; +import com.hchyun.generator.controller.AjaxResult; +import com.hchyun.generator.utils.GenDateUtils; +import com.hchyun.generator.utils.GenDictUtils; +import com.hchyun.generator.utils.GenStringUtils; +import com.hchyun.generator.aop.Excel; +import com.hchyun.generator.aop.Excel.Type; +import com.hchyun.generator.aop.Excel.ColumnType; +import com.hchyun.generator.utils.exception.GenCustomException; +import com.hchyun.generator.utils.reflect.ReflectUtils; +import com.hchyun.generator.utils.text.Convert; +import org.apache.poi.hssf.usermodel.HSSFDateUtil; +import org.apache.poi.ss.usermodel.*; +import org.apache.poi.ss.util.CellRangeAddressList; +import org.apache.poi.xssf.streaming.SXSSFWorkbook; +import org.apache.poi.xssf.usermodel.XSSFDataValidation; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.*; +import java.lang.reflect.Field; +import java.math.BigDecimal; +import java.text.DecimalFormat; +import java.util.*; +import java.util.stream.Collectors; + +/** + * Excel相关处理 + * + * @author hchyun + */ +public class GenExcelUtil { + private static final Logger log = LoggerFactory.getLogger(GenExcelUtil.class); + + /** + * Excel sheet最大行数,默认65536 + */ + public static final int sheetSize = 65536; + + /** + * 工作表名称 + */ + private String sheetName; + + /** + * 导出类型(EXPORT:导出数据;IMPORT:导入模板) + */ + private Type type; + + /** + * 工作薄对象 + */ + private Workbook wb; + + /** + * 工作表对象 + */ + private Sheet sheet; + + /** + * 样式列表 + */ + private Map styles; + + /** + * 导入导出数据列表 + */ + private List list; + + /** + * 注解列表 + */ + private List fields; + + /** + * 统计列表 + */ + private Map statistics = new HashMap(); + + /** + * 数字格式 + */ + private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00"); + + /** + * 实体对象 + */ + public Class clazz; + + public GenExcelUtil(Class clazz) { + this.clazz = clazz; + } + + public void init(List list, String sheetName, Type type) { + if (list == null) { + list = new ArrayList(); + } + this.list = list; + this.sheetName = sheetName; + this.type = type; + createExcelField(); + createWorkbook(); + } + + /** + * 对excel表单默认第一个索引名转换成list + * + * @param is 输入流 + * @return 转换后集合 + */ + public List importExcel(InputStream is) throws Exception { + return importExcel(GenStringUtils.EMPTY, is); + } + + /** + * 对excel表单指定表格索引名转换成list + * + * @param sheetName 表格索引名 + * @param is 输入流 + * @return 转换后集合 + */ + public List importExcel(String sheetName, InputStream is) throws Exception { + this.type = Type.IMPORT; + this.wb = WorkbookFactory.create(is); + List list = new ArrayList(); + Sheet sheet = null; + if (GenStringUtils.isNotEmpty(sheetName)) { + // 如果指定sheet名,则取指定sheet中的内容. + sheet = wb.getSheet(sheetName); + } else { + // 如果传入的sheet名不存在则默认指向第1个sheet. + sheet = wb.getSheetAt(0); + } + + if (sheet == null) { + throw new IOException("文件sheet不存在"); + } + + int rows = sheet.getPhysicalNumberOfRows(); + + if (rows > 0) { + // 定义一个map用于存放excel列的序号和field. + Map cellMap = new HashMap(); + // 获取表头 + Row heard = sheet.getRow(0); + for (int i = 0; i < heard.getPhysicalNumberOfCells(); i++) { + Cell cell = heard.getCell(i); + if (GenStringUtils.isNotNull(cell)) { + String value = this.getCellValue(heard, i).toString(); + cellMap.put(value, i); + } else { + cellMap.put(null, i); + } + } + // 有数据时才处理 得到类的所有field. + Field[] allFields = clazz.getDeclaredFields(); + // 定义一个map用于存放列的序号和field. + Map fieldsMap = new HashMap(); + for (int col = 0; col < allFields.length; col++) { + Field field = allFields[col]; + Excel attr = field.getAnnotation(Excel.class); + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) { + // 设置类的私有字段属性可访问. + field.setAccessible(true); + Integer column = cellMap.get(attr.name()); + if (column != null) { + fieldsMap.put(column, field); + } + } + } + for (int i = 1; i < rows; i++) { + // 从第2行开始取数据,默认第一行是表头. + Row row = sheet.getRow(i); + T entity = null; + for (Map.Entry entry : fieldsMap.entrySet()) { + Object val = this.getCellValue(row, entry.getKey()); + + // 如果不存在实例则新建. + entity = (entity == null ? clazz.newInstance() : entity); + // 从map中得到对应列的field. + Field field = fieldsMap.get(entry.getKey()); + // 取得类型,并根据对象类型设置值. + Class fieldType = field.getType(); + if (String.class == fieldType) { + String s = Convert.toStr(val); + if (GenStringUtils.endsWith(s, ".0")) { + val = GenStringUtils.substringBefore(s, ".0"); + } else { + val = Convert.toStr(val); + } + } else if ((Integer.TYPE == fieldType || Integer.class == fieldType) && GenStringUtils.isNumeric(Convert.toStr(val))) { + val = Convert.toInt(val); + } else if (Long.TYPE == fieldType || Long.class == fieldType) { + val = Convert.toLong(val); + } else if (Double.TYPE == fieldType || Double.class == fieldType) { + val = Convert.toDouble(val); + } else if (Float.TYPE == fieldType || Float.class == fieldType) { + val = Convert.toFloat(val); + } else if (BigDecimal.class == fieldType) { + val = Convert.toBigDecimal(val); + } else if (Date.class == fieldType) { + if (val instanceof String) { + val = GenDateUtils.parseDate(val); + } else if (val instanceof Double) { + val = DateUtil.getJavaDate((Double) val); + } + } + if (GenStringUtils.isNotNull(fieldType)) { + Excel attr = field.getAnnotation(Excel.class); + String propertyName = field.getName(); + if (GenStringUtils.isNotEmpty(attr.targetAttr())) { + propertyName = field.getName() + "." + attr.targetAttr(); + } else if (GenStringUtils.isNotEmpty(attr.readConverterExp())) { + val = reverseByExp(Convert.toStr(val), attr.readConverterExp(), attr.separator()); + } else if (GenStringUtils.isNotEmpty(attr.dictType())) { + val = reverseDictByExp(Convert.toStr(val), attr.dictType(), attr.separator()); + } + ReflectUtils.invokeSetter(entity, propertyName, val); + } + } + list.add(entity); + } + } + return list; + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @param list 导出数据集合 + * @param sheetName 工作表的名称 + * @return 结果 + */ + public AjaxResult exportExcel(List list, String sheetName) { + this.init(list, sheetName, Type.EXPORT); + return exportExcel(); + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @param sheetName 工作表的名称 + * @return 结果 + */ + public AjaxResult importTemplateExcel(String sheetName) { + this.init(null, sheetName, Type.IMPORT); + return exportExcel(); + } + + /** + * 对list数据源将其里面的数据导入到excel表单 + * + * @return 结果 + */ + public AjaxResult exportExcel() { + OutputStream out = null; + try { + // 取出一共有多少个sheet. + double sheetNo = Math.ceil(list.size() / sheetSize); + for (int index = 0; index <= sheetNo; index++) { + createSheet(sheetNo, index); + + // 产生一行 + Row row = sheet.createRow(0); + int column = 0; + // 写入各个字段的列头名称 + for (Object[] os : fields) { + Excel excel = (Excel) os[1]; + this.createCell(excel, row, column++); + } + if (Type.EXPORT.equals(type)) { + fillExcelData(index, row); + addStatisticsRow(); + } + } + String filename = encodingFilename(sheetName); + out = new FileOutputStream(getAbsoluteFile(filename)); + wb.write(out); + return AjaxResult.success(filename); + } catch (Exception e) { + log.error("导出Excel异常{}", e.getMessage()); + throw new GenCustomException("导出Excel失败,请联系网站管理员!"); + } finally { + if (wb != null) { + try { + wb.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + if (out != null) { + try { + out.close(); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + } + } + + /** + * 填充excel数据 + * + * @param index 序号 + * @param row 单元格行 + */ + public void fillExcelData(int index, Row row) { + int startNo = index * sheetSize; + int endNo = Math.min(startNo + sheetSize, list.size()); + for (int i = startNo; i < endNo; i++) { + row = sheet.createRow(i + 1 - startNo); + // 得到导出对象. + T vo = (T) list.get(i); + int column = 0; + for (Object[] os : fields) { + Field field = (Field) os[0]; + Excel excel = (Excel) os[1]; + // 设置实体类私有属性可访问 + field.setAccessible(true); + this.addCell(excel, row, vo, field, column++); + } + } + } + + /** + * 创建表格样式 + * + * @param wb 工作薄对象 + * @return 样式列表 + */ + private Map createStyles(Workbook wb) { + // 写入各条记录,每条记录对应excel表中的一行 + Map styles = new HashMap(); + CellStyle style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setBorderRight(BorderStyle.THIN); + style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderLeft(BorderStyle.THIN); + style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderTop(BorderStyle.THIN); + style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setBorderBottom(BorderStyle.THIN); + style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex()); + Font dataFont = wb.createFont(); + dataFont.setFontName("Arial"); + dataFont.setFontHeightInPoints((short) 10); + style.setFont(dataFont); + styles.put("data", style); + + style = wb.createCellStyle(); + style.cloneStyleFrom(styles.get("data")); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex()); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + Font headerFont = wb.createFont(); + headerFont.setFontName("Arial"); + headerFont.setFontHeightInPoints((short) 10); + headerFont.setBold(true); + headerFont.setColor(IndexedColors.WHITE.getIndex()); + style.setFont(headerFont); + styles.put("header", style); + + style = wb.createCellStyle(); + style.setAlignment(HorizontalAlignment.CENTER); + style.setVerticalAlignment(VerticalAlignment.CENTER); + Font totalFont = wb.createFont(); + totalFont.setFontName("Arial"); + totalFont.setFontHeightInPoints((short) 10); + style.setFont(totalFont); + styles.put("total", style); + + return styles; + } + + /** + * 创建单元格 + */ + public Cell createCell(Excel attr, Row row, int column) { + // 创建列 + Cell cell = row.createCell(column); + // 写入列信息 + cell.setCellValue(attr.name()); + setDataValidation(attr, row, column); + cell.setCellStyle(styles.get("header")); + return cell; + } + + /** + * 设置单元格信息 + * + * @param value 单元格值 + * @param attr 注解相关 + * @param cell 单元格信息 + */ + public void setCellVo(Object value, Excel attr, Cell cell) { + if (ColumnType.STRING == attr.cellType()) { + cell.setCellType(CellType.STRING); + cell.setCellValue(GenStringUtils.isNull(value) ? attr.defaultValue() : value + attr.suffix()); + } else if (ColumnType.NUMERIC == attr.cellType()) { + cell.setCellType(CellType.NUMERIC); + cell.setCellValue(GenStringUtils.contains(Convert.toStr(value), ".") ? Convert.toDouble(value) : Convert.toInt(value)); + } + } + + /** + * 创建表格样式 + */ + public void setDataValidation(Excel attr, Row row, int column) { + String a = attr.name(); + if (attr.name().indexOf("注:") >= 0) { + sheet.setColumnWidth(column, 6000); + } else { + // 设置列宽 + sheet.setColumnWidth(column, (int) ((attr.width() + 0.72) * 256)); + row.setHeight((short) (attr.height() * 20)); + } + // 如果设置了提示信息则鼠标放上去提示. + if (GenStringUtils.isNotEmpty(attr.prompt())) { + // 这里默认设了2-101列提示. + setXSSFPrompt(sheet, "", attr.prompt(), 1, 100, column, column); + } + // 如果设置了combo属性则本列只能选择不能输入 + if (attr.combo().length > 0) { + // 这里默认设了2-101列只能选择不能输入. + setXSSFValidation(sheet, attr.combo(), 1, 100, column, column); + } + } + + /** + * 添加单元格 + */ + public Cell addCell(Excel attr, Row row, T vo, Field field, int column) { + Cell cell = null; + try { + // 设置行高 + row.setHeight((short) (attr.height() * 20)); + // 根据Excel中设置情况决定是否导出,有些情况需要保持为空,希望用户填写这一列. + if (attr.isExport()) { + // 创建cell + cell = row.createCell(column); + cell.setCellStyle(styles.get("data")); + + // 用于读取对象中的属性 + Object value = getTargetValue(vo, field, attr); + String dateFormat = attr.dateFormat(); + String readConverterExp = attr.readConverterExp(); + String separator = attr.separator(); + String dictType = attr.dictType(); + if (GenStringUtils.isNotEmpty(dateFormat) && GenStringUtils.isNotNull(value)) { + cell.setCellValue(GenDateUtils.parseDateToStr(dateFormat, (Date) value)); + } else if (GenStringUtils.isNotEmpty(readConverterExp) && GenStringUtils.isNotNull(value)) { + cell.setCellValue(convertByExp(Convert.toStr(value), readConverterExp, separator)); + } else if (GenStringUtils.isNotEmpty(dictType) && GenStringUtils.isNotNull(value)) { + cell.setCellValue(convertDictByExp(Convert.toStr(value), dictType, separator)); + } else if (value instanceof BigDecimal && -1 != attr.scale()) { + cell.setCellValue((((BigDecimal) value).setScale(attr.scale(), attr.roundingMode())).toString()); + } else { + // 设置列类型 + setCellVo(value, attr, cell); + } + addStatisticsData(column, Convert.toStr(value), attr); + } + } catch (Exception e) { + log.error("导出Excel失败{}", e); + } + return cell; + } + + /** + * 设置 POI XSSFSheet 单元格提示 + * + * @param sheet 表单 + * @param promptTitle 提示标题 + * @param promptContent 提示内容 + * @param firstRow 开始行 + * @param endRow 结束行 + * @param firstCol 开始列 + * @param endCol 结束列 + */ + public void setXSSFPrompt(Sheet sheet, String promptTitle, String promptContent, int firstRow, int endRow, + int firstCol, int endCol) { + DataValidationHelper helper = sheet.getDataValidationHelper(); + DataValidationConstraint constraint = helper.createCustomConstraint("DD1"); + CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + DataValidation dataValidation = helper.createValidation(constraint, regions); + dataValidation.createPromptBox(promptTitle, promptContent); + dataValidation.setShowPromptBox(true); + sheet.addValidationData(dataValidation); + } + + /** + * 设置某些列的值只能输入预制的数据,显示下拉框. + * + * @param sheet 要设置的sheet. + * @param textlist 下拉框显示的内容 + * @param firstRow 开始行 + * @param endRow 结束行 + * @param firstCol 开始列 + * @param endCol 结束列 + * @return 设置好的sheet. + */ + public void setXSSFValidation(Sheet sheet, String[] textlist, int firstRow, int endRow, int firstCol, int endCol) { + DataValidationHelper helper = sheet.getDataValidationHelper(); + // 加载下拉列表内容 + DataValidationConstraint constraint = helper.createExplicitListConstraint(textlist); + // 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列 + CellRangeAddressList regions = new CellRangeAddressList(firstRow, endRow, firstCol, endCol); + // 数据有效性对象 + DataValidation dataValidation = helper.createValidation(constraint, regions); + // 处理Excel兼容性问题 + if (dataValidation instanceof XSSFDataValidation) { + dataValidation.setSuppressDropDownArrow(true); + dataValidation.setShowErrorBox(true); + } else { + dataValidation.setSuppressDropDownArrow(false); + } + + sheet.addValidationData(dataValidation); + } + + /** + * 解析导出值 0=男,1=女,2=未知 + * + * @param propertyValue 参数值 + * @param converterExp 翻译注解 + * @param separator 分隔符 + * @return 解析后值 + */ + public static String convertByExp(String propertyValue, String converterExp, String separator) { + StringBuilder propertyString = new StringBuilder(); + String[] convertSource = converterExp.split(","); + for (String item : convertSource) { + String[] itemArray = item.split("="); + if (GenStringUtils.containsAny(separator, propertyValue)) { + for (String value : propertyValue.split(separator)) { + if (itemArray[0].equals(value)) { + propertyString.append(itemArray[1] + separator); + break; + } + } + } else { + if (itemArray[0].equals(propertyValue)) { + return itemArray[1]; + } + } + } + return GenStringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 反向解析值 男=0,女=1,未知=2 + * + * @param propertyValue 参数值 + * @param converterExp 翻译注解 + * @param separator 分隔符 + * @return 解析后值 + */ + public static String reverseByExp(String propertyValue, String converterExp, String separator) { + StringBuilder propertyString = new StringBuilder(); + String[] convertSource = converterExp.split(","); + for (String item : convertSource) { + String[] itemArray = item.split("="); + if (GenStringUtils.containsAny(separator, propertyValue)) { + for (String value : propertyValue.split(separator)) { + if (itemArray[1].equals(value)) { + propertyString.append(itemArray[0] + separator); + break; + } + } + } else { + if (itemArray[1].equals(propertyValue)) { + return itemArray[0]; + } + } + } + return GenStringUtils.stripEnd(propertyString.toString(), separator); + } + + /** + * 解析字典值 + * + * @param dictValue 字典值 + * @param dictType 字典类型 + * @param separator 分隔符 + * @return 字典标签 + */ + public static String convertDictByExp(String dictValue, String dictType, String separator) { + return GenDictUtils.getDictLabel(dictType, dictValue, separator); + } + + /** + * 反向解析值字典值 + * + * @param dictLabel 字典标签 + * @param dictType 字典类型 + * @param separator 分隔符 + * @return 字典值 + */ + public static String reverseDictByExp(String dictLabel, String dictType, String separator) { + return GenDictUtils.getDictValue(dictType, dictLabel, separator); + } + + /** + * 合计统计信息 + */ + private void addStatisticsData(Integer index, String text, Excel entity) { + if (entity != null && entity.isStatistics()) { + Double temp = 0D; + if (!statistics.containsKey(index)) { + statistics.put(index, temp); + } + try { + temp = Double.valueOf(text); + } catch (NumberFormatException e) { + } + statistics.put(index, statistics.get(index) + temp); + } + } + + /** + * 创建统计行 + */ + public void addStatisticsRow() { + if (statistics.size() > 0) { + Cell cell = null; + Row row = sheet.createRow(sheet.getLastRowNum() + 1); + Set keys = statistics.keySet(); + cell = row.createCell(0); + cell.setCellStyle(styles.get("total")); + cell.setCellValue("合计"); + + for (Integer key : keys) { + cell = row.createCell(key); + cell.setCellStyle(styles.get("total")); + cell.setCellValue(DOUBLE_FORMAT.format(statistics.get(key))); + } + statistics.clear(); + } + } + + /** + * 编码文件名 + */ + public String encodingFilename(String filename) { + filename = UUID.randomUUID().toString() + "_" + filename + ".xlsx"; + return filename; + } + + /** + * 获取下载路径 + * + * @param filename 文件名称 + */ + public String getAbsoluteFile(String filename) { + String downloadPath = Config.getDownloadPath() + filename; + File desc = new File(downloadPath); + if (!desc.getParentFile().exists()) { + desc.getParentFile().mkdirs(); + } + return downloadPath; + } + + /** + * 获取bean中的属性值 + * + * @param vo 实体对象 + * @param field 字段 + * @param excel 注解 + * @return 最终的属性值 + * @throws Exception + */ + private Object getTargetValue(T vo, Field field, Excel excel) throws Exception { + Object o = field.get(vo); + if (GenStringUtils.isNotEmpty(excel.targetAttr())) { + String target = excel.targetAttr(); + if (target.indexOf(".") > -1) { + String[] targets = target.split("[.]"); + for (String name : targets) { + o = getValue(o, name); + } + } else { + o = getValue(o, target); + } + } + return o; + } + + /** + * 以类的属性的get方法方法形式获取值 + * + * @param o + * @param name + * @return value + * @throws Exception + */ + private Object getValue(Object o, String name) throws Exception { + if (GenStringUtils.isNotEmpty(name)) { + Class clazz = o.getClass(); + Field field = clazz.getDeclaredField(name); + field.setAccessible(true); + o = field.get(o); + } + return o; + } + + /** + * todo + * 得到所有定义字段 + */ + private void createExcelField() { + this.fields = new ArrayList(); + List tempFields = new ArrayList<>(); + tempFields.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields())); + tempFields.addAll(Arrays.asList(clazz.getDeclaredFields())); + for (Field field : tempFields) { + // 单注解 + if (field.isAnnotationPresent(Excel.class)) { + putToField(field, field.getAnnotation(Excel.class)); + } + + // 多注解 + if (field.isAnnotationPresent(Excels.class)) { + Excels attrs = field.getAnnotation(Excels.class); + Excel[] excels = attrs.value(); + for (Excel excel : excels) { + putToField(field, excel); + } + } + } + this.fields = this.fields.stream().sorted(Comparator.comparing(objects -> ((Excel) objects[1]).sort())).collect(Collectors.toList()); + } + + /** + * 放到字段集合中 + */ + private void putToField(Field field, Excel attr) { + if (attr != null && (attr.type() == Type.ALL || attr.type() == type)) { + this.fields.add(new Object[]{field, attr}); + } + } + + /** + * 创建一个工作簿 + */ + public void createWorkbook() { + this.wb = new SXSSFWorkbook(500); + } + + /** + * 创建工作表 + * + * @param sheetNo sheet数量 + * @param index 序号 + */ + public void createSheet(double sheetNo, int index) { + this.sheet = wb.createSheet(); + this.styles = createStyles(wb); + // 设置工作表的名称. + if (sheetNo == 0) { + wb.setSheetName(index, sheetName); + } else { + wb.setSheetName(index, sheetName + index); + } + } + + /** + * 获取单元格值 + * + * @param row 获取的行 + * @param column 获取单元格列号 + * @return 单元格值 + */ + public Object getCellValue(Row row, int column) { + if (row == null) { + return row; + } + Object val = ""; + try { + Cell cell = row.getCell(column); + if (GenStringUtils.isNotNull(cell)) { + if (cell.getCellTypeEnum() == CellType.NUMERIC || cell.getCellTypeEnum() == CellType.FORMULA) { + val = cell.getNumericCellValue(); + if (HSSFDateUtil.isCellDateFormatted(cell)) { + val = DateUtil.getJavaDate((Double) val); // POI Excel 日期格式转换 + } else { + if ((Double) val % 1 > 0) { + val = new BigDecimal(val.toString()); + } else { + val = new DecimalFormat("0").format(val); + } + } + } else if (cell.getCellTypeEnum() == CellType.STRING) { + val = cell.getStringCellValue(); + } else if (cell.getCellTypeEnum() == CellType.BOOLEAN) { + val = cell.getBooleanCellValue(); + } else if (cell.getCellTypeEnum() == CellType.ERROR) { + val = cell.getErrorCellValue(); + } + + } + } catch (Exception e) { + return val; + } + return val; + } +} \ No newline at end of file diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/redis/GenRedisCache.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/redis/GenRedisCache.java new file mode 100644 index 0000000..e60b7bd --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/redis/GenRedisCache.java @@ -0,0 +1,210 @@ +package com.hchyun.generator.utils.redis; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.HashOperations; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; +import org.springframework.stereotype.Component; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; + +/** + * spring redis 工具类 + * + * @author hchyun + **/ +@SuppressWarnings(value = {"unchecked", "rawtypes"}) +@Component +public class GenRedisCache { + @Autowired + public RedisTemplate redisTemplate; + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + */ + public void setCacheObject(final String key, final T value) { + redisTemplate.opsForValue().set(key, value); + } + + /** + * 缓存基本的对象,Integer、String、实体类等 + * + * @param key 缓存的键值 + * @param value 缓存的值 + * @param timeout 时间 + * @param timeUnit 时间颗粒度 + */ + public void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) { + redisTemplate.opsForValue().set(key, value, timeout, timeUnit); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout) { + return expire(key, timeout, TimeUnit.SECONDS); + } + + /** + * 设置有效时间 + * + * @param key Redis键 + * @param timeout 超时时间 + * @param unit 时间单位 + * @return true=设置成功;false=设置失败 + */ + public boolean expire(final String key, final long timeout, final TimeUnit unit) { + return redisTemplate.expire(key, timeout, unit); + } + + /** + * 获得缓存的基本对象。 + * + * @param key 缓存键值 + * @return 缓存键值对应的数据 + */ + public T getCacheObject(final String key) { + ValueOperations operation = redisTemplate.opsForValue(); + return operation.get(key); + } + + /** + * 删除单个对象 + * + * @param key + */ + public boolean deleteObject(final String key) { + return redisTemplate.delete(key); + } + + /** + * 删除集合对象 + * + * @param collection 多个对象 + * @return + */ + public long deleteObject(final Collection collection) { + return redisTemplate.delete(collection); + } + + /** + * 缓存List数据 + * + * @param key 缓存的键值 + * @param dataList 待缓存的List数据 + * @return 缓存的对象 + */ + public long setCacheList(final String key, final List dataList) { + Long count = redisTemplate.opsForList().rightPushAll(key, dataList); + return count == null ? 0 : count; + } + + /** + * 获得缓存的list对象 + * + * @param key 缓存的键值 + * @return 缓存键值对应的数据 + */ + public List getCacheList(final String key) { + return redisTemplate.opsForList().range(key, 0, -1); + } + + /** + * 缓存Set + * + * @param key 缓存键值 + * @param dataSet 缓存的数据 + * @return 缓存数据的对象 + */ + public long setCacheSet(final String key, final Set dataSet) { + Long count = redisTemplate.opsForSet().add(key, dataSet); + return count == null ? 0 : count; + } + + /** + * 获得缓存的set + * + * @param key + * @return + */ + public Set getCacheSet(final String key) { + return redisTemplate.opsForSet().members(key); + } + + /** + * 缓存Map + * + * @param key + * @param dataMap + */ + public void setCacheMap(final String key, final Map dataMap) { + if (dataMap != null) { + redisTemplate.opsForHash().putAll(key, dataMap); + } + } + + /** + * 获得缓存的Map + * + * @param key + * @return + */ + public Map getCacheMap(final String key) { + return redisTemplate.opsForHash().entries(key); + } + + /** + * 往Hash中存入数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @param value 值 + */ + public void setCacheMapValue(final String key, final String hKey, final T value) { + redisTemplate.opsForHash().put(key, hKey, value); + } + + /** + * 获取Hash中的数据 + * + * @param key Redis键 + * @param hKey Hash键 + * @return Hash中的对象 + */ + public T getCacheMapValue(final String key, final String hKey) { + HashOperations opsForHash = redisTemplate.opsForHash(); + return opsForHash.get(key, hKey); + } + + /** + * 获取多个Hash中的数据 + * + * @param key Redis键 + * @param hKeys Hash键集合 + * @return Hash对象集合 + */ + public List getMultiCacheMapValue(final String key, final Collection hKeys) { + return redisTemplate.opsForHash().multiGet(key, hKeys); + } + + /** + * 获得缓存的基本对象列表 + * + * @param pattern 字符串前缀 + * @return 对象列表 + */ + public Collection keys(final String pattern) { + return redisTemplate.keys(pattern); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/reflect/ReflectUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/reflect/ReflectUtils.java new file mode 100644 index 0000000..4046014 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/reflect/ReflectUtils.java @@ -0,0 +1,322 @@ +package com.hchyun.generator.utils.reflect; + +import com.hchyun.generator.utils.GenDateUtils; +import com.hchyun.generator.utils.text.Convert; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.Validate; +import org.apache.poi.ss.usermodel.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.lang.reflect.*; +import java.util.Date; + +/** + * 反射工具类. 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数. + * + * @author hchyun + */ +@SuppressWarnings("rawtypes") +public class ReflectUtils { + private static final String SETTER_PREFIX = "set"; + + private static final String GETTER_PREFIX = "get"; + + private static final String CGLIB_CLASS_SEPARATOR = "$$"; + + private static Logger logger = LoggerFactory.getLogger(ReflectUtils.class); + + /** + * 调用Getter方法. + * 支持多级,如:对象名.对象名.方法 + */ + @SuppressWarnings("unchecked") + public static E invokeGetter(Object obj, String propertyName) { + Object object = obj; + for (String name : StringUtils.split(propertyName, ".")) { + String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name); + object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{}); + } + return (E) object; + } + + /** + * 调用Setter方法, 仅匹配方法名。 + * 支持多级,如:对象名.对象名.方法 + */ + public static void invokeSetter(Object obj, String propertyName, E value) { + Object object = obj; + String[] names = StringUtils.split(propertyName, "."); + for (int i = 0; i < names.length; i++) { + if (i < names.length - 1) { + String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]); + object = invokeMethod(object, getterMethodName, new Class[]{}, new Object[]{}); + } else { + String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]); + invokeMethodByName(object, setterMethodName, new Object[]{value}); + } + } + } + + /** + * 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数. + */ + @SuppressWarnings("unchecked") + public static E getFieldValue(final Object obj, final String fieldName) { + Field field = getAccessibleField(obj, fieldName); + if (field == null) { + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + return null; + } + E result = null; + try { + result = (E) field.get(obj); + } catch (IllegalAccessException e) { + logger.error("不可能抛出的异常{}", e.getMessage()); + } + return result; + } + + /** + * 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数. + */ + public static void setFieldValue(final Object obj, final String fieldName, final E value) { + Field field = getAccessibleField(obj, fieldName); + if (field == null) { + // throw new IllegalArgumentException("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + fieldName + "] 字段 "); + return; + } + try { + field.set(obj, value); + } catch (IllegalAccessException e) { + logger.error("不可能抛出的异常: {}", e.getMessage()); + } + } + + /** + * 直接调用对象方法, 无视private/protected修饰符. + * 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用. + * 同时匹配方法名+参数类型, + */ + @SuppressWarnings("unchecked") + public static E invokeMethod(final Object obj, final String methodName, final Class[] parameterTypes, + final Object[] args) { + if (obj == null || methodName == null) { + return null; + } + Method method = getAccessibleMethod(obj, methodName, parameterTypes); + if (method == null) { + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); + return null; + } + try { + return (E) method.invoke(obj, args); + } catch (Exception e) { + String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; + throw convertReflectionExceptionToUnchecked(msg, e); + } + } + + /** + * 直接调用对象方法, 无视private/protected修饰符, + * 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用. + * 只匹配函数名,如果有多个同名函数调用第一个。 + */ + @SuppressWarnings("unchecked") + public static E invokeMethodByName(final Object obj, final String methodName, final Object[] args) { + Method method = getAccessibleMethodByName(obj, methodName, args.length); + if (method == null) { + // 如果为空不报错,直接返回空。 + logger.debug("在 [" + obj.getClass() + "] 中,没有找到 [" + methodName + "] 方法 "); + return null; + } + try { + // 类型转换(将参数数据类型转换为目标方法参数类型) + Class[] cs = method.getParameterTypes(); + for (int i = 0; i < cs.length; i++) { + if (args[i] != null && !args[i].getClass().equals(cs[i])) { + if (cs[i] == String.class) { + args[i] = Convert.toStr(args[i]); + if (StringUtils.endsWith((String) args[i], ".0")) { + args[i] = StringUtils.substringBefore((String) args[i], ".0"); + } + } else if (cs[i] == Integer.class) { + args[i] = Convert.toInt(args[i]); + } else if (cs[i] == Long.class) { + args[i] = Convert.toLong(args[i]); + } else if (cs[i] == Double.class) { + args[i] = Convert.toDouble(args[i]); + } else if (cs[i] == Float.class) { + args[i] = Convert.toFloat(args[i]); + } else if (cs[i] == Date.class) { + if (args[i] instanceof String) { + args[i] = GenDateUtils.parseDate(args[i]); + } else { + args[i] = DateUtil.getJavaDate((Double) args[i]); + } + } + } + } + return (E) method.invoke(obj, args); + } catch (Exception e) { + String msg = "method: " + method + ", obj: " + obj + ", args: " + args + ""; + throw convertReflectionExceptionToUnchecked(msg, e); + } + } + + /** + * 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + */ + public static Field getAccessibleField(final Object obj, final String fieldName) { + // 为空不报错。直接返回 null + if (obj == null) { + return null; + } + Validate.notBlank(fieldName, "fieldName can't be blank"); + for (Class superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) { + try { + Field field = superClass.getDeclaredField(fieldName); + makeAccessible(field); + return field; + } catch (NoSuchFieldException e) { + continue; + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + * 匹配函数名+参数类型。 + * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) + */ + public static Method getAccessibleMethod(final Object obj, final String methodName, + final Class... parameterTypes) { + // 为空不报错。直接返回 null + if (obj == null) { + return null; + } + Validate.notBlank(methodName, "methodName can't be blank"); + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { + try { + Method method = searchType.getDeclaredMethod(methodName, parameterTypes); + makeAccessible(method); + return method; + } catch (NoSuchMethodException e) { + continue; + } + } + return null; + } + + /** + * 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问. + * 如向上转型到Object仍无法找到, 返回null. + * 只匹配函数名。 + * 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args) + */ + public static Method getAccessibleMethodByName(final Object obj, final String methodName, int argsNum) { + // 为空不报错。直接返回 null + if (obj == null) { + return null; + } + Validate.notBlank(methodName, "methodName can't be blank"); + for (Class searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) { + Method[] methods = searchType.getDeclaredMethods(); + for (Method method : methods) { + if (method.getName().equals(methodName) && method.getParameterTypes().length == argsNum) { + makeAccessible(method); + return method; + } + } + } + return null; + } + + /** + * 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Method method) { + if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) + && !method.isAccessible()) { + method.setAccessible(true); + } + } + + /** + * 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。 + */ + public static void makeAccessible(Field field) { + if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) + || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) { + field.setAccessible(true); + } + } + + /** + * 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处 + * 如无法找到, 返回Object.class. + */ + @SuppressWarnings("unchecked") + public static Class getClassGenricType(final Class clazz) { + return getClassGenricType(clazz, 0); + } + + /** + * 通过反射, 获得Class定义中声明的父类的泛型参数的类型. + * 如无法找到, 返回Object.class. + */ + public static Class getClassGenricType(final Class clazz, final int index) { + Type genType = clazz.getGenericSuperclass(); + + if (!(genType instanceof ParameterizedType)) { + logger.debug(clazz.getSimpleName() + "'s superclass not ParameterizedType"); + return Object.class; + } + + Type[] params = ((ParameterizedType) genType).getActualTypeArguments(); + + if (index >= params.length || index < 0) { + logger.debug("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: " + + params.length); + return Object.class; + } + if (!(params[index] instanceof Class)) { + logger.debug(clazz.getSimpleName() + " not set the actual class on superclass generic parameter"); + return Object.class; + } + + return (Class) params[index]; + } + + public static Class getUserClass(Object instance) { + if (instance == null) { + throw new RuntimeException("Instance must not be null"); + } + Class clazz = instance.getClass(); + if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) { + Class superClass = clazz.getSuperclass(); + if (superClass != null && !Object.class.equals(superClass)) { + return superClass; + } + } + return clazz; + + } + + /** + * 将反射时的checked exception转换为unchecked exception. + */ + public static RuntimeException convertReflectionExceptionToUnchecked(String msg, Exception e) { + if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException + || e instanceof NoSuchMethodException) { + return new IllegalArgumentException(msg, e); + } else if (e instanceof InvocationTargetException) { + return new RuntimeException(msg, ((InvocationTargetException) e).getTargetException()); + } + return new RuntimeException(msg, e); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/spring/GenSpringUtils.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/spring/GenSpringUtils.java new file mode 100644 index 0000000..fe38e8b --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/spring/GenSpringUtils.java @@ -0,0 +1,131 @@ +package com.hchyun.generator.utils.spring; + +import com.hchyun.generator.utils.GenStringUtils; +import org.springframework.aop.framework.AopContext; +import org.springframework.beans.BeansException; +import org.springframework.beans.factory.NoSuchBeanDefinitionException; +import org.springframework.beans.factory.config.BeanFactoryPostProcessor; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +/** + * spring工具类 方便在非spring管理环境中获取bean + * + * @author hchyun + */ +@Component +public final class GenSpringUtils implements BeanFactoryPostProcessor, ApplicationContextAware { + /** + * Spring应用上下文环境 + */ + private static ConfigurableListableBeanFactory beanFactory; + + private static ApplicationContext applicationContext; + + @Override + public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { + GenSpringUtils.beanFactory = beanFactory; + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + GenSpringUtils.applicationContext = applicationContext; + } + + /** + * 获取对象 + * + * @param name + * @return Object 一个以所给名字注册的bean的实例 + * @throws BeansException + */ + @SuppressWarnings("unchecked") + public static T getBean(String name) throws BeansException { + return (T) beanFactory.getBean(name); + } + + /** + * 获取类型为requiredType的对象 + * + * @param clz + * @return + * @throws BeansException + */ + public static T getBean(Class clz) throws BeansException { + T result = (T) beanFactory.getBean(clz); + return result; + } + + /** + * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true + * + * @param name + * @return boolean + */ + public static boolean containsBean(String name) { + return beanFactory.containsBean(name); + } + + /** + * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException) + * + * @param name + * @return boolean + * @throws NoSuchBeanDefinitionException + */ + public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException { + return beanFactory.isSingleton(name); + } + + /** + * @param name + * @return Class 注册对象的类型 + * @throws NoSuchBeanDefinitionException + */ + public static Class getType(String name) throws NoSuchBeanDefinitionException { + return beanFactory.getType(name); + } + + /** + * 如果给定的bean名字在bean定义中有别名,则返回这些别名 + * + * @param name + * @return + * @throws NoSuchBeanDefinitionException + */ + public static String[] getAliases(String name) throws NoSuchBeanDefinitionException { + return beanFactory.getAliases(name); + } + + /** + * 获取aop代理对象 + * + * @param invoker + * @return + */ + @SuppressWarnings("unchecked") + public static T getAopProxy(T invoker) { + return (T) AopContext.currentProxy(); + } + + /** + * 获取当前的环境配置,无配置返回null + * + * @return 当前的环境配置 + */ + public static String[] getActiveProfiles() { + return applicationContext.getEnvironment().getActiveProfiles(); + } + + /** + * 获取当前的环境配置,当有多个环境配置时,只获取第一个 + * + * @return 当前的环境配置 + */ + public static String getActiveProfile() { + final String[] activeProfiles = getActiveProfiles(); + return GenStringUtils.isNotEmpty(activeProfiles) ? activeProfiles[0] : null; + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/sql/GenSqlUtil.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/sql/GenSqlUtil.java new file mode 100644 index 0000000..f4d9846 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/sql/GenSqlUtil.java @@ -0,0 +1,33 @@ +package com.hchyun.generator.utils.sql; + +import com.hchyun.generator.utils.GenStringUtils; +import com.hchyun.generator.utils.exception.GenBaseException; + +/** + * sql操作工具类 + * + * @author hchyun + */ +public class GenSqlUtil { + /** + * 仅支持字母、数字、下划线、空格、逗号、小数点(支持多个字段排序) + */ + public static String SQL_PATTERN = "[a-zA-Z0-9_\\ \\,\\.]+"; + + /** + * 检查字符,防止注入绕过 + */ + public static String escapeOrderBySql(String value) { + if (GenStringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { + throw new GenBaseException("参数不符合规范,不能进行查询"); + } + return value; + } + + /** + * 验证 order by 语法是否符合规范 + */ + public static boolean isValidOrderBySql(String value) { + return value.matches(SQL_PATTERN); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/CharsetKit.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/CharsetKit.java new file mode 100644 index 0000000..ef4af2e --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/CharsetKit.java @@ -0,0 +1,92 @@ +package com.hchyun.generator.utils.text; + + +import com.hchyun.generator.utils.GenStringUtils; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +/** + * 字符集工具类 + * + * @author hchyun + */ +public class CharsetKit { + /** + * ISO-8859-1 + */ + public static final String ISO_8859_1 = "ISO-8859-1"; + /** + * UTF-8 + */ + public static final String UTF_8 = "UTF-8"; + /** + * GBK + */ + public static final String GBK = "GBK"; + + /** + * ISO-8859-1 + */ + public static final Charset CHARSET_ISO_8859_1 = Charset.forName(ISO_8859_1); + /** + * UTF-8 + */ + public static final Charset CHARSET_UTF_8 = Charset.forName(UTF_8); + /** + * GBK + */ + public static final Charset CHARSET_GBK = Charset.forName(GBK); + + /** + * 转换为Charset对象 + * + * @param charset 字符集,为空则返回默认字符集 + * @return Charset + */ + public static Charset charset(String charset) { + return GenStringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, String srcCharset, String destCharset) { + return convert(source, Charset.forName(srcCharset), Charset.forName(destCharset)); + } + + /** + * 转换字符串的字符集编码 + * + * @param source 字符串 + * @param srcCharset 源字符集,默认ISO-8859-1 + * @param destCharset 目标字符集,默认UTF-8 + * @return 转换后的字符集 + */ + public static String convert(String source, Charset srcCharset, Charset destCharset) { + if (null == srcCharset) { + srcCharset = StandardCharsets.ISO_8859_1; + } + + if (null == destCharset) { + srcCharset = StandardCharsets.UTF_8; + } + + if (GenStringUtils.isEmpty(source) || srcCharset.equals(destCharset)) { + return source; + } + return new String(source.getBytes(srcCharset), destCharset); + } + + /** + * @return 系统字符集编码 + */ + public static String systemCharset() { + return Charset.defaultCharset().name(); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/Convert.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/Convert.java new file mode 100644 index 0000000..5d55ab0 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/Convert.java @@ -0,0 +1,851 @@ +package com.hchyun.generator.utils.text; + + +import com.hchyun.generator.utils.GenStringUtils; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.text.NumberFormat; +import java.util.Set; + +/** + * 类型转换器 + * + * @author hchyun + */ +public class Convert { + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static String toStr(Object value, String defaultValue) { + if (null == value) { + return defaultValue; + } + if (value instanceof String) { + return (String) value; + } + return value.toString(); + } + + /** + * 转换为字符串
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static String toStr(Object value) { + return toStr(value, null); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Character toChar(Object value, Character defaultValue) { + if (null == value) { + return defaultValue; + } + if (value instanceof Character) { + return (Character) value; + } + + final String valueStr = toStr(value, null); + return GenStringUtils.isEmpty(valueStr) ? defaultValue : valueStr.charAt(0); + } + + /** + * 转换为字符
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Character toChar(Object value) { + return toChar(value, null); + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Byte toByte(Object value, Byte defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Byte) { + return (Byte) value; + } + if (value instanceof Number) { + return ((Number) value).byteValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Byte.parseByte(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为byte
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Byte toByte(Object value) { + return toByte(value, null); + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Short toShort(Object value, Short defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Short) { + return (Short) value; + } + if (value instanceof Number) { + return ((Number) value).shortValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Short.parseShort(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Short
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Short toShort(Object value) { + return toShort(value, null); + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Number toNumber(Object value, Number defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Number) { + return (Number) value; + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return NumberFormat.getInstance().parse(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Number
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Number toNumber(Object value) { + return toNumber(value, null); + } + + /** + * 转换为int
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Integer toInt(Object value, Integer defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Integer) { + return (Integer) value; + } + if (value instanceof Number) { + return ((Number) value).intValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Integer.parseInt(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为int
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Integer toInt(Object value) { + return toInt(value, null); + } + + /** + * 转换为Integer数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String str) { + return toIntArray(",", str); + } + + /** + * 转换为Long数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String str) { + return toLongArray(",", str); + } + + /** + * 转换为Integer数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static Integer[] toIntArray(String split, String str) { + if (GenStringUtils.isEmpty(str)) { + return new Integer[]{}; + } + String[] arr = str.split(split); + final Integer[] ints = new Integer[arr.length]; + for (int i = 0; i < arr.length; i++) { + final Integer v = toInt(arr[i], 0); + ints[i] = v; + } + return ints; + } + + /** + * 转换为Long数组
+ * + * @param split 分隔符 + * @param str 被转换的值 + * @return 结果 + */ + public static Long[] toLongArray(String split, String str) { + if (GenStringUtils.isEmpty(str)) { + return new Long[]{}; + } + String[] arr = str.split(split); + final Long[] longs = new Long[arr.length]; + for (int i = 0; i < arr.length; i++) { + final Long v = toLong(arr[i], null); + longs[i] = v; + } + return longs; + } + + /** + * 转换为String数组
+ * + * @param str 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String str) { + return toStrArray(",", str); + } + + /** + * 转换为String数组
+ * + * @param split 分隔符 + * @param split 被转换的值 + * @return 结果 + */ + public static String[] toStrArray(String split, String str) { + return str.split(split); + } + + /** + * 转换为long
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Long toLong(Object value, Long defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Long) { + return (Long) value; + } + if (value instanceof Number) { + return ((Number) value).longValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).longValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为long
+ * 如果给定的值为null,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Long toLong(Object value) { + return toLong(value, null); + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Double toDouble(Object value, Double defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Double) { + return (Double) value; + } + if (value instanceof Number) { + return ((Number) value).doubleValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + // 支持科学计数法 + return new BigDecimal(valueStr.trim()).doubleValue(); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为double
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Double toDouble(Object value) { + return toDouble(value, null); + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Float toFloat(Object value, Float defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Float) { + return (Float) value; + } + if (value instanceof Number) { + return ((Number) value).floatValue(); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Float.parseFloat(valueStr.trim()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Float
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Float toFloat(Object value) { + return toFloat(value, null); + } + + /** + * 转换为boolean
+ * String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static Boolean toBool(Object value, Boolean defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof Boolean) { + return (Boolean) value; + } + String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + valueStr = valueStr.trim().toLowerCase(); + switch (valueStr) { + case "true": + return true; + case "false": + return false; + case "yes": + return true; + case "ok": + return true; + case "no": + return false; + case "1": + return true; + case "0": + return false; + default: + return defaultValue; + } + } + + /** + * 转换为boolean
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static Boolean toBool(Object value) { + return toBool(value, null); + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * + * @param clazz Enum的Class + * @param value 值 + * @param defaultValue 默认值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value, E defaultValue) { + if (value == null) { + return defaultValue; + } + if (clazz.isAssignableFrom(value.getClass())) { + @SuppressWarnings("unchecked") + E myE = (E) value; + return myE; + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return Enum.valueOf(clazz, valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为Enum对象
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * + * @param clazz Enum的Class + * @param value 值 + * @return Enum + */ + public static > E toEnum(Class clazz, Object value) { + return toEnum(clazz, value, null); + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value, BigInteger defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof BigInteger) { + return (BigInteger) value; + } + if (value instanceof Long) { + return BigInteger.valueOf((Long) value); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return new BigInteger(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为BigInteger
+ * 如果给定的值为空,或者转换失败,返回默认值null
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigInteger toBigInteger(Object value) { + return toBigInteger(value, null); + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @param defaultValue 转换错误时的默认值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value, BigDecimal defaultValue) { + if (value == null) { + return defaultValue; + } + if (value instanceof BigDecimal) { + return (BigDecimal) value; + } + if (value instanceof Long) { + return new BigDecimal((Long) value); + } + if (value instanceof Double) { + return new BigDecimal((Double) value); + } + if (value instanceof Integer) { + return new BigDecimal((Integer) value); + } + final String valueStr = toStr(value, null); + if (GenStringUtils.isEmpty(valueStr)) { + return defaultValue; + } + try { + return new BigDecimal(valueStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * 转换为BigDecimal
+ * 如果给定的值为空,或者转换失败,返回默认值
+ * 转换失败不会报错 + * + * @param value 被转换的值 + * @return 结果 + */ + public static BigDecimal toBigDecimal(Object value) { + return toBigDecimal(value, null); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @return 字符串 + */ + public static String utf8Str(Object obj) { + return str(obj, CharsetKit.CHARSET_UTF_8); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charsetName 字符集 + * @return 字符串 + */ + public static String str(Object obj, String charsetName) { + return str(obj, Charset.forName(charsetName)); + } + + /** + * 将对象转为字符串
+ * 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法 + * + * @param obj 对象 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(Object obj, Charset charset) { + if (null == obj) { + return null; + } + + if (obj instanceof String) { + return (String) obj; + } else if (obj instanceof byte[] || obj instanceof Byte[]) { + return str((Byte[]) obj, charset); + } else if (obj instanceof ByteBuffer) { + return str((ByteBuffer) obj, charset); + } + return obj.toString(); + } + + /** + * 将byte数组转为字符串 + * + * @param bytes byte数组 + * @param charset 字符集 + * @return 字符串 + */ + public static String str(byte[] bytes, String charset) { + return str(bytes, GenStringUtils.isEmpty(charset) ? Charset.defaultCharset() : Charset.forName(charset)); + } + + /** + * 解码字节码 + * + * @param data 字符串 + * @param charset 字符集,如果此字段为空,则解码的结果取决于平台 + * @return 解码后的字符串 + */ + public static String str(byte[] data, Charset charset) { + if (data == null) { + return null; + } + + if (null == charset) { + return new String(data); + } + return new String(data, charset); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, String charset) { + if (data == null) { + return null; + } + + return str(data, Charset.forName(charset)); + } + + /** + * 将编码的byteBuffer数据转换为字符串 + * + * @param data 数据 + * @param charset 字符集,如果为空使用当前系统字符集 + * @return 字符串 + */ + public static String str(ByteBuffer data, Charset charset) { + if (null == charset) { + charset = Charset.defaultCharset(); + } + return charset.decode(data).toString(); + } + + // ----------------------------------------------------------------------- 全角半角转换 + + /** + * 半角转全角 + * + * @param input String. + * @return 全角字符串. + */ + public static String toSBC(String input) { + return toSBC(input, null); + } + + /** + * 半角转全角 + * + * @param input String + * @param notConvertSet 不替换的字符集合 + * @return 全角字符串. + */ + public static String toSBC(String input, Set notConvertSet) { + char c[] = input.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == ' ') { + c[i] = '\u3000'; + } else if (c[i] < '\177') { + c[i] = (char) (c[i] + 65248); + + } + } + return new String(c); + } + + /** + * 全角转半角 + * + * @param input String. + * @return 半角字符串 + */ + public static String toDBC(String input) { + return toDBC(input, null); + } + + /** + * 替换全角为半角 + * + * @param text 文本 + * @param notConvertSet 不替换的字符集合 + * @return 替换后的字符 + */ + public static String toDBC(String text, Set notConvertSet) { + char c[] = text.toCharArray(); + for (int i = 0; i < c.length; i++) { + if (null != notConvertSet && notConvertSet.contains(c[i])) { + // 跳过不替换的字符 + continue; + } + + if (c[i] == '\u3000') { + c[i] = ' '; + } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { + c[i] = (char) (c[i] - 65248); + } + } + String returnString = new String(c); + + return returnString; + } + + /** + * 数字金额大写转换 先写个完整的然后将如零拾替换成零 + * + * @param n 数字 + * @return 中文大写数字 + */ + public static String digitUppercase(double n) { + String[] fraction = {"角", "分"}; + String[] digit = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; + String[][] unit = {{"元", "万", "亿"}, {"", "拾", "佰", "仟"}}; + + String head = n < 0 ? "负" : ""; + n = Math.abs(n); + + String s = ""; + for (int i = 0; i < fraction.length; i++) { + s += (digit[(int) (Math.floor(n * 10 * Math.pow(10, i)) % 10)] + fraction[i]).replaceAll("(零.)+", ""); + } + if (s.length() < 1) { + s = "整"; + } + int integerPart = (int) Math.floor(n); + + for (int i = 0; i < unit[0].length && integerPart > 0; i++) { + String p = ""; + for (int j = 0; j < unit[1].length && n > 0; j++) { + p = digit[integerPart % 10] + unit[1][j] + p; + integerPart = integerPart / 10; + } + s = p.replaceAll("(零.)*零$", "").replaceAll("^$", "零") + unit[0][i] + s; + } + return head + s.replaceAll("(零.)*零元", "元").replaceFirst("(零.)+", "").replaceAll("(零.)+", "零").replaceAll("^整$", "零元整"); + } +} diff --git a/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/StrFormatter.java b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/StrFormatter.java new file mode 100644 index 0000000..998eb32 --- /dev/null +++ b/hchyun/hchyun-generator/src/main/java/com/hchyun/generator/utils/text/StrFormatter.java @@ -0,0 +1,77 @@ +package com.hchyun.generator.utils.text; + + +import com.hchyun.generator.utils.GenStringUtils; + +/** + * 字符串格式化 + * + * @author hchyun + */ +public class StrFormatter { + public static final String EMPTY_JSON = "{}"; + public static final char C_BACKSLASH = '\\'; + public static final char C_DELIM_START = '{'; + public static final char C_DELIM_END = '}'; + + /** + * 格式化字符串
+ * 此方法只是简单将占位符 {} 按照顺序替换为参数
+ * 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可
+ * 例:
+ * 通常使用:format("this is {} for {}", "a", "b") -> this is a for b
+ * 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a
+ * 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b
+ * + * @param strPattern 字符串模板 + * @param argArray 参数列表 + * @return 结果 + */ + public static String format(final String strPattern, final Object... argArray) { + if (GenStringUtils.isEmpty(strPattern) || GenStringUtils.isEmpty(argArray)) { + return strPattern; + } + final int strPatternLength = strPattern.length(); + + // 初始化定义好的长度以获得更好的性能 + StringBuilder sbuf = new StringBuilder(strPatternLength + 50); + + int handledPosition = 0; + int delimIndex;// 占位符所在位置 + for (int argIndex = 0; argIndex < argArray.length; argIndex++) { + delimIndex = strPattern.indexOf(EMPTY_JSON, handledPosition); + if (delimIndex == -1) { + if (handledPosition == 0) { + return strPattern; + } else { // 字符串模板剩余部分不再包含占位符,加入剩余部分后返回结果 + sbuf.append(strPattern, handledPosition, strPatternLength); + return sbuf.toString(); + } + } else { + if (delimIndex > 0 && strPattern.charAt(delimIndex - 1) == C_BACKSLASH) { + if (delimIndex > 1 && strPattern.charAt(delimIndex - 2) == C_BACKSLASH) { + // 转义符之前还有一个转义符,占位符依旧有效 + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } else { + // 占位符被转义 + argIndex--; + sbuf.append(strPattern, handledPosition, delimIndex - 1); + sbuf.append(C_DELIM_START); + handledPosition = delimIndex + 1; + } + } else { + // 正常占位符 + sbuf.append(strPattern, handledPosition, delimIndex); + sbuf.append(Convert.utf8Str(argArray[argIndex])); + handledPosition = delimIndex + 2; + } + } + } + // 加入最后一个占位符后所有的字符 + sbuf.append(strPattern, handledPosition, strPattern.length()); + + return sbuf.toString(); + } +} diff --git a/hchyun/hchyun-generator/src/main/resources/vm/java/controller.java.vm b/hchyun/hchyun-generator/src/main/resources/vm/java/controller.java.vm index 983af71..5472106 100644 --- a/hchyun/hchyun-generator/src/main/resources/vm/java/controller.java.vm +++ b/hchyun/hchyun-generator/src/main/resources/vm/java/controller.java.vm @@ -61,15 +61,15 @@ public class ${ClassName}Controller extends HcyBaseController { public Serializable list(@Validated @RequestBody ${ClassName} ${className}) { try { startPage(${className}.getParams()); - ServerResult> serverResult = ${className}Service.select${ClassName}List(${className}); - if (serverResult.isStart()) { + ServerResult> genServerResult = ${className}Service.select${ClassName}List(${className}); + if (genServerResult.isStart()) { #if($table.crud || $table.sub || $table.tplCategory.equals("ass")) - return getDataTable(serverResult.getData()); + return getDataTable(genServerResult.getData()); #elseif($table.tree) - return AjaxResult.success(serverResult.getData()); + return AjaxResult.success(genServerResult.getData()); #end } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -86,12 +86,12 @@ public class ${ClassName}Controller extends HcyBaseController { @PutMapping("/export") public AjaxResult export(@Validated @RequestBody ${ClassName} ${className}) { try { - ServerResult> serverResult = ${className}Service.select${ClassName}List(${className}); + ServerResult> genServerResult = ${className}Service.select${ClassName}List(${className}); ExcelUtil<${ClassName}> util = new ExcelUtil<${ClassName}>(${ClassName}. class); - if (serverResult.isStart()) { - return util.exportExcel(serverResult.getData(), "${businessName}"); + if (genServerResult.isStart()) { + return util.exportExcel(genServerResult.getData(), "${businessName}"); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -108,11 +108,11 @@ public class ${ClassName}Controller extends HcyBaseController { @GetMapping(value = "/{${pkColumn.javaField}}") public AjaxResult getInfo(@PathVariable("${pkColumn.javaField}") ${pkColumn.javaType} ${pkColumn.javaField}) { try { - ServerResult<${ClassName}> serverResult = ${className}Service.select${ClassName}ById(${pkColumn.javaField}); - if (serverResult.isStart()) { - return AjaxResult.success(serverResult.getData()); + ServerResult<${ClassName}> genServerResult = ${className}Service.select${ClassName}ById(${pkColumn.javaField}); + if (genServerResult.isStart()) { + return AjaxResult.success(genServerResult.getData()); } else { - return AjaxResult.info(serverResult.getMsg()); + return AjaxResult.info(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -151,11 +151,11 @@ public class ${ClassName}Controller extends HcyBaseController { #end #end try { - ServerResult serverResult = ${className}Service.insert${ClassName}(${className}); - if (serverResult.isStart()) { + ServerResult genServerResult = ${className}Service.insert${ClassName}(${className}); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -195,11 +195,11 @@ public class ${ClassName}Controller extends HcyBaseController { } #end #end - ServerResult serverResult = ${className}Service.update${ClassName}(${className}); - if (serverResult.isStart()) { + ServerResult genServerResult = ${className}Service.update${ClassName}(${className}); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } } catch (RuntimeException e) { logger.error(e.getMessage()); @@ -220,11 +220,11 @@ public class ${ClassName}Controller extends HcyBaseController { if (${pkColumn.javaField}s.length<0){ return AjaxResult.error("id不能为空!"); } - ServerResult serverResult = ${className}Service.delete${ClassName}ByIds(${pkColumn.javaField}s); - if (serverResult.isStart()) { + ServerResult genServerResult = ${className}Service.delete${ClassName}ByIds(${pkColumn.javaField}s); + if (genServerResult.isStart()) { return AjaxResult.success(); } else { - return AjaxResult.error(serverResult.getMsg()); + return AjaxResult.error(genServerResult.getMsg()); } }catch (RuntimeException e){ logger.error(e.getMessage());