合并代码生成模块

This commit is contained in:
clay 2021-06-17 00:50:52 +08:00
parent 55df9c31a0
commit 136998c938
82 changed files with 741 additions and 6368 deletions

View File

@ -7,7 +7,7 @@ ebts:
# 版权年份 # 版权年份
copyrightYear: 2020 copyrightYear: 2020
# 实例演示开关 # 实例演示开关
demoEnabled: true demoEnabled: false
# 文件路径 示例( Windows配置D:/ebts/uploadPath,Linux配置(宝塔) /www/wwwroot/ebts/uploadPath) # 文件路径 示例( Windows配置D:/ebts/uploadPath,Linux配置(宝塔) /www/wwwroot/ebts/uploadPath)
# profile: /www/wwwroot/gen/uploadPath # profile: /www/wwwroot/gen/uploadPath
profile: D:/gen/uploadPath profile: D:/gen/uploadPath

View File

@ -10,7 +10,6 @@ import org.springframework.stereotype.Component;
*/ */
@Component @Component
@ConfigurationProperties(prefix = "ebts") @ConfigurationProperties(prefix = "ebts")
//@ConfigurationProperties(prefix = "ftp.service")
public class EBTSConfig { public class EBTSConfig {
/** /**
* 项目名称 * 项目名称

View File

@ -36,6 +36,11 @@ public class ServerResult<T> {
this.sheetName = sheetName; this.sheetName = sheetName;
this.msg = "操作成功"; this.msg = "操作成功";
} }
public ServerResult(T data) {
this.data = data;
this.start = true;
this.msg = "操作成功";
}
public ServerResult(boolean start, String msg) { public ServerResult(boolean start, String msg) {
this.start = start; this.start = start;

View File

@ -412,4 +412,8 @@ public class StringUtils extends org.apache.commons.lang3.StringUtils {
return (T) obj; return (T) obj;
} }
public static String toLoad(String str){
return str.substring(0,1).toLowerCase()+str.substring(1);
}
} }

View File

@ -7,8 +7,6 @@ import com.ebts.common.exception.CustomException;
import com.ebts.common.exception.DemoModeException; import com.ebts.common.exception.DemoModeException;
import com.ebts.common.exception.EbtsException; import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.StringUtils; import com.ebts.common.utils.StringUtils;
import com.ebts.generator.utils.exception.GenCustomException;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.AccessDeniedException;
@ -59,26 +57,6 @@ public class GlobalExceptionHandler {
return AjaxResult.error(e.getCode(), e.getMessage()); return AjaxResult.error(e.getCode(), e.getMessage());
} }
/**
* GenEBTS基础异常
*/
@ExceptionHandler(GenEbtsException.class)
public AjaxResult genEbtsException(GenEbtsException e) {
return AjaxResult.error(e.getMsg());
}
/**
* 业务异常
*/
@ExceptionHandler(GenCustomException.class)
public AjaxResult genBusinessException(GenCustomException e) {
if (StringUtils.isNull(e.getCode())) {
return AjaxResult.error(e.getMessage());
}
return AjaxResult.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(NoHandlerFoundException.class) @ExceptionHandler(NoHandlerFoundException.class)
public AjaxResult handlerNoFoundException(Exception e) { public AjaxResult handlerNoFoundException(Exception e) {
log.error(e.getMessage(), e); log.error(e.getMessage(), e);

View File

@ -154,10 +154,10 @@
<artifactId>springfox-swagger-ui</artifactId> <artifactId>springfox-swagger-ui</artifactId>
</dependency> </dependency>
<!-- 通用工具--> <!-- 通用工具-->
<!-- <dependency>--> <dependency>
<!-- <groupId>com.ebts</groupId>--> <groupId>com.ebts</groupId>
<!-- <artifactId>ebts-common</artifactId>--> <artifactId>ebts-common</artifactId>
<!-- </dependency>--> </dependency>
</dependencies> </dependencies>

View File

@ -1,139 +0,0 @@
package com.ebts.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 binlin
*/
@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;
}
}
}

View File

@ -1,17 +0,0 @@
package com.ebts.generator.aop;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Excel注解集
*
* @author binlin
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Excels {
Excel[] value();
}

View File

@ -1,36 +0,0 @@
package com.ebts.generator.aop;
import com.ebts.generator.enums.GenBusinessType;
import com.ebts.generator.enums.GenOperatorType;
import java.lang.annotation.*;
/**
* 自定义操作日志记录注解
*
* @author binlin
*/
@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;
}

View File

@ -1,153 +0,0 @@
package com.ebts.generator.controller;
import com.ebts.generator.utils.GenHttpStatus;
import com.ebts.generator.utils.GenStringUtils;
import java.util.HashMap;
/**
* 操作消息提醒
*
* @author binlin
*/
public class AjaxResult extends HashMap<String, Object> {
/**
* 状态码
*/
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);
}
}

View File

@ -3,12 +3,12 @@ package com.ebts.generator.controller;
import java.io.Serializable; import java.io.Serializable;
import java.util.List; import java.util.List;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.generator.enums.GenBusinessType; import com.ebts.common.core.controller.BaseController;
import com.ebts.generator.utils.GenBaseController; import com.ebts.common.core.entity.AjaxResult;
import com.ebts.generator.utils.GenReturnConstants; import com.ebts.common.enums.BusinessType;
import com.ebts.generator.utils.GenServerResult; import com.ebts.common.utils.ServerResult;
import com.ebts.generator.utils.poi.GenExcelUtil; import com.ebts.common.utils.poi.ExcelUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -32,7 +32,7 @@ import com.ebts.generator.service.ApiClassService;
*/ */
@RestController @RestController
@RequestMapping("/tool/apiclass") @RequestMapping("/tool/apiclass")
public class ApiClassController extends GenBaseController { public class ApiClassController extends BaseController {
protected final Logger logger = LoggerFactory.getLogger(ApiClassController.class); protected final Logger logger = LoggerFactory.getLogger(ApiClassController.class);
@Autowired @Autowired
@ -47,11 +47,11 @@ public class ApiClassController extends GenBaseController {
@PreAuthorize("@ebts.hasAnyPermi('tool:apiclass:querylist')") @PreAuthorize("@ebts.hasAnyPermi('tool:apiclass:querylist')")
@GetMapping("querylist") @GetMapping("querylist")
public AjaxResult queryList() { public AjaxResult queryList() {
GenServerResult<List<ApiClass>> genServerResult = apiClassService.selectApiclassList(new ApiClass()); ServerResult<List<ApiClass>> ServerResult = apiClassService.selectApiclassList(new ApiClass());
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -62,11 +62,11 @@ public class ApiClassController extends GenBaseController {
@GetMapping("/list") @GetMapping("/list")
public Serializable list(ApiClass apiclass) { public Serializable list(ApiClass apiclass) {
startPage(); startPage();
GenServerResult<List<ApiClass>> genServerResult = apiClassService.selectApiclassList(apiclass); ServerResult<List<ApiClass>> ServerResult = apiClassService.selectApiclassList(apiclass);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -74,15 +74,15 @@ public class ApiClassController extends GenBaseController {
* 导出接口类名列表 * 导出接口类名列表
*/ */
@PreAuthorize("@ebts.hasPermi('tool:apiclass:export')") @PreAuthorize("@ebts.hasPermi('tool:apiclass:export')")
@Log(title = "接口类名", businessType = GenBusinessType.EXPORT) @Log(title = "接口类名", businessType = BusinessType.EXPORT)
@GetMapping("/export") @GetMapping("/export")
public AjaxResult export(ApiClass apiclass) { public AjaxResult export(ApiClass apiclass) {
GenServerResult<List<ApiClass>> genServerResult = apiClassService.selectApiclassList(apiclass); ServerResult<List<ApiClass>> ServerResult = apiClassService.selectApiclassList(apiclass);
GenExcelUtil<ApiClass> util = new GenExcelUtil<ApiClass>(ApiClass.class); ExcelUtil<ApiClass> util = new ExcelUtil<>(ApiClass.class);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return util.exportExcel(genServerResult.getData(), "apiclass"); return util.exportExcel(ServerResult.getData(), "apiclass");
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -92,11 +92,11 @@ public class ApiClassController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('tool:apiclass:query')") @PreAuthorize("@ebts.hasPermi('tool:apiclass:query')")
@GetMapping(value = "/{id}") @GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) { public AjaxResult getInfo(@PathVariable("id") Long id) {
GenServerResult<ApiClass> genServerResult = apiClassService.selectApiclassById(id); ServerResult<ApiClass> ServerResult = apiClassService.selectApiclassById(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -104,7 +104,7 @@ public class ApiClassController extends GenBaseController {
* 新增接口类名 * 新增接口类名
*/ */
@PreAuthorize("@ebts.hasPermi('tool:apiclass:add')") @PreAuthorize("@ebts.hasPermi('tool:apiclass:add')")
@Log(title = "接口类名", businessType = GenBusinessType.INSERT) @Log(title = "接口类名", businessType = BusinessType.INSERT)
@PostMapping @PostMapping
public AjaxResult add(@RequestBody ApiClass apiclass) { public AjaxResult add(@RequestBody ApiClass apiclass) {
if (apiclass.getmId() == null || apiclass.getmId() < 0) { if (apiclass.getmId() == null || apiclass.getmId() < 0) {
@ -116,11 +116,11 @@ public class ApiClassController extends GenBaseController {
if (apiclass.getcDescribe() == null || apiclass.getcDescribe().equals("")) { if (apiclass.getcDescribe() == null || apiclass.getcDescribe().equals("")) {
return AjaxResult.error("类描述不能为空!"); return AjaxResult.error("类描述不能为空!");
} }
GenServerResult<Integer> genServerResult = apiClassService.insertApiclass(apiclass); ServerResult<Integer> ServerResult = apiClassService.insertApiclass(apiclass);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -128,7 +128,7 @@ public class ApiClassController extends GenBaseController {
* 修改接口类名 * 修改接口类名
*/ */
@PreAuthorize("@ebts.hasPermi('tool:apiclass:edit')") @PreAuthorize("@ebts.hasPermi('tool:apiclass:edit')")
@Log(title = "接口类名", businessType = GenBusinessType.UPDATE) @Log(title = "接口类名", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult edit(@RequestBody ApiClass apiclass) { public AjaxResult edit(@RequestBody ApiClass apiclass) {
if (apiclass.getmId() == null || apiclass.getmId() < 0) { if (apiclass.getmId() == null || apiclass.getmId() < 0) {
@ -140,11 +140,11 @@ public class ApiClassController extends GenBaseController {
if (apiclass.getcDescribe() == null || apiclass.getcDescribe().equals("")) { if (apiclass.getcDescribe() == null || apiclass.getcDescribe().equals("")) {
return AjaxResult.error("类描述不能为空!"); return AjaxResult.error("类描述不能为空!");
} }
GenServerResult<Integer> genServerResult = apiClassService.updateApiclass(apiclass); ServerResult<Integer> ServerResult = apiClassService.updateApiclass(apiclass);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -152,17 +152,17 @@ public class ApiClassController extends GenBaseController {
* 删除接口类名 * 删除接口类名
*/ */
@PreAuthorize("@ebts.hasPermi('tool:apiclass:remove')") @PreAuthorize("@ebts.hasPermi('tool:apiclass:remove')")
@Log(title = "接口类名", businessType = GenBusinessType.DELETE) @Log(title = "接口类名", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}") @DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) { public AjaxResult remove(@PathVariable Long[] ids) {
if (ids.length < 0) { if (ids.length < 0) {
return AjaxResult.error("id不能为空!"); return AjaxResult.error("id不能为空!");
} }
GenServerResult<Integer> genServerResult = apiClassService.deleteApiclassByIds(ids); ServerResult<Integer> ServerResult = apiClassService.deleteApiclassByIds(ids);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
} }

View File

@ -4,17 +4,16 @@ import java.io.*;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.generator.enums.GenBusinessType; import com.ebts.common.constant.ReturnConstants;
import com.ebts.generator.utils.GenBaseController; import com.ebts.common.core.controller.BaseController;
import com.ebts.generator.utils.GenReturnConstants; import com.ebts.common.core.entity.AjaxResult;
import com.ebts.generator.utils.GenServerResult; import com.ebts.common.core.page.TableDataInfo;
import com.ebts.generator.utils.page.GenTableDataInfo; import com.ebts.common.core.text.Convert;
import com.ebts.generator.utils.text.Convert; import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.ServerResult;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -41,7 +40,7 @@ import com.ebts.generator.service.GenTableService;
*/ */
@RestController @RestController
@RequestMapping("/tool/gen") @RequestMapping("/tool/gen")
public class GenController extends GenBaseController { public class GenController extends BaseController {
private Logger logger = LoggerFactory.getLogger(GenController.class); private Logger logger = LoggerFactory.getLogger(GenController.class);
@Autowired @Autowired
@ -94,7 +93,7 @@ public class GenController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('tool:gen:list')") @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
@GetMapping(value = "/column/{talbleId}") @GetMapping(value = "/column/{talbleId}")
public Serializable columnList(Long tableId) { public Serializable columnList(Long tableId) {
GenTableDataInfo dataInfo = new GenTableDataInfo(); TableDataInfo dataInfo = new TableDataInfo();
List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId); List<GenTableColumn> list = genTableColumnService.selectGenTableColumnListByTableId(tableId);
dataInfo.setRows(list); dataInfo.setRows(list);
dataInfo.setTotal(list.size()); dataInfo.setTotal(list.size());
@ -105,7 +104,7 @@ public class GenController extends GenBaseController {
* 导入表结构(保存) * 导入表结构(保存)
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:list')") @PreAuthorize("@ebts.hasPermi('tool:gen:list')")
@Log(title = "代码生成", businessType = GenBusinessType.IMPORT) @Log(title = "代码生成", businessType = BusinessType.IMPORT)
@PostMapping("/importTable") @PostMapping("/importTable")
public AjaxResult importTableSave(String tables) { public AjaxResult importTableSave(String tables) {
String[] tableNames = Convert.toStrArray(tables); String[] tableNames = Convert.toStrArray(tables);
@ -120,7 +119,7 @@ public class GenController extends GenBaseController {
* 修改保存代码生成业务 * 修改保存代码生成业务
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:edit')") @PreAuthorize("@ebts.hasPermi('tool:gen:edit')")
@Log(title = "代码生成", businessType = GenBusinessType.UPDATE) @Log(title = "代码生成", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult editSave(@Validated @RequestBody GenTable genTable) { public AjaxResult editSave(@Validated @RequestBody GenTable genTable) {
genTableService.validateEdit(genTable); genTableService.validateEdit(genTable);
@ -132,19 +131,19 @@ public class GenController extends GenBaseController {
* 删除代码生成 * 删除代码生成
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:remove')") @PreAuthorize("@ebts.hasPermi('tool:gen:remove')")
@Log(title = "代码生成", businessType = GenBusinessType.DELETE) @Log(title = "代码生成", businessType = BusinessType.DELETE)
@DeleteMapping("/{tableIds}") @DeleteMapping("/{tableIds}")
public AjaxResult remove(@PathVariable Long[] tableIds) { public AjaxResult remove(@PathVariable Long[] tableIds) {
try { try {
GenServerResult<Integer> genServerResult = genTableService.deleteGenTableByIds(tableIds); ServerResult<Integer> ServerResult = genTableService.deleteGenTableByIds(tableIds);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return AjaxResult.error(GenReturnConstants.SYS_ERROR); return AjaxResult.error(ReturnConstants.SYS_ERROR);
} }
} }
@ -162,7 +161,7 @@ public class GenController extends GenBaseController {
* 生成代码(下载方式) * 生成代码(下载方式)
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:code')") @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/download/{tableName}") @GetMapping("/download/{tableName}")
public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException { public void download(HttpServletResponse response, @PathVariable("tableName") String tableName) throws IOException {
byte[] data = genTableService.downloadCode(tableName); byte[] data = genTableService.downloadCode(tableName);
@ -173,7 +172,7 @@ public class GenController extends GenBaseController {
* 生成代码(自定义路径) * 生成代码(自定义路径)
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:code')") @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/genCode/{tableName}") @GetMapping("/genCode/{tableName}")
public AjaxResult genCode(@PathVariable("tableName") String tableName) { public AjaxResult genCode(@PathVariable("tableName") String tableName) {
boolean start = genTableService.generatorCode(tableName); boolean start = genTableService.generatorCode(tableName);
@ -188,7 +187,7 @@ public class GenController extends GenBaseController {
* 同步数据库 * 同步数据库
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:edit')") @PreAuthorize("@ebts.hasPermi('tool:gen:edit')")
@Log(title = "代码生成", businessType = GenBusinessType.UPDATE) @Log(title = "代码生成", businessType = BusinessType.UPDATE)
@GetMapping("/synchDb/{tableName}") @GetMapping("/synchDb/{tableName}")
public AjaxResult synchDb(@PathVariable("tableName") String tableName) { public AjaxResult synchDb(@PathVariable("tableName") String tableName) {
genTableService.synchDb(tableName); genTableService.synchDb(tableName);
@ -199,7 +198,7 @@ public class GenController extends GenBaseController {
* 批量生成代码 * 批量生成代码
*/ */
@PreAuthorize("@ebts.hasPermi('tool:gen:code')") @PreAuthorize("@ebts.hasPermi('tool:gen:code')")
@Log(title = "代码生成", businessType = GenBusinessType.GENCODE) @Log(title = "代码生成", businessType = BusinessType.GENCODE)
@GetMapping("/batchGenCode") @GetMapping("/batchGenCode")
public void batchGenCode(HttpServletResponse response, String tables) throws IOException { public void batchGenCode(HttpServletResponse response, String tables) throws IOException {
String[] tableNames = Convert.toStrArray(tables); String[] tableNames = Convert.toStrArray(tables);

View File

@ -5,12 +5,13 @@ import java.io.Serializable;
import java.util.Map; import java.util.Map;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.AjaxResult;
import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dto.InterTableDto; import com.ebts.generator.dto.InterTableDto;
import com.ebts.generator.enums.GenBusinessType;
import com.ebts.generator.utils.GenBaseController;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenServerResult;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -37,7 +38,7 @@ import javax.servlet.http.HttpServletResponse;
@RestController @RestController
@RequestMapping("/generator/intertable") @RequestMapping("/generator/intertable")
public class InterTableController extends GenBaseController { public class InterTableController extends BaseController {
protected final Logger logger = LoggerFactory.getLogger(InterTableController.class); protected final Logger logger = LoggerFactory.getLogger(InterTableController.class);
@Autowired @Autowired
@ -49,11 +50,11 @@ public class InterTableController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('generator:intertable:list')") @PreAuthorize("@ebts.hasPermi('generator:intertable:list')")
@GetMapping("/list") @GetMapping("/list")
public Serializable list(InterTable interTable) { public Serializable list(InterTable interTable) {
GenServerResult<Map<String, Object>> genServerResult = interTableService.selectInterTableList(interTable); ServerResult<Map<String, Object>> ServerResult = interTableService.selectInterTableList(interTable);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -62,14 +63,14 @@ public class InterTableController extends GenBaseController {
*/ */
@PreAuthorize("@ebts.hasPermi('generator:intertable:classpreview')") @PreAuthorize("@ebts.hasPermi('generator:intertable:classpreview')")
@Log(title = "预览代码(工作流)", businessType = GenBusinessType.GENCODE) @Log(title = "预览代码(工作流)", businessType = BusinessType.GENCODE)
@GetMapping("/classpreview/{id}") @GetMapping("/classpreview/{id}")
public AjaxResult classPreview(@PathVariable("id") Long id) { public AjaxResult classPreview(@PathVariable("id") Long id) {
GenServerResult<Map<String, String>> genServerResult = interTableService.previewCodeCalss(id); ServerResult<Map<String, String>> ServerResult = interTableService.previewCodeCalss(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -77,14 +78,14 @@ public class InterTableController extends GenBaseController {
* 预览代码(工作台) * 预览代码(工作台)
*/ */
@PreAuthorize("@ebts.hasPermi('generator:intertable:modulepreview')") @PreAuthorize("@ebts.hasPermi('generator:intertable:modulepreview')")
@Log(title = "预览代码(工作台)", businessType = GenBusinessType.GENCODE) @Log(title = "预览代码(工作台)", businessType = BusinessType.GENCODE)
@GetMapping("/modulepreview/{id}") @GetMapping("/modulepreview/{id}")
public AjaxResult modulePreview(@PathVariable("id") Long id) { public AjaxResult modulePreview(@PathVariable("id") Long id) {
GenServerResult<Map<String, Object>> genServerResult = interTableService.previewCodeMoudle(id); ServerResult<Map<String, Object>> ServerResult = interTableService.previewCodeMoudle(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -96,16 +97,16 @@ public class InterTableController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('generator:intertable:classgen')") @PreAuthorize("@ebts.hasPermi('generator:intertable:classgen')")
@Log(title = "生成代码(工作流)", businessType = GenBusinessType.GENCODE) @Log(title = "生成代码(工作流)", businessType = BusinessType.GENCODE)
@GetMapping("/classgen/{id}") @GetMapping("/classgen/{id}")
public AjaxResult classGenerator(@PathVariable("id") Long id, HttpServletResponse response) { public AjaxResult classGenerator(@PathVariable("id") Long id, HttpServletResponse response) {
try { try {
GenServerResult<byte[]> genServerResult = interTableService.generatorCodeClass(id); ServerResult<byte[]> ServerResult = interTableService.generatorCodeClass(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
genCode(response, genServerResult.getData()); genCode(response, ServerResult.getData());
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
@ -121,20 +122,20 @@ public class InterTableController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('generator:intertable:moudlegen')") @PreAuthorize("@ebts.hasPermi('generator:intertable:moudlegen')")
@Log(title = "生成代码(工作台)", businessType = GenBusinessType.GENCODE) @Log(title = "生成代码(工作台)", businessType = BusinessType.GENCODE)
@GetMapping("/moudlegen/{id}") @GetMapping("/moudlegen/{id}")
public AjaxResult moudleGenerator(@PathVariable("id") Long id, HttpServletResponse response) { public AjaxResult moudleGenerator(@PathVariable("id") Long id, HttpServletResponse response) {
try { try {
GenServerResult<byte[]> genServerResult = interTableService.generatorCodeMoudle(id); ServerResult<byte[]> ServerResult = interTableService.generatorCodeMoudle(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
genCode(response, genServerResult.getData()); genCode(response, ServerResult.getData());
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} catch (RuntimeException | IOException e) { } catch (RuntimeException | IOException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
return AjaxResult.error(GenReturnConstants.SYS_ERROR); return AjaxResult.error(ReturnConstants.SYS_ERROR);
} }
} }
@ -143,14 +144,14 @@ public class InterTableController extends GenBaseController {
* 修改接口信息 * 修改接口信息
*/ */
@PreAuthorize("@ebts.hasPermi('generator:intertable:edit')") @PreAuthorize("@ebts.hasPermi('generator:intertable:edit')")
@Log(title = "接口信息", businessType = GenBusinessType.UPDATE) @Log(title = "接口信息", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult edit(@Validated @RequestBody InterTableDto interTableDto) { public AjaxResult edit(@Validated @RequestBody InterTableDto interTableDto) {
GenServerResult<Integer> genServerResult = interTableService.updateInterTable(interTableDto); ServerResult<Integer> ServerResult = interTableService.updateInterTable(interTableDto);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -172,11 +173,11 @@ public class InterTableController extends GenBaseController {
// * 导出接口信息列表 // * 导出接口信息列表
// */ // */
// @PreAuthorize("@ebts.hasPermi('generator:intertable:export')") // @PreAuthorize("@ebts.hasPermi('generator:intertable:export')")
// @Log(title = "接口信息", businessType = GenBusinessType.EXPORT) // @Log(title = "接口信息", businessType = BusinessType.EXPORT)
// @GetMapping("/export") // @GetMapping("/export")
// public GenResult export(InterTable interTable) { // public GenResult export(InterTable interTable) {
// try { // try {
// GenServerResult<List<InterTable>> serverResult = interTableService.selectInterTableList(interTable); // ServerResult<List<InterTable>> serverResult = interTableService.selectInterTableList(interTable);
// GenExcelUtil<InterTable> util = new GenExcelUtil<InterTable>(InterTable. class); // GenExcelUtil<InterTable> util = new GenExcelUtil<InterTable>(InterTable. class);
// if (serverResult.isStart()) { // if (serverResult.isStart()) {
// return util.exportExcel(serverResult.getData(), "intertable"); // return util.exportExcel(serverResult.getData(), "intertable");
@ -185,7 +186,7 @@ public class InterTableController extends GenBaseController {
// } // }
// } catch (RuntimeException e) { // } catch (RuntimeException e) {
// logger.error(e.getMessage()); // logger.error(e.getMessage());
// return GenResult.error(GenReturnConstants.SYS_ERROR); // return GenResult.error(ReturnConstants.SYS_ERROR);
// } // }
// } // }
@ -196,7 +197,7 @@ public class InterTableController extends GenBaseController {
// @GetMapping(value = "/{id}") // @GetMapping(value = "/{id}")
// public GenResult Info(@PathVariable("id") Long id) { // public GenResult Info(@PathVariable("id") Long id) {
// try { // try {
// GenServerResult<InterTable> serverResult = interTableService.selectInterTableById(id); // ServerResult<InterTable> serverResult = interTableService.selectInterTableById(id);
// if (serverResult.isStart()) { // if (serverResult.isStart()) {
// return GenResult.success(serverResult.getData()); // return GenResult.success(serverResult.getData());
// } else { // } else {
@ -204,7 +205,7 @@ public class InterTableController extends GenBaseController {
// } // }
// } catch (RuntimeException e) { // } catch (RuntimeException e) {
// logger.error(e.getMessage()); // logger.error(e.getMessage());
// return GenResult.error(GenReturnConstants.SYS_ERROR); // return GenResult.error(ReturnConstants.SYS_ERROR);
// } // }
// } // }
// //
@ -212,11 +213,11 @@ public class InterTableController extends GenBaseController {
// * 新增接口信息 // * 新增接口信息
// */ // */
// @PreAuthorize("@ebts.hasPermi('generator:intertable:add')") // @PreAuthorize("@ebts.hasPermi('generator:intertable:add')")
// @Log(title = "接口信息", businessType = GenBusinessType.INSERT) // @Log(title = "接口信息", businessType = BusinessType.INSERT)
// @PostMapping // @PostMapping
// public GenResult add(@RequestBody InterTable interTable) { // public GenResult add(@RequestBody InterTable interTable) {
// try { // try {
// GenServerResult<Integer> serverResult = interTableService.insertInterTable(interTable); // ServerResult<Integer> serverResult = interTableService.insertInterTable(interTable);
// if (serverResult.isStart()) { // if (serverResult.isStart()) {
// return GenResult.success(); // return GenResult.success();
// } else { // } else {
@ -224,7 +225,7 @@ public class InterTableController extends GenBaseController {
// } // }
// } catch (RuntimeException e) { // } catch (RuntimeException e) {
// logger.error(e.getMessage()); // logger.error(e.getMessage());
// return GenResult.error(GenReturnConstants.SYS_ERROR); // return GenResult.error(ReturnConstants.SYS_ERROR);
// } // }
// } // }
// //
@ -232,14 +233,14 @@ public class InterTableController extends GenBaseController {
// * 删除接口信息 // * 删除接口信息
// */ // */
// @PreAuthorize("@ebts.hasPermi('generator:intertable:remove')") // @PreAuthorize("@ebts.hasPermi('generator:intertable:remove')")
// @Log(title = "接口信息", businessType = GenBusinessType.DELETE) // @Log(title = "接口信息", businessType = BusinessType.DELETE)
// @DeleteMapping("/{ids}") // @DeleteMapping("/{ids}")
// public GenResult remove(@PathVariable Long[] ids) { // public GenResult remove(@PathVariable Long[] ids) {
// try { // try {
// if (ids.length<0){ // if (ids.length<0){
// return GenResult.error("id不能为空!"); // return GenResult.error("id不能为空!");
// } // }
// GenServerResult<Integer> serverResult = interTableService.deleteInterTableByIds(ids); // ServerResult<Integer> serverResult = interTableService.deleteInterTableByIds(ids);
// if (serverResult.isStart()) { // if (serverResult.isStart()) {
// return GenResult.success(); // return GenResult.success();
// } else { // } else {
@ -247,7 +248,7 @@ public class InterTableController extends GenBaseController {
// } // }
// }catch (RuntimeException e){ // }catch (RuntimeException e){
// logger.error(e.getMessage()); // logger.error(e.getMessage());
// return GenResult.error(GenReturnConstants.SYS_ERROR); // return GenResult.error(ReturnConstants.SYS_ERROR);
// } // }
// } // }
} }

View File

@ -4,12 +4,12 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.generator.enums.GenBusinessType; import com.ebts.common.core.controller.BaseController;
import com.ebts.generator.utils.GenBaseController; import com.ebts.common.core.entity.AjaxResult;
import com.ebts.generator.utils.GenReturnConstants; import com.ebts.common.enums.BusinessType;
import com.ebts.generator.utils.GenServerResult; import com.ebts.common.utils.ServerResult;
import com.ebts.generator.utils.poi.GenExcelUtil; import com.ebts.common.utils.poi.ExcelUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -33,7 +33,7 @@ import com.ebts.generator.service.ModuleService;
*/ */
@RestController @RestController
@RequestMapping("/tool/module") @RequestMapping("/tool/module")
public class ModuleController extends GenBaseController { public class ModuleController extends BaseController {
protected final Logger logger = LoggerFactory.getLogger(ModuleController.class); protected final Logger logger = LoggerFactory.getLogger(ModuleController.class);
@Autowired @Autowired
@ -48,11 +48,11 @@ public class ModuleController extends GenBaseController {
@PreAuthorize("@ebts.hasAnyPermi('tool:module:querylist')") @PreAuthorize("@ebts.hasAnyPermi('tool:module:querylist')")
@GetMapping("querylist") @GetMapping("querylist")
public AjaxResult queryList() { public AjaxResult queryList() {
GenServerResult<List<Module>> genServerResult = moduleService.selectModuleList(new Module()); ServerResult<List<Module>> ServerResult = moduleService.selectModuleList(new Module());
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -64,11 +64,11 @@ public class ModuleController extends GenBaseController {
@GetMapping("/list") @GetMapping("/list")
public Serializable list(Module module) { public Serializable list(Module module) {
startPage(); startPage();
GenServerResult<List<Module>> genServerResult = moduleService.selectModuleList(module); ServerResult<List<Module>> ServerResult = moduleService.selectModuleList(module);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -76,15 +76,15 @@ public class ModuleController extends GenBaseController {
* 导出模块管理列表 * 导出模块管理列表
*/ */
@PreAuthorize("@ebts.hasPermi('tool:module:export')") @PreAuthorize("@ebts.hasPermi('tool:module:export')")
@Log(title = "模块管理", businessType = GenBusinessType.EXPORT) @Log(title = "模块管理", businessType = BusinessType.EXPORT)
@GetMapping("/export") @GetMapping("/export")
public AjaxResult export(Module module) { public AjaxResult export(Module module) {
GenServerResult<List<Module>> genServerResult = moduleService.selectModuleList(module); ServerResult<List<Module>> ServerResult = moduleService.selectModuleList(module);
GenExcelUtil<Module> util = new GenExcelUtil<Module>(Module.class); ExcelUtil<Module> util = new ExcelUtil<Module>(Module.class);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return util.exportExcel(genServerResult.getData(), "module"); return util.exportExcel(ServerResult.getData(), "module");
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -94,11 +94,11 @@ public class ModuleController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('tool:module:query')") @PreAuthorize("@ebts.hasPermi('tool:module:query')")
@GetMapping(value = "/{id}") @GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) { public AjaxResult getInfo(@PathVariable("id") Long id) {
GenServerResult<Module> genServerResult = moduleService.selectModuleById(id); ServerResult<Module> ServerResult = moduleService.selectModuleById(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -106,7 +106,7 @@ public class ModuleController extends GenBaseController {
* 新增模块管理 * 新增模块管理
*/ */
@PreAuthorize("@ebts.hasPermi('tool:module:add')") @PreAuthorize("@ebts.hasPermi('tool:module:add')")
@Log(title = "模块管理", businessType = GenBusinessType.INSERT) @Log(title = "模块管理", businessType = BusinessType.INSERT)
@PostMapping @PostMapping
public AjaxResult add(@RequestBody Module module) { public AjaxResult add(@RequestBody Module module) {
if (module.getmName() == null || module.getmName().equals("")) { if (module.getmName() == null || module.getmName().equals("")) {
@ -115,16 +115,11 @@ public class ModuleController extends GenBaseController {
if (module.getmDescribe() == null || module.getmDescribe().equals("")) { if (module.getmDescribe() == null || module.getmDescribe().equals("")) {
return AjaxResult.error("模块描述不能为空!"); return AjaxResult.error("模块描述不能为空!");
} }
try { ServerResult<Integer> ServerResult = moduleService.insertModule(module);
GenServerResult<Integer> genServerResult = moduleService.insertModule(module); if (ServerResult.isStart()) {
if (genServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
}
} catch (RuntimeException e) {
logger.error(e.getMessage());
return AjaxResult.error(GenReturnConstants.SYS_ERROR);
} }
} }
@ -132,7 +127,7 @@ public class ModuleController extends GenBaseController {
* 修改模块管理 * 修改模块管理
*/ */
@PreAuthorize("@ebts.hasPermi('tool:module:edit')") @PreAuthorize("@ebts.hasPermi('tool:module:edit')")
@Log(title = "模块管理", businessType = GenBusinessType.UPDATE) @Log(title = "模块管理", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult edit(@RequestBody Module module) { public AjaxResult edit(@RequestBody Module module) {
if (module.getmName() == null || module.getmName().equals("")) { if (module.getmName() == null || module.getmName().equals("")) {
@ -141,11 +136,11 @@ public class ModuleController extends GenBaseController {
if (module.getmDescribe() == null || module.getmDescribe().equals("")) { if (module.getmDescribe() == null || module.getmDescribe().equals("")) {
return AjaxResult.error("模块描述不能为空!"); return AjaxResult.error("模块描述不能为空!");
} }
GenServerResult<Integer> genServerResult = moduleService.updateModule(module); ServerResult<Integer> ServerResult = moduleService.updateModule(module);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -153,17 +148,17 @@ public class ModuleController extends GenBaseController {
* 删除模块管理 * 删除模块管理
*/ */
@PreAuthorize("@ebts.hasPermi('tool:module:remove')") @PreAuthorize("@ebts.hasPermi('tool:module:remove')")
@Log(title = "模块管理", businessType = GenBusinessType.DELETE) @Log(title = "模块管理", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}") @DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) { public AjaxResult remove(@PathVariable Long[] ids) {
if (ids.length < 0) { if (ids.length < 0) {
return AjaxResult.error("id不能为空!"); return AjaxResult.error("id不能为空!");
} }
GenServerResult<Integer> genServerResult = moduleService.deleteModuleByIds(ids); ServerResult<Integer> ServerResult = moduleService.deleteModuleByIds(ids);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
} }

View File

@ -1,11 +1,16 @@
package com.ebts.generator.controller; package com.ebts.generator.controller;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.AjaxResult;
import com.ebts.common.utils.MapExcelUtil;
import com.ebts.common.utils.ServerResult;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.utils.sql.GenSqlUtil;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import com.ebts.generator.entity.UniCon; import com.ebts.generator.entity.UniCon;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.service.QueryService; import com.ebts.generator.service.QueryService;
import com.ebts.generator.utils.*; import com.ebts.generator.utils.*;
import com.ebts.generator.utils.sql.GenSqlUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -26,7 +31,7 @@ import java.util.Map;
*/ */
@RestController @RestController
@RequestMapping("/query") @RequestMapping("/query")
public class QueryController extends GenBaseController { public class QueryController extends BaseController {
private Logger logger = LoggerFactory.getLogger(QueryController.class); private Logger logger = LoggerFactory.getLogger(QueryController.class);
@ -42,9 +47,9 @@ public class QueryController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('query:list')") @PreAuthorize("@ebts.hasPermi('query:list')")
@GetMapping("/{id}") @GetMapping("/{id}")
public AjaxResult Info(@PathVariable("id") Long id) { public AjaxResult Info(@PathVariable("id") Long id) {
GenServerResult<UniQuery> genServerResult = queryService.selectQueryById(id); ServerResult<UniQuery> ServerResult = queryService.selectQueryById(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
UniQuery uniQuery = genServerResult.getData(); UniQuery uniQuery = ServerResult.getData();
Map<String, Object> modeMap = new HashMap<>(); Map<String, Object> modeMap = new HashMap<>();
List<UniCon> uniCons = uniQuery.getUniCons(); List<UniCon> uniCons = uniQuery.getUniCons();
uniQuery.setUniCons(null); uniQuery.setUniCons(null);
@ -52,7 +57,7 @@ public class QueryController extends GenBaseController {
modeMap.put("list", uniCons); modeMap.put("list", uniCons);
return AjaxResult.success(modeMap); return AjaxResult.success(modeMap);
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -65,11 +70,11 @@ public class QueryController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('query:edit')") @PreAuthorize("@ebts.hasPermi('query:edit')")
@PutMapping @PutMapping
public AjaxResult edit(@Validated @RequestBody UniQuery uniQuery) { public AjaxResult edit(@Validated @RequestBody UniQuery uniQuery) {
GenServerResult genServerResult = queryService.updateQueryInfo(uniQuery); ServerResult ServerResult = queryService.updateQueryInfo(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -82,11 +87,11 @@ public class QueryController extends GenBaseController {
@PreAuthorize("@ebts.hasAnyPermi('query:export')") @PreAuthorize("@ebts.hasAnyPermi('query:export')")
@PutMapping("export") @PutMapping("export")
public AjaxResult export(@Validated @RequestBody UniQuery uniQuery) { public AjaxResult export(@Validated @RequestBody UniQuery uniQuery) {
GenServerResult<List<Map<String, Object>>> genServerResult = queryService.previewQuery(uniQuery); ServerResult<List<Map<String, Object>>> ServerResult = queryService.previewQuery(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return new GenMapExcelUtil().exportExcel(genServerResult.getData(), uniQuery.getUqName()); return new MapExcelUtil().exportExcel(ServerResult.getData(), uniQuery.getUqName());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -100,11 +105,11 @@ public class QueryController extends GenBaseController {
@PutMapping("preview") @PutMapping("preview")
public Serializable Preview(@Validated @RequestBody UniQuery uniQuery) { public Serializable Preview(@Validated @RequestBody UniQuery uniQuery) {
startPage(uniQuery); startPage(uniQuery);
GenServerResult<List<Map<String, Object>>> genServerResult = queryService.previewQuery(uniQuery); ServerResult<List<Map<String, Object>>> ServerResult = queryService.previewQuery(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -121,11 +126,11 @@ public class QueryController extends GenBaseController {
return AjaxResult.error("id不能为空!"); return AjaxResult.error("id不能为空!");
} else { } else {
if (uniQuery.getIsRelease() == 1 || uniQuery.getIsRelease() == 2) { if (uniQuery.getIsRelease() == 1 || uniQuery.getIsRelease() == 2) {
GenServerResult<Integer> genServerResult = queryService.Release(uniQuery); ServerResult<Integer> ServerResult = queryService.Release(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} else { } else {
return AjaxResult.error("状态输入错误!"); return AjaxResult.error("状态输入错误!");
@ -139,7 +144,7 @@ public class QueryController extends GenBaseController {
protected void startPage(UniQuery uniQuery) { protected void startPage(UniQuery uniQuery) {
Integer pageNum = uniQuery.getPageNum(); Integer pageNum = uniQuery.getPageNum();
Integer pageSize = uniQuery.getPageSize(); Integer pageSize = uniQuery.getPageSize();
if (GenStringUtils.isNotNull(pageNum) && GenStringUtils.isNotNull(pageSize)) { if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
String orderBy = GenSqlUtil.escapeOrderBySql(""); String orderBy = GenSqlUtil.escapeOrderBySql("");
PageHelper.startPage(pageNum, pageSize, orderBy); PageHelper.startPage(pageNum, pageSize, orderBy);
} }

View File

@ -4,14 +4,14 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.AjaxResult;
import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.ServerResult;
import com.ebts.common.utils.poi.ExcelUtil;
import com.ebts.generator.entity.Regular; import com.ebts.generator.entity.Regular;
import com.ebts.generator.enums.GenBusinessType;
import com.ebts.generator.service.RegularService; import com.ebts.generator.service.RegularService;
import com.ebts.generator.utils.GenBaseController;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.poi.GenExcelUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -33,7 +33,7 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RestController @RestController
@RequestMapping("/tool/regular") @RequestMapping("/tool/regular")
public class RegularController extends GenBaseController { public class RegularController extends BaseController {
protected final Logger logger = LoggerFactory.getLogger(RegularController.class); protected final Logger logger = LoggerFactory.getLogger(RegularController.class);
@Autowired @Autowired
@ -49,11 +49,11 @@ public class RegularController extends GenBaseController {
@GetMapping("/list") @GetMapping("/list")
public Serializable list(Regular regular) { public Serializable list(Regular regular) {
startPage(); startPage();
GenServerResult<List<Regular>> genServerResult = regularService.selectRegularList(regular); ServerResult<List<Regular>> ServerResult = regularService.selectRegularList(regular);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -66,11 +66,11 @@ public class RegularController extends GenBaseController {
@GetMapping("/option") @GetMapping("/option")
public Serializable option() { public Serializable option() {
startPage(); startPage();
GenServerResult<List<Regular>> genServerResult = regularService.selectRegularOption(); ServerResult<List<Regular>> ServerResult = regularService.selectRegularOption();
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -81,15 +81,15 @@ public class RegularController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('tool:regular:export')") @PreAuthorize("@ebts.hasPermi('tool:regular:export')")
@Log(title = "校验规则", businessType = GenBusinessType.EXPORT) @Log(title = "校验规则", businessType = BusinessType.EXPORT)
@GetMapping("/export") @GetMapping("/export")
public AjaxResult export(Regular regular) { public AjaxResult export(Regular regular) {
GenServerResult<List<Regular>> genServerResult = regularService.selectRegularList(regular); ServerResult<List<Regular>> ServerResult = regularService.selectRegularList(regular);
GenExcelUtil<Regular> util = new GenExcelUtil<Regular>(Regular.class); ExcelUtil<Regular> util = new ExcelUtil<Regular>(Regular.class);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return util.exportExcel(genServerResult.getData(), "regular"); return util.exportExcel(ServerResult.getData(), "regular");
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -102,11 +102,11 @@ public class RegularController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('tool:regular:query')") @PreAuthorize("@ebts.hasPermi('tool:regular:query')")
@GetMapping(value = "/{id}") @GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) { public AjaxResult getInfo(@PathVariable("id") Long id) {
GenServerResult<Regular> genServerResult = regularService.selectRegularById(id); ServerResult<Regular> ServerResult = regularService.selectRegularById(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -117,7 +117,7 @@ public class RegularController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('tool:regular:add')") @PreAuthorize("@ebts.hasPermi('tool:regular:add')")
@Log(title = "校验规则", businessType = GenBusinessType.INSERT) @Log(title = "校验规则", businessType = BusinessType.INSERT)
@PostMapping @PostMapping
public AjaxResult add(@RequestBody Regular regular) { public AjaxResult add(@RequestBody Regular regular) {
if (regular.getName() == null || regular.getName().equals("")) { if (regular.getName() == null || regular.getName().equals("")) {
@ -132,11 +132,11 @@ public class RegularController extends GenBaseController {
if (!verifyRegular(regular)) { if (!verifyRegular(regular)) {
return AjaxResult.error("正则表达式校验不通过!"); return AjaxResult.error("正则表达式校验不通过!");
} }
GenServerResult<Integer> genServerResult = regularService.insertRegular(regular); ServerResult<Integer> ServerResult = regularService.insertRegular(regular);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -147,7 +147,7 @@ public class RegularController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('tool:regular:edit')") @PreAuthorize("@ebts.hasPermi('tool:regular:edit')")
@Log(title = "校验规则", businessType = GenBusinessType.UPDATE) @Log(title = "校验规则", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult edit(@RequestBody Regular regular) { public AjaxResult edit(@RequestBody Regular regular) {
if (regular.getName() == null || regular.getName().equals("")) { if (regular.getName() == null || regular.getName().equals("")) {
@ -162,11 +162,11 @@ public class RegularController extends GenBaseController {
if (!verifyRegular(regular)) { if (!verifyRegular(regular)) {
return AjaxResult.error("正则表达式校验不通过!"); return AjaxResult.error("正则表达式校验不通过!");
} }
GenServerResult<Integer> genServerResult = regularService.updateRegular(regular); ServerResult<Integer> ServerResult = regularService.updateRegular(regular);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -177,17 +177,17 @@ public class RegularController extends GenBaseController {
* @return * @return
*/ */
@PreAuthorize("@ebts.hasPermi('tool:regular:remove')") @PreAuthorize("@ebts.hasPermi('tool:regular:remove')")
@Log(title = "校验规则", businessType = GenBusinessType.DELETE) @Log(title = "校验规则", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}") @DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) { public AjaxResult remove(@PathVariable Long[] ids) {
if (ids.length == 0) { if (ids.length == 0) {
return AjaxResult.error("需要删除id数不能为空!"); return AjaxResult.error("需要删除id数不能为空!");
} }
GenServerResult<Integer> genServerResult = regularService.deleteRegularByIds(ids); ServerResult<Integer> ServerResult = regularService.deleteRegularByIds(ids);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }

View File

@ -1,9 +1,10 @@
package com.ebts.generator.controller; package com.ebts.generator.controller;
import com.ebts.common.core.entity.AjaxResult;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.RelColumn; import com.ebts.generator.entity.RelColumn;
import com.ebts.generator.entity.RelTable; import com.ebts.generator.entity.RelTable;
import com.ebts.generator.service.RelService; import com.ebts.generator.service.RelService;
import com.ebts.generator.utils.GenServerResult;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -36,11 +37,11 @@ public class RelController {
@PreAuthorize("@ebts.hasAnyPermi('rel:tableinfo')") @PreAuthorize("@ebts.hasAnyPermi('rel:tableinfo')")
@GetMapping("/tableinfo") @GetMapping("/tableinfo")
public AjaxResult tableinfos() { public AjaxResult tableinfos() {
GenServerResult<List<Map<String, Object>>> genServerResult = relService.tableInfos(); ServerResult<List<Map<String, Object>>> ServerResult = relService.tableInfos();
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -54,33 +55,33 @@ public class RelController {
@PreAuthorize("@ebts.hasAnyPermi('rel:tableinfo')") @PreAuthorize("@ebts.hasAnyPermi('rel:tableinfo')")
@GetMapping("/{tableName}/{relId}") @GetMapping("/{tableName}/{relId}")
public AjaxResult relColumns(@PathVariable("tableName") String tableName, @PathVariable("relId") Long relId) { public AjaxResult relColumns(@PathVariable("tableName") String tableName, @PathVariable("relId") Long relId) {
GenServerResult<List<RelColumn>> genServerResult = relService.relColumns(tableName, relId); ServerResult<List<RelColumn>> ServerResult = relService.relColumns(tableName, relId);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@PreAuthorize("@ebts.hasAnyPermi('rel:colums')") @PreAuthorize("@ebts.hasAnyPermi('rel:colums')")
@GetMapping("/{tableName}") @GetMapping("/{tableName}")
public AjaxResult tableColumns(@PathVariable("tableName") String tableName) { public AjaxResult tableColumns(@PathVariable("tableName") String tableName) {
GenServerResult<List<Map<String, Object>>> genServerResult = relService.tableColumns(tableName); ServerResult<List<Map<String, Object>>> ServerResult = relService.tableColumns(tableName);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@PreAuthorize("@ebts.hasAnyPermi('rel:colums')") @PreAuthorize("@ebts.hasAnyPermi('rel:colums')")
@GetMapping("/colums/{tableId}") @GetMapping("/colums/{tableId}")
public AjaxResult relTableByTableId(@PathVariable("tableId") Long tableId) { public AjaxResult relTableByTableId(@PathVariable("tableId") Long tableId) {
GenServerResult<List<RelTable>> genServerResult = relService.relTableByTableId(tableId); ServerResult<List<RelTable>> ServerResult = relService.relTableByTableId(tableId);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }

View File

@ -4,14 +4,14 @@ import java.io.Serializable;
import java.util.List; import java.util.List;
import com.ebts.generator.aop.Log; import com.ebts.common.annotation.Log;
import com.ebts.common.core.controller.BaseController;
import com.ebts.common.core.entity.AjaxResult;
import com.ebts.common.enums.BusinessType;
import com.ebts.common.utils.ServerResult;
import com.ebts.common.utils.poi.ExcelUtil;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.enums.GenBusinessType;
import com.ebts.generator.service.UniQueryService; import com.ebts.generator.service.UniQueryService;
import com.ebts.generator.utils.GenBaseController;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.poi.GenExcelUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.access.prepost.PreAuthorize;
@ -33,7 +33,7 @@ import org.springframework.web.bind.annotation.RestController;
*/ */
@RestController @RestController
@RequestMapping("/tool/query") @RequestMapping("/tool/query")
public class UniQueryController extends GenBaseController { public class UniQueryController extends BaseController {
protected final Logger logger = LoggerFactory.getLogger(UniQueryController.class); protected final Logger logger = LoggerFactory.getLogger(UniQueryController.class);
@Autowired @Autowired
@ -46,11 +46,11 @@ public class UniQueryController extends GenBaseController {
@GetMapping("/list") @GetMapping("/list")
public Serializable list(UniQuery uniQuery) { public Serializable list(UniQuery uniQuery) {
startPage(); startPage();
GenServerResult<List<UniQuery>> genServerResult = uniQueryService.selectUniQueryList(uniQuery); ServerResult<List<UniQuery>> ServerResult = uniQueryService.selectUniQueryList(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return getDataTable(genServerResult.getData()); return getDataTable(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -58,15 +58,15 @@ public class UniQueryController extends GenBaseController {
* 导出万能查询列表 * 导出万能查询列表
*/ */
@PreAuthorize("@ebts.hasPermi('tool:query:export')") @PreAuthorize("@ebts.hasPermi('tool:query:export')")
@Log(title = "万能查询", businessType = GenBusinessType.EXPORT) @Log(title = "万能查询", businessType = BusinessType.EXPORT)
@GetMapping("/export") @GetMapping("/export")
public AjaxResult export(UniQuery uniQuery) { public AjaxResult export(UniQuery uniQuery) {
GenServerResult<List<UniQuery>> genServerResult = uniQueryService.selectUniQueryList(uniQuery); ServerResult<List<UniQuery>> ServerResult = uniQueryService.selectUniQueryList(uniQuery);
GenExcelUtil<UniQuery> util = new GenExcelUtil<UniQuery>(UniQuery.class); ExcelUtil<UniQuery> util = new ExcelUtil<UniQuery>(UniQuery.class);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return util.exportExcel(genServerResult.getData(), "query"); return util.exportExcel(ServerResult.getData(), "query");
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -76,11 +76,11 @@ public class UniQueryController extends GenBaseController {
@PreAuthorize("@ebts.hasPermi('tool:query:query')") @PreAuthorize("@ebts.hasPermi('tool:query:query')")
@GetMapping(value = "/{id}") @GetMapping(value = "/{id}")
public AjaxResult getInfo(@PathVariable("id") Long id) { public AjaxResult getInfo(@PathVariable("id") Long id) {
GenServerResult<UniQuery> genServerResult = uniQueryService.selectUniQueryById(id); ServerResult<UniQuery> ServerResult = uniQueryService.selectUniQueryById(id);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(genServerResult.getData()); return AjaxResult.success(ServerResult.getData());
} else { } else {
return AjaxResult.info(genServerResult.getMsg()); return AjaxResult.info(ServerResult.getMsg());
} }
} }
@ -88,7 +88,7 @@ public class UniQueryController extends GenBaseController {
* 新增万能查询 * 新增万能查询
*/ */
@PreAuthorize("@ebts.hasPermi('tool:query:add')") @PreAuthorize("@ebts.hasPermi('tool:query:add')")
@Log(title = "万能查询", businessType = GenBusinessType.INSERT) @Log(title = "万能查询", businessType = BusinessType.INSERT)
@PostMapping @PostMapping
public AjaxResult add(@RequestBody UniQuery uniQuery) { public AjaxResult add(@RequestBody UniQuery uniQuery) {
if (uniQuery.getUqName() == null || uniQuery.getUqName().equals("")) { if (uniQuery.getUqName() == null || uniQuery.getUqName().equals("")) {
@ -97,11 +97,11 @@ public class UniQueryController extends GenBaseController {
if (uniQuery.getUqDescribe() == null || uniQuery.getUqDescribe().equals("")) { if (uniQuery.getUqDescribe() == null || uniQuery.getUqDescribe().equals("")) {
return AjaxResult.error("描述不能为空!"); return AjaxResult.error("描述不能为空!");
} }
GenServerResult<Integer> genServerResult = uniQueryService.insertUniQuery(uniQuery); ServerResult<Integer> ServerResult = uniQueryService.insertUniQuery(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -109,7 +109,7 @@ public class UniQueryController extends GenBaseController {
* 简单修改万能能查询 * 简单修改万能能查询
*/ */
@PreAuthorize("@ebts.hasPermi('tool:query:edit')") @PreAuthorize("@ebts.hasPermi('tool:query:edit')")
@Log(title = "万能查询", businessType = GenBusinessType.UPDATE) @Log(title = "万能查询", businessType = BusinessType.UPDATE)
@PutMapping @PutMapping
public AjaxResult edit(@RequestBody UniQuery uniQuery) { public AjaxResult edit(@RequestBody UniQuery uniQuery) {
if (uniQuery.getUqName() == null || uniQuery.getUqName().equals("")) { if (uniQuery.getUqName() == null || uniQuery.getUqName().equals("")) {
@ -118,11 +118,11 @@ public class UniQueryController extends GenBaseController {
if (uniQuery.getUqDescribe() == null || uniQuery.getUqDescribe().equals("")) { if (uniQuery.getUqDescribe() == null || uniQuery.getUqDescribe().equals("")) {
return AjaxResult.error("描述不能为空!"); return AjaxResult.error("描述不能为空!");
} }
GenServerResult<Integer> genServerResult = uniQueryService.updateUniQuery(uniQuery); ServerResult<Integer> ServerResult = uniQueryService.updateUniQuery(uniQuery);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
@ -130,17 +130,17 @@ public class UniQueryController extends GenBaseController {
* 删除万能查询 * 删除万能查询
*/ */
@PreAuthorize("@ebts.hasPermi('tool:query:remove')") @PreAuthorize("@ebts.hasPermi('tool:query:remove')")
@Log(title = "万能查询", businessType = GenBusinessType.DELETE) @Log(title = "万能查询", businessType = BusinessType.DELETE)
@DeleteMapping("/{ids}") @DeleteMapping("/{ids}")
public AjaxResult remove(@PathVariable Long[] ids) { public AjaxResult remove(@PathVariable Long[] ids) {
if (ids.length < 0) { if (ids.length < 0) {
return AjaxResult.error("id不能为空!"); return AjaxResult.error("id不能为空!");
} }
GenServerResult<Integer> genServerResult = uniQueryService.deleteUniQueryByIds(ids); ServerResult<Integer> ServerResult = uniQueryService.deleteUniQueryByIds(ids);
if (genServerResult.isStart()) { if (ServerResult.isStart()) {
return AjaxResult.success(); return AjaxResult.success();
} else { } else {
return AjaxResult.error(genServerResult.getMsg()); return AjaxResult.error(ServerResult.getMsg());
} }
} }
} }

View File

@ -1,8 +1,8 @@
package com.ebts.generator.dao; package com.ebts.generator.dao;
import com.ebts.common.core.entity.entity.Menu;
import com.ebts.generator.entity.UniCon; import com.ebts.generator.entity.UniCon;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.utils.entity.GenMenu;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -58,10 +58,10 @@ public interface QueryDao {
/** /**
* 插入到菜单 * 插入到菜单
* @param genMenu * @param menu
* @return * @return
*/ */
Integer insertMenu(GenMenu genMenu); Integer insertMenu(Menu menu);
/** /**
* 删除菜单 * 删除菜单

View File

@ -1,6 +1,7 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.generator.aop.Excel; import com.ebts.common.annotation.Excel;
import com.ebts.common.core.entity.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
@ -13,7 +14,7 @@ import java.util.List;
* @author binlin * @author binlin
* @date 2021-01-24 * @date 2021-01-24
*/ */
public class ApiClass extends GenBaseEntity { public class ApiClass extends BaseEntity {
/** /**

View File

@ -1,131 +0,0 @@
package com.ebts.generator.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.ebts.generator.aop.Excel;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* Entity基类
*
* @author binlin
*/
public class GenBaseEntity implements Serializable {
/**
* 创建者
*/
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<String, Object> params;
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<String, Object> getParams() {
if (params == null) {
params = new HashMap<>();
}
return params;
}
public void setParams(Map<String, Object> params) {
this.params = params;
}
}

View File

@ -4,7 +4,8 @@ import java.util.List;
import javax.validation.Valid; import javax.validation.Valid;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
import com.ebts.generator.utils.GenStringUtils; import com.ebts.common.core.entity.BaseEntity;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.utils.constant.GenConstants; import com.ebts.generator.utils.constant.GenConstants;
import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.ArrayUtils;
@ -13,7 +14,7 @@ import org.apache.commons.lang3.ArrayUtils;
* *
* @author binlin * @author binlin
*/ */
public class GenTable extends GenBaseEntity { public class GenTable extends BaseEntity {
/** /**
@ -395,7 +396,7 @@ public class GenTable extends GenBaseEntity {
} }
public static boolean isSub(String tplCategory) { public static boolean isSub(String tplCategory) {
return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_SUB, tplCategory); return tplCategory != null && StringUtils.equals(GenConstants.TPL_SUB, tplCategory);
} }
public boolean isTree() { public boolean isTree() {
@ -403,7 +404,7 @@ public class GenTable extends GenBaseEntity {
} }
public static boolean isTree(String tplCategory) { public static boolean isTree(String tplCategory) {
return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_TREE, tplCategory); return tplCategory != null && StringUtils.equals(GenConstants.TPL_TREE, tplCategory);
} }
public boolean isCrud() { public boolean isCrud() {
@ -411,7 +412,7 @@ public class GenTable extends GenBaseEntity {
} }
public static boolean isCrud(String tplCategory) { public static boolean isCrud(String tplCategory) {
return tplCategory != null && GenStringUtils.equals(GenConstants.TPL_CRUD, tplCategory); return tplCategory != null && StringUtils.equals(GenConstants.TPL_CRUD, tplCategory);
} }
public boolean isSuperColumn(String javaField) { public boolean isSuperColumn(String javaField) {
@ -420,9 +421,9 @@ public class GenTable extends GenBaseEntity {
public static boolean isSuperColumn(String tplCategory, String javaField) { public static boolean isSuperColumn(String tplCategory, String javaField) {
if (isTree(tplCategory)) { if (isTree(tplCategory)) {
return GenStringUtils.equalsAnyIgnoreCase(javaField, return StringUtils.equalsAnyIgnoreCase(javaField,
ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY)); ArrayUtils.addAll(GenConstants.TREE_ENTITY, GenConstants.BASE_ENTITY));
} }
return GenStringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY); return StringUtils.equalsAnyIgnoreCase(javaField, GenConstants.BASE_ENTITY);
} }
} }

View File

@ -1,6 +1,7 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.generator.utils.GenStringUtils; import com.ebts.common.core.entity.BaseEntity;
import com.ebts.common.utils.StringUtils;
import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotBlank;
@ -10,7 +11,7 @@ import javax.validation.constraints.NotBlank;
* *
* @author binlin * @author binlin
*/ */
public class GenTableColumn extends GenBaseEntity { public class GenTableColumn extends BaseEntity {
/** /**
@ -188,7 +189,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public String getCapJavaField() { public String getCapJavaField() {
return GenStringUtils.capitalize(javaField); return StringUtils.capitalize(javaField);
} }
public void setIsPk(String isPk) { public void setIsPk(String isPk) {
@ -204,7 +205,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isPk(String isPk) { public boolean isPk(String isPk) {
return isPk != null && GenStringUtils.equals("1", isPk); return isPk != null && StringUtils.equals("1", isPk);
} }
public String getIsIncrement() { public String getIsIncrement() {
@ -220,7 +221,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isIncrement(String isIncrement) { public boolean isIncrement(String isIncrement) {
return isIncrement != null && GenStringUtils.equals("1", isIncrement); return isIncrement != null && StringUtils.equals("1", isIncrement);
} }
public void setIsRequired(String isRequired) { public void setIsRequired(String isRequired) {
@ -236,7 +237,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isRequired(String isRequired) { public boolean isRequired(String isRequired) {
return isRequired != null && GenStringUtils.equals("1", isRequired); return isRequired != null && StringUtils.equals("1", isRequired);
} }
public void setIsInsert(String isInsert) { public void setIsInsert(String isInsert) {
@ -252,7 +253,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isInsert(String isInsert) { public boolean isInsert(String isInsert) {
return isInsert != null && GenStringUtils.equals("1", isInsert); return isInsert != null && StringUtils.equals("1", isInsert);
} }
public void setIsEdit(String isEdit) { public void setIsEdit(String isEdit) {
@ -268,7 +269,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isEdit(String isEdit) { public boolean isEdit(String isEdit) {
return isEdit != null && GenStringUtils.equals("1", isEdit); return isEdit != null && StringUtils.equals("1", isEdit);
} }
public void setIsList(String isList) { public void setIsList(String isList) {
@ -284,7 +285,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isList(String isList) { public boolean isList(String isList) {
return isList != null && GenStringUtils.equals("1", isList); return isList != null && StringUtils.equals("1", isList);
} }
public void setIsQuery(String isQuery) { public void setIsQuery(String isQuery) {
@ -300,7 +301,7 @@ public class GenTableColumn extends GenBaseEntity {
} }
public boolean isQuery(String isQuery) { public boolean isQuery(String isQuery) {
return isQuery != null && GenStringUtils.equals("1", isQuery); return isQuery != null && StringUtils.equals("1", isQuery);
} }
public void setQueryType(String queryType) { public void setQueryType(String queryType) {
@ -340,8 +341,8 @@ public class GenTableColumn extends GenBaseEntity {
} }
public static boolean isSuperColumn(String javaField) { public static boolean isSuperColumn(String javaField) {
return GenStringUtils.equalsAnyIgnoreCase(javaField, return StringUtils.equalsAnyIgnoreCase(javaField,
// GenBaseEntity // BaseEntity
"createBy", "createTime", "updateBy", "updateTime", "remark", "createBy", "createTime", "updateBy", "updateTime", "remark",
// TreeEntity // TreeEntity
"parentName", "parentId", "orderNum", "ancestors"); "parentName", "parentId", "orderNum", "ancestors");
@ -353,15 +354,15 @@ public class GenTableColumn extends GenBaseEntity {
public static boolean isUsableColumn(String javaField) { public static boolean isUsableColumn(String javaField) {
// isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单 // isSuperColumn()中的名单用于避免生成多余Domain属性,若某些属性在生成页面时需要用到不能忽略,则放在此处白名单
return GenStringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark"); return StringUtils.equalsAnyIgnoreCase(javaField, "parentId", "orderNum", "remark");
} }
public String readConverterExp() { public String readConverterExp() {
String remarks = GenStringUtils.substringBetween(this.columnComment, "(", ")"); String remarks = StringUtils.substringBetween(this.columnComment, "(", ")");
StringBuffer sb = new StringBuffer(); StringBuffer sb = new StringBuffer();
if (GenStringUtils.isNotEmpty(remarks)) { if (StringUtils.isNotEmpty(remarks)) {
for (String value : remarks.split(" ")) { for (String value : remarks.split(" ")) {
if (GenStringUtils.isNotEmpty(value)) { if (StringUtils.isNotEmpty(value)) {
Object startStr = value.subSequence(0, 1); Object startStr = value.subSequence(0, 1);
String endStr = value.substring(1); String endStr = value.substring(1);
sb.append("").append(startStr).append("=").append(endStr).append(","); sb.append("").append(startStr).append("=").append(endStr).append(",");

View File

@ -1,7 +1,7 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.common.annotation.Excel;
import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonFormat;
import com.ebts.generator.aop.Excel;
import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModel;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;

View File

@ -1,6 +1,7 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.generator.aop.Excel; import com.ebts.common.annotation.Excel;
import com.ebts.common.core.entity.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
@ -12,7 +13,7 @@ import java.util.List;
* @author binlin * @author binlin
* @date 2021-01-24 * @date 2021-01-24
*/ */
public class Module extends GenBaseEntity { public class Module extends BaseEntity {
/** /**

View File

@ -1,6 +1,7 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.generator.aop.Excel; import com.ebts.common.annotation.Excel;
import com.ebts.common.core.entity.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
@ -10,7 +11,7 @@ import org.apache.commons.lang3.builder.ToStringStyle;
* @author binlin * @author binlin
* @date 2021-01-18 * @date 2021-01-18
*/ */
public class Regular extends GenBaseEntity { public class Regular extends BaseEntity {
/** /**

View File

@ -1,5 +1,6 @@
package com.ebts.generator.entity; package com.ebts.generator.entity;
import com.ebts.common.core.entity.BaseEntity;
import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle; import org.apache.commons.lang3.builder.ToStringStyle;
@ -12,7 +13,7 @@ import java.util.List;
* @author binlin * @author binlin
* @date 2021-01-30 * @date 2021-01-30
*/ */
public class UniQuery extends GenBaseEntity { public class UniQuery extends BaseEntity {
/** /**
* id * id

View File

@ -1,58 +0,0 @@
package com.ebts.generator.enums;
/**
* 业务操作类型
*
* @author binlin
*/
public enum GenBusinessType {
/**
* 其它
*/
OTHER,
/**
* 新增
*/
INSERT,
/**
* 修改
*/
UPDATE,
/**
* 删除
*/
DELETE,
/**
* 授权
*/
GRANT,
/**
* 导出
*/
EXPORT,
/**
* 导入
*/
IMPORT,
/**
* 强退
*/
FORCE,
/**
* 生成代码
*/
GENCODE,
/**
* 清空数据
*/
CLEAN,
}

View File

@ -1,23 +0,0 @@
package com.ebts.generator.enums;
/**
* 操作人类别
*
* @author binlin
*/
public enum GenOperatorType {
/**
* 其它
*/
OTHER,
/**
* 后台用户
*/
MANAGE,
/**
* 手机端用户
*/
MOBILE
}

View File

@ -2,8 +2,8 @@ package com.ebts.generator.service;
import java.util.List; import java.util.List;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.ApiClass; import com.ebts.generator.entity.ApiClass;
import com.ebts.generator.utils.GenServerResult;
/** /**
* 接口类名Service接口 * 接口类名Service接口
@ -18,7 +18,7 @@ public interface ApiClassService {
* @param id 接口类名ID * @param id 接口类名ID
* @return 接口类名 * @return 接口类名
*/ */
GenServerResult<ApiClass> selectApiclassById(Long id); ServerResult<ApiClass> selectApiclassById(Long id);
/** /**
* 查询接口类名列表 * 查询接口类名列表
@ -26,7 +26,7 @@ public interface ApiClassService {
* @param apiclass 接口类名 * @param apiclass 接口类名
* @return 接口类名集合 * @return 接口类名集合
*/ */
GenServerResult<List<ApiClass>> selectApiclassList(ApiClass apiclass); ServerResult<List<ApiClass>> selectApiclassList(ApiClass apiclass);
/** /**
* 新增接口类名 * 新增接口类名
@ -34,7 +34,7 @@ public interface ApiClassService {
* @param apiclass 接口类名 * @param apiclass 接口类名
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> insertApiclass(ApiClass apiclass); ServerResult<Integer> insertApiclass(ApiClass apiclass);
/** /**
* 修改接口类名 * 修改接口类名
@ -42,7 +42,7 @@ public interface ApiClassService {
* @param apiclass 接口类名 * @param apiclass 接口类名
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> updateApiclass(ApiClass apiclass); ServerResult<Integer> updateApiclass(ApiClass apiclass);
/** /**
* 批量删除接口类名 * 批量删除接口类名
@ -50,7 +50,7 @@ public interface ApiClassService {
* @param ids 需要删除的接口类名ID * @param ids 需要删除的接口类名ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteApiclassByIds(Long[] ids); ServerResult<Integer> deleteApiclassByIds(Long[] ids);
/** /**
* 删除接口类名信息 * 删除接口类名信息
@ -58,5 +58,5 @@ public interface ApiClassService {
* @param id 接口类名ID * @param id 接口类名ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteApiclassById(Long id); ServerResult<Integer> deleteApiclassById(Long id);
} }

View File

@ -16,7 +16,7 @@ public interface GenTableColumnService {
* @param tableId 业务字段编号 * @param tableId 业务字段编号
* @return 业务字段集合 * @return 业务字段集合
*/ */
public List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId); List<GenTableColumn> selectGenTableColumnListByTableId(Long tableId);
/** /**
* 新增业务字段 * 新增业务字段
@ -24,7 +24,7 @@ public interface GenTableColumnService {
* @param genTableColumn 业务字段信息 * @param genTableColumn 业务字段信息
* @return 结果 * @return 结果
*/ */
public int insertGenTableColumn(GenTableColumn genTableColumn); int insertGenTableColumn(GenTableColumn genTableColumn);
/** /**
* 修改业务字段 * 修改业务字段
@ -32,7 +32,7 @@ public interface GenTableColumnService {
* @param genTableColumn 业务字段信息 * @param genTableColumn 业务字段信息
* @return 结果 * @return 结果
*/ */
public int updateGenTableColumn(GenTableColumn genTableColumn); int updateGenTableColumn(GenTableColumn genTableColumn);
/** /**
* 删除业务字段信息 * 删除业务字段信息
@ -40,5 +40,5 @@ public interface GenTableColumnService {
* @param ids 需要删除的数据ID * @param ids 需要删除的数据ID
* @return 结果 * @return 结果
*/ */
public int deleteGenTableColumnByIds(String ids); int deleteGenTableColumnByIds(String ids);
} }

View File

@ -3,8 +3,8 @@ package com.ebts.generator.service;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.GenTable; import com.ebts.generator.entity.GenTable;
import com.ebts.generator.utils.GenServerResult;
/** /**
* 业务 服务层 * 业务 服务层
@ -65,7 +65,7 @@ public interface GenTableService {
* @param tableIds 需要删除的表数据ID * @param tableIds 需要删除的表数据ID
* @return 结果 * @return 结果
*/ */
public GenServerResult<Integer> deleteGenTableByIds(Long[] tableIds); public ServerResult<Integer> deleteGenTableByIds(Long[] tableIds);
/** /**
* 导入表结构 * 导入表结构

View File

@ -2,9 +2,9 @@ package com.ebts.generator.service;
import java.util.Map; import java.util.Map;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dto.InterTableDto; import com.ebts.generator.dto.InterTableDto;
import com.ebts.generator.entity.InterTable; import com.ebts.generator.entity.InterTable;
import com.ebts.generator.utils.GenServerResult;
/** /**
* 接口信息Service接口 * 接口信息Service接口
@ -19,7 +19,7 @@ public interface InterTableService {
* @param id 接口信息ID * @param id 接口信息ID
* @return 接口信息 * @return 接口信息
*/ */
GenServerResult<InterTable> selectInterTableById(Long id); ServerResult<InterTable> selectInterTableById(Long id);
/** /**
* 查询接口信息列表 * 查询接口信息列表
@ -27,7 +27,7 @@ public interface InterTableService {
* @param interTable 接口信息 * @param interTable 接口信息
* @return 接口信息集合 * @return 接口信息集合
*/ */
GenServerResult<Map<String, Object>> selectInterTableList(InterTable interTable); ServerResult<Map<String, Object>> selectInterTableList(InterTable interTable);
/** /**
* 新增接口信息 * 新增接口信息
@ -35,7 +35,7 @@ public interface InterTableService {
* @param interTable 接口信息 * @param interTable 接口信息
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> insertInterTable(InterTable interTable); ServerResult<Integer> insertInterTable(InterTable interTable);
/** /**
* 修改接口信息 * 修改接口信息
@ -43,7 +43,7 @@ public interface InterTableService {
* @param interTableDto 接口信息 * @param interTableDto 接口信息
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> updateInterTable(InterTableDto interTableDto); ServerResult<Integer> updateInterTable(InterTableDto interTableDto);
/** /**
* 批量删除接口信息 * 批量删除接口信息
@ -51,7 +51,7 @@ public interface InterTableService {
* @param ids 需要删除的接口信息ID * @param ids 需要删除的接口信息ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteInterTableByIds(Long[] ids); ServerResult<Integer> deleteInterTableByIds(Long[] ids);
/** /**
* 删除接口信息信息 * 删除接口信息信息
@ -59,7 +59,7 @@ public interface InterTableService {
* @param id 接口信息ID * @param id 接口信息ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteInterTableById(Long id); ServerResult<Integer> deleteInterTableById(Long id);
/** /**
* 预览代码(工作流) * 预览代码(工作流)
@ -67,7 +67,7 @@ public interface InterTableService {
* @param cid * @param cid
* @return * @return
*/ */
GenServerResult<Map<String, String>> previewCodeCalss(Long cid); ServerResult<Map<String, String>> previewCodeCalss(Long cid);
/** /**
* 预览代码()工作台 * 预览代码()工作台
@ -75,7 +75,7 @@ public interface InterTableService {
* @param mid * @param mid
* @return * @return
*/ */
GenServerResult<Map<String, Object>> previewCodeMoudle(Long mid); ServerResult<Map<String, Object>> previewCodeMoudle(Long mid);
/** /**
* 生成代码(工作流) * 生成代码(工作流)
@ -83,7 +83,7 @@ public interface InterTableService {
* @param cid * @param cid
* @return * @return
*/ */
GenServerResult<byte[]> generatorCodeClass(Long cid); ServerResult<byte[]> generatorCodeClass(Long cid);
/** /**
* 生成代码(工作台) * 生成代码(工作台)
@ -91,6 +91,6 @@ public interface InterTableService {
* @param mid * @param mid
* @return * @return
*/ */
GenServerResult<byte[]> generatorCodeMoudle(Long mid); ServerResult<byte[]> generatorCodeMoudle(Long mid);
} }

View File

@ -1,8 +1,8 @@
package com.ebts.generator.service; package com.ebts.generator.service;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.Module; import com.ebts.generator.entity.Module;
import com.ebts.generator.utils.GenServerResult;
import java.util.List; import java.util.List;
@ -19,7 +19,7 @@ public interface ModuleService {
* @param id 模块管理ID * @param id 模块管理ID
* @return 模块管理 * @return 模块管理
*/ */
GenServerResult<Module> selectModuleById(Long id); ServerResult<Module> selectModuleById(Long id);
/** /**
* 查询模块管理列表 * 查询模块管理列表
@ -27,7 +27,7 @@ public interface ModuleService {
* @param module 模块管理 * @param module 模块管理
* @return 模块管理集合 * @return 模块管理集合
*/ */
GenServerResult<List<Module>> selectModuleList(Module module); ServerResult<List<Module>> selectModuleList(Module module);
/** /**
* 新增模块管理 * 新增模块管理
@ -35,7 +35,7 @@ public interface ModuleService {
* @param module 模块管理 * @param module 模块管理
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> insertModule(Module module); ServerResult<Integer> insertModule(Module module);
/** /**
* 修改模块管理 * 修改模块管理
@ -43,7 +43,7 @@ public interface ModuleService {
* @param module 模块管理 * @param module 模块管理
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> updateModule(Module module); ServerResult<Integer> updateModule(Module module);
/** /**
* 批量删除模块管理 * 批量删除模块管理
@ -51,7 +51,7 @@ public interface ModuleService {
* @param ids 需要删除的模块管理ID * @param ids 需要删除的模块管理ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteModuleByIds(Long[] ids); ServerResult<Integer> deleteModuleByIds(Long[] ids);
/** /**
* 删除模块管理信息 * 删除模块管理信息
@ -59,5 +59,5 @@ public interface ModuleService {
* @param id 模块管理ID * @param id 模块管理ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteModuleById(Long id); ServerResult<Integer> deleteModuleById(Long id);
} }

View File

@ -1,7 +1,7 @@
package com.ebts.generator.service; package com.ebts.generator.service;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.utils.GenServerResult;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -18,7 +18,7 @@ public interface QueryService {
* @param id * @param id
* @return * @return
*/ */
GenServerResult<UniQuery> selectQueryById(Long id); ServerResult<UniQuery> selectQueryById(Long id);
/** /**
* 修改基础信息 * 修改基础信息
@ -26,7 +26,7 @@ public interface QueryService {
* @param uniQuery * @param uniQuery
* @return * @return
*/ */
GenServerResult<Integer> updateQueryInfo(UniQuery uniQuery); ServerResult<Integer> updateQueryInfo(UniQuery uniQuery);
/** /**
* 预览万能查询数据 * 预览万能查询数据
@ -34,11 +34,11 @@ public interface QueryService {
* @param uniQuery * @param uniQuery
* @return * @return
*/ */
GenServerResult<List<Map<String, Object>>> previewQuery(UniQuery uniQuery); ServerResult<List<Map<String, Object>>> previewQuery(UniQuery uniQuery);
/** /**
* @param uniQuery * @param uniQuery
* @return * @return
*/ */
GenServerResult<Integer> Release(UniQuery uniQuery); ServerResult<Integer> Release(UniQuery uniQuery);
} }

View File

@ -1,7 +1,7 @@
package com.ebts.generator.service; package com.ebts.generator.service;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.Regular; import com.ebts.generator.entity.Regular;
import com.ebts.generator.utils.GenServerResult;
import java.util.List; import java.util.List;
@ -18,7 +18,7 @@ public interface RegularService {
* @param id 校验规则ID * @param id 校验规则ID
* @return 校验规则 * @return 校验规则
*/ */
GenServerResult<Regular> selectRegularById(Long id); ServerResult<Regular> selectRegularById(Long id);
/** /**
* 查询校验规则列表 * 查询校验规则列表
@ -26,13 +26,13 @@ public interface RegularService {
* @param regular 校验规则 * @param regular 校验规则
* @return 校验规则集合 * @return 校验规则集合
*/ */
GenServerResult<List<Regular>> selectRegularList(Regular regular); ServerResult<List<Regular>> selectRegularList(Regular regular);
/** /**
* 查询校验规则下拉框列表 * 查询校验规则下拉框列表
* *
* @return 校验规则集合 * @return 校验规则集合
*/ */
GenServerResult<List<Regular>> selectRegularOption(); ServerResult<List<Regular>> selectRegularOption();
/** /**
* 新增校验规则 * 新增校验规则
@ -40,7 +40,7 @@ public interface RegularService {
* @param regular 校验规则 * @param regular 校验规则
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> insertRegular(Regular regular); ServerResult<Integer> insertRegular(Regular regular);
/** /**
* 修改校验规则 * 修改校验规则
@ -48,7 +48,7 @@ public interface RegularService {
* @param regular 校验规则 * @param regular 校验规则
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> updateRegular(Regular regular); ServerResult<Integer> updateRegular(Regular regular);
/** /**
* 批量删除校验规则 * 批量删除校验规则
@ -56,7 +56,7 @@ public interface RegularService {
* @param ids 需要删除的校验规则ID * @param ids 需要删除的校验规则ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteRegularByIds(Long[] ids); ServerResult<Integer> deleteRegularByIds(Long[] ids);
/** /**
* 删除校验规则信息 * 删除校验规则信息
@ -64,5 +64,5 @@ public interface RegularService {
* @param id 校验规则ID * @param id 校验规则ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteRegularById(Long id); ServerResult<Integer> deleteRegularById(Long id);
} }

View File

@ -1,8 +1,8 @@
package com.ebts.generator.service; package com.ebts.generator.service;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.RelColumn; import com.ebts.generator.entity.RelColumn;
import com.ebts.generator.entity.RelTable; import com.ebts.generator.entity.RelTable;
import com.ebts.generator.utils.GenServerResult;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -19,7 +19,7 @@ public interface RelService {
* *
* @return * @return
*/ */
GenServerResult<List<Map<String, Object>>> tableInfos(); ServerResult<List<Map<String, Object>>> tableInfos();
/** /**
* 获取到关联边字段信息 * 获取到关联边字段信息
@ -28,7 +28,7 @@ public interface RelService {
* @param relId 关联关系id * @param relId 关联关系id
* @return * @return
*/ */
GenServerResult<List<RelColumn>> relColumns(String tableName, Long relId); ServerResult<List<RelColumn>> relColumns(String tableName, Long relId);
/** /**
* 通过tableName获取到字段信息 * 通过tableName获取到字段信息
@ -36,7 +36,7 @@ public interface RelService {
* @param tableName * @param tableName
* @return * @return
*/ */
GenServerResult<List<Map<String,Object>>> tableColumns(String tableName); ServerResult<List<Map<String,Object>>> tableColumns(String tableName);
/** /**
* 通过主表id查询子表信息 * 通过主表id查询子表信息
@ -44,6 +44,6 @@ public interface RelService {
* @param tableId * @param tableId
* @return * @return
*/ */
GenServerResult<List<RelTable>> relTableByTableId(Long tableId); ServerResult<List<RelTable>> relTableByTableId(Long tableId);
} }

View File

@ -2,8 +2,8 @@ package com.ebts.generator.service;
import java.util.List; import java.util.List;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.utils.GenServerResult;
/** /**
* 万能查询Service接口 * 万能查询Service接口
@ -18,7 +18,7 @@ public interface UniQueryService {
* @param id 万能查询ID * @param id 万能查询ID
* @return 万能查询 * @return 万能查询
*/ */
GenServerResult<UniQuery> selectUniQueryById(Long id); ServerResult<UniQuery> selectUniQueryById(Long id);
/** /**
* 查询万能查询列表 * 查询万能查询列表
@ -26,7 +26,7 @@ public interface UniQueryService {
* @param uniQuery 万能查询 * @param uniQuery 万能查询
* @return 万能查询集合 * @return 万能查询集合
*/ */
GenServerResult<List<UniQuery>> selectUniQueryList(UniQuery uniQuery); ServerResult<List<UniQuery>> selectUniQueryList(UniQuery uniQuery);
/** /**
* 新增万能查询 * 新增万能查询
@ -34,7 +34,7 @@ public interface UniQueryService {
* @param uniQuery 万能查询 * @param uniQuery 万能查询
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> insertUniQuery(UniQuery uniQuery); ServerResult<Integer> insertUniQuery(UniQuery uniQuery);
/** /**
* 修改万能查询 * 修改万能查询
@ -42,7 +42,7 @@ public interface UniQueryService {
* @param uniQuery 万能查询 * @param uniQuery 万能查询
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> updateUniQuery(UniQuery uniQuery); ServerResult<Integer> updateUniQuery(UniQuery uniQuery);
/** /**
* 批量删除万能查询 * 批量删除万能查询
@ -50,7 +50,7 @@ public interface UniQueryService {
* @param ids 需要删除的万能查询ID * @param ids 需要删除的万能查询ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteUniQueryByIds(Long[] ids); ServerResult<Integer> deleteUniQueryByIds(Long[] ids);
/** /**
* 删除万能查询信息 * 删除万能查询信息
@ -58,5 +58,5 @@ public interface UniQueryService {
* @param id 万能查询ID * @param id 万能查询ID
* @return 结果 * @return 结果
*/ */
GenServerResult<Integer> deleteUniQueryById(Long id); ServerResult<Integer> deleteUniQueryById(Long id);
} }

View File

@ -2,13 +2,13 @@ package com.ebts.generator.service.impl;
import java.util.List; import java.util.List;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.ApiClassDao; import com.ebts.generator.dao.ApiClassDao;
import com.ebts.generator.entity.ApiClass; import com.ebts.generator.entity.ApiClass;
import com.ebts.generator.service.ApiClassService; import com.ebts.generator.service.ApiClassService;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenSecurityUtils;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -34,17 +34,17 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 接口类名 * @return 接口类名
*/ */
@Override @Override
public GenServerResult<ApiClass> selectApiclassById(Long id) { public ServerResult<ApiClass> selectApiclassById(Long id) {
try { try {
ApiClass apiclass = apiclassDao.selectApiclassById(id); ApiClass apiclass = apiclassDao.selectApiclassById(id);
if (apiclass != null) { if (apiclass != null) {
return new GenServerResult<>(true, apiclass); return new ServerResult<>(true, apiclass);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -55,17 +55,17 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 接口类名 * @return 接口类名
*/ */
@Override @Override
public GenServerResult<List<ApiClass>> selectApiclassList(ApiClass apiclass) { public ServerResult<List<ApiClass>> selectApiclassList(ApiClass apiclass) {
try { try {
List<ApiClass> apiClassList = apiclassDao.selectApiclassList(apiclass); List<ApiClass> apiClassList = apiclassDao.selectApiclassList(apiclass);
if (apiClassList.size() > 0) { if (apiClassList.size() > 0) {
return new GenServerResult<>(true, apiClassList); return new ServerResult<>(true, apiClassList);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -76,18 +76,18 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> insertApiclass(ApiClass apiclass) { public ServerResult<Integer> insertApiclass(ApiClass apiclass) {
try { try {
apiclass.setCreateBy(GenSecurityUtils.getUserId()); apiclass.setCreateBy(SecurityUtils.getUserId());
Integer renewal = apiclassDao.insertApiclass(apiclass); Integer renewal = apiclassDao.insertApiclass(apiclass);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.OP_ERROR); return new ServerResult<Integer>(false, ReturnConstants.OP_ERROR);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -98,18 +98,18 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> updateApiclass(ApiClass apiclass) { public ServerResult<Integer> updateApiclass(ApiClass apiclass) {
try { try {
apiclass.setUpdateBy(GenSecurityUtils.getUserId()); apiclass.setUpdateBy(SecurityUtils.getUserId());
Integer renewal = apiclassDao.updateApiclass(apiclass); Integer renewal = apiclassDao.updateApiclass(apiclass);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -120,17 +120,17 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteApiclassByIds(Long[] ids) { public ServerResult<Integer> deleteApiclassByIds(Long[] ids) {
try { try {
Integer renewal = apiclassDao.deleteApiclassByIds(ids); Integer renewal = apiclassDao.deleteApiclassByIds(ids);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -141,17 +141,17 @@ public class ApiClassServiceImpl implements ApiClassService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteApiclassById(Long id) { public ServerResult<Integer> deleteApiclassById(Long id) {
try { try {
Integer renewal = apiclassDao.deleteApiclassById(id); Integer renewal = apiclassDao.deleteApiclassById(id);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
} }

View File

@ -3,11 +3,10 @@ package com.ebts.generator.service.impl;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.text.Convert;
import com.ebts.common.exception.EbtsException;
import com.ebts.generator.service.GenTableColumnService; import com.ebts.generator.service.GenTableColumnService;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.exception.GenCustomException;
import com.ebts.generator.utils.exception.GenEbtsException;
import com.ebts.generator.utils.text.Convert;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -39,7 +38,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
return genTableColumnDao.selectGenTableColumnListByTableId(tableId); return genTableColumnDao.selectGenTableColumnListByTableId(tableId);
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -55,7 +54,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
return genTableColumnDao.insertGenTableColumn(genTableColumn); return genTableColumnDao.insertGenTableColumn(genTableColumn);
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -73,7 +72,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
return genTableColumnDao.updateGenTableColumn(genTableColumns); return genTableColumnDao.updateGenTableColumn(genTableColumns);
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -89,7 +88,7 @@ public class GenTableColumnServiceImpl implements GenTableColumnService {
return genTableColumnDao.deleteGenTableColumnByIds(Convert.toLongArray(ids)); return genTableColumnDao.deleteGenTableColumnByIds(Convert.toLongArray(ids));
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
} }

View File

@ -12,15 +12,19 @@ import java.util.stream.Collectors;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import com.ebts.common.constant.Constants;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.text.CharsetKit;
import com.ebts.common.exception.CustomException;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.dao.RelDao; import com.ebts.generator.dao.RelDao;
import com.ebts.generator.entity.*; import com.ebts.generator.entity.*;
import com.ebts.generator.service.GenTableService; import com.ebts.generator.service.GenTableService;
import com.ebts.generator.utils.*; import com.ebts.generator.utils.*;
import com.ebts.generator.utils.constant.Constants;
import com.ebts.generator.utils.constant.GenConstants; import com.ebts.generator.utils.constant.GenConstants;
import com.ebts.generator.utils.exception.GenCustomException;
import com.ebts.generator.utils.exception.GenEbtsException;
import com.ebts.generator.utils.text.CharsetKit;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template; import org.apache.velocity.Template;
@ -70,7 +74,7 @@ public class GenTableServiceImpl implements GenTableService {
return genTable; return genTable;
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -86,7 +90,7 @@ public class GenTableServiceImpl implements GenTableService {
return genTableDao.selectGenTableList(genTable); return genTableDao.selectGenTableList(genTable);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -102,7 +106,7 @@ public class GenTableServiceImpl implements GenTableService {
return genTableDao.selectDbTableList(genTable); return genTableDao.selectDbTableList(genTable);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -118,7 +122,7 @@ public class GenTableServiceImpl implements GenTableService {
return genTableDao.selectDbTableListByNames(tableNames); return genTableDao.selectDbTableListByNames(tableNames);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -133,7 +137,7 @@ public class GenTableServiceImpl implements GenTableService {
return genTableDao.selectGenTableAll(); return genTableDao.selectGenTableAll();
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -161,11 +165,11 @@ public class GenTableServiceImpl implements GenTableService {
relTables = genTable.getRelTables(); relTables = genTable.getRelTables();
for (int i = 0; i < relTables.size(); i++) { for (int i = 0; i < relTables.size(); i++) {
RelTable relTable = relTables.get(i); RelTable relTable = relTables.get(i);
relTable.setTableAs(GenStringUtils.sqlFormat(relTable.getTableName())); relTable.setTableAs(StringUtils.sqlFormat(relTable.getTableName()));
relTable.setRelAs(GenStringUtils.sqlFormat(relTable.getRelName())); relTable.setRelAs(StringUtils.sqlFormat(relTable.getRelName()));
relTable.setRelClass(GenUtils.convertClassName(relTable.getRelName())); relTable.setRelClass(GenUtils.convertClassName(relTable.getRelName()));
relTable.setCreateBy(GenSecurityUtils.getUserId()); relTable.setCreateBy(SecurityUtils.getUserId());
relTable.setRelclass(GenStringUtils.uncapitalize(relTable.getRelClass())); relTable.setRelclass(StringUtils.uncapitalize(relTable.getRelClass()));
relTables.set(i,relTable); relTables.set(i,relTable);
} }
if (relTables != null) { if (relTables != null) {
@ -176,9 +180,9 @@ public class GenTableServiceImpl implements GenTableService {
} }
} }
} }
} catch (GenCustomException e) { } catch (CustomException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -190,7 +194,7 @@ public class GenTableServiceImpl implements GenTableService {
*/ */
@Override @Override
@Transactional @Transactional
public GenServerResult<Integer> deleteGenTableByIds(Long[] tableIds) { public ServerResult<Integer> deleteGenTableByIds(Long[] tableIds) {
try { try {
genTableDao.deleteGenTableByIds(tableIds); genTableDao.deleteGenTableByIds(tableIds);
genTableColumnDao.deleteGenTableColumnByIds(tableIds); genTableColumnDao.deleteGenTableColumnByIds(tableIds);
@ -203,11 +207,11 @@ public class GenTableServiceImpl implements GenTableService {
} }
} }
} }
return new GenServerResult<>(true); return new ServerResult<>(true);
} catch (RuntimeException e) { } catch (RuntimeException e) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -219,7 +223,7 @@ public class GenTableServiceImpl implements GenTableService {
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public void importGenTable(List<GenTable> tableList) { public void importGenTable(List<GenTable> tableList) {
Long operName = GenSecurityUtils.getUserId(); Long operName = SecurityUtils.getUserId();
try { try {
for (GenTable table : tableList) { for (GenTable table : tableList) {
String tableName = table.getTableName(); String tableName = table.getTableName();
@ -234,9 +238,9 @@ public class GenTableServiceImpl implements GenTableService {
} }
} }
} }
} catch (Exception e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException("导入失败:" + e.getMessage(),e); throw new EbtsException("导入失败:" + e.getMessage(),e);
} }
} }
@ -293,7 +297,7 @@ public class GenTableServiceImpl implements GenTableService {
return dataMap; return dataMap;
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -313,7 +317,7 @@ public class GenTableServiceImpl implements GenTableService {
return outputStream.toByteArray(); return outputStream.toByteArray();
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -340,7 +344,7 @@ public class GenTableServiceImpl implements GenTableService {
// 获取模板列表 // 获取模板列表
List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory()); List<String> templates = VelocityUtils.getTemplateList(table.getTplCategory());
for (String template : templates) { for (String template : templates) {
if (!GenStringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) { if (!StringUtils.containsAny(template, "table.sql.vm", "api.js.vm", "index.vue.vm", "index-tree.vue.vm")) {
// 渲染模板 // 渲染模板
if (template.equals("vm/java/rel-entity.java.vm")){ if (template.equals("vm/java/rel-entity.java.vm")){
List<RelTable> relTables = table.getRelTables(); List<RelTable> relTables = table.getRelTables();
@ -384,7 +388,7 @@ public class GenTableServiceImpl implements GenTableService {
return true; return true;
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -402,8 +406,8 @@ public class GenTableServiceImpl implements GenTableService {
List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); List<String> tableColumnNames = tableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
List<GenTableColumn> dbTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName); List<GenTableColumn> dbTableColumns = genTableColumnDao.selectDbTableColumnsByName(tableName);
if (GenStringUtils.isEmpty(dbTableColumns)) { if (StringUtils.isEmpty(dbTableColumns)) {
throw new GenCustomException("同步数据失败,原表结构不存在"); throw new CustomException("同步数据失败,原表结构不存在");
} }
List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList()); List<String> dbTableColumnNames = dbTableColumns.stream().map(GenTableColumn::getColumnName).collect(Collectors.toList());
@ -415,12 +419,12 @@ public class GenTableServiceImpl implements GenTableService {
}); });
List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList()); List<GenTableColumn> delColumns = tableColumns.stream().filter(column -> !dbTableColumnNames.contains(column.getColumnName())).collect(Collectors.toList());
if (GenStringUtils.isNotEmpty(delColumns)) { if (StringUtils.isNotEmpty(delColumns)) {
genTableColumnDao.deleteGenTableColumns(delColumns); genTableColumnDao.deleteGenTableColumns(delColumns);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -446,7 +450,7 @@ public class GenTableServiceImpl implements GenTableService {
return outputStream.toByteArray(); return outputStream.toByteArray();
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -462,7 +466,7 @@ public class GenTableServiceImpl implements GenTableService {
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -547,17 +551,17 @@ public class GenTableServiceImpl implements GenTableService {
if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) { if (GenConstants.TPL_TREE.equals(genTable.getTplCategory())) {
String options = JSON.toJSONString(genTable.getParams()); String options = JSON.toJSONString(genTable.getParams());
JSONObject paramsObj = JSONObject.parseObject(options); JSONObject paramsObj = JSONObject.parseObject(options);
if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) { if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_CODE))) {
throw new GenCustomException("树编码字段不能为空"); throw new CustomException("树编码字段不能为空");
} else if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) { } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_PARENT_CODE))) {
throw new GenCustomException("树父编码字段不能为空"); throw new CustomException("树父编码字段不能为空");
} else if (GenStringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) { } else if (StringUtils.isEmpty(paramsObj.getString(GenConstants.TREE_NAME))) {
throw new GenCustomException("树名称字段不能为空"); throw new CustomException("树名称字段不能为空");
} else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) { } else if (GenConstants.TPL_SUB.equals(genTable.getTplCategory())) {
if (GenStringUtils.isEmpty(genTable.getSubTableName())) { if (StringUtils.isEmpty(genTable.getSubTableName())) {
throw new GenCustomException("关联子表的表名不能为空"); throw new CustomException("关联子表的表名不能为空");
} else if (GenStringUtils.isEmpty(genTable.getSubTableFkName())) { } else if (StringUtils.isEmpty(genTable.getSubTableFkName())) {
throw new GenCustomException("子表关联的外键名不能为空"); throw new CustomException("子表关联的外键名不能为空");
} }
} else if (GenConstants.TPL_ASS.equals(genTable.getTplCategory())) { } else if (GenConstants.TPL_ASS.equals(genTable.getTplCategory())) {
// todo 规则校验 // todo 规则校验
@ -577,7 +581,7 @@ public class GenTableServiceImpl implements GenTableService {
break; break;
} }
} }
if (GenStringUtils.isNull(table.getPkColumn())) { if (StringUtils.isNull(table.getPkColumn())) {
table.setPkColumn(table.getColumns().get(0)); table.setPkColumn(table.getColumns().get(0));
} }
if (GenConstants.TPL_SUB.equals(table.getTplCategory())) { if (GenConstants.TPL_SUB.equals(table.getTplCategory())) {
@ -587,7 +591,7 @@ public class GenTableServiceImpl implements GenTableService {
break; break;
} }
} }
if (GenStringUtils.isNull(table.getSubTable().getPkColumn())) { if (StringUtils.isNull(table.getSubTable().getPkColumn())) {
table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0)); table.getSubTable().setPkColumn(table.getSubTable().getColumns().get(0));
} }
} }
@ -600,7 +604,7 @@ public class GenTableServiceImpl implements GenTableService {
*/ */
public void setSubTable(GenTable table) { public void setSubTable(GenTable table) {
String subTableName = table.getSubTableName(); String subTableName = table.getSubTableName();
if (GenStringUtils.isNotEmpty(subTableName)) { if (StringUtils.isNotEmpty(subTableName)) {
table.setSubTable(genTableDao.selectGenTableByName(subTableName)); table.setSubTable(genTableDao.selectGenTableByName(subTableName));
} }
} }
@ -612,7 +616,7 @@ public class GenTableServiceImpl implements GenTableService {
*/ */
public void setTableFromOptions(GenTable genTable) { public void setTableFromOptions(GenTable genTable) {
JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions()); JSONObject paramsObj = JSONObject.parseObject(genTable.getOptions());
if (GenStringUtils.isNotNull(paramsObj)) { if (StringUtils.isNotNull(paramsObj)) {
String treeCode = paramsObj.getString(GenConstants.TREE_CODE); String treeCode = paramsObj.getString(GenConstants.TREE_CODE);
String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE); String treeParentCode = paramsObj.getString(GenConstants.TREE_PARENT_CODE);
String treeName = paramsObj.getString(GenConstants.TREE_NAME); String treeName = paramsObj.getString(GenConstants.TREE_NAME);
@ -636,7 +640,7 @@ public class GenTableServiceImpl implements GenTableService {
*/ */
public static String getGenPath(GenTable table, String template) { public static String getGenPath(GenTable table, String template) {
String genPath = table.getGenPath(); String genPath = table.getGenPath();
if (GenStringUtils.equals(genPath, "/")) { if (StringUtils.equals(genPath, "/")) {
return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table); return System.getProperty("user.dir") + File.separator + "src" + File.separator + VelocityUtils.getFileName(template, table);
} }
return genPath + File.separator + VelocityUtils.getFileName(template, table); return genPath + File.separator + VelocityUtils.getFileName(template, table);

View File

@ -10,6 +10,11 @@ import java.util.Map;
import java.util.zip.ZipEntry; import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; import java.util.zip.ZipOutputStream;
import com.ebts.common.constant.Constants;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.ApiClassDao; import com.ebts.generator.dao.ApiClassDao;
import com.ebts.generator.dao.GenTableDao; import com.ebts.generator.dao.GenTableDao;
import com.ebts.generator.dao.ModuleDao; import com.ebts.generator.dao.ModuleDao;
@ -17,8 +22,6 @@ import com.ebts.generator.dto.InterTableDto;
import com.ebts.generator.entity.ApiClass; import com.ebts.generator.entity.ApiClass;
import com.ebts.generator.entity.Module; import com.ebts.generator.entity.Module;
import com.ebts.generator.utils.*; import com.ebts.generator.utils.*;
import com.ebts.generator.utils.constant.Constants;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -59,17 +62,17 @@ public class InterTableServiceImpl implements InterTableService {
* @return 接口信息 * @return 接口信息
*/ */
@Override @Override
public GenServerResult<InterTable> selectInterTableById(Long id) { public ServerResult<InterTable> selectInterTableById(Long id) {
try { try {
InterTable interTable = interTableDao.selectInterTableById(id); InterTable interTable = interTableDao.selectInterTableById(id);
if (interTable != null) { if (interTable != null) {
return new GenServerResult<InterTable>(true, interTable); return new ServerResult<InterTable>(true, interTable);
} else { } else {
return new GenServerResult<InterTable>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<InterTable>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -80,7 +83,7 @@ public class InterTableServiceImpl implements InterTableService {
* @return 接口信息 * @return 接口信息
*/ */
@Override @Override
public GenServerResult<Map<String, Object>> selectInterTableList(InterTable interTable) { public ServerResult<Map<String, Object>> selectInterTableList(InterTable interTable) {
try { try {
Map<String, Object> modeMap = new HashMap<String, Object>(); Map<String, Object> modeMap = new HashMap<String, Object>();
if (interTable.getType() == 1) { if (interTable.getType() == 1) {
@ -92,10 +95,10 @@ public class InterTableServiceImpl implements InterTableService {
} }
List<InterTable> interTableList = interTableDao.selectInterTableList(interTable); List<InterTable> interTableList = interTableDao.selectInterTableList(interTable);
modeMap.put("rows", interTableList); modeMap.put("rows", interTableList);
return new GenServerResult<Map<String, Object>>(true, modeMap); return new ServerResult<Map<String, Object>>(true, modeMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -106,18 +109,18 @@ public class InterTableServiceImpl implements InterTableService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> insertInterTable(InterTable interTable) { public ServerResult<Integer> insertInterTable(InterTable interTable) {
try { try {
interTable.setCreateBy(GenSecurityUtils.getUserId()); interTable.setCreateBy(SecurityUtils.getUserId());
Integer renewal = interTableDao.insertInterTable(interTable); Integer renewal = interTableDao.insertInterTable(interTable);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -129,7 +132,7 @@ public class InterTableServiceImpl implements InterTableService {
*/ */
@Override @Override
@Transactional @Transactional
public GenServerResult<Integer> updateInterTable(InterTableDto interTableDto) { public ServerResult<Integer> updateInterTable(InterTableDto interTableDto) {
try { try {
List<InterTable> interTables = interTableDto.getInterTables(); List<InterTable> interTables = interTableDto.getInterTables();
Integer renewal = 0; Integer renewal = 0;
@ -145,19 +148,19 @@ public class InterTableServiceImpl implements InterTableService {
Integer renewalTables = 0; Integer renewalTables = 0;
if (interTables.size() > 0) { if (interTables.size() > 0) {
for (int i = 0; i < interTables.size(); i++) { for (int i = 0; i < interTables.size(); i++) {
interTables.get(i).setCreateBy(GenSecurityUtils.getUserId()); interTables.get(i).setCreateBy(SecurityUtils.getUserId());
} }
renewalTables = interTableDao.insertInterTables(interTables); renewalTables = interTableDao.insertInterTables(interTables);
} }
if (renewalTables > 0 || renewal > 0) { if (renewalTables > 0 || renewal > 0) {
return new GenServerResult<Integer>(true, renewalTables); return new ServerResult<Integer>(true, renewalTables);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -168,17 +171,17 @@ public class InterTableServiceImpl implements InterTableService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteInterTableByIds(Long[] ids) { public ServerResult<Integer> deleteInterTableByIds(Long[] ids) {
try { try {
Integer renewal = interTableDao.deleteInterTableByIds(ids); Integer renewal = interTableDao.deleteInterTableByIds(ids);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -189,31 +192,31 @@ public class InterTableServiceImpl implements InterTableService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteInterTableById(Long id) { public ServerResult<Integer> deleteInterTableById(Long id) {
try { try {
Integer renewal = interTableDao.deleteInterTableById(id); Integer renewal = interTableDao.deleteInterTableById(id);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@Override @Override
public GenServerResult<Map<String, String>> previewCodeCalss(Long cid) { public ServerResult<Map<String, String>> previewCodeCalss(Long cid) {
try { try {
Map<String, String> dataMap = new LinkedHashMap<String, String>(); Map<String, String> dataMap = new LinkedHashMap<String, String>();
ApiClass apiclass = interTableDao.selectInterTableClass(cid); ApiClass apiclass = interTableDao.selectInterTableClass(cid);
if (apiclass == null) { if (apiclass == null) {
return new GenServerResult<Map<String, String>>(false, GenReturnConstants.INTER_NULL); return new ServerResult<Map<String, String>>(false, ReturnConstants.INTER_NULL);
} }
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
VelocityContext context = GenInterTableUtils.prepareClassContext(apiclass); VelocityContext context = InterTableUtils.prepareClassContext(apiclass);
Map<String, String> templates = GenInterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8);
template.merge(context, sw); template.merge(context, sw);
@ -223,24 +226,24 @@ public class InterTableServiceImpl implements InterTableService {
template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
template.merge(context, sw); template.merge(context, sw);
dataMap.put(getSqlName(apiclass.getcName()), sw.toString()); dataMap.put(getSqlName(apiclass.getcName()), sw.toString());
return new GenServerResult<Map<String, String>>(true, dataMap); return new ServerResult<Map<String, String>>(true, dataMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@Override @Override
public GenServerResult<Map<String, Object>> previewCodeMoudle(Long mid) { public ServerResult<Map<String, Object>> previewCodeMoudle(Long mid) {
try { try {
Map<String, Object> dataMap = new LinkedHashMap<String, Object>(); Map<String, Object> dataMap = new LinkedHashMap<String, Object>();
List<InterTable> interTableList = interTableDao.selectInterTableModule(mid); List<InterTable> interTableList = interTableDao.selectInterTableModule(mid);
if (interTableList.size() == 0) { if (interTableList.size() == 0) {
return new GenServerResult<Map<String, Object>>(false, "该模块下接口为空,请先创建接口!"); return new ServerResult<Map<String, Object>>(false, "该模块下接口为空,请先创建接口!");
} }
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
List<VelocityContext> contextList = GenInterTableUtils.prepareMoudleContext(interTableList); List<VelocityContext> contextList = InterTableUtils.prepareMoudleContext(interTableList);
Map<String, String> templates = GenInterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sqlsw = new StringWriter(); StringWriter sqlsw = new StringWriter();
Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
for (VelocityContext context : contextList) { for (VelocityContext context : contextList) {
@ -251,29 +254,29 @@ public class InterTableServiceImpl implements InterTableService {
dataMap.put(getJavaClassName((String) context.get("ClassName")), sw.toString()); dataMap.put(getJavaClassName((String) context.get("ClassName")), sw.toString());
} }
dataMap.put(getSqlName("module"), sqlsw.toString()); dataMap.put(getSqlName("module"), sqlsw.toString());
return new GenServerResult<Map<String, Object>>(true, dataMap); return new ServerResult<Map<String, Object>>(true, dataMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@Override @Override
@Transactional @Transactional
public GenServerResult<byte[]> generatorCodeClass(Long cid) { public ServerResult<byte[]> generatorCodeClass(Long cid) {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream); ZipOutputStream zip = new ZipOutputStream(outputStream);
ApiClass apiclass = interTableDao.selectInterTableClass(cid); ApiClass apiclass = interTableDao.selectInterTableClass(cid);
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
VelocityContext context = GenInterTableUtils.prepareClassContext(apiclass); VelocityContext context = InterTableUtils.prepareClassContext(apiclass);
Map<String, String> templates = GenInterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sw = new StringWriter(); StringWriter sw = new StringWriter();
Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8); Template template = Velocity.getTemplate(templates.get("java"), Constants.UTF8);
template.merge(context, sw); template.merge(context, sw);
zip = genCode(getJavaClassName(apiclass.getcName()), zip, sw); zip = genCode(getJavaClassName(apiclass.getcName()), zip, sw);
if (zip == null) { if (zip == null) {
return new GenServerResult<byte[]>(false, "代码生成失败!"); return new ServerResult<byte[]>(false, "代码生成失败!");
} }
sw = new StringWriter(); sw = new StringWriter();
template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); template = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
@ -281,35 +284,35 @@ public class InterTableServiceImpl implements InterTableService {
zip = genCode(getSqlName(apiclass.getcName()), zip, sw); zip = genCode(getSqlName(apiclass.getcName()), zip, sw);
if (zip == null) { if (zip == null) {
return new GenServerResult<byte[]>(false, "代码生成失败!"); return new ServerResult<byte[]>(false, "代码生成失败!");
} }
int start = genTableDao.insertMenu(sw.toString()); int start = genTableDao.insertMenu(sw.toString());
if (!(start > 0)) { if (!(start > 0)) {
return new GenServerResult<byte[]>(false, GenReturnConstants.DB_EX); return new ServerResult<byte[]>(false, ReturnConstants.DB_EX);
} }
IOUtils.closeQuietly(zip); IOUtils.closeQuietly(zip);
return new GenServerResult<byte[]>(true, outputStream.toByteArray()); return new ServerResult<byte[]>(true, outputStream.toByteArray());
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new GenEbtsException("代码生成失败!",e); throw new EbtsException("代码生成失败!",e);
} }
} }
@Override @Override
@Transactional @Transactional
public GenServerResult<byte[]> generatorCodeMoudle(Long mid) { public ServerResult<byte[]> generatorCodeMoudle(Long mid) {
try { try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream); ZipOutputStream zip = new ZipOutputStream(outputStream);
List<InterTable> interTableList = interTableDao.selectInterTableModule(mid); List<InterTable> interTableList = interTableDao.selectInterTableModule(mid);
if (interTableList.size() == 0) { if (interTableList.size() == 0) {
return new GenServerResult<byte[]>(false, "该模块下接口为空,请先创建接口!"); return new ServerResult<byte[]>(false, "该模块下接口为空,请先创建接口!");
} }
VelocityInitializer.initVelocity(); VelocityInitializer.initVelocity();
List<VelocityContext> contextList = GenInterTableUtils.prepareMoudleContext(interTableList); List<VelocityContext> contextList = InterTableUtils.prepareMoudleContext(interTableList);
Map<String, String> templates = GenInterTableUtils.getTemplateList(2); Map<String, String> templates = InterTableUtils.getTemplateList(2);
StringWriter sqlsw = new StringWriter(); StringWriter sqlsw = new StringWriter();
Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8); Template sqltemplate = Velocity.getTemplate(templates.get("sql"), Constants.UTF8);
for (VelocityContext context : contextList) { for (VelocityContext context : contextList) {
@ -323,15 +326,15 @@ public class InterTableServiceImpl implements InterTableService {
if (zip != null) { if (zip != null) {
int start = genTableDao.insertMenu(sqlsw.toString()); int start = genTableDao.insertMenu(sqlsw.toString());
if (!(start > 0)) { if (!(start > 0)) {
return new GenServerResult<byte[]>(false, GenReturnConstants.DB_EX); return new ServerResult<byte[]>(false, ReturnConstants.DB_EX);
} }
} }
IOUtils.closeQuietly(zip); IOUtils.closeQuietly(zip);
return new GenServerResult<byte[]>(true, outputStream.toByteArray()); return new ServerResult<byte[]>(true, outputStream.toByteArray());
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
throw new GenEbtsException("代码生成失败!",e); throw new EbtsException("代码生成失败!",e);
} }
} }
@ -352,10 +355,10 @@ public class InterTableServiceImpl implements InterTableService {
public String getJavaClassName(String cName) { public String getJavaClassName(String cName) {
return GenInterTableUtils.getUpperCase(cName) + "Controller.java"; return InterTableUtils.getUpperCase(cName) + "Controller.java";
} }
public String getSqlName(String cName) { public String getSqlName(String cName) {
return GenInterTableUtils.getUpperCase(cName) + ".sql"; return InterTableUtils.getUpperCase(cName) + ".sql";
} }
} }

View File

@ -2,13 +2,13 @@ package com.ebts.generator.service.impl;
import java.util.List; import java.util.List;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.ModuleDao; import com.ebts.generator.dao.ModuleDao;
import com.ebts.generator.entity.Module; import com.ebts.generator.entity.Module;
import com.ebts.generator.service.ModuleService; import com.ebts.generator.service.ModuleService;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenSecurityUtils;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -34,17 +34,17 @@ public class ModuleServiceImpl implements ModuleService {
* @return 模块管理 * @return 模块管理
*/ */
@Override @Override
public GenServerResult<Module> selectModuleById(Long id) { public ServerResult<Module> selectModuleById(Long id) {
try { try {
Module module = moduleDao.selectModuleById(id); Module module = moduleDao.selectModuleById(id);
if (module != null) { if (module != null) {
return new GenServerResult<Module>(true, module); return new ServerResult<Module>(true, module);
} else { } else {
return new GenServerResult<Module>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<Module>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -55,17 +55,17 @@ public class ModuleServiceImpl implements ModuleService {
* @return 模块管理 * @return 模块管理
*/ */
@Override @Override
public GenServerResult<List<Module>> selectModuleList(Module module) { public ServerResult<List<Module>> selectModuleList(Module module) {
try { try {
List<Module> moduleList = moduleDao.selectModuleList(module); List<Module> moduleList = moduleDao.selectModuleList(module);
if (moduleList.size() > 0) { if (moduleList.size() > 0) {
return new GenServerResult<List<Module>>(true, moduleList); return new ServerResult<List<Module>>(true, moduleList);
} else { } else {
return new GenServerResult<List<Module>>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<List<Module>>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -76,18 +76,18 @@ public class ModuleServiceImpl implements ModuleService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> insertModule(Module module) { public ServerResult<Integer> insertModule(Module module) {
try { try {
module.setCreateBy(GenSecurityUtils.getUserId()); module.setCreateBy(SecurityUtils.getUserId());
Integer renewal = moduleDao.insertModule(module); Integer renewal = moduleDao.insertModule(module);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -98,18 +98,18 @@ public class ModuleServiceImpl implements ModuleService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> updateModule(Module module) { public ServerResult<Integer> updateModule(Module module) {
try { try {
module.setUpdateBy(GenSecurityUtils.getUserId()); module.setUpdateBy(SecurityUtils.getUserId());
Integer renewal = moduleDao.updateModule(module); Integer renewal = moduleDao.updateModule(module);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -120,17 +120,17 @@ public class ModuleServiceImpl implements ModuleService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteModuleByIds(Long[] ids) { public ServerResult<Integer> deleteModuleByIds(Long[] ids) {
try { try {
Integer renewal = moduleDao.deleteModuleByIds(ids); Integer renewal = moduleDao.deleteModuleByIds(ids);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -141,17 +141,17 @@ public class ModuleServiceImpl implements ModuleService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteModuleById(Long id) { public ServerResult<Integer> deleteModuleById(Long id) {
try { try {
Integer renewal = moduleDao.deleteModuleById(id); Integer renewal = moduleDao.deleteModuleById(id);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
} }

View File

@ -1,16 +1,16 @@
package com.ebts.generator.service.impl; package com.ebts.generator.service.impl;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.entity.entity.Menu;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.QueryDao; import com.ebts.generator.dao.QueryDao;
import com.ebts.generator.dao.UniQueryDao; import com.ebts.generator.dao.UniQueryDao;
import com.ebts.generator.entity.UniCon; import com.ebts.generator.entity.UniCon;
import com.ebts.generator.entity.UniQuery; import com.ebts.generator.entity.UniQuery;
import com.ebts.generator.service.QueryService; import com.ebts.generator.service.QueryService;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenSecurityUtils;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.entity.GenMenu;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -41,54 +41,54 @@ public class QueryServiceImpl implements QueryService {
* 查询万能查询的基本信息和条件信息 * 查询万能查询的基本信息和条件信息
*/ */
@Override @Override
public GenServerResult<UniQuery> selectQueryById(Long id) { public ServerResult<UniQuery> selectQueryById(Long id) {
try { try {
UniQuery uniQuery = queryDao.selectQueryInfo(id); UniQuery uniQuery = queryDao.selectQueryInfo(id);
if (uniQuery != null) { if (uniQuery != null) {
return new GenServerResult<>(true, uniQuery); return new ServerResult<>(true, uniQuery);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GenServerResult<Integer> Release(UniQuery uniQuery) { public ServerResult<Integer> Release(UniQuery uniQuery) {
try { try {
Integer isRelease = queryDao.Release(uniQuery.getId()); Integer isRelease = queryDao.Release(uniQuery.getId());
if ((isRelease == 1 && uniQuery.getIsRelease() == 2) || (isRelease == 2 && uniQuery.getIsRelease() == 1)) { if ((isRelease == 1 && uniQuery.getIsRelease() == 2) || (isRelease == 2 && uniQuery.getIsRelease() == 1)) {
if (uniQuery.getIsRelease() == 1) { if (uniQuery.getIsRelease() == 1) {
UniQuery query = uniQueryDao.selectUniQueryById(uniQuery.getId()); UniQuery query = uniQueryDao.selectUniQueryById(uniQuery.getId());
GenMenu genMenu = new GenMenu(query.getId(), query.getUqName(), GenSecurityUtils.getUserId()); Menu Menu = new Menu(query.getId(), query.getUqName(), SecurityUtils.getUserId());
Integer insermenu = queryDao.insertMenu(genMenu); Integer insermenu = queryDao.insertMenu(Menu);
if (insermenu == 0) { if (insermenu == 0) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} else { } else {
Integer deleteMenu = queryDao.deleteMenu("data/" + uniQuery.getId()); Integer deleteMenu = queryDao.deleteMenu("data/" + uniQuery.getId());
if (deleteMenu == 0) { if (deleteMenu == 0) {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} }
Integer release = queryDao.changeRelease(uniQuery); Integer release = queryDao.changeRelease(uniQuery);
if (release > 0) { if (release > 0) {
return new GenServerResult<>(true); return new ServerResult<>(true);
} else { } else {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.STATE_ERROR); return new ServerResult<>(false, ReturnConstants.STATE_ERROR);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -97,7 +97,7 @@ public class QueryServiceImpl implements QueryService {
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GenServerResult<Integer> updateQueryInfo(UniQuery uniQuery) { public ServerResult<Integer> updateQueryInfo(UniQuery uniQuery) {
try { try {
int uqrenewal = uniQueryDao.updateUniQuery(uniQuery); int uqrenewal = uniQueryDao.updateUniQuery(uniQuery);
if (uqrenewal > 0) { if (uqrenewal > 0) {
@ -105,40 +105,41 @@ public class QueryServiceImpl implements QueryService {
queryDao.deleteUniCon(uniQuery.getId()); queryDao.deleteUniCon(uniQuery.getId());
Integer ucrenewal = queryDao.insertUniCon(uniQuery.getUniCons()); Integer ucrenewal = queryDao.insertUniCon(uniQuery.getUniCons());
if (ucrenewal == 0) { if (ucrenewal == 0) {
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} }
} }
return new GenServerResult<>(true); return new ServerResult<>(true);
} }
return new GenServerResult<>(false, GenReturnConstants.OP_ERROR); return new ServerResult<>(false, ReturnConstants.OP_ERROR);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@Override @Override
public GenServerResult<List<Map<String, Object>>> previewQuery(UniQuery uniQuery) { public ServerResult<List<Map<String, Object>>> previewQuery(UniQuery uniQuery) {
try { try {
StringBuilder sql = new StringBuilder(uniQuery.getUqSql().toLowerCase()); StringBuilder sql = new StringBuilder(uniQuery.getUqSql().toLowerCase());
List<UniCon> uniConList = uniQuery.getUniCons(); List<UniCon> uniConList = uniQuery.getUniCons();
if (sql.toString().contains("insert") || sql.toString().contains("delete ") || sql.toString().contains("update ") || 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("drop ") || sql.toString().contains("database ") || sql.toString().contains("create ") ||
sql.toString().contains("view ") || sql.toString().contains("alter ") || sql.toString().contains("gen_")) { sql.toString().contains("view ") || sql.toString().contains("alter ") || sql.toString().contains("gen_")) {
return new GenServerResult<>(false, "sql语句含有insert,delete,update,drop,database,view,alter,gen_等特殊字符!"); return new ServerResult<>(false, "sql语句含有insert,delete,update,drop,database,view,alter,gen_等特殊字符!");
} }
if (uniConList.size() > 0) { if (uniConList.size() > 0) {
sql.append(" where 1 = 1"); sql.append(" where 1 = 1");
for (UniCon uniCon : uniConList) { for (UniCon uniCon : uniConList) {
if (!uniCon.getUcMock().equals("") && uniCon.getUcMock() != null) if (!uniCon.getUcMock().equals("") && uniCon.getUcMock() != null) {
sql.append(conversionPreview(uniCon)); sql.append(conversionPreview(uniCon));
} }
} }
}
List<Map<String, Object>> dataMap = queryDao.UniQuery(sql.toString()); List<Map<String, Object>> dataMap = queryDao.UniQuery(sql.toString());
return new GenServerResult<>(true, dataMap); return new ServerResult<>(true, dataMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }

View File

@ -2,14 +2,14 @@ package com.ebts.generator.service.impl;
import java.util.List; import java.util.List;
import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.DateUtils;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.RegularDao; import com.ebts.generator.dao.RegularDao;
import com.ebts.generator.entity.Regular; import com.ebts.generator.entity.Regular;
import com.ebts.generator.service.RegularService; import com.ebts.generator.service.RegularService;
import com.ebts.generator.utils.GenDateUtils;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenSecurityUtils;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -35,17 +35,17 @@ public class RegularServiceImpl implements RegularService {
* @return 校验规则 * @return 校验规则
*/ */
@Override @Override
public GenServerResult<Regular> selectRegularById(Long id) { public ServerResult<Regular> selectRegularById(Long id) {
try { try {
Regular regular = regularDao.selectRegularById(id); Regular regular = regularDao.selectRegularById(id);
if (regular != null) { if (regular != null) {
return new GenServerResult<>(true, regular); return new ServerResult<>(true, regular);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -56,17 +56,17 @@ public class RegularServiceImpl implements RegularService {
* @return 校验规则 * @return 校验规则
*/ */
@Override @Override
public GenServerResult<List<Regular>> selectRegularList(Regular regular) { public ServerResult<List<Regular>> selectRegularList(Regular regular) {
try { try {
List<Regular> regulars = regularDao.selectRegularList(regular); List<Regular> regulars = regularDao.selectRegularList(regular);
if (regulars.size() > 0) { if (regulars.size() > 0) {
return new GenServerResult<>(true, regulars); return new ServerResult<>(true, regulars);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
/** /**
@ -75,17 +75,17 @@ public class RegularServiceImpl implements RegularService {
* @return 校验规则 * @return 校验规则
*/ */
@Override @Override
public GenServerResult<List<Regular>> selectRegularOption() { public ServerResult<List<Regular>> selectRegularOption() {
try { try {
List<Regular> regulars = regularDao.selectRegularOption(); List<Regular> regulars = regularDao.selectRegularOption();
if (regulars.size() > 0) { if (regulars.size() > 0) {
return new GenServerResult<>(true, regulars); return new ServerResult<>(true, regulars);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -96,15 +96,15 @@ public class RegularServiceImpl implements RegularService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> insertRegular(Regular regular) { public ServerResult<Integer> insertRegular(Regular regular) {
try { try {
regular.setCreateTime(GenDateUtils.getNowDate()); regular.setCreateTime(DateUtils.getNowDate());
regular.setCreateBy(GenSecurityUtils.getUserId()); regular.setCreateBy(SecurityUtils.getUserId());
int renewal = regularDao.insertRegular(regular); int renewal = regularDao.insertRegular(regular);
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -115,15 +115,15 @@ public class RegularServiceImpl implements RegularService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> updateRegular(Regular regular) { public ServerResult<Integer> updateRegular(Regular regular) {
try { try {
regular.setUpdateTime(GenDateUtils.getNowDate()); regular.setUpdateTime(DateUtils.getNowDate());
regular.setUpdateBy(GenSecurityUtils.getUserId()); regular.setUpdateBy(SecurityUtils.getUserId());
int renewal = regularDao.updateRegular(regular); int renewal = regularDao.updateRegular(regular);
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -134,13 +134,13 @@ public class RegularServiceImpl implements RegularService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteRegularByIds(Long[] ids) { public ServerResult<Integer> deleteRegularByIds(Long[] ids) {
try { try {
Integer renewals = regularDao.deleteRegularByIds(ids); Integer renewals = regularDao.deleteRegularByIds(ids);
return new GenServerResult<>(true, renewals); return new ServerResult<>(true, renewals);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -151,13 +151,13 @@ public class RegularServiceImpl implements RegularService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> deleteRegularById(Long id) { public ServerResult<Integer> deleteRegularById(Long id) {
try { try {
Integer renewal = regularDao.deleteRegularById(id); Integer renewal = regularDao.deleteRegularById(id);
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
} }

View File

@ -1,13 +1,12 @@
package com.ebts.generator.service.impl; package com.ebts.generator.service.impl;
import com.ebts.common.exception.EbtsException;
import com.ebts.common.utils.ServerResult;
import com.ebts.generator.dao.RelDao; import com.ebts.generator.dao.RelDao;
import com.ebts.generator.entity.RelColumn; import com.ebts.generator.entity.RelColumn;
import com.ebts.generator.entity.RelTable; import com.ebts.generator.entity.RelTable;
import com.ebts.generator.service.RelService; import com.ebts.generator.service.RelService;
import com.ebts.generator.utils.GenReturnConstants;
import com.ebts.generator.utils.GenServerResult;
import com.ebts.generator.utils.RelUtil; import com.ebts.generator.utils.RelUtil;
import com.ebts.generator.utils.exception.GenEbtsException;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -34,13 +33,13 @@ public class RelServiceImpl implements RelService {
* @return * @return
*/ */
@Override @Override
public GenServerResult<List<Map<String, Object>>> tableInfos() { public ServerResult<List<Map<String, Object>>> tableInfos() {
try { try {
List<Map<String, Object>> dataMap = relDao.tableInfos(); List<Map<String, Object>> dataMap = relDao.tableInfos();
return new GenServerResult<>(dataMap); return new ServerResult<>(dataMap);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException("获取数据库表信息错误",e); throw new EbtsException("获取数据库表信息错误",e);
} }
} }
@ -52,38 +51,38 @@ public class RelServiceImpl implements RelService {
* @return * @return
*/ */
@Override @Override
public GenServerResult<List<RelColumn>> relColumns(String tableName, Long relId) { public ServerResult<List<RelColumn>> relColumns(String tableName, Long relId) {
try { try {
List<RelColumn> relColumns = relDao.selectTableColumn(tableName); List<RelColumn> relColumns = relDao.selectTableColumn(tableName);
for (RelColumn relColumn : relColumns) { for (RelColumn relColumn : relColumns) {
RelUtil.initRelColumn(relColumn, relId); RelUtil.initRelColumn(relColumn, relId);
} }
return new GenServerResult<>(true,relColumns); return new ServerResult<>(relColumns);
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException("获取关联边字段信息错误",e); throw new EbtsException("获取关联边字段信息错误",e);
} }
} }
@Override @Override
public GenServerResult<List<Map<String, Object>>> tableColumns(String tableName) { public ServerResult<List<Map<String, Object>>> tableColumns(String tableName) {
try { try {
List<Map<String,Object>> columns = relDao.tableColumns(tableName); List<Map<String,Object>> columns = relDao.tableColumns(tableName);
return new GenServerResult<>(columns); return new ServerResult<>(columns);
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException("获取字段信息错误",e); throw new EbtsException("获取字段信息错误",e);
} }
} }
@Override @Override
public GenServerResult<List<RelTable>> relTableByTableId(Long tableId) { public ServerResult<List<RelTable>> relTableByTableId(Long tableId) {
try { try {
List<RelTable> relTables = relDao.relTableByTableId(tableId); List<RelTable> relTables = relDao.relTableByTableId(tableId);
return new GenServerResult<>(relTables); return new ServerResult<>(relTables);
}catch (RuntimeException e){ }catch (RuntimeException e){
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException("获取关联数据错误",e); throw new EbtsException("获取关联数据错误",e);
} }
} }
} }

View File

@ -2,10 +2,10 @@ package com.ebts.generator.service.impl;
import java.util.List; import java.util.List;
import com.ebts.generator.utils.GenReturnConstants; import com.ebts.common.constant.ReturnConstants;
import com.ebts.generator.utils.GenSecurityUtils; import com.ebts.common.exception.EbtsException;
import com.ebts.generator.utils.GenServerResult; import com.ebts.common.utils.SecurityUtils;
import com.ebts.generator.utils.exception.GenEbtsException; import com.ebts.common.utils.ServerResult;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -36,17 +36,17 @@ public class UniQueryServiceImpl implements UniQueryService {
* @return 万能查询 * @return 万能查询
*/ */
@Override @Override
public GenServerResult<UniQuery> selectUniQueryById(Long id) { public ServerResult<UniQuery> selectUniQueryById(Long id) {
try { try {
UniQuery uniQuery = uniQueryDao.selectUniQueryById(id); UniQuery uniQuery = uniQueryDao.selectUniQueryById(id);
if (uniQuery != null) { if (uniQuery != null) {
return new GenServerResult<UniQuery>(true, uniQuery); return new ServerResult<UniQuery>(true, uniQuery);
} else { } else {
return new GenServerResult<UniQuery>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<UniQuery>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -57,17 +57,17 @@ public class UniQueryServiceImpl implements UniQueryService {
* @return 万能查询 * @return 万能查询
*/ */
@Override @Override
public GenServerResult<List<UniQuery>> selectUniQueryList(UniQuery uniQuery) { public ServerResult<List<UniQuery>> selectUniQueryList(UniQuery uniQuery) {
try { try {
List<UniQuery> uniQueryList = uniQueryDao.selectUniQueryList(uniQuery); List<UniQuery> uniQueryList = uniQueryDao.selectUniQueryList(uniQuery);
if (uniQueryList.size() > 0) { if (uniQueryList.size() > 0) {
return new GenServerResult<List<UniQuery>>(true, uniQueryList); return new ServerResult<List<UniQuery>>(true, uniQueryList);
} else { } else {
return new GenServerResult<List<UniQuery>>(false, GenReturnConstants.RESULT_EMPTY); return new ServerResult<List<UniQuery>>(false, ReturnConstants.RESULT_EMPTY);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -78,18 +78,18 @@ public class UniQueryServiceImpl implements UniQueryService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> insertUniQuery(UniQuery uniQuery) { public ServerResult<Integer> insertUniQuery(UniQuery uniQuery) {
try { try {
uniQuery.setCreateBy(GenSecurityUtils.getUserId()); uniQuery.setCreateBy(SecurityUtils.getUserId());
Integer renewal = uniQueryDao.insertUniQuery(uniQuery); Integer renewal = uniQueryDao.insertUniQuery(uniQuery);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -100,18 +100,18 @@ public class UniQueryServiceImpl implements UniQueryService {
* @return 结果 * @return 结果
*/ */
@Override @Override
public GenServerResult<Integer> updateUniQuery(UniQuery uniQuery) { public ServerResult<Integer> updateUniQuery(UniQuery uniQuery) {
try { try {
uniQuery.setUpdateBy(GenSecurityUtils.getUserId()); uniQuery.setUpdateBy(SecurityUtils.getUserId());
Integer renewal = uniQueryDao.updateUniQuery(uniQuery); Integer renewal = uniQueryDao.updateUniQuery(uniQuery);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<Integer>(true, renewal); return new ServerResult<Integer>(true, renewal);
} else { } else {
return new GenServerResult<Integer>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<Integer>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -123,21 +123,21 @@ public class UniQueryServiceImpl implements UniQueryService {
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GenServerResult<Integer> deleteUniQueryByIds(Long[] ids) { public ServerResult<Integer> deleteUniQueryByIds(Long[] ids) {
try { try {
Integer renewal = uniQueryDao.deleteUniQueryByIds(ids); Integer renewal = uniQueryDao.deleteUniQueryByIds(ids);
for (Long id : ids) { for (Long id : ids) {
uniQueryDao.deleteUniQueryByUqId(id); uniQueryDao.deleteUniQueryByUqId(id);
} }
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} else { } else {
TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
@ -149,18 +149,18 @@ public class UniQueryServiceImpl implements UniQueryService {
*/ */
@Override @Override
@Transactional(rollbackFor = Exception.class) @Transactional(rollbackFor = Exception.class)
public GenServerResult<Integer> deleteUniQueryById(Long id) { public ServerResult<Integer> deleteUniQueryById(Long id) {
try { try {
Integer renewal = uniQueryDao.deleteUniQueryById(id); Integer renewal = uniQueryDao.deleteUniQueryById(id);
uniQueryDao.deleteUniQueryByUqId(id); uniQueryDao.deleteUniQueryByUqId(id);
if (renewal > 0) { if (renewal > 0) {
return new GenServerResult<>(true, renewal); return new ServerResult<>(true, renewal);
} else { } else {
return new GenServerResult<>(false, GenReturnConstants.SYS_FAILL); return new ServerResult<>(false, ReturnConstants.SYS_FAILL);
} }
} catch (RuntimeException e) { } catch (RuntimeException e) {
logger.error(e.getMessage()); logger.error(e.getMessage());
throw new GenEbtsException(GenReturnConstants.OP_ERROR,e); throw new EbtsException(ReturnConstants.OP_ERROR,e);
} }
} }
} }

View File

@ -1,90 +0,0 @@
package com.ebts.generator.utils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ebts.generator.utils.page.GenPageDomain;
import com.ebts.generator.utils.page.GenTableDataInfo;
import com.ebts.generator.utils.page.GenTableSupport;
import com.ebts.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<String, Object> 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);
}
}

View File

@ -1,144 +0,0 @@
package com.ebts.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 binlin
*/
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 + "分钟";
}
}

View File

@ -1,148 +0,0 @@
package com.ebts.generator.utils;
import com.ebts.generator.utils.constant.Constants;
import com.ebts.generator.utils.entity.GenDictData;
import com.ebts.generator.utils.redis.GenRedisCache;
import com.ebts.generator.utils.spring.GenSpringUtils;
import java.util.Collection;
import java.util.List;
/**
* 字典工具类
*
* @author binlin
*/
public class GenDictUtils {
/**
* 分隔符
*/
public static final String SEPARATOR = ",";
/**
* 设置字典缓存
*
* @param key 参数键
* @param genDictData 字典数据列表
*/
public static void setDictCache(String key, List<GenDictData> genDictData) {
GenSpringUtils.getBean(GenRedisCache.class).setCacheObject(getCacheKey(key), genDictData);
}
/**
* 获取字典缓存
*
* @param key 参数键
* @return dictDatas 字典数据列表
*/
public static List<GenDictData> getDictCache(String key) {
Object cacheObj = GenSpringUtils.getBean(GenRedisCache.class).getCacheObject(getCacheKey(key));
if (GenStringUtils.isNotNull(cacheObj)) {
List<GenDictData> 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<GenDictData> 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<GenDictData> 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<String> 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;
}
}

View File

@ -1,93 +0,0 @@
package com.ebts.generator.utils;
/**
* 返回状态码
*
* @author binlin
*/
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;
}

View File

@ -1,295 +0,0 @@
package com.ebts.generator.utils;
import com.ebts.generator.config.Config;
import com.ebts.generator.controller.AjaxResult;
import com.ebts.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<String, CellStyle> styles;
/**
* 导入导出数据列表
*/
private List<Map<String, Object>> list;
/**
* 注解列表
*/
private List<String> herders;
/**
* 对list数据源将其里面的数据导入到excel表单
*
* @param list 导出数据集合
* @param sheetName 工作表的名称
* @return 结果
*/
public AjaxResult exportExcel(List<Map<String, Object>> list, String sheetName) {
this.init(list, sheetName);
return exportExcel();
}
public void init(List<Map<String, Object>> list, String sheetName) {
if (list == null) {
list = new ArrayList<Map<String, Object>>();
}
this.list = list;
this.sheetName = sheetName;
createExcelField();
createWorkbook();
}
/**
* 创建一个工作簿
*/
public void createWorkbook() {
this.wb = new SXSSFWorkbook(500);
}
/**
* 得到所有定义字段
*/
private void createExcelField() {
this.herders = new ArrayList<String>();
Map<String, Object> modeMap = this.list.get(0);
for (String key : modeMap.keySet()) {
this.herders.add(key);
}
}
/**
* 创建表格样式
*
* @param wb 工作薄对象
* @return 样式列表
*/
private Map<String, CellStyle> createStyles(Workbook wb) {
// 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
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();
}
}
}
}
}

View File

@ -1,24 +0,0 @@
package com.ebts.generator.utils;
import com.ebts.generator.utils.spring.GenSpringUtils;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
/**
* 获取i18n资源文件
*
* @author binlin
*/
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());
}
}

View File

@ -1,29 +0,0 @@
package com.ebts.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 = "操作失败!";
}

View File

@ -1,34 +0,0 @@
package com.ebts.generator.utils;
import com.alibaba.fastjson.JSONObject;
import com.ebts.generator.utils.exception.GenCustomException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
/**
* 安全服务工具类
*
* @author binlin
*/
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();
}
}

View File

@ -1,94 +0,0 @@
package com.ebts.generator.utils;
/**
* @author clay
* @version 1.0
* @mail 20932067@zju.edu.cn
* @date 2020/12/15 21:34
*/
public class GenServerResult<T> {
private T data;// 成功时返回的数据
private Integer count;
private boolean start;
private String msg;
private String sheetName;
public GenServerResult() {
}
public GenServerResult(T data) {
this.data = data;
this.start = true;
this.msg = "操作成功";
}
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;
}
}

View File

@ -1,119 +0,0 @@
package com.ebts.generator.utils;
import com.ebts.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 binlin
*/
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;
}
}

View File

@ -1,415 +0,0 @@
package com.ebts.generator.utils;
import com.ebts.generator.utils.text.StrFormatter;
import java.util.*;
/**
* 字符串工具类
*
* @author binlin
*/
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> 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);
}
/**
* 格式化文本, {} 表示占位符<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @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<String> str2Set(String str, String sep) {
return new HashSet<String>(str2List(str, sep, true, false));
}
/**
* 字符串转list
*
* @param str 字符串
* @param sep 分隔符
* @param filterBlank 过滤纯空白
* @param trim 去掉首尾空白
* @return list集合
*/
public static final List<String> str2List(String str, String sep, boolean filterBlank, boolean trim) {
List<String> list = new ArrayList<String>();
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;
}
public static String toLoad(String str){
return str.substring(0,1).toLowerCase()+str.substring(1);
}
@SuppressWarnings("unchecked")
public static <T> T cast(Object obj) {
return (T) obj;
}
}

View File

@ -2,6 +2,7 @@ package com.ebts.generator.utils;
import java.util.Arrays; import java.util.Arrays;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.utils.constant.GenConstants; import com.ebts.generator.utils.constant.GenConstants;
import org.apache.commons.lang3.RegExUtils; import org.apache.commons.lang3.RegExUtils;
import com.ebts.generator.config.GenConfig; import com.ebts.generator.config.GenConfig;
@ -36,7 +37,7 @@ public class GenUtils {
column.setTableId(table.getTableId()); column.setTableId(table.getTableId());
column.setCreateBy(table.getCreateBy()); column.setCreateBy(table.getCreateBy());
// 设置java字段名 // 设置java字段名
column.setJavaField(GenStringUtils.toCamelCase(columnName)); column.setJavaField(StringUtils.toCamelCase(columnName));
// 设置默认类型 // 设置默认类型
column.setJavaType(GenConstants.TYPE_STRING); column.setJavaType(GenConstants.TYPE_STRING);
@ -52,7 +53,7 @@ public class GenUtils {
column.setHtmlType(GenConstants.HTML_INPUT); column.setHtmlType(GenConstants.HTML_INPUT);
// 如果是浮点型 统一用BigDecimal // 如果是浮点型 统一用BigDecimal
String[] str = GenStringUtils.split(GenStringUtils.substringBetween(column.getColumnType(), "(", ")"), ","); String[] str = StringUtils.split(StringUtils.substringBetween(column.getColumnType(), "(", ")"), ",");
if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) {
column.setJavaType(GenConstants.TYPE_BIGDECIMAL); column.setJavaType(GenConstants.TYPE_BIGDECIMAL);
} }
@ -83,28 +84,28 @@ public class GenUtils {
} }
// 查询字段类型 // 查询字段类型
if (GenStringUtils.endsWithIgnoreCase(columnName, "name")) { if (StringUtils.endsWithIgnoreCase(columnName, "name")) {
column.setQueryType(GenConstants.QUERY_LIKE); column.setQueryType(GenConstants.QUERY_LIKE);
} }
// 状态字段设置单选框 // 状态字段设置单选框
if (GenStringUtils.endsWithIgnoreCase(columnName, "status")) { if (StringUtils.endsWithIgnoreCase(columnName, "status")) {
column.setHtmlType(GenConstants.HTML_RADIO); column.setHtmlType(GenConstants.HTML_RADIO);
} }
// 类型&性别字段设置下拉框 // 类型&性别字段设置下拉框
else if (GenStringUtils.endsWithIgnoreCase(columnName, "type") else if (StringUtils.endsWithIgnoreCase(columnName, "type")
|| GenStringUtils.endsWithIgnoreCase(columnName, "sex")) { || StringUtils.endsWithIgnoreCase(columnName, "sex")) {
column.setHtmlType(GenConstants.HTML_SELECT); column.setHtmlType(GenConstants.HTML_SELECT);
} }
// 图片字段设置图片上传控件 // 图片字段设置图片上传控件
else if (GenStringUtils.endsWithIgnoreCase(columnName, "image")) { else if (StringUtils.endsWithIgnoreCase(columnName, "image")) {
column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD); column.setHtmlType(GenConstants.HTML_IMAGE_UPLOAD);
} }
// 文件字段设置文件上传控件 // 文件字段设置文件上传控件
else if (GenStringUtils.endsWithIgnoreCase(columnName, "file")) { else if (StringUtils.endsWithIgnoreCase(columnName, "file")) {
column.setHtmlType(GenConstants.HTML_FILE_UPLOAD); column.setHtmlType(GenConstants.HTML_FILE_UPLOAD);
} }
// 内容字段设置富文本控件 // 内容字段设置富文本控件
else if (GenStringUtils.endsWithIgnoreCase(columnName, "content")) { else if (StringUtils.endsWithIgnoreCase(columnName, "content")) {
column.setHtmlType(GenConstants.HTML_EDITOR); column.setHtmlType(GenConstants.HTML_EDITOR);
} }
} }
@ -129,7 +130,7 @@ public class GenUtils {
public static String getModuleName(String packageName) { public static String getModuleName(String packageName) {
int lastIndex = packageName.lastIndexOf("."); int lastIndex = packageName.lastIndexOf(".");
int nameLength = packageName.length(); int nameLength = packageName.length();
String moduleName = GenStringUtils.substring(packageName, lastIndex + 1, nameLength); String moduleName = StringUtils.substring(packageName, lastIndex + 1, nameLength);
return moduleName; return moduleName;
} }
@ -142,7 +143,7 @@ public class GenUtils {
public static String getBusinessName(String tableName) { public static String getBusinessName(String tableName) {
int lastIndex = tableName.lastIndexOf("_"); int lastIndex = tableName.lastIndexOf("_");
int nameLength = tableName.length(); int nameLength = tableName.length();
String businessName = GenStringUtils.substring(tableName, lastIndex + 1, nameLength); String businessName = StringUtils.substring(tableName, lastIndex + 1, nameLength);
return businessName; return businessName;
} }
@ -155,11 +156,11 @@ public class GenUtils {
public static String convertClassName(String tableName) { public static String convertClassName(String tableName) {
boolean autoRemovePre = GenConfig.getAutoRemovePre(); boolean autoRemovePre = GenConfig.getAutoRemovePre();
String tablePrefix = GenConfig.getTablePrefix(); String tablePrefix = GenConfig.getTablePrefix();
if (autoRemovePre && GenStringUtils.isNotEmpty(tablePrefix)) { if (autoRemovePre && StringUtils.isNotEmpty(tablePrefix)) {
String[] searchList = GenStringUtils.split(tablePrefix, ","); String[] searchList = StringUtils.split(tablePrefix, ",");
tableName = replaceFirst(tableName, searchList); tableName = replaceFirst(tableName, searchList);
} }
return GenStringUtils.convertToCamelCase(tableName); return StringUtils.convertToCamelCase(tableName);
} }
/** /**
@ -197,8 +198,8 @@ public class GenUtils {
* @return 截取后的列类型 * @return 截取后的列类型
*/ */
public static String getDbType(String columnType) { public static String getDbType(String columnType) {
if (GenStringUtils.indexOf(columnType, "(") > 0) { if (StringUtils.indexOf(columnType, "(") > 0) {
return GenStringUtils.substringBefore(columnType, "("); return StringUtils.substringBefore(columnType, "(");
} else { } else {
return columnType; return columnType;
} }
@ -211,8 +212,8 @@ public class GenUtils {
* @return 截取后的列类型 * @return 截取后的列类型
*/ */
public static Integer getColumnLength(String columnType) { public static Integer getColumnLength(String columnType) {
if (GenStringUtils.indexOf(columnType, "(") > 0) { if (StringUtils.indexOf(columnType, "(") > 0) {
String length = GenStringUtils.substringBetween(columnType, "(", ")"); String length = StringUtils.substringBetween(columnType, "(", ")");
return Integer.valueOf(length); return Integer.valueOf(length);
} else { } else {
return 0; return 0;

View File

@ -1,5 +1,7 @@
package com.ebts.generator.utils; package com.ebts.generator.utils;
import com.ebts.common.utils.DateUtils;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.generator.entity.ApiClass; import com.ebts.generator.entity.ApiClass;
import com.ebts.generator.entity.InterTable; import com.ebts.generator.entity.InterTable;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -9,7 +11,10 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
public class GenInterTableUtils { /**
* @author 18209
*/
public class InterTableUtils {
public static List<VelocityContext> prepareMoudleContext(List<InterTable> interTableList) { public static List<VelocityContext> prepareMoudleContext(List<InterTable> interTableList) {
List<ApiClass> apiClassList = new ArrayList<ApiClass>(); List<ApiClass> apiClassList = new ArrayList<ApiClass>();
for (int i = 0; i < interTableList.size(); i++) { for (int i = 0; i < interTableList.size(); i++) {
@ -57,7 +62,7 @@ public class GenInterTableUtils {
permission = true; permission = true;
} }
} }
velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("createBy", SecurityUtils.getUserId());
velocityContext.put("Permission", permission); velocityContext.put("Permission", permission);
velocityContext.put("packageName", "com.huhyun." + module); velocityContext.put("packageName", "com.huhyun." + module);
velocityContext.put("prefix", module + ":" + getLowerCase(className)); velocityContext.put("prefix", module + ":" + getLowerCase(className));
@ -67,7 +72,7 @@ public class GenInterTableUtils {
velocityContext.put("functionName", apiclass.getcDescribe()); velocityContext.put("functionName", apiclass.getcDescribe());
velocityContext.put("author", apiclass.getAuthor()); velocityContext.put("author", apiclass.getAuthor());
velocityContext.put("emali", apiclass.getEmail()); velocityContext.put("emali", apiclass.getEmail());
velocityContext.put("time", GenDateUtils.getTime()); velocityContext.put("time", DateUtils.getTime());
contextList.add(velocityContext); contextList.add(velocityContext);
} }
@ -82,7 +87,7 @@ public class GenInterTableUtils {
permission = true; permission = true;
} }
} }
velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("createBy", SecurityUtils.getUserId());
velocityContext.put("Permission", permission); velocityContext.put("Permission", permission);
velocityContext.put("packageName", apiclass.getPackageName()); velocityContext.put("packageName", apiclass.getPackageName());
velocityContext.put("ClassName", getUpperCase(apiclass.getcName())); velocityContext.put("ClassName", getUpperCase(apiclass.getcName()));
@ -92,7 +97,7 @@ public class GenInterTableUtils {
velocityContext.put("functionName", apiclass.getcDescribe()); velocityContext.put("functionName", apiclass.getcDescribe());
velocityContext.put("author", apiclass.getAuthor()); velocityContext.put("author", apiclass.getAuthor());
velocityContext.put("emali", apiclass.getEmail()); velocityContext.put("emali", apiclass.getEmail());
velocityContext.put("time", GenDateUtils.getTime()); velocityContext.put("time", DateUtils.getTime());
return velocityContext; return velocityContext;
} }

View File

@ -1,5 +1,6 @@
package com.ebts.generator.utils; package com.ebts.generator.utils;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.entity.RelColumn; import com.ebts.generator.entity.RelColumn;
import com.ebts.generator.utils.constant.GenConstants; import com.ebts.generator.utils.constant.GenConstants;
@ -21,7 +22,7 @@ public class RelUtil {
//设置创建者id //设置创建者id
relColumn.setCreateBy(1); relColumn.setCreateBy(1);
//转为设置java字段名称 //转为设置java字段名称
relColumn.setJavaField(GenStringUtils.toCamelCase(columnName)); relColumn.setJavaField(StringUtils.toCamelCase(columnName));
//默认类型 //默认类型
relColumn.setJavaType(GenConstants.TYPE_STRING); relColumn.setJavaType(GenConstants.TYPE_STRING);
//默认查询条件 精确查询 //默认查询条件 精确查询
@ -39,7 +40,7 @@ public class RelUtil {
relColumn.setHtmlType(GenConstants.HTML_INPUT); relColumn.setHtmlType(GenConstants.HTML_INPUT);
// 如果是浮点型 统一用BigDecimal // 如果是浮点型 统一用BigDecimal
String[] str = GenStringUtils.split(GenStringUtils.substringBetween(relColumn.getColumnType(), "(", ")"), ","); String[] str = StringUtils.split(StringUtils.substringBetween(relColumn.getColumnType(), "(", ")"), ",");
if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) { if (str != null && str.length == 2 && Integer.parseInt(str[1]) > 0) {
relColumn.setJavaType(GenConstants.TYPE_BIGDECIMAL); relColumn.setJavaType(GenConstants.TYPE_BIGDECIMAL);
} }
@ -59,16 +60,16 @@ public class RelUtil {
//初始化字典 //初始化字典
relColumn.setDictType(""); relColumn.setDictType("");
// 查询字段类型 // 查询字段类型
if (GenStringUtils.endsWithIgnoreCase(columnName, "name")) { if (StringUtils.endsWithIgnoreCase(columnName, "name")) {
relColumn.setQueryType(GenConstants.QUERY_LIKE); relColumn.setQueryType(GenConstants.QUERY_LIKE);
} }
// 状态字段设置单选框 // 状态字段设置单选框
if (GenStringUtils.endsWithIgnoreCase(columnName, "status")) { if (StringUtils.endsWithIgnoreCase(columnName, "status")) {
relColumn.setHtmlType(GenConstants.HTML_RADIO); relColumn.setHtmlType(GenConstants.HTML_RADIO);
} }
// 类型&性别字段设置下拉框 // 类型&性别字段设置下拉框
else if (GenStringUtils.endsWithIgnoreCase(columnName, "type") else if (StringUtils.endsWithIgnoreCase(columnName, "type")
|| GenStringUtils.endsWithIgnoreCase(columnName, "sex")) { || StringUtils.endsWithIgnoreCase(columnName, "sex")) {
relColumn.setHtmlType(GenConstants.HTML_SELECT); relColumn.setHtmlType(GenConstants.HTML_SELECT);
} }
} }

View File

@ -2,7 +2,7 @@ package com.ebts.generator.utils;
import java.util.Properties; import java.util.Properties;
import com.ebts.generator.utils.constant.Constants; import com.ebts.common.constant.Constants;
import org.apache.velocity.app.Velocity; import org.apache.velocity.app.Velocity;
/** /**

View File

@ -4,6 +4,9 @@ import java.util.ArrayList;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import com.ebts.common.utils.DateUtils;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.common.utils.StringUtils;
import com.ebts.generator.entity.RelTable; import com.ebts.generator.entity.RelTable;
import com.ebts.generator.utils.constant.GenConstants; import com.ebts.generator.utils.constant.GenConstants;
import org.apache.velocity.VelocityContext; import org.apache.velocity.VelocityContext;
@ -47,17 +50,17 @@ public class VelocityUtils {
VelocityContext velocityContext = new VelocityContext(); VelocityContext velocityContext = new VelocityContext();
velocityContext.put("tplCategory", genTable.getTplCategory()); velocityContext.put("tplCategory", genTable.getTplCategory());
velocityContext.put("tableName", genTable.getTableName()); velocityContext.put("tableName", genTable.getTableName());
velocityContext.put("functionName", GenStringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】"); velocityContext.put("functionName", StringUtils.isNotEmpty(functionName) ? functionName : "【请填写功能名称】");
velocityContext.put("ClassName", genTable.getClassName()); velocityContext.put("ClassName", genTable.getClassName());
velocityContext.put("className", GenStringUtils.uncapitalize(genTable.getClassName())); velocityContext.put("className", StringUtils.uncapitalize(genTable.getClassName()));
velocityContext.put("moduleName", genTable.getModuleName()); velocityContext.put("moduleName", genTable.getModuleName());
velocityContext.put("BusinessName", GenStringUtils.capitalize(genTable.getBusinessName())); velocityContext.put("BusinessName", StringUtils.capitalize(genTable.getBusinessName()));
velocityContext.put("businessName", genTable.getBusinessName()); velocityContext.put("businessName", genTable.getBusinessName());
velocityContext.put("basePackage", getPackagePrefix(packageName)); velocityContext.put("basePackage", getPackagePrefix(packageName));
velocityContext.put("packageName", packageName); velocityContext.put("packageName", packageName);
velocityContext.put("author", genTable.getFunctionAuthor()); velocityContext.put("author", genTable.getFunctionAuthor());
velocityContext.put("datetime", GenDateUtils.getDate()); velocityContext.put("datetime", DateUtils.getDate());
velocityContext.put("createBy", GenSecurityUtils.getUserId()); velocityContext.put("createBy", SecurityUtils.getUserId());
velocityContext.put("pkColumn", genTable.getPkColumn()); velocityContext.put("pkColumn", genTable.getPkColumn());
velocityContext.put("importList", getImportList(genTable)); velocityContext.put("importList", getImportList(genTable));
velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName)); velocityContext.put("permissionPrefix", getPermissionPrefix(moduleName, businessName));
@ -78,7 +81,7 @@ public class VelocityUtils {
public static void setRelVelocityContext(VelocityContext context, GenTable genTable) { public static void setRelVelocityContext(VelocityContext context, GenTable genTable) {
context.put("relTables", genTable.getRelTables()); context.put("relTables", genTable.getRelTables());
context.put("tableMapping", GenStringUtils.sqlFormat(genTable.getTableName())); context.put("tableMapping", StringUtils.sqlFormat(genTable.getTableName()));
} }
public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) { public static void setMenuVelocityContext(VelocityContext context, GenTable genTable) {
@ -112,17 +115,17 @@ public class VelocityUtils {
String subTableName = genTable.getSubTableName(); String subTableName = genTable.getSubTableName();
String subTableFkName = genTable.getSubTableFkName(); String subTableFkName = genTable.getSubTableFkName();
String subClassName = genTable.getSubTable().getClassName(); String subClassName = genTable.getSubTable().getClassName();
String subTableFkClassName = GenStringUtils.convertToCamelCase(subTableFkName); String subTableFkClassName = StringUtils.convertToCamelCase(subTableFkName);
context.put("tableMapping", GenStringUtils.sqlFormat(genTable.getTableName())); context.put("tableMapping", StringUtils.sqlFormat(genTable.getTableName()));
context.put("subMapping", GenStringUtils.sqlFormat(subTable.getTableName())); context.put("subMapping", StringUtils.sqlFormat(subTable.getTableName()));
context.put("subTable", subTable); context.put("subTable", subTable);
context.put("subTableName", subTableName); context.put("subTableName", subTableName);
context.put("subTableFkName", subTableFkName); context.put("subTableFkName", subTableFkName);
context.put("subTableFkClassName", subTableFkClassName); context.put("subTableFkClassName", subTableFkClassName);
context.put("subTableFkclassName", GenStringUtils.uncapitalize(subTableFkClassName)); context.put("subTableFkclassName", StringUtils.uncapitalize(subTableFkClassName));
context.put("subClassName", subClassName); context.put("subClassName", subClassName);
context.put("subclassName", GenStringUtils.uncapitalize(subClassName)); context.put("subclassName", StringUtils.uncapitalize(subClassName));
context.put("subImportList", getImportList(genTable.getSubTable())); context.put("subImportList", getImportList(genTable.getSubTable()));
} }
@ -163,34 +166,34 @@ public class VelocityUtils {
// 模块名 // 模块名
String moduleName = genTable.getModuleName(); String moduleName = genTable.getModuleName();
String javaPath = PROJECT_PATH + "/" + GenStringUtils.replace(packageName, ".", "/"); String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, relTable.getRelClass()); fileName = StringUtils.format("{}/entity/{}.java", javaPath, relTable.getRelClass());
return fileName; return fileName;
} }
public static String getPreviewName(String template, String ClassName) { public static String getPreviewName(String template, String ClassName) {
String fileName = ""; String fileName = "";
if (template.contains("entity.java.vm")) { if (template.contains("entity.java.vm")) {
fileName = GenStringUtils.format("{}.java", ClassName); fileName = StringUtils.format("{}.java", ClassName);
} }
if (template.contains("sub-entity.java.vm") && GenStringUtils.equals(GenConstants.TPL_SUB, ClassName)) { if (template.contains("sub-entity.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, ClassName)) {
fileName = GenStringUtils.format("{}.java", ClassName); fileName = StringUtils.format("{}.java", ClassName);
} else if (template.contains("rel-entity.java.vm")) { } else if (template.contains("rel-entity.java.vm")) {
fileName = GenStringUtils.format("{}.java", ClassName); fileName = StringUtils.format("{}.java", ClassName);
} else if (template.contains("dao.java.vm")) { } else if (template.contains("dao.java.vm")) {
fileName = GenStringUtils.format("{}Dao.java", ClassName); fileName = StringUtils.format("{}Dao.java", ClassName);
} else if (template.contains("service.java.vm")) { } else if (template.contains("service.java.vm")) {
fileName = GenStringUtils.format("{}Service.java", ClassName); fileName = StringUtils.format("{}Service.java", ClassName);
} else if (template.contains("serviceImpl.java.vm")) { } else if (template.contains("serviceImpl.java.vm")) {
fileName = GenStringUtils.format("{}ServiceImpl.java", ClassName); fileName = StringUtils.format("{}ServiceImpl.java", ClassName);
} else if (template.contains("controller.java.vm")) { } else if (template.contains("controller.java.vm")) {
fileName = GenStringUtils.format("{}Controller.java",ClassName); fileName = StringUtils.format("{}Controller.java",ClassName);
} else if (template.contains("mapper.xml.vm")) { } else if (template.contains("mapper.xml.vm")) {
fileName = GenStringUtils.format("{}Mapper.xml",ClassName); fileName = StringUtils.format("{}Mapper.xml",ClassName);
} else if (template.contains("table.sql.vm")) { } else if (template.contains("table.sql.vm")) {
fileName = ClassName + "menu.sql"; fileName = ClassName + "menu.sql";
} else if (template.contains("api.js.vm")) { } else if (template.contains("api.js.vm")) {
fileName = GenStringUtils.format("{}.js", GenStringUtils.toLoad(ClassName)); fileName = StringUtils.format("{}.js", StringUtils.toLoad(ClassName));
} else if (template.contains("index.vue.vm")) { } else if (template.contains("index.vue.vm")) {
fileName = "index.vue"; fileName = "index.vue";
} else if (template.contains("index-tree.vue.vm")) { } else if (template.contains("index-tree.vue.vm")) {
@ -214,35 +217,35 @@ public class VelocityUtils {
// 业务名称 // 业务名称
String businessName = genTable.getBusinessName(); String businessName = genTable.getBusinessName();
String javaPath = PROJECT_PATH + "/" + GenStringUtils.replace(packageName, ".", "/"); String javaPath = PROJECT_PATH + "/" + StringUtils.replace(packageName, ".", "/");
String mybatisPath = MYBATIS_PATH + "/" + moduleName; String mybatisPath = MYBATIS_PATH + "/" + moduleName;
String vuePath = "vue"; String vuePath = "vue";
if (template.contains("entity.java.vm")) { if (template.contains("entity.java.vm")) {
fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, className); fileName = StringUtils.format("{}/entity/{}.java", javaPath, className);
} }
if (template.contains("sub-entity.java.vm") && GenStringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) { if (template.contains("sub-entity.java.vm") && StringUtils.equals(GenConstants.TPL_SUB, genTable.getTplCategory())) {
fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, genTable.getSubTable().getClassName()); fileName = StringUtils.format("{}/entity/{}.java", javaPath, genTable.getSubTable().getClassName());
} else if (template.contains("ass-entity.java.vm")) { } else if (template.contains("ass-entity.java.vm")) {
fileName = GenStringUtils.format("{}/entity/{}.java", javaPath, GenUtils.convertClassName(genTable.getAssTableName())); fileName = StringUtils.format("{}/entity/{}.java", javaPath, GenUtils.convertClassName(genTable.getAssTableName()));
} else if (template.contains("dao.java.vm")) { } else if (template.contains("dao.java.vm")) {
fileName = GenStringUtils.format("{}/dao/{}Dao.java", javaPath, className); fileName = StringUtils.format("{}/dao/{}Dao.java", javaPath, className);
} else if (template.contains("service.java.vm")) { } else if (template.contains("service.java.vm")) {
fileName = GenStringUtils.format("{}/service/{}Service.java", javaPath, className); fileName = StringUtils.format("{}/service/{}Service.java", javaPath, className);
} else if (template.contains("serviceImpl.java.vm")) { } else if (template.contains("serviceImpl.java.vm")) {
fileName = GenStringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className); fileName = StringUtils.format("{}/service/impl/{}ServiceImpl.java", javaPath, className);
} else if (template.contains("controller.java.vm")) { } else if (template.contains("controller.java.vm")) {
fileName = GenStringUtils.format("{}/controller/{}Controller.java", javaPath, className); fileName = StringUtils.format("{}/controller/{}Controller.java", javaPath, className);
} else if (template.contains("mapper.xml.vm")) { } else if (template.contains("mapper.xml.vm")) {
fileName = GenStringUtils.format("{}/{}Mapper.xml", mybatisPath, className); fileName = StringUtils.format("{}/{}Mapper.xml", mybatisPath, className);
} else if (template.contains("table.sql.vm")) { } else if (template.contains("table.sql.vm")) {
fileName = businessName + "menu.sql"; fileName = businessName + "menu.sql";
} else if (template.contains("api.js.vm")) { } else if (template.contains("api.js.vm")) {
fileName = GenStringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName); fileName = StringUtils.format("{}/api/{}/{}.js", vuePath, moduleName, businessName);
} else if (template.contains("index.vue.vm")) { } else if (template.contains("index.vue.vm")) {
fileName = GenStringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
} else if (template.contains("index-tree.vue.vm")) { } else if (template.contains("index-tree.vue.vm")) {
fileName = GenStringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName); fileName = StringUtils.format("{}/views/{}/{}/index.vue", vuePath, moduleName, businessName);
} }
return fileName; return fileName;
} }
@ -255,7 +258,7 @@ public class VelocityUtils {
*/ */
public static String getPackagePrefix(String packageName) { public static String getPackagePrefix(String packageName) {
int lastIndex = packageName.lastIndexOf("."); int lastIndex = packageName.lastIndexOf(".");
String basePackage = GenStringUtils.substring(packageName, 0, lastIndex); String basePackage = StringUtils.substring(packageName, 0, lastIndex);
return basePackage; return basePackage;
} }
@ -269,7 +272,7 @@ public class VelocityUtils {
List<GenTableColumn> columns = genTable.getColumns(); List<GenTableColumn> columns = genTable.getColumns();
GenTable subGenTable = genTable.getSubTable(); GenTable subGenTable = genTable.getSubTable();
HashSet<String> importList = new HashSet<String>(); HashSet<String> importList = new HashSet<String>();
if (GenStringUtils.isNotNull(subGenTable)) { if (StringUtils.isNotNull(subGenTable)) {
importList.add("java.util.List"); importList.add("java.util.List");
} }
for (GenTableColumn column : columns) { for (GenTableColumn column : columns) {
@ -291,7 +294,7 @@ public class VelocityUtils {
* @return 返回权限前缀 * @return 返回权限前缀
*/ */
public static String getPermissionPrefix(String moduleName, String businessName) { public static String getPermissionPrefix(String moduleName, String businessName) {
return GenStringUtils.format("{}:{}", moduleName, businessName); return StringUtils.format("{}:{}", moduleName, businessName);
} }
/** /**
@ -301,7 +304,7 @@ public class VelocityUtils {
* @return 上级菜单ID字段 * @return 上级菜单ID字段
*/ */
public static String getParentMenuId(JSONObject paramsObj) { public static String getParentMenuId(JSONObject paramsObj) {
if (GenStringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) { if (StringUtils.isNotEmpty(paramsObj) && paramsObj.containsKey(GenConstants.PARENT_MENU_ID)) {
return paramsObj.getString(GenConstants.PARENT_MENU_ID); return paramsObj.getString(GenConstants.PARENT_MENU_ID);
} }
return DEFAULT_PARENT_MENU_ID; return DEFAULT_PARENT_MENU_ID;
@ -315,9 +318,9 @@ public class VelocityUtils {
*/ */
public static String getTreecode(JSONObject paramsObj) { public static String getTreecode(JSONObject paramsObj) {
if (paramsObj.containsKey(GenConstants.TREE_CODE)) { if (paramsObj.containsKey(GenConstants.TREE_CODE)) {
return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_CODE));
} }
return GenStringUtils.EMPTY; return StringUtils.EMPTY;
} }
/** /**
@ -328,9 +331,9 @@ public class VelocityUtils {
*/ */
public static String getTreeParentCode(JSONObject paramsObj) { public static String getTreeParentCode(JSONObject paramsObj) {
if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) { if (paramsObj.containsKey(GenConstants.TREE_PARENT_CODE)) {
return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_PARENT_CODE));
} }
return GenStringUtils.EMPTY; return StringUtils.EMPTY;
} }
/** /**
@ -341,9 +344,9 @@ public class VelocityUtils {
*/ */
public static String getTreeName(JSONObject paramsObj) { public static String getTreeName(JSONObject paramsObj) {
if (paramsObj.containsKey(GenConstants.TREE_NAME)) { if (paramsObj.containsKey(GenConstants.TREE_NAME)) {
return GenStringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME)); return StringUtils.toCamelCase(paramsObj.getString(GenConstants.TREE_NAME));
} }
return GenStringUtils.EMPTY; return StringUtils.EMPTY;
} }
/** /**

View File

@ -1,128 +0,0 @@
package com.ebts.generator.utils.constant;
/**
* 通用常量信息
*
* @author binlin
*/
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";
}

View File

@ -1,93 +0,0 @@
package com.ebts.generator.utils.constant;
/**
* 返回状态码
*
* @author binlin
*/
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;
}

View File

@ -1,89 +0,0 @@
package com.ebts.generator.utils.constant;
/**
* 用户常量信息
*
* @author binlin
*/
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";
}

View File

@ -1,175 +0,0 @@
package com.ebts.generator.utils.entity;
import com.ebts.generator.aop.Excel;
import com.ebts.generator.aop.Excel.ColumnType;
import com.ebts.generator.entity.GenBaseEntity;
import com.ebts.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 binlin
*/
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();
}
}

View File

@ -1,263 +0,0 @@
package com.ebts.generator.utils.entity;
import com.ebts.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 binlin
*/
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<GenMenu> children = new ArrayList<GenMenu>();
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<GenMenu> getChildren() {
return children;
}
public void setChildren(List<GenMenu> 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();
}
}

View File

@ -1,84 +0,0 @@
package com.ebts.generator.utils.exception;
import com.ebts.generator.utils.GenMessageUtils;
import com.ebts.generator.utils.GenStringUtils;
/**
* 基础异常
*
* @author binlin
*/
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;
}
}

View File

@ -1,37 +0,0 @@
package com.ebts.generator.utils.exception;
/**
* 自定义异常
*
* @author binlin
*/
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;
}
}

View File

@ -1,32 +0,0 @@
package com.ebts.generator.utils.exception;
/**
* @Author 18209
* @Date 2021/6/7 23:32
* @Email clay@hchyun.com
* @Version 1.0
*/
public class GenEbtsException extends RuntimeException {
private String msg;
private Exception exception;
public GenEbtsException(String opError, Exception e) {
this.msg = opError;
this.exception = e;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
@Override
public String getMessage() {
return exception.getMessage();
}
}

View File

@ -1,70 +0,0 @@
package com.ebts.generator.utils.page;
import com.ebts.generator.utils.GenStringUtils;
/**
* 分页数据
*
* @author binlin
*/
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;
}
}

View File

@ -1,82 +0,0 @@
package com.ebts.generator.utils.page;
import java.io.Serializable;
import java.util.List;
/**
* 表格分页数据对象
*
* @author binlin
*/
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;
}
}

View File

@ -1,47 +0,0 @@
package com.ebts.generator.utils.page;
import com.ebts.generator.utils.GenServletUtils;
/**
* 表格数据处理
*
* @author binlin
*/
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();
}
}

View File

@ -1,811 +0,0 @@
package com.ebts.generator.utils.poi;
import com.ebts.generator.aop.Excels;
import com.ebts.generator.config.Config;
import com.ebts.generator.controller.AjaxResult;
import com.ebts.generator.utils.GenDateUtils;
import com.ebts.generator.utils.GenDictUtils;
import com.ebts.generator.utils.GenStringUtils;
import com.ebts.generator.aop.Excel;
import com.ebts.generator.aop.Excel.Type;
import com.ebts.generator.aop.Excel.ColumnType;
import com.ebts.generator.utils.exception.GenCustomException;
import com.ebts.generator.utils.reflect.ReflectUtils;
import com.ebts.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 binlin
*/
public class GenExcelUtil<T> {
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<String, CellStyle> styles;
/**
* 导入导出数据列表
*/
private List<T> list;
/**
* 注解列表
*/
private List<Object[]> fields;
/**
* 统计列表
*/
private Map<Integer, Double> statistics = new HashMap<Integer, Double>();
/**
* 数字格式
*/
private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("######0.00");
/**
* 实体对象
*/
public Class<T> clazz;
public GenExcelUtil(Class<T> clazz) {
this.clazz = clazz;
}
public void init(List<T> list, String sheetName, Type type) {
if (list == null) {
list = new ArrayList<T>();
}
this.list = list;
this.sheetName = sheetName;
this.type = type;
createExcelField();
createWorkbook();
}
/**
* 对excel表单默认第一个索引名转换成list
*
* @param is 输入流
* @return 转换后集合
*/
public List<T> importExcel(InputStream is) throws Exception {
return importExcel(GenStringUtils.EMPTY, is);
}
/**
* 对excel表单指定表格索引名转换成list
*
* @param sheetName 表格索引名
* @param is 输入流
* @return 转换后集合
*/
public List<T> importExcel(String sheetName, InputStream is) throws Exception {
this.type = Type.IMPORT;
this.wb = WorkbookFactory.create(is);
List<T> list = new ArrayList<T>();
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<String, Integer> cellMap = new HashMap<String, Integer>();
// 获取表头
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<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
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<Integer, Field> 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<T> 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<String, CellStyle> createStyles(Workbook wb) {
// 写入各条记录,每条记录对应excel表中的一行
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
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<Integer> 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<Object[]>();
List<Field> 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;
}
}

View File

@ -1,210 +0,0 @@
package com.ebts.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 binlin
**/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class GenRedisCache {
@Autowired
public RedisTemplate redisTemplate;
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
*/
public <T> void setCacheObject(final String key, final T value) {
redisTemplate.opsForValue().set(key, value);
}
/**
* 缓存基本的对象,Integer、String、实体类等
*
* @param key 缓存的键值
* @param value 缓存的值
* @param timeout 时间
* @param timeUnit 时间颗粒度
*/
public <T> 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> T getCacheObject(final String key) {
ValueOperations<String, T> 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 <T> long setCacheList(final String key, final List<T> dataList) {
Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0 : count;
}
/**
* 获得缓存的list对象
*
* @param key 缓存的键值
* @return 缓存键值对应的数据
*/
public <T> List<T> getCacheList(final String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* 缓存Set
*
* @param key 缓存键值
* @param dataSet 缓存的数据
* @return 缓存数据的对象
*/
public <T> long setCacheSet(final String key, final Set<T> dataSet) {
Long count = redisTemplate.opsForSet().add(key, dataSet);
return count == null ? 0 : count;
}
/**
* 获得缓存的set
*
* @param key
* @return
*/
public <T> Set<T> getCacheSet(final String key) {
return redisTemplate.opsForSet().members(key);
}
/**
* 缓存Map
*
* @param key
* @param dataMap
*/
public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
if (dataMap != null) {
redisTemplate.opsForHash().putAll(key, dataMap);
}
}
/**
* 获得缓存的Map
*
* @param key
* @return
*/
public <T> Map<String, T> getCacheMap(final String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 往Hash中存入数据
*
* @param key Redis键
* @param hKey Hash键
* @param value 值
*/
public <T> 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> T getCacheMapValue(final String key, final String hKey) {
HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
/**
* 获取多个Hash中的数据
*
* @param key Redis键
* @param hKeys Hash键集合
* @return Hash对象集合
*/
public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
/**
* 获得缓存的基本对象列表
*
* @param pattern 字符串前缀
* @return 对象列表
*/
public Collection<String> keys(final String pattern) {
return redisTemplate.keys(pattern);
}
}

View File

@ -1,322 +0,0 @@
package com.ebts.generator.utils.reflect;
import com.ebts.generator.utils.GenDateUtils;
import com.ebts.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 binlin
*/
@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> 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 <E> 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> 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 <E> 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> 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> 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 <T> Class<T> 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);
}
}

View File

@ -1,131 +0,0 @@
package com.ebts.generator.utils.spring;
import com.ebts.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 binlin
*/
@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> T getBean(String name) throws BeansException {
return (T) beanFactory.getBean(name);
}
/**
* 获取类型为requiredType的对象
*
* @param clz
* @return
* @throws BeansException
*/
public static <T> T getBean(Class<T> 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> 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;
}
}

View File

@ -1,7 +1,7 @@
package com.ebts.generator.utils.sql; package com.ebts.generator.utils.sql;
import com.ebts.generator.utils.GenStringUtils; import com.ebts.common.exception.BaseException;
import com.ebts.generator.utils.exception.GenBaseException; import com.ebts.common.utils.StringUtils;
/** /**
* sql操作工具类 * sql操作工具类
@ -18,8 +18,8 @@ public class GenSqlUtil {
* 检查字符,防止注入绕过 * 检查字符,防止注入绕过
*/ */
public static String escapeOrderBySql(String value) { public static String escapeOrderBySql(String value) {
if (GenStringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) { if (StringUtils.isNotEmpty(value) && !isValidOrderBySql(value)) {
throw new GenBaseException("参数不符合规范,不能进行查询"); throw new BaseException("参数不符合规范,不能进行查询");
} }
return value; return value;
} }

View File

@ -1,92 +0,0 @@
package com.ebts.generator.utils.text;
import com.ebts.generator.utils.GenStringUtils;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 字符集工具类
*
* @author binlin
*/
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();
}
}

View File

@ -1,851 +0,0 @@
package com.ebts.generator.utils.text;
import com.ebts.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 binlin
*/
public class Convert {
/**
* 转换为字符串<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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();
}
/**
* 转换为字符串<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static String toStr(Object value) {
return toStr(value, null);
}
/**
* 转换为字符<br>
* 如果给定的值为null,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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);
}
/**
* 转换为字符<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Character toChar(Object value) {
return toChar(value, null);
}
/**
* 转换为byte<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Byte toByte(Object value) {
return toByte(value, null);
}
/**
* 转换为Short<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Short toShort(Object value) {
return toShort(value, null);
}
/**
* 转换为Number<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Number toNumber(Object value) {
return toNumber(value, null);
}
/**
* 转换为int<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Integer toInt(Object value) {
return toInt(value, null);
}
/**
* 转换为Integer数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Integer[] toIntArray(String str) {
return toIntArray(",", str);
}
/**
* 转换为Long数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static Long[] toLongArray(String str) {
return toLongArray(",", str);
}
/**
* 转换为Integer数组<br>
*
* @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数组<br>
*
* @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数组<br>
*
* @param str 被转换的值
* @return 结果
*/
public static String[] toStrArray(String str) {
return toStrArray(",", str);
}
/**
* 转换为String数组<br>
*
* @param split 分隔符
* @param split 被转换的值
* @return 结果
*/
public static String[] toStrArray(String split, String str) {
return str.split(split);
}
/**
* 转换为long<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为<code>null</code>,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Long toLong(Object value) {
return toLong(value, null);
}
/**
* 转换为double<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Double toDouble(Object value) {
return toDouble(value, null);
}
/**
* 转换为Float<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Float toFloat(Object value) {
return toFloat(value, null);
}
/**
* 转换为boolean<br>
* String支持的值为:true、false、yes、ok、no,1,0 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static Boolean toBool(Object value) {
return toBool(value, null);
}
/**
* 转换为Enum对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
*
* @param clazz Enum的Class
* @param value 值
* @param defaultValue 默认值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> 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对象<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
*
* @param clazz Enum的Class
* @param value 值
* @return Enum
*/
public static <E extends Enum<E>> E toEnum(Class<E> clazz, Object value) {
return toEnum(clazz, value, null);
}
/**
* 转换为BigInteger<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<code>null</code><br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigInteger toBigInteger(Object value) {
return toBigInteger(value, null);
}
/**
* 转换为BigDecimal<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @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<br>
* 如果给定的值为空,或者转换失败,返回默认值<br>
* 转换失败不会报错
*
* @param value 被转换的值
* @return 结果
*/
public static BigDecimal toBigDecimal(Object value) {
return toBigDecimal(value, null);
}
/**
* 将对象转为字符串<br>
* 1、Byte数组和ByteBuffer会被转换为对应字符串的数组 2、对象数组会调用Arrays.toString方法
*
* @param obj 对象
* @return 字符串
*/
public static String utf8Str(Object obj) {
return str(obj, CharsetKit.CHARSET_UTF_8);
}
/**
* 将对象转为字符串<br>
* 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));
}
/**
* 将对象转为字符串<br>
* 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<Character> 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<Character> 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("^整$", "零元整");
}
}

View File

@ -1,77 +0,0 @@
package com.ebts.generator.utils.text;
import com.ebts.generator.utils.GenStringUtils;
/**
* 字符串格式化
*
* @author binlin
*/
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 = '}';
/**
* 格式化字符串<br>
* 此方法只是简单将占位符 {} 按照顺序替换为参数<br>
* 如果想输出 {} 使用 \\转义 { 即可,如果想输出 {} 之前的 \ 使用双转义符 \\\\ 即可<br>
* 例:<br>
* 通常使用:format("this is {} for {}", "a", "b") -> this is a for b<br>
* 转义{}: format("this is \\{} for {}", "a", "b") -> this is \{} for a<br>
* 转义\: format("this is \\\\{} for {}", "a", "b") -> this is \a for b<br>
*
* @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();
}
}