✨ Introducing new features. up aj-report V0.9.6.1 支持http 数据源

This commit is contained in:
qraddx committed 2022-02-13 21:36:27 +08:00
1 parent 3058892a72
commit 7e7db12fa4
211 files changed
+7704 -7037

No files matched your search

@@ -20,6 +20,7 @@ import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.druid.DruidConfig;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pigx.codegen.entity.GenDatasourceConf;
import com.pig4cloud.pigx.codegen.mapper.GenDatasourceConfMapper;
@@ -123,6 +124,12 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
dataSourceProperty.setUrl(conf.getUrl());
dataSourceProperty.setUsername(conf.getUsername());
dataSourceProperty.setPassword(conf.getPassword());
// 增加 ValidationQuery 参数
DruidConfig druidConfig = new DruidConfig();
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
druidConfig.setValidationQuery(urlEnum.getValidationQuery());
dataSourceProperty.setDruid(druidConfig);
DataSource dataSource = druidDataSourceCreator.createDataSource(dataSourceProperty);
DynamicRoutingDataSource dynamicRoutingDataSource = SpringContextHolder.getBean(DynamicRoutingDataSource.class);
@@ -144,7 +151,7 @@ public class GenDatasourceConfServiceImpl extends ServiceImpl<GenDatasourceConfM
else if (DsJdbcUrlEnum.MSSQL.getDbName().equals(conf.getDsType())) {
// 主机形式 sql server 特殊处理
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getInstance(), conf.getPort(), conf.getDsName());
url = String.format(urlEnum.getUrl(), conf.getHost(), conf.getPort(), conf.getDsName());
}
else {
DsJdbcUrlEnum urlEnum = DsJdbcUrlEnum.get(conf.getDsType());
@@ -19,7 +19,6 @@
and T.tableName = #{tableName}
</if>
</where>
ORDER BY T.tableName
</select>
<sql id="queryColumn">
@@ -0,0 +1,30 @@
package com.anjiplus.template.gaea.business.config;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Locale;
import java.util.TimeZone;
/**
* @author lengleng
* @date 2022/2/13
*/
@Configuration
public class JacksonConfiguration {
private static final String ASIA_SHANGHAI = "Asia/Shanghai";
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> {
builder.locale(Locale.CHINA);
builder.timeZone(TimeZone.getTimeZone(ASIA_SHANGHAI));
builder.simpleDateFormat("yyyy-MM-dd HH:mm:ss");
builder.serializerByType(Long.class, ToStringSerializer.instance);
};
}
}
@@ -0,0 +1,55 @@
package com.anjiplus.template.gaea.business.enums;
public enum SetTypeEnum {
SQL("sql", "sql"), HTTP("http", "http"),;
private String codeValue;
private String codeDesc;
private SetTypeEnum(String codeValue, String codeDesc) {
this.codeValue = codeValue;
this.codeDesc = codeDesc;
}
public String getCodeValue() {
return this.codeValue;
}
public String getCodeDesc() {
return this.codeDesc;
}
// 根据codeValue获取枚举
public static SetTypeEnum parseFromCodeValue(String codeValue) {
for (SetTypeEnum e : SetTypeEnum.values()) {
if (e.codeValue == codeValue) {
return e;
}
}
return null;
}
// 根据codeValue获取描述
public static String getCodeDescByCodeBalue(String codeValue) {
SetTypeEnum enumItem = parseFromCodeValue(codeValue);
return enumItem == null ? "" : enumItem.getCodeDesc();
}
// 验证codeValue是否有效
public static boolean validateCodeValue(String codeValue) {
return parseFromCodeValue(codeValue) != null;
}
// 列出所有值字符串
public static String getString() {
StringBuffer buffer = new StringBuffer();
for (SetTypeEnum e : SetTypeEnum.values()) {
buffer.append(e.codeValue).append("--").append(e.getCodeDesc()).append(", ");
}
buffer.deleteCharAt(buffer.lastIndexOf(","));
return buffer.toString().trim();
}
}
@@ -16,29 +16,28 @@ import java.io.IOException;
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 设置允许Cookie
res.addHeader("Access-Control-Allow-Credentials", "true");
// 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
// 设置允许跨域请求的方法
res.addHeader("Access-Control-Allow-Methods", "*");
// 允许跨域请求包含content-type
res.addHeader("Access-Control-Allow-Headers", "*");
res.addHeader("Access-Control-Expose-Headers", "*");
chain.doFilter(req, res);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
// 设置允许Cookie
res.addHeader("Access-Control-Allow-Credentials", "true");
// 允许http://www.xxx.com域(自行设置,这里只做示例)发起跨域请求
res.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
// 设置允许跨域请求的方法
res.addHeader("Access-Control-Allow-Methods", "*");
// 允许跨域请求包含content-type
res.addHeader("Access-Control-Allow-Headers", "*");
res.addHeader("Access-Control-Expose-Headers", "*");
chain.doFilter(req, res);
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
@@ -2,63 +2,66 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.controller;
import com.anji.plus.gaea.annotation.Permission;
import com.anji.plus.gaea.annotation.AccessKey;
import com.anji.plus.gaea.bean.KeyValue;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.curd.controller.GaeaBaseController;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.dto.AccessAuthorityDto;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.param.AccessAuthorityParam;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity.AccessAuthority;
import com.anjiplus.template.gaea.business.modules.accessauthority.service.AccessAuthorityService;
import io.swagger.annotations.Api;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.dto.AccessAuthorityDto;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.param.AccessAuthorityParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* @desc 权限管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
* @desc 权限管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@RestController
@Api(tags = "权限管理管理")
@RequestMapping("/accessAuthority")
@Permission(code = "authorityManage", name = "权限管理")
public class AccessAuthorityController
extends GaeaBaseController<AccessAuthorityParam, AccessAuthority, AccessAuthorityDto> {
public class AccessAuthorityController extends GaeaBaseController<AccessAuthorityParam, AccessAuthority, AccessAuthorityDto> {
@Autowired
private AccessAuthorityService accessAuthorityService;
@Autowired
private AccessAuthorityService accessAuthorityService;
@Override
public GaeaBaseService<AccessAuthorityParam, AccessAuthority> getService() {
return accessAuthorityService;
}
@Override
public GaeaBaseService<AccessAuthorityParam, AccessAuthority> getService() {
return accessAuthorityService;
}
@Override
public AccessAuthority getEntity() {
return new AccessAuthority();
}
@Override
public AccessAuthority getEntity() {
return new AccessAuthority();
}
@Override
public AccessAuthorityDto getDTO() {
return new AccessAuthorityDto();
}
@Override
public AccessAuthorityDto getDTO() {
return new AccessAuthorityDto();
}
/**
* 获取一二级菜单
* @return
*/
@Permission(code = "query", name = "查询")
@GetMapping("/menuTree")
public ResponseBean menuTree() {
String username = UserContentHolder.getContext().getUsername();
List<TreeNode> parentTreeList = accessAuthorityService.getAuthorityTree(username, false);
return responseSuccessWithData(parentTreeList);
}
}
/**
* 获取一二级菜单
* @return
*/
@Permission( code = "query", name = "查询")
@GetMapping("/menuTree")
public ResponseBean menuTree(){
String username = UserContentHolder.getContext().getUsername();
List<TreeNode> parentTreeList = accessAuthorityService.getAuthorityTree(username, false);
return responseSuccessWithData(parentTreeList);
}
}
@@ -1,56 +1,58 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.controller.dto;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import io.swagger.annotations.ApiModelProperty;
import com.anji.plus.gaea.annotation.Formatter;
import lombok.Data;
/**
* @description 权限管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
*
* @description 权限管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@Data
public class AccessAuthorityDto extends GaeaBaseDTO implements Serializable {
/** 父菜单代码 */
@ApiModelProperty(value = "父菜单代码")
private String parentTarget;
/** 父菜单代码 */
@ApiModelProperty(value = "父菜单代码")
private String parentTarget;
/** 目标菜单 */
@ApiModelProperty(value = "菜单代码")
@NotEmpty(message = "6002")
private String target;
/** 目标菜单 */
@ApiModelProperty(value = "菜单代码")
@NotEmpty(message = "6002")
private String target;
/** 目标菜单名称 */
@ApiModelProperty(value = "菜单名称")
@NotEmpty(message = "6002")
private String targetName;
/** 目标菜单名称 */
@ApiModelProperty(value = "菜单名称")
@NotEmpty(message = "6002")
private String targetName;
/** 目标按钮 */
@ApiModelProperty(value = "按钮代码")
@NotEmpty(message = "6002")
private String action;
/** 目标按钮 */
@ApiModelProperty(value = "按钮代码")
@NotEmpty(message = "6002")
private String action;
/** 目标按钮名称 */
@ApiModelProperty(value = "按钮名称")
@NotEmpty(message = "6002")
private String actionName;
/** 目标按钮名称 */
@ApiModelProperty(value = "按钮名称")
@NotEmpty(message = "6002")
private String actionName;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
@ApiModelProperty(value = "sort")
private Integer sort;
}
@ApiModelProperty(value = "sort")
private Integer sort;
}
@@ -1,43 +1,44 @@
/**/
package com.anjiplus.template.gaea.business.modules.accessauthority.controller.param;
import lombok.Data;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
import lombok.Data;
import java.util.List;
import java.io.Serializable;
import java.util.Date;
/**
* @desc AccessAuthority 权限管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
* @desc AccessAuthority 权限管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@Data
public class AccessAuthorityParam extends PageParam implements Serializable {
public class AccessAuthorityParam extends PageParam implements Serializable{
/** 父菜单代码 */
@Query(value = QueryEnum.LIKE)
private String parentTarget;
/** 父菜单代码 */
@Query(value = QueryEnum.LIKE)
private String parentTarget;
/** 菜单代码 */
@Query(value = QueryEnum.LIKE)
private String target;
/** 菜单代码 */
@Query(value = QueryEnum.LIKE)
private String target;
/** 菜单名称 */
@Query(value = QueryEnum.LIKE)
private String targetName;
/** 菜单名称 */
@Query(value = QueryEnum.LIKE)
private String targetName;
/** 按钮代码 */
@Query(value = QueryEnum.LIKE)
private String action;
/** 按钮代码 */
@Query(value = QueryEnum.LIKE)
private String action;
/** 按钮名称 */
@Query(value = QueryEnum.LIKE)
private String actionName;
/** 按钮名称 */
@Query(value = QueryEnum.LIKE)
private String actionName;
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
}
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
}
@@ -1,16 +1,17 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity.AccessAuthority;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
/**
* AccessAuthority Mapper
*
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
* AccessAuthority Mapper
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@Mapper
public interface AccessAuthorityMapper extends GaeaBaseMapper<AccessAuthority> {
}
}
@@ -1,40 +1,43 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import com.anji.plus.gaea.curd.entity.GaeaBaseEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import javax.validation.constraints.*;
import java.util.Date;
/**
* @description 权限管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@TableName(keepGlobalPrefix = true, value = "access_authority")
* @description 权限管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@TableName(keepGlobalPrefix=true, value="access_authority")
@Data
public class AccessAuthority extends GaeaBaseEntity {
/** 父菜单代码 */
private String parentTarget;
/** 父菜单代码 */
private String parentTarget;
/** 菜单代码 */
private String target;
/** 菜单代码 */
private String target;
/** 菜单名称 */
private String targetName;
/** 菜单名称 */
private String targetName;
/** 按钮代码 */
private String action;
/** 按钮代码 */
private String action;
/** 按钮名称 */
private String actionName;
/** 按钮名称 */
private String actionName;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
private Integer sort;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
private Integer sort;
}
@@ -2,29 +2,28 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.service;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.param.AccessAuthorityParam;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity.AccessAuthority;
import com.anjiplus.template.gaea.business.modules.accessauthority.controller.param.AccessAuthorityParam;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import java.util.List;
/**
* @desc AccessAuthority 权限管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
* @desc AccessAuthority 权限管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
public interface AccessAuthorityService extends GaeaBaseService<AccessAuthorityParam, AccessAuthority> {
/**
* @param loginName 当前登录的用户名
* @param withActionNode 带第三层的按钮节点
* @return
*/
List<TreeNode> getAuthorityTree(String loginName, boolean withActionNode);
/**
* @param loginName 当前登录的用户名
* @param withActionNode 带第三层的按钮节点
* @return
*/
List<TreeNode> getAuthorityTree(String loginName, boolean withActionNode);
/**
* 扫描所有mvc url的需要权限码,建立拦截体系
*/
void scanGaeaSecurityAuthorities();
}
/**
* 扫描所有mvc url的需要权限码,建立拦截体系
*/
void scanGaeaSecurityAuthorities();
}
@@ -1,15 +1,16 @@
package com.anjiplus.template.gaea.business.modules.accessauthority.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.cache.CacheHelper;
import com.anji.plus.gaea.constant.Enabled;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.init.InitRequestUrlMappings;
import com.anjiplus.template.gaea.business.constant.BusinessConstant;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.AccessAuthorityMapper;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity.AccessAuthority;
import com.anjiplus.template.gaea.business.modules.accessauthority.service.AccessAuthorityService;
import com.anjiplus.template.gaea.business.modules.accessauthority.dao.AccessAuthorityMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
@@ -23,116 +24,117 @@ import java.util.Map;
import java.util.stream.Collectors;
/**
* @desc AccessAuthority 权限管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
* @desc AccessAuthority 权限管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:10.009
**/
@Service
public class AccessAuthorityServiceImpl implements AccessAuthorityService {
@Autowired
private InitRequestUrlMappings initRequestUrlMappings;
@Autowired
private InitRequestUrlMappings initRequestUrlMappings;
@Autowired
private CacheHelper cacheHelper;
@Autowired
private CacheHelper cacheHelper;
@Autowired
private AccessAuthorityMapper accessAuthorityMapper;
@Autowired
private AccessAuthorityMapper accessAuthorityMapper;
@Override
public GaeaBaseMapper<AccessAuthority> getMapper() {
return accessAuthorityMapper;
}
@Override
public GaeaBaseMapper<AccessAuthority> getMapper() {
return accessAuthorityMapper;
}
@Override
public List<TreeNode> getAuthorityTree(String loginName, boolean withActionNode) {
// 查询出所有的菜单记录
LambdaQueryWrapper<AccessAuthority> wrapper = Wrappers.lambdaQuery();
wrapper.select(AccessAuthority::getParentTarget, AccessAuthority::getTarget, AccessAuthority::getTargetName,
AccessAuthority::getAction, AccessAuthority::getActionName).eq(AccessAuthority::getEnableFlag, 1)
.eq(AccessAuthority::getDeleteFlag, 0).orderByAsc(AccessAuthority::getSort);
// 按operator去筛选 后面再加where
List<AccessAuthority> accessAuthorityList = getMapper().selectList(wrapper);
@Override
public List<TreeNode> getAuthorityTree(String loginName, boolean withActionNode) {
// 查询出所有的菜单记录
LambdaQueryWrapper<AccessAuthority> wrapper = Wrappers.lambdaQuery();
wrapper.select(AccessAuthority::getParentTarget, AccessAuthority::getTarget, AccessAuthority::getTargetName, AccessAuthority::getAction, AccessAuthority::getActionName)
.eq(AccessAuthority::getEnableFlag, 1)
.eq(AccessAuthority::getDeleteFlag, 0)
.orderByAsc(AccessAuthority::getSort);
// 按operator去筛选 后面再加where
List<AccessAuthority> accessAuthorityList = getMapper().selectList(wrapper);
// 筛选出一级菜单
List<TreeNode> parentNodes = accessAuthorityList.stream()
.filter(accessAuthority -> StringUtils.isBlank(accessAuthority.getParentTarget())).map(item -> {
TreeNode treeNode = new TreeNode();
treeNode.setId(item.getTarget());
treeNode.setLabel(item.getTargetName());
return treeNode;
}).collect(Collectors.toList());
// 筛选出一级菜单
List<TreeNode> parentNodes = accessAuthorityList.stream().filter(accessAuthority -> StringUtils.isBlank(accessAuthority.getParentTarget()))
.map(item -> {
TreeNode treeNode = new TreeNode();
treeNode.setId(item.getTarget());
treeNode.setLabel(item.getTargetName());
return treeNode;
}).collect(Collectors.toList());
// 菜单-按钮的map
Map<String, List<AccessAuthority>> targetActionsMap = accessAuthorityList.stream()
.filter(accessAuthority -> StringUtils.isNoneBlank(accessAuthority.getParentTarget()))
.collect(Collectors.groupingBy(AccessAuthority::getTarget));
// 菜单-按钮的map
Map<String, List<AccessAuthority>> targetActionsMap = accessAuthorityList.stream()
.filter(accessAuthority -> StringUtils.isNoneBlank(accessAuthority.getParentTarget()))
.collect(Collectors.groupingBy(AccessAuthority::getTarget));
// 设置每个一级菜单的二菜单
parentNodes.stream().forEach(parentNode -> {
List<String> alreadyTargets = new ArrayList<>();
// 设置每个一级菜单的二菜单
parentNodes.stream().forEach(parentNode -> {
List<String> alreadyTargets = new ArrayList<>();
accessAuthorityList.stream().forEach(authority -> {
if (!StringUtils.equals(parentNode.getId(), authority.getParentTarget())
|| alreadyTargets.contains(authority.getTarget())) {
return;
}
// 找到一级菜单对应的二级菜单
accessAuthorityList.stream().forEach(authority -> {
if(!StringUtils.equals(parentNode.getId(), authority.getParentTarget()) || alreadyTargets.contains(authority.getTarget())){
return;
}
// 找到一级菜单对应的二级菜单
// 初始化二级菜单节点
TreeNode levelTwoMenuNode = new TreeNode();
levelTwoMenuNode.setId(authority.getTarget());
levelTwoMenuNode.setLabel(authority.getTargetName());
levelTwoMenuNode.setChildren(new ArrayList<TreeNode>());
// 初始化二级菜单节点
TreeNode levelTwoMenuNode = new TreeNode();
levelTwoMenuNode.setId(authority.getTarget());
levelTwoMenuNode.setLabel(authority.getTargetName());
levelTwoMenuNode.setChildren(new ArrayList<TreeNode>());
// 初始化二级菜单的按钮
if (withActionNode) {
List<AccessAuthority> actionList = targetActionsMap.get(authority.getTarget());
if (actionList != null && !actionList.isEmpty()) {
actionList.stream().forEach(action -> {
TreeNode buttonNode = new TreeNode();
buttonNode.setId(String.format("%s_%s", action.getTarget(), action.getAction()));
buttonNode.setLabel(action.getActionName());
levelTwoMenuNode.getChildren().add(buttonNode);
});
}
}
// 初始化二级菜单的按钮
if(withActionNode){
List<AccessAuthority> actionList = targetActionsMap.get(authority.getTarget());
if(actionList != null && !actionList.isEmpty()){
actionList.stream().forEach(action ->{
TreeNode buttonNode = new TreeNode();
buttonNode.setId(String.format("%s_%s", action.getTarget(), action.getAction()));
buttonNode.setLabel(action.getActionName());
levelTwoMenuNode.getChildren().add(buttonNode);
});
}
}
// 将上面找到的二级菜单加入到一菜单的子树中去
List<TreeNode> children = parentNode.getChildren();
if (children == null) {
children = new ArrayList<TreeNode>();
}
children.add(levelTwoMenuNode);
parentNode.setChildren(children);
// 将上面找到的二级菜单加入到一菜单的子树中去
List<TreeNode> children = parentNode.getChildren();
if(children == null){
children = new ArrayList<TreeNode>();
}
children.add(levelTwoMenuNode);
parentNode.setChildren(children);
// 已经找过的二级菜单,后面不在重复添加
alreadyTargets.add(authority.getTarget());
});
});
// 已经找过的二级菜单,后面不在重复添加
alreadyTargets.add(authority.getTarget());
});
});
return parentNodes;
}
return parentNodes;
}
@Override
public void scanGaeaSecurityAuthorities() {
/*
* 获取当前应用中所有的请求信息 { "applicationName": "aj-report", "authCode":
* "authorityManage:query", "authName": "权限管理查询", "beanName":
* "accessAuthorityController", "menuCode": "authorityManage", "path":
* "GET#/accessAuthority/menuTree" }
*/
List<InitRequestUrlMappings.RequestInfo> requestInfos = initRequestUrlMappings
.getRequestInfos(Enabled.YES.getValue());
@Override
public void scanGaeaSecurityAuthorities() {
/* 获取当前应用中所有的请求信息
{
"applicationName": "aj-report",
"authCode": "authorityManage:query",
"authName": "权限管理查询",
"beanName": "accessAuthorityController",
"menuCode": "authorityManage",
"path": "GET#/accessAuthority/menuTree"
}*/
List<InitRequestUrlMappings.RequestInfo> requestInfos = initRequestUrlMappings.getRequestInfos(Enabled.YES.getValue());
// key="GET#/accessAuthority/menuTree" value="authorityManage:query"
Map<String, String> securityAuthorityMap = new HashMap<String, String>();
requestInfos.stream().forEach(requestInfo -> {
securityAuthorityMap.put(requestInfo.getPath(), requestInfo.getAuthCode());
});
// key="GET#/accessAuthority/menuTree" value="authorityManage:query"
Map<String, String> securityAuthorityMap = new HashMap<String, String>();
requestInfos.stream().forEach(requestInfo -> {
securityAuthorityMap.put(requestInfo.getPath(), requestInfo.getAuthCode());
});
// 将key存入到缓存中
cacheHelper.hashSet(BusinessConstant.GAEA_SECURITY_AUTHORITIES, securityAuthorityMap);
}
}
// 将key存入到缓存中
cacheHelper.hashSet(BusinessConstant.GAEA_SECURITY_AUTHORITIES, securityAuthorityMap);
}
}
@@ -2,70 +2,74 @@
package com.anjiplus.template.gaea.business.modules.accessrole.controller;
import com.anji.plus.gaea.annotation.Permission;
import com.anji.plus.gaea.annotation.AccessKey;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.curd.controller.GaeaBaseController;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.dto.AccessRoleDto;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.param.AccessRoleParam;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessRole;
import com.anjiplus.template.gaea.business.modules.accessrole.service.AccessRoleService;
import io.swagger.annotations.Api;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.dto.AccessRoleDto;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.param.AccessRoleParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;
import java.util.List;
import java.util.Map;
/**
* @desc 角色管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* @desc 角色管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@RestController
@Api(tags = "角色管理管理")
@RequestMapping("/accessRole")
@Permission(code = "roleManage", name = "角色管理")
public class AccessRoleController extends GaeaBaseController<AccessRoleParam, AccessRole, AccessRoleDto> {
@Autowired
private AccessRoleService accessRoleService;
@Autowired
private AccessRoleService accessRoleService;
@Override
public GaeaBaseService<AccessRoleParam, AccessRole> getService() {
return accessRoleService;
}
@Override
public GaeaBaseService<AccessRoleParam, AccessRole> getService() {
return accessRoleService;
}
@Override
public AccessRole getEntity() {
return new AccessRole();
}
@Override
public AccessRole getEntity() {
return new AccessRole();
}
@Override
public AccessRoleDto getDTO() {
return new AccessRoleDto();
}
@Override
public AccessRoleDto getDTO() {
return new AccessRoleDto();
}
/**
* 获取角色的 菜单按钮树 一级菜单 二级菜单 三级按钮
* @return
*/
@Permission(code = "grantAuthority", name = "分配权限")
@GetMapping("/authorityTree/{roleCode}")
public ResponseBean authorityTree(@PathVariable("roleCode") String roleCode) {
String operator = UserContentHolder.getContext().getUsername();
Map map = accessRoleService.getAuthorityTree(roleCode, operator);
return responseSuccessWithData(map);
}
/**
* 获取角色的 菜单按钮树 一级菜单 二级菜单 三级按钮
* @return
*/
@Permission( code = "grantAuthority", name = "分配权限")
@GetMapping("/authorityTree/{roleCode}")
public ResponseBean authorityTree(@PathVariable("roleCode")String roleCode){
String operator = UserContentHolder.getContext().getUsername();
Map map = accessRoleService.getAuthorityTree(roleCode, operator);
return responseSuccessWithData(map);
}
/**
* 保存角色的权限
* @return
*/
@Permission(code = "grantAuthority", name = "分配权限")
@PostMapping("/saveAuthorityTree")
public ResponseBean saveAuthorityTree(@RequestBody AccessRoleDto dto) {
Boolean data = accessRoleService.saveAuthorityTree(dto);
return responseSuccessWithData(data);
}
}
/**
* 保存角色的权限
* @return
*/
@Permission( code = "grantAuthority", name = "分配权限")
@PostMapping("/saveAuthorityTree")
public ResponseBean saveAuthorityTree(@RequestBody AccessRoleDto dto){
Boolean data = accessRoleService.saveAuthorityTree(dto);
return responseSuccessWithData(data);
}
}
@@ -1,43 +1,46 @@
package com.anjiplus.template.gaea.business.modules.accessrole.controller.dto;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import io.swagger.annotations.ApiModelProperty;
import com.anji.plus.gaea.annotation.Formatter;
import lombok.Data;
/**
* @description 角色管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
*
* @description 角色管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@Data
public class AccessRoleDto extends GaeaBaseDTO implements Serializable {
/** 角色编码 */
@ApiModelProperty(value = "角色编码")
@NotEmpty(message = "6002")
private String roleCode;
/** 角色编码 */
@ApiModelProperty(value = "角色编码")
@NotEmpty(message = "6002")
private String roleCode;
/** 角色名称 */
@ApiModelProperty(value = "角色名称")
@NotEmpty(message = "6002")
private String roleName;
/** 角色名称 */
@ApiModelProperty(value = "角色名称")
@NotEmpty(message = "6002")
private String roleName;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
/** 角色保存的权限 */
private List<String> authorityList;
}
/** 角色保存的权限 */
private List<String> authorityList;
}
@@ -1,31 +1,33 @@
/**/
package com.anjiplus.template.gaea.business.modules.accessrole.controller.param;
import lombok.Data;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
import lombok.Data;
import java.util.List;
import java.io.Serializable;
import java.util.Date;
/**
* @desc AccessRole 角色管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* @desc AccessRole 角色管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@Data
public class AccessRoleParam extends PageParam implements Serializable {
public class AccessRoleParam extends PageParam implements Serializable{
/** 角色编码 */
@Query(value = QueryEnum.LIKE)
private String roleCode;
/** 角色编码 */
@Query(value = QueryEnum.LIKE)
private String roleCode;
// 角色名称
@Query(value = QueryEnum.LIKE)
private String roleName;
// 角色名称
@Query(value = QueryEnum.LIKE)
private String roleName;
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
}
}
@@ -5,11 +5,10 @@ import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessR
import org.apache.ibatis.annotations.Mapper;
/**
* AccessRoleAuthority Mapper
*
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* AccessRoleAuthority Mapper
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@Mapper
public interface AccessRoleAuthorityMapper extends GaeaBaseMapper<AccessRoleAuthority> {
@@ -1,21 +1,22 @@
package com.anjiplus.template.gaea.business.modules.accessrole.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessRole;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* AccessRole Mapper
*
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* AccessRole Mapper
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@Mapper
public interface AccessRoleMapper extends GaeaBaseMapper<AccessRole> {
List<String> checkedAuthoritys(@Param("roleCode") String roleCode);
}
List<String> checkedAuthoritys(@Param("roleCode")String roleCode);
}
@@ -1,29 +1,30 @@
package com.anjiplus.template.gaea.business.modules.accessrole.dao.entity;
import lombok.Data;
import com.anji.plus.gaea.curd.entity.GaeaBaseEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import javax.validation.constraints.*;
import java.util.Date;
/**
* @description 角色管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@TableName(keepGlobalPrefix = true, value = "access_role")
* @description 角色管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@TableName(keepGlobalPrefix=true, value="access_role")
@Data
public class AccessRole extends GaeaBaseEntity {
/** 角色编码 */
private String roleCode;
/** 角色编码 */
private String roleCode;
/** 角色名称 */
private String roleName;
/** 角色名称 */
private String roleName;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
}
@@ -1,8 +1,10 @@
package com.anjiplus.template.gaea.business.modules.accessrole.dao.entity;
import com.anji.plus.gaea.curd.entity.GaeaBaseEntity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import lombok.Data;
import java.util.Date;
@@ -12,32 +14,31 @@ import java.util.Date;
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@TableName(keepGlobalPrefix = true, value = "access_role_authority")
@TableName(keepGlobalPrefix=true, value="access_role_authority")
@Data
public class AccessRoleAuthority extends GaeaBaseEntity {
/** 角色编码 */
private String roleCode;
/** 角色编码 */
private String roleCode;
/** 菜单代码 */
private String target;
/** 菜单代码 */
private String target;
/** 按钮代码 */
private String action;
/** 按钮代码 */
private String action;
@TableField(exist = false)
private String createBy;
@TableField(exist = false)
private String createBy;
@TableField(exist = false)
private Date createTime;
@TableField(exist = false)
private Date createTime;
@TableField(exist = false)
private String updateBy;
@TableField(exist = false)
private String updateBy;
@TableField(exist = false)
private Date updateTime;
@TableField(exist = false)
private Integer version;
@TableField(exist = false)
private Date updateTime;
@TableField(exist = false)
private Integer version;
}
@@ -1,33 +1,34 @@
package com.anjiplus.template.gaea.business.modules.accessrole.service;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.dto.AccessRoleDto;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.param.AccessRoleParam;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessRole;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.param.AccessRoleParam;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import java.util.Map;
/**
* @desc AccessRole 角色管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* @desc AccessRole 角色管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
public interface AccessRoleService extends GaeaBaseService<AccessRoleParam, AccessRole> {
/**
* 查询某角色的权限树
* @param roleCode 被操作的对象
* @param operator 当前登录者
* @return
*/
Map getAuthorityTree(String roleCode, String operator);
/** 查询某角色的权限树
* @param roleCode 被操作的对象
* @param operator 当前登录者
* @return
*/
Map getAuthorityTree(String roleCode, String operator);
/**
* 保存角色的权限
* @param accessRoleDto
* @return
*/
Boolean saveAuthorityTree(AccessRoleDto accessRoleDto);
}
/** 保存角色的权限
* @param accessRoleDto
* @return
*/
Boolean saveAuthorityTree(AccessRoleDto accessRoleDto);
}
@@ -8,10 +8,10 @@ import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.accessauthority.service.AccessAuthorityService;
import com.anjiplus.template.gaea.business.modules.accessrole.controller.dto.AccessRoleDto;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.AccessRoleAuthorityMapper;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.AccessRoleMapper;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessRole;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessRoleAuthority;
import com.anjiplus.template.gaea.business.modules.accessrole.service.AccessRoleService;
import com.anjiplus.template.gaea.business.modules.accessrole.dao.AccessRoleMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
@@ -24,81 +24,78 @@ import java.util.Map;
import java.util.stream.Collectors;
/**
* @desc AccessRole 角色管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
* @desc AccessRole 角色管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:14.136
**/
@Service
public class AccessRoleServiceImpl implements AccessRoleService {
@Autowired
private AccessRoleMapper accessRoleMapper;
@Autowired
private AccessRoleMapper accessRoleMapper;
@Autowired
private AccessRoleAuthorityMapper accessRoleAuthorityMapper;
@Autowired
private AccessRoleAuthorityMapper accessRoleAuthorityMapper;
@Autowired
private AccessAuthorityService accessAuthorityService;
@Autowired
private AccessAuthorityService accessAuthorityService;
@Override
public GaeaBaseMapper<AccessRole> getMapper() {
return accessRoleMapper;
}
@Override
public GaeaBaseMapper<AccessRole> getMapper() {
return accessRoleMapper;
}
@Override
public Map getAuthorityTree(String roleCode, String operator) {
Map<String, Object> result = new HashMap<String, Object>();
@Override
public Map getAuthorityTree(String roleCode, String operator) {
Map<String, Object> result = new HashMap<String, Object>();
// 菜单按钮树
List<TreeNode> treeData = accessAuthorityService.getAuthorityTree(operator, true);
// 菜单按钮树
List<TreeNode> treeData = accessAuthorityService.getAuthorityTree(operator, true);
// 该角色已选中的菜单及按钮
// List<String> checkedKeys = accessRoleMapper.checkedAuthoritys(roleCode);
// 该角色已选中的菜单及按钮
// List<String> checkedKeys = accessRoleMapper.checkedAuthoritys(roleCode);
LambdaQueryWrapper<AccessRoleAuthority> accessRoleAuthorityWrapper = Wrappers.lambdaQuery();
accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction);
accessRoleAuthorityWrapper.eq(AccessRoleAuthority::getRoleCode, roleCode);
List<AccessRoleAuthority> accessRoleAuthorities = accessRoleAuthorityMapper
.selectList(accessRoleAuthorityWrapper);
List<String> checkedKeys = accessRoleAuthorities.stream().map(accessRoleAuthority -> accessRoleAuthority
.getTarget().concat("_").concat(accessRoleAuthority.getAction())).distinct()
.collect(Collectors.toList());
LambdaQueryWrapper<AccessRoleAuthority> accessRoleAuthorityWrapper = Wrappers.lambdaQuery();
accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction);
accessRoleAuthorityWrapper.eq(AccessRoleAuthority::getRoleCode, roleCode);
List<AccessRoleAuthority> accessRoleAuthorities = accessRoleAuthorityMapper.selectList(accessRoleAuthorityWrapper);
List<String> checkedKeys = accessRoleAuthorities.stream()
.map(accessRoleAuthority -> accessRoleAuthority.getTarget().concat("_").concat(accessRoleAuthority.getAction())).distinct().collect(Collectors.toList());
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
@Override
public Boolean saveAuthorityTree(AccessRoleDto accessRoleDto) {
// 校验
String roleCode = accessRoleDto.getRoleCode();
List<String> authorityList = accessRoleDto.getAuthorityList();
if (StringUtils.isBlank(roleCode)) {
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, roleCode);
}
if (authorityList == null || authorityList.isEmpty()) {
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, authorityList);
}
@Override
public Boolean saveAuthorityTree(AccessRoleDto accessRoleDto) {
// 校验
String roleCode = accessRoleDto.getRoleCode();
List<String> authorityList = accessRoleDto.getAuthorityList();
if(StringUtils.isBlank(roleCode)){
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, roleCode);
}
if(authorityList == null || authorityList.isEmpty()){
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, authorityList);
}
// 先清除该角色已保存的权限
LambdaQueryWrapper<AccessRoleAuthority> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessRoleAuthority::getRoleCode, roleCode);
accessRoleAuthorityMapper.delete(wrapper);
// 保存勾选的权限(菜单和按钮)
authorityList.stream().forEach(authorityStr -> {
if (!authorityStr.contains("_")) {
return;
}
String[] array = authorityStr.split("_");
AccessRoleAuthority accessRoleAuthority = new AccessRoleAuthority();
accessRoleAuthority.setRoleCode(roleCode);
accessRoleAuthority.setTarget(array[0].trim());
accessRoleAuthority.setAction(array[1].trim());
accessRoleAuthorityMapper.insert(accessRoleAuthority);
});
return true;
}
// 先清除该角色已保存的权限
LambdaQueryWrapper<AccessRoleAuthority> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessRoleAuthority::getRoleCode, roleCode);
accessRoleAuthorityMapper.delete(wrapper);
// 保存勾选的权限(菜单和按钮)
authorityList.stream().forEach(authorityStr -> {
if(!authorityStr.contains("_")){
return;
}
String[] array = authorityStr.split("_");
AccessRoleAuthority accessRoleAuthority = new AccessRoleAuthority();
accessRoleAuthority.setRoleCode(roleCode);
accessRoleAuthority.setTarget(array[0].trim());
accessRoleAuthority.setAction(array[1].trim());
accessRoleAuthorityMapper.insert(accessRoleAuthority);
});
return true;
}
}
@@ -6,101 +6,108 @@ import com.anji.plus.gaea.bean.ResponseBean;
import com.anji.plus.gaea.curd.controller.GaeaBaseController;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.AccessUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.GaeaUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.UpdatePasswordDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser;
import com.anjiplus.template.gaea.business.modules.accessuser.service.AccessUserService;
import io.swagger.annotations.Api;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.AccessUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import io.swagger.annotations.Api;
import java.util.Map;
/**
* @desc 用户管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* @desc 用户管理 controller
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@RestController
@Api(tags = "用户管理管理")
@RequestMapping("/accessUser")
@Permission(code = "userManage", name = "用户管理")
public class AccessUserController extends GaeaBaseController<AccessUserParam, AccessUser, AccessUserDto> {
@Autowired
private AccessUserService accessUserService;
@Autowired
private AccessUserService accessUserService;
@Override
public GaeaBaseService<AccessUserParam, AccessUser> getService() {
return accessUserService;
}
@Override
public GaeaBaseService<AccessUserParam, AccessUser> getService() {
return accessUserService;
}
@Override
public AccessUser getEntity() {
return new AccessUser();
}
@Override
public AccessUser getEntity() {
return new AccessUser();
}
@Override
public AccessUserDto getDTO() {
return new AccessUserDto();
}
@Override
public AccessUserDto getDTO() {
return new AccessUserDto();
}
/**
* 获取用户的角色树
* @return
*/
@Permission(code = "grantRole", name = "分配角色")
@GetMapping("/roleTree/{loginName}")
public ResponseBean getRoleTree(@PathVariable("loginName") String loginName) {
String operator = UserContentHolder.getContext().getUsername();
Map map = accessUserService.getRoleTree(loginName, operator);
return responseSuccessWithData(map);
}
/**
* 保存用户的角色树
* @return
*/
@Permission(code = "grantRole", name = "分配角色")
@PostMapping("/saveRoleTree")
public ResponseBean saveRoleTree(@RequestBody AccessUserDto dto) {
Boolean data = accessUserService.saveRoleTree(dto);
return responseSuccessWithData(data);
}
/**
* 获取用户的角色树
* @return
*/
@Permission( code = "grantRole", name = "分配角色")
@GetMapping("/roleTree/{loginName}")
public ResponseBean getRoleTree(@PathVariable("loginName")String loginName){
String operator = UserContentHolder.getContext().getUsername();
Map map = accessUserService.getRoleTree(loginName, operator);
return responseSuccessWithData(map);
}
/**
* 重置密码
* @param dto
* @return
*/
@Permission(code = "resetPassword", name = "重置密码")
@PostMapping({ "/resetPassword" })
public ResponseBean resetPassword(@RequestBody @Validated GaeaUserDto dto) {
Boolean data = accessUserService.resetPassword(dto);
return responseSuccessWithData(data);
}
/**
* 保存用户的角色树
* @return
*/
@Permission( code = "grantRole", name = "分配角色")
@PostMapping("/saveRoleTree")
public ResponseBean saveRoleTree(@RequestBody AccessUserDto dto){
Boolean data = accessUserService.saveRoleTree(dto);
return responseSuccessWithData(data);
}
/**
* 简单实现登录
* @param dto
* @return
*/
@PostMapping({ "/login" })
public ResponseBean login(@RequestBody @Validated GaeaUserDto dto) {
return responseSuccessWithData(accessUserService.login(dto));
}
/**
* 修改自己的密码
* @param dto
* @return
*/
@PostMapping("/updatePassword")
public ResponseBean updatePassword(@RequestBody UpdatePasswordDto dto) {
return responseSuccessWithData(accessUserService.updatePassword(dto));
}
/**
* 重置密码
* @param dto
* @return
*/
@Permission( code = "resetPassword", name = "重置密码")
@PostMapping({"/resetPassword"})
public ResponseBean resetPassword(@RequestBody @Validated GaeaUserDto dto) {
Boolean data = accessUserService.resetPassword(dto);
return responseSuccessWithData(data);
}
/**
* 简单实现登录
* @param dto
* @return
*/
@PostMapping({"/login"})
public ResponseBean login(@RequestBody @Validated GaeaUserDto dto) {
return responseSuccessWithData(accessUserService.login(dto));
}
/**
* 修改自己的密码
* @param dto
* @return
*/
@PostMapping("/updatePassword")
public ResponseBean updatePassword(@RequestBody UpdatePasswordDto dto) {
return responseSuccessWithData(accessUserService.updatePassword(dto));
}
}
@@ -1,64 +1,66 @@
package com.anjiplus.template.gaea.business.modules.accessuser.controller.dto;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import com.anji.plus.gaea.curd.dto.GaeaBaseDTO;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser;
import io.swagger.annotations.ApiModelProperty;
import com.anji.plus.gaea.annotation.Formatter;
import lombok.Data;
import java.util.Date;
import java.util.List;
/**
* @description 用户管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
*
* @description 用户管理 dto
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@Data
public class AccessUserDto extends GaeaBaseDTO implements Serializable {
/**  登录名 */
@ApiModelProperty(value = " 登录名")
@NotEmpty(message = "6002")
private String loginName;
/**  登录名 */
@ApiModelProperty(value = " 登录名")
@NotEmpty(message = "6002")
private String loginName;
/** 真实用户 */
@ApiModelProperty(value = "真实用户")
@NotEmpty(message = "6002")
private String realName;
/** 真实用户 */
@ApiModelProperty(value = "真实用户")
@NotEmpty(message = "6002")
private String realName;
/** 手机号码 */
@ApiModelProperty(value = "手机号码")
private String phone;
/** 手机号码 */
@ApiModelProperty(value = "手机号码")
private String phone;
/** 用户邮箱 */
@ApiModelProperty(value = "用户邮箱")
private String email;
/** 用户邮箱 */
@ApiModelProperty(value = "用户邮箱")
private String email;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
@NotNull(message = "6002")
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
/** 最后一次登录IP */
@ApiModelProperty(value = "最后一次登录IP")
private String lastLoginIp;
/** 最后一次登录IP */
@ApiModelProperty(value = "最后一次登录IP")
private String lastLoginIp;
/** 最后一次登陆时间 */
@ApiModelProperty(value = "最后一次登陆时间")
private Date lastLoginTime;
/** 最后一次登陆时间 */
@ApiModelProperty(value = "最后一次登陆时间")
private Date lastLoginTime;
/** 备注 */
@ApiModelProperty(value = "备注")
private String remark;
/** 用户勾选的角色 */
private List<String> roleCodeList;
/** 备注 */
@ApiModelProperty(value = "备注")
private String remark;
/** 用户勾选的角色 */
private List<String> roleCodeList;
}
@@ -11,21 +11,20 @@ import java.util.List;
@Data
public class GaeaUserDto {
@ApiModelProperty(value = "登录名")
@NotBlank
private String loginName;
@ApiModelProperty(value = "登录名")
@NotBlank
private String loginName;
@ApiModelProperty(value = "密码")
@NotBlank
private String password;
@ApiModelProperty(value = "密码")
@NotBlank
private String password;
/** 真实用户 */
private String realName;
/** 真实用户 */
private String realName;
/** 登录成功后的 */
private String token;
/** 用户所拥有的权限合集 */
private List<String> authorities;
/** 登录成功后的 */
private String token;
/** 用户所拥有的权限合集 */
private List<String> authorities;
}
@@ -5,21 +5,21 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.List;
@ApiModel(value = "修改密码")
@Data
public class UpdatePasswordDto {
@ApiModelProperty(value = "旧密码密码")
@NotBlank
private String oldPassword;
@ApiModelProperty(value = "旧密码密码")
@NotBlank
private String oldPassword;
@ApiModelProperty(value = "密码")
@NotBlank
private String password;
@ApiModelProperty(value = "密码")
@NotBlank
private String confirmPassword;
@ApiModelProperty(value = "密码")
@NotBlank
private String password;
@ApiModelProperty(value = "密码")
@NotBlank
private String confirmPassword;
}
@@ -1,35 +1,37 @@
/**/
package com.anjiplus.template.gaea.business.modules.accessuser.controller.param;
import lombok.Data;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
import lombok.Data;
import java.util.List;
import java.io.Serializable;
import java.util.Date;
/**
* @desc AccessUser 用户管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* @desc AccessUser 用户管理查询输入类
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@Data
public class AccessUserParam extends PageParam implements Serializable {
public class AccessUserParam extends PageParam implements Serializable{
//  登录名
@Query(value = QueryEnum.LIKE)
private String loginName;
//  登录名
@Query(value = QueryEnum.LIKE)
private String loginName;
// 真实用户
@Query(value = QueryEnum.LIKE)
private String realName;
// 真实用户
@Query(value = QueryEnum.LIKE)
private String realName;
// 手机号码
@Query(value = QueryEnum.LIKE)
private String phone;
// 手机号码
@Query(value = QueryEnum.LIKE)
private String phone;
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
// 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG
@Query
private Integer enableFlag;
}
}
@@ -1,26 +1,26 @@
package com.anjiplus.template.gaea.business.modules.accessuser.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.List;
/**
* AccessUser Mapper
*
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* AccessUser Mapper
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@Mapper
public interface AccessUserMapper extends GaeaBaseMapper<AccessUser> {
/**
* 查询用户所拥有的所有角色下的权限
* @param loginName
* @return
*/
List<String> queryAuthoritiesByLoginName(@Param("loginName") String loginName);
}
/** 查询用户所拥有的所有角色下的权限
* @param loginName
* @return
*/
List<String> queryAuthoritiesByLoginName(@Param("loginName")String loginName);
}
@@ -5,11 +5,10 @@ import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessU
import org.apache.ibatis.annotations.Mapper;
/**
* AccessUser Mapper
*
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* AccessUser Mapper
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@Mapper
public interface AccessUserRoleMapper extends GaeaBaseMapper<AccessUserRole> {
@@ -1,49 +1,48 @@
package com.anjiplus.template.gaea.business.modules.accessuser.dao.entity;
import lombok.Data;
import com.anji.plus.gaea.curd.entity.GaeaBaseEntity;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import javax.validation.constraints.*;
import java.util.Date;
/**
* @description 用户管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@TableName(keepGlobalPrefix = true, value = "access_user")
* @description 用户管理 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@TableName(keepGlobalPrefix=true, value="access_user")
@Data
public class AccessUser extends GaeaBaseEntity {
/**  登录名 */
private String loginName;
/**  登录名 */
private String loginName;
/** 密码 */
private String password;
/** 密码 */
private String password;
/** 真实用户 */
private String realName;
/** 真实用户 */
private String realName;
/** 手机号码 */
private String phone;
/** 手机号码 */
private String phone;
/** 用户邮箱 */
private String email;
/** 用户邮箱 */
private String email;
/** 备注 */
private String remark;
/** 备注 */
private String remark;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 最后一次登录IP */
private String lastLoginIp;
/** 最后一次登录IP */
private String lastLoginIp;
/** 最后一次登陆时间 */
private Date lastLoginTime;
/** 最后一次登陆时间 */
private Date lastLoginTime;
}
@@ -9,33 +9,32 @@ import lombok.Data;
import java.util.Date;
/**
* @description 用户--角色关联关系 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@TableName(keepGlobalPrefix = true, value = "access_user_role")
* @description 用户--角色关联关系 entity
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@TableName(keepGlobalPrefix=true, value="access_user_role")
@Data
public class AccessUserRole extends GaeaBaseEntity {
/**  登录名 */
private String loginName;
/**  登录名 */
private String loginName;
/** 角色编码 */
private String roleCode;
/** 角色编码 */
private String roleCode;
@TableField(exist = false)
private String createBy;
@TableField(exist = false)
private String createBy;
@TableField(exist = false)
private Date createTime;
@TableField(exist = false)
private Date createTime;
@TableField(exist = false)
private String updateBy;
@TableField(exist = false)
private String updateBy;
@TableField(exist = false)
private Date updateTime;
@TableField(exist = false)
private Integer version;
@TableField(exist = false)
private Date updateTime;
@TableField(exist = false)
private Integer version;
}
@@ -1,56 +1,52 @@
package com.anjiplus.template.gaea.business.modules.accessuser.service;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.AccessUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.GaeaUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.UpdatePasswordDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import java.util.Map;
/**
* @desc AccessUser 用户管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* @desc AccessUser 用户管理服务接口
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
public interface AccessUserService extends GaeaBaseService<AccessUserParam, AccessUser> {
/**
* 获取用户的角色树
* @param loginName 被操作的对象
* @param operator 当前登录者
* @return
*/
Map getRoleTree(String loginName, String operator);
/** 获取用户的角色树
* @param loginName 被操作的对象
* @param operator 当前登录者
* @return
*/
Map getRoleTree(String loginName, String operator);
/**
* 保存用户的角色树
* @param accessUserDto
* @return
*/
Boolean saveRoleTree(AccessUserDto accessUserDto);
/**
* 重置密码
* @param gaeaUserDto
* @return
*/
Boolean resetPassword(GaeaUserDto gaeaUserDto);
/** 保存用户的角色树
* @param accessUserDto
* @return
*/
Boolean saveRoleTree(AccessUserDto accessUserDto);
/**
* 用户登录
* @param gaeaUserDto
* @return
*/
GaeaUserDto login(GaeaUserDto gaeaUserDto);
/** 重置密码
* @param gaeaUserDto
* @return
*/
Boolean resetPassword(GaeaUserDto gaeaUserDto);
/**
* 修改密码
* @param dto
* @return
*/
Boolean updatePassword(UpdatePasswordDto dto);
/** 用户登录
* @param gaeaUserDto
* @return
*/
GaeaUserDto login(GaeaUserDto gaeaUserDto);
/**
* 修改密码
* @param dto
* @return
*/
Boolean updatePassword(UpdatePasswordDto dto);
}
@@ -5,9 +5,9 @@ import com.alibaba.fastjson.JSONObject;
import com.anji.plus.gaea.bean.TreeNode;
import com.anji.plus.gaea.cache.CacheHelper;
import com.anji.plus.gaea.constant.BaseOperationEnum;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessException;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.holder.UserContentHolder;
import com.anji.plus.gaea.utils.GaeaUtils;
import com.anji.plus.gaea.utils.JwtBean;
@@ -20,11 +20,11 @@ import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessR
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.AccessUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.GaeaUserDto;
import com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.UpdatePasswordDto;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.AccessUserMapper;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.AccessUserRoleMapper;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUserRole;
import com.anjiplus.template.gaea.business.modules.accessuser.service.AccessUserService;
import com.anjiplus.template.gaea.business.modules.accessuser.dao.AccessUserMapper;
import com.anjiplus.template.gaea.business.util.MD5Util;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -37,228 +37,226 @@ import java.util.*;
import java.util.stream.Collectors;
/**
* @desc AccessUser 用户管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
* @desc AccessUser 用户管理服务实现
* @author 木子李·De <lide1202@hotmail.com>
* @date 2019-02-17 08:50:11.902
**/
@Service
public class AccessUserServiceImpl implements AccessUserService {
@Autowired
private AccessRoleMapper accessRoleMapper;
@Autowired
private AccessRoleMapper accessRoleMapper;
@Autowired
private AccessUserMapper accessUserMapper;
@Autowired
private AccessUserMapper accessUserMapper;
@Autowired
private AccessUserRoleMapper accessUserRoleMapper;
@Autowired
private AccessUserRoleMapper accessUserRoleMapper;
@Autowired
private AccessRoleAuthorityMapper accessRoleAuthorityMapper;
@Autowired
private AccessRoleAuthorityMapper accessRoleAuthorityMapper;
@Value("${customer.user.default.password:'123456'}")
private String defaultPassword;
@Value("${customer.user.default.password:'123456'}")
private String defaultPassword;
@Override
public GaeaBaseMapper<AccessUser> getMapper() {
return accessUserMapper;
}
@Override
public GaeaBaseMapper<AccessUser> getMapper() {
return accessUserMapper;
}
@Autowired
private JwtBean jwtBean;
@Autowired
private JwtBean jwtBean;
@Autowired
private CacheHelper cacheHelper;
@Autowired
private CacheHelper cacheHelper;
@Override
public Map getRoleTree(String loginName, String operator) {
Map<String, Object> result = new HashMap<String, Object>();
List<TreeNode> treeData = new ArrayList<>();
List checkedKeys = new ArrayList();
@Override
public Map getRoleTree(String loginName, String operator) {
Map<String, Object> result = new HashMap<String, Object>();
List<TreeNode> treeData = new ArrayList<>();
List checkedKeys = new ArrayList();
// 角色树
LambdaQueryWrapper<AccessRole> roleQuery = Wrappers.lambdaQuery();
roleQuery.select(AccessRole::getRoleCode, AccessRole::getRoleName);
// 按operator去筛选role 后面再加where
List<AccessRole> roleList = accessRoleMapper.selectList(roleQuery);
if (roleList == null || roleList.isEmpty()) {
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
treeData = roleList.stream().map(role -> {
TreeNode treeNode = new TreeNode();
treeNode.setId(role.getRoleCode());
treeNode.setLabel(role.getRoleName());
return treeNode;
}).collect(Collectors.toList());
// 角色树
LambdaQueryWrapper<AccessRole> roleQuery = Wrappers.lambdaQuery();
roleQuery.select(AccessRole::getRoleCode, AccessRole::getRoleName);
// 按operator去筛选role 后面再加where
List<AccessRole> roleList = accessRoleMapper.selectList(roleQuery);
if(roleList == null || roleList.isEmpty()){
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
treeData = roleList.stream().map(role -> {
TreeNode treeNode = new TreeNode();
treeNode.setId(role.getRoleCode());
treeNode.setLabel(role.getRoleName());
return treeNode;
}).collect(Collectors.toList());
// 该用户已保存的角色
LambdaQueryWrapper<AccessUserRole> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.select(AccessUserRole::getRoleCode).eq(AccessUserRole::getLoginName, loginName);
checkedKeys = accessUserRoleMapper.selectObjs(queryWrapper);
// 该用户已保存的角色
LambdaQueryWrapper<AccessUserRole> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.select(AccessUserRole::getRoleCode)
.eq(AccessUserRole::getLoginName, loginName);
checkedKeys = accessUserRoleMapper.selectObjs(queryWrapper);
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
result.put("treeData", treeData);
result.put("checkedKeys", checkedKeys);
return result;
}
@Override
public Boolean saveRoleTree(AccessUserDto accessUserDto) {
// 校验
String loginName = accessUserDto.getLoginName();
List<String> roleCodeList = accessUserDto.getRoleCodeList();
if (StringUtils.isBlank(loginName)) {
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, loginName);
}
if (roleCodeList == null || roleCodeList.isEmpty()) {
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, roleCodeList);
}
@Override
public Boolean saveRoleTree(AccessUserDto accessUserDto) {
// 校验
String loginName = accessUserDto.getLoginName();
List<String> roleCodeList = accessUserDto.getRoleCodeList();
if(StringUtils.isBlank(loginName)){
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, loginName);
}
if(roleCodeList == null || roleCodeList.isEmpty()){
throw BusinessExceptionBuilder.build(ResponseCode.NOT_EMPTY, roleCodeList);
}
// 先清除该用户已保存的角色
LambdaQueryWrapper<AccessUserRole> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUserRole::getLoginName, loginName);
accessUserRoleMapper.delete(wrapper);
// 先清除该用户已保存的角色
LambdaQueryWrapper<AccessUserRole> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUserRole::getLoginName, loginName);
accessUserRoleMapper.delete(wrapper);
// 保存勾选的角色
roleCodeList.stream().forEach(roleCode -> {
AccessUserRole accessUserRole = new AccessUserRole();
accessUserRole.setLoginName(loginName);
accessUserRole.setRoleCode(roleCode);
accessUserRoleMapper.insert(accessUserRole);
});
return true;
}
// 保存勾选的角色
roleCodeList.stream().forEach(roleCode -> {
AccessUserRole accessUserRole = new AccessUserRole();
accessUserRole.setLoginName(loginName);
accessUserRole.setRoleCode(roleCode);
accessUserRoleMapper.insert(accessUserRole);
});
return true;
}
@Override
public Boolean resetPassword(GaeaUserDto gaeaUserDto) {
return false;
}
@Override
public Boolean resetPassword(GaeaUserDto gaeaUserDto) {
return false;
}
@Override
public GaeaUserDto login(GaeaUserDto gaeaUserDto) {
@Override
public GaeaUserDto login(GaeaUserDto gaeaUserDto) {
String loginName = gaeaUserDto.getLoginName();
String password = gaeaUserDto.getPassword();
String loginName = gaeaUserDto.getLoginName();
String password = gaeaUserDto.getPassword();
// 1.判断用户是否存在
LambdaQueryWrapper<AccessUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUser::getLoginName, loginName);
AccessUser accessUser = accessUserMapper.selectOne(wrapper);
if (null == accessUser) {
throw BusinessExceptionBuilder.build(ResponseCode.LOGIN_ERROR);
}
// 2.密码错误
if (!accessUser.getPassword().equals(MD5Util.encrypt(password))) {
throw BusinessExceptionBuilder.build(ResponseCode.USER_PASSWORD_ERROR);
}
// 1.判断用户是否存在
LambdaQueryWrapper<AccessUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUser::getLoginName, loginName);
AccessUser accessUser = accessUserMapper.selectOne(wrapper);
if (null == accessUser) {
throw BusinessExceptionBuilder.build(ResponseCode.LOGIN_ERROR);
}
// 2.密码错误
if (!accessUser.getPassword().equals(MD5Util.encrypt(password))) {
throw BusinessExceptionBuilder.build(ResponseCode.USER_PASSWORD_ERROR);
}
// 3.如果该用户登录未过期,这里允许一个用户在多个终端登录
String tokenKey = String.format(BusinessConstant.GAEA_SECURITY_LOGIN_TOKEN, loginName);
String token = "";
GaeaUserDto gaeaUser = new GaeaUserDto();
if (cacheHelper.exist(tokenKey)) {
token = cacheHelper.stringGet(tokenKey);
}
else {
// 生成用户token
String uuid = GaeaUtils.UUID();
token = jwtBean.createToken(loginName, uuid);
cacheHelper.stringSetExpire(tokenKey, token, 3600);
}
// 3.如果该用户登录未过期,这里允许一个用户在多个终端登录
String tokenKey = String.format(BusinessConstant.GAEA_SECURITY_LOGIN_TOKEN, loginName);
String token = "";
GaeaUserDto gaeaUser = new GaeaUserDto();
if (cacheHelper.exist(tokenKey)) {
token = cacheHelper.stringGet(tokenKey);
} else {
// 生成用户token
String uuid = GaeaUtils.UUID();
token = jwtBean.createToken(loginName, uuid);
cacheHelper.stringSetExpire(tokenKey, token, 3600);
}
// 4.读取用户最新人权限主信息
String userKey = String.format(BusinessConstant.GAEA_SECURITY_LOGIN_USER, loginName);
// 4.读取用户最新人权限主信息
String userKey = String.format(BusinessConstant.GAEA_SECURITY_LOGIN_USER, loginName);
// 为了兼容底层其他数据库,不再写自定义sql
// List<String> authorities =
// accessUserMapper.queryAuthoritiesByLoginName(loginName);
//为了兼容底层其他数据库,不再写自定义sql
// List<String> authorities = accessUserMapper.queryAuthoritiesByLoginName(loginName);
// 当前用户的roleCode集合
LambdaQueryWrapper<AccessUserRole> accessUserWrapper = Wrappers.lambdaQuery();
accessUserWrapper.select(AccessUserRole::getRoleCode);
accessUserWrapper.eq(AccessUserRole::getLoginName, loginName);
List<AccessUserRole> accessUserRoles = accessUserRoleMapper.selectList(accessUserWrapper);
Set<String> roleCodeSet = accessUserRoles.stream().map(AccessUserRole::getRoleCode).collect(Collectors.toSet());
if (roleCodeSet.size() < 1) {
gaeaUser.setAuthorities(new ArrayList<>());
}
else {
LambdaQueryWrapper<AccessRoleAuthority> accessRoleAuthorityWrapper = Wrappers.lambdaQuery();
accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction);
accessRoleAuthorityWrapper.in(AccessRoleAuthority::getRoleCode, roleCodeSet);
List<AccessRoleAuthority> accessRoleAuthorities = accessRoleAuthorityMapper
.selectList(accessRoleAuthorityWrapper);
List<String> authorities = accessRoleAuthorities.stream().map(accessRoleAuthority -> accessRoleAuthority
.getTarget().concat(":").concat(accessRoleAuthority.getAction())).distinct()
.collect(Collectors.toList());
gaeaUser.setAuthorities(authorities);
}
//当前用户的roleCode集合
LambdaQueryWrapper<AccessUserRole> accessUserWrapper = Wrappers.lambdaQuery();
accessUserWrapper.select(AccessUserRole::getRoleCode);
accessUserWrapper.eq(AccessUserRole::getLoginName, loginName);
List<AccessUserRole> accessUserRoles = accessUserRoleMapper.selectList(accessUserWrapper);
Set<String> roleCodeSet = accessUserRoles.stream().map(AccessUserRole::getRoleCode).collect(Collectors.toSet());
if (roleCodeSet.size() < 1) {
gaeaUser.setAuthorities(new ArrayList<>());
}else {
LambdaQueryWrapper<AccessRoleAuthority> accessRoleAuthorityWrapper = Wrappers.lambdaQuery();
accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction);
accessRoleAuthorityWrapper.in(AccessRoleAuthority::getRoleCode, roleCodeSet);
List<AccessRoleAuthority> accessRoleAuthorities = accessRoleAuthorityMapper.selectList(accessRoleAuthorityWrapper);
List<String> authorities = accessRoleAuthorities.stream()
.map(accessRoleAuthority -> accessRoleAuthority.getTarget().concat(":").concat(accessRoleAuthority.getAction())).distinct().collect(Collectors.toList());
gaeaUser.setAuthorities(authorities);
}
gaeaUser.setLoginName(loginName);
gaeaUser.setRealName(accessUser.getRealName());
gaeaUser.setToken(token);
gaeaUser.setLoginName(loginName);
gaeaUser.setRealName(accessUser.getRealName());
gaeaUser.setToken(token);
String gaeaUserStr = JSONObject.toJSONString(gaeaUser);
cacheHelper.stringSetExpire(userKey, gaeaUserStr, 3600);
String gaeaUserStr = JSONObject.toJSONString(gaeaUser);
cacheHelper.stringSetExpire(userKey, gaeaUserStr, 3600);
return gaeaUser;
}
return gaeaUser;
}
/**
* 修改密码
* @param dto
* @return
*/
@Override
public Boolean updatePassword(UpdatePasswordDto dto) {
if (!dto.getConfirmPassword().equals(dto.getPassword())) {
// 密码和确认密码不一致
throw BusinessExceptionBuilder.build(ResponseCode.USER_INCONSISTENT_PASSWORD_ERROR);
}
// 新密码不能与老密码一样
if (StringUtils.equals(dto.getOldPassword(), dto.getPassword())) {
throw BusinessExceptionBuilder.build(ResponseCode.USER_PASSWORD_CONFIG_PASSWORD_CANOT_EQUAL);
}
/**
* 修改密码
*
* @param dto
* @return
*/
@Override
public Boolean updatePassword(UpdatePasswordDto dto) {
if (!dto.getConfirmPassword().equals(dto.getPassword())) {
//密码和确认密码不一致
throw BusinessExceptionBuilder.build(ResponseCode.USER_INCONSISTENT_PASSWORD_ERROR);
}
//新密码不能与老密码一样
if(StringUtils.equals(dto.getOldPassword(), dto.getPassword())){
throw BusinessExceptionBuilder.build(ResponseCode.USER_PASSWORD_CONFIG_PASSWORD_CANOT_EQUAL);
}
String username = UserContentHolder.getUsername();
String username = UserContentHolder.getUsername();
LambdaQueryWrapper<AccessUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUser::getLoginName, username);
AccessUser accessUser = selectOne(wrapper);
String password = accessUser.getPassword();
if (!MD5Util.encrypt(dto.getOldPassword()).equals(password)) {
throw BusinessExceptionBuilder.build(ResponseCode.USER_OLD_PASSWORD_ERROR);
}
accessUser.setPassword(MD5Util.encrypt(dto.getPassword()));
accessUserMapper.updateById(accessUser);
return true;
}
LambdaQueryWrapper<AccessUser> wrapper = Wrappers.lambdaQuery();
wrapper.eq(AccessUser::getLoginName, username);
AccessUser accessUser = selectOne(wrapper);
String password = accessUser.getPassword();
if (!MD5Util.encrypt(dto.getOldPassword()).equals(password)) {
throw BusinessExceptionBuilder.build(ResponseCode.USER_OLD_PASSWORD_ERROR);
}
accessUser.setPassword(MD5Util.encrypt(dto.getPassword()));
/**
* 操作前处理
* @param entity 前端传递的对象
* @param operationEnum 操作类型
* @throws BusinessException 阻止程序继续执行或回滚事务
*/
@Override
public void processBeforeOperation(AccessUser entity, BaseOperationEnum operationEnum) throws BusinessException {
// 过滤密码
switch (operationEnum) {
case INSERT:
// gaea是为了和前端加密保持一致
entity.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("gaea"))));
break;
case UPDATE:
// 更新用户不允许修改密码
entity.setPassword(null);
break;
default:
accessUserMapper.updateById(accessUser);
return true;
}
break;
}
/**
* 操作前处理
*
* @param entity 前端传递的对象
* @param operationEnum 操作类型
* @throws BusinessException 阻止程序继续执行或回滚事务
*/
@Override
public void processBeforeOperation(AccessUser entity, BaseOperationEnum operationEnum) throws BusinessException {
//过滤密码
switch (operationEnum) {
case INSERT:
//gaea是为了和前端加密保持一致
entity.setPassword(MD5Util.encrypt(MD5Util.encrypt(defaultPassword.concat("gaea"))));
break;
case UPDATE:
//更新用户不允许修改密码
entity.setPassword(null);
break;
default:
}
break;
}
}
}
@@ -4,12 +4,15 @@ package com.anjiplus.template.gaea.business.modules.dashboard.controller;
import com.anji.plus.gaea.annotation.Permission;
import com.anji.plus.gaea.annotation.log.GaeaAuditLog;
import com.anji.plus.gaea.bean.ResponseBean;
import com.anjiplus.template.gaea.business.modules.dashboard.service.ReportDashboardService;
import com.anjiplus.template.gaea.business.modules.dashboard.controller.dto.ChartDto;
import com.anjiplus.template.gaea.business.modules.dashboard.controller.dto.ReportDashboardObjectDto;
import com.anjiplus.template.gaea.business.modules.dashboard.service.ReportDashboardService;
import com.anjiplus.template.gaea.business.modules.reportshare.controller.dto.ReportShareDto;
import com.anjiplus.template.gaea.business.modules.reportshare.service.ReportShareService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -17,80 +20,89 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @desc 大屏设计 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
* @desc 大屏设计 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@RestController
@Api(tags = "大屏设计管理")
@Permission(code = "bigScreenManage", name = "大屏报表")
@RequestMapping("/reportDashboard")
public class ReportDashboardController {
@Autowired
private ReportDashboardService reportDashboardService;
@Autowired
private ReportDashboardService reportDashboardService;
/**
* 预览、查询大屏详情
* @param reportCode
* @return
*/
@GetMapping({ "/{reportCode}" })
@Permission(code = "view", name = "查看大屏")
public ResponseBean detail(@PathVariable("reportCode") String reportCode) {
return ResponseBean.builder().data(reportDashboardService.getDetail(reportCode)).build();
}
@Autowired
private ReportShareService reportShareService;
/**
* 保存大屏设计
* @param dto
* @return
*/
@PostMapping
@Permission(code = "design", name = "设计大屏")
@GaeaAuditLog(pageTitle = "新增")
public ResponseBean insert(@RequestBody ReportDashboardObjectDto dto) {
reportDashboardService.insertDashboard(dto);
return ResponseBean.builder().build();
}
/**
* 预览、查询大屏详情
* @param reportCode
* @return
*/
@GetMapping({"/{reportCode}"})
@Permission(code = "view", name = "查看大屏")
public ResponseBean detail(@PathVariable("reportCode") String reportCode) {
return ResponseBean.builder().data(reportDashboardService.getDetail(reportCode)).build();
}
/**
* 获取去单个图层数据
* @param dto
* @return
*/
@PostMapping("/getData")
@Permission(code = "view", name = "查看大屏")
public ResponseBean getData(@RequestBody ChartDto dto) {
return ResponseBean.builder().data(reportDashboardService.getChartData(dto)).build();
}
/**
* 保存大屏设计
* @param dto
* @return
*/
@PostMapping
@Permission(code = "design", name = "设计大屏")
@GaeaAuditLog(pageTitle = "新增")
public ResponseBean insert(@RequestBody ReportDashboardObjectDto dto) {
reportDashboardService.insertDashboard(dto);
return ResponseBean.builder().build();
}
/**
* 导出大屏
* @param reportCode
* @return
*/
@GetMapping("/export")
@Permission(code = "export", name = "导出大屏")
public ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response,
@RequestParam("reportCode") String reportCode,
@RequestParam(value = "showDataSet", required = false, defaultValue = "1") Integer showDataSet) {
return reportDashboardService.exportDashboard(request, response, reportCode, showDataSet);
}
/**
* 导入大屏
* @param file 导入的zip文件
* @param reportCode
* @return
*/
@PostMapping("/import/{reportCode}")
@Permission(code = "import", name = "导入大屏")
public ResponseBean importDashboard(@RequestParam("file") MultipartFile file,
@PathVariable("reportCode") String reportCode) {
reportDashboardService.importDashboard(file, reportCode);
return ResponseBean.builder().build();
}
/**
* 获取去单个图层数据
* @param dto
* @return
*/
@PostMapping("/getData")
@Permission(code = "view", name = "查看大屏")
public ResponseBean getData(@RequestBody ChartDto dto) {
return ResponseBean.builder().data(reportDashboardService.getChartData(dto)).build();
}
/**
* 导出大屏
* @param reportCode
* @return
*/
@GetMapping("/export")
@Permission(code = "export", name = "导出大屏")
public ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response,
@RequestParam("reportCode") String reportCode, @RequestParam(value = "showDataSet",required = false, defaultValue = "1") Integer showDataSet) {
return reportDashboardService.exportDashboard(request, response, reportCode, showDataSet);
}
/**
* 导入大屏
* @param file 导入的zip文件
* @param reportCode
* @return
*/
@PostMapping("/import/{reportCode}")
@Permission(code = "import", name = "导入大屏")
public ResponseBean importDashboard(@RequestParam("file") MultipartFile file, @PathVariable("reportCode") String reportCode) {
reportDashboardService.importDashboard(file, reportCode);
return ResponseBean.builder().build();
}
@PostMapping("/share")
@GaeaAuditLog(pageTitle = "分享")
public ResponseBean share(@Validated @RequestBody ReportShareDto dto) {
return ResponseBean.builder().data(reportShareService.insertShare(dto)).build();
}
}
@@ -6,43 +6,46 @@ import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
*
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@Data
public class ChartDto implements Serializable {
private String chartType;
private String chartType;
/** 数据集编码 */
private String setCode;
/**数据集编码*/
private String setCode;
/** 传入的自定义参数 */
private Map<String, Object> contextData;
/** 传入的自定义参数*/
private Map<String, Object> contextData;
/** 图表属性 */
private Map<String, String> chartProperties;
/**图表属性*/
private Map<String, String> chartProperties;
/** 时间字段 */
private String timeLineFiled;
/**时间字段*/
private String timeLineFiled;
/** 时间颗粒度 */
private String particles;
/**时间颗粒度*/
private String particles;
/** 时间格式化 */
private String dataTimeFormat;
/**时间格式化*/
private String dataTimeFormat;
/** 时间展示层 */
private String timeLineFormat;
/**时间展示层*/
private String timeLineFormat;
private int timeUnit;
private int timeUnit;
/** 时间区间 */
private String startTime;
/**时间区间*/
private String startTime;
/**时间区间*/
private String endTime;
/** 时间区间 */
private String endTime;
}
@@ -8,47 +8,48 @@ import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
*
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@Data
public class ReportDashboardDto extends GaeaBaseDTO implements Serializable {
/** 报表编码 */
private String reportCode;
/** 报表编码 */
private String reportCode;
/** 看板标题 */
private String title;
/** 看板标题 */
private String title;
/** 宽度px */
private Long width;
/** 宽度px */
private Long width;
/** 高度px */
private Long height;
/** 高度px */
private Long height;
/** 背景色 */
private String backgroundColor;
/** 背景色 */
private String backgroundColor;
/** 背景图片 */
private String backgroundImage;
/** 背景图片 */
private String backgroundImage;
/** 工作台中的辅助线 */
private String presetLine;
/** 工作台中的辅助线 */
private String presetLine;
/** 自动刷新间隔秒,数据字典REFRESH_TYPE */
private Integer refreshSeconds;
/** 自动刷新间隔秒,数据字典REFRESH_TYPE */
private Integer refreshSeconds;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 排序,降序 */
private Integer sort;
/** 排序,降序 */
private Integer sort;
private List<ReportDashboardWidgetDto> widgets;
private List<ReportDashboardWidgetDto> widgets;
}
@@ -7,25 +7,26 @@ import lombok.Data;
import java.io.Serializable;
import java.util.List;
/**
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
*
* @description 大屏设计 dto
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@Data
public class ReportDashboardObjectDto implements Serializable {
/** 报表编码 */
private String reportCode;
/** 报表编码 */
private String reportCode;
/**
* 报表编码
*/
private ReportDashboardDto dashboard;
/**
* 报表编码
*/
private ReportDashboardDto dashboard;
/**
* 大屏画布中的组件
*/
private List<ReportDashboardWidgetDto> widgets;
/**
* 大屏画布中的组件
*/
private List<ReportDashboardWidgetDto> widgets;
}
@@ -1,17 +1,20 @@
/**/
package com.anjiplus.template.gaea.business.modules.dashboard.controller.param;
import com.anji.plus.gaea.curd.params.PageParam;
import lombok.Data;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
import java.util.List;
/**
* @desc ReportDashboard 大屏设计查询输入类
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
* @desc ReportDashboard 大屏设计查询输入类
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@Data
public class ReportDashboardParam extends PageParam implements Serializable {
public class ReportDashboardParam extends PageParam implements Serializable{
}
@@ -1,15 +1,15 @@
package com.anjiplus.template.gaea.business.modules.dashboard.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.dashboard.dao.entity.ReportDashboard;
import org.apache.ibatis.annotations.Mapper;
/**
* ReportDashboard Mapper
*
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
* ReportDashboard Mapper
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@Mapper
public interface ReportDashboardMapper extends GaeaBaseMapper<ReportDashboard> {
@@ -9,46 +9,46 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 大屏设计 entity
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_dashboard")
* @description 大屏设计 entity
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_dashboard")
@Data
public class ReportDashboard extends GaeaBaseEntity {
@ApiModelProperty(value = "报表编码")
@Unique(code = ResponseCode.REPORT_CODE_ISEXIST)
private String reportCode;
@ApiModelProperty(value = "报表编码")
@Unique(code = ResponseCode.REPORT_CODE_ISEXIST)
private String reportCode;
@ApiModelProperty(value = "看板标题")
private String title;
@ApiModelProperty(value = "看板标题")
private String title;
@ApiModelProperty(value = "宽度px")
private Long width;
@ApiModelProperty(value = "宽度px")
private Long width;
@ApiModelProperty(value = "高度px")
private Long height;
@ApiModelProperty(value = "高度px")
private Long height;
@ApiModelProperty(value = "背景色")
private String backgroundColor;
@ApiModelProperty(value = "背景色")
private String backgroundColor;
@ApiModelProperty(value = "背景图片")
private String backgroundImage;
@ApiModelProperty(value = "背景图片")
private String backgroundImage;
@ApiModelProperty(value = "工作台中的辅助线")
private String presetLine;
@ApiModelProperty(value = "工作台中的辅助线")
private String presetLine;
@ApiModelProperty(value = "自动刷新间隔秒,数据字典REFRESH_TYPE")
private Integer refreshSeconds;
@ApiModelProperty(value = "自动刷新间隔秒,数据字典REFRESH_TYPE")
private Integer refreshSeconds;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "排序,降序")
private Integer sort;
@ApiModelProperty(value = "排序,降序")
private Integer sort;
}
@@ -10,17 +10,17 @@ import java.util.List;
*/
public interface ChartStrategy {
/**
* 图表类型
* @return
*/
String type();
/**
* 针对每种图表类型做单独的数据转换解析
* @param dto
* @return
*/
Object transform(ChartDto dto, List<JSONObject> data);
/**
* 图表类型
* @return
*/
String type();
/**
* 针对每种图表类型做单独的数据转换解析
*
* @param dto
* @return
*/
Object transform(ChartDto dto, List<JSONObject> data);
}
@@ -13,47 +13,49 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @desc ReportDashboard 大屏设计服务接口
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
* @desc ReportDashboard 大屏设计服务接口
* @author Raod
* @date 2021-04-12 14:52:21.761
**/
public interface ReportDashboardService extends GaeaBaseService<ReportDashboardParam, ReportDashboard> {
/***
* 查询详情
* @param reportCode
*/
ReportDashboardObjectDto getDetail(String reportCode);
/***
* 查询详情
*
* @param reportCode
*/
ReportDashboardObjectDto getDetail(String reportCode);
/***
* 保存大屏设计
* @param dto
*/
void insertDashboard(ReportDashboardObjectDto dto);
/***
* 保存大屏设计
*
* @param dto
*/
void insertDashboard(ReportDashboardObjectDto dto);
/**
* 获取单个图表数据
* @param dto
* @return
*/
Object getChartData(ChartDto dto);
/**
* 导出大屏,zip文件
* @param request
* @param response
* @param reportCode
* @return
*/
ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response, String reportCode,
Integer showDataSet);
/**
* 获取单个图表数据
* @param dto
* @return
*/
Object getChartData(ChartDto dto);
/**
* 导入大屏zip
* @param file
* @param reportCode
* @return
*/
void importDashboard(MultipartFile file, String reportCode);
/**
* 导出大屏,zip文件
* @param request
* @param response
* @param reportCode
* @return
*/
ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response, String reportCode, Integer showDataSet);
/**
* 导入大屏zip
* @param file
* @param reportCode
* @return
*/
void importDashboard(MultipartFile file, String reportCode);
}
@@ -8,54 +8,72 @@ import org.springframework.stereotype.Component;
import java.util.List;
/**
* 柱状体或者折线图 Created by raodeming on 2021/4/26.
* 柱状体或者折线图
* Created by raodeming on 2021/4/26.
*/
@Component
public class BarChartServiceImpl implements ChartStrategy {
/**
* 图表类型
*
* @return
*/
@Override
public String type() {
return "widget-barchart|widget-linechart";
}
/**
* 图表类型
* @return
*/
@Override
public String type() {
return "widget-barchart|widget-linechart";
}
/**
* 针对每种图表类型做单独的数据转换解析
*
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// JSONObject json = new JSONObject();
// List<Object> xAxis = new ArrayList<>();
// List<Object> series = new ArrayList<>();
// data.forEach(jsonObject -> {
// jsonObject.forEach((s, o) -> {
// if ("xAxis".equals(s)) {
// xAxis.add(o);
// } else {
// series.add(o);
// }
// });
// });
//
// json.put("xAxis", xAxis);
// JSONArray objects = new JSONArray();
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("data", series);
// objects.add(jsonObject);
// json.put("series", objects);
// return json.toJSONString();
return data;
}
/**
* 针对每种图表类型做单独的数据转换解析
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// JSONObject json = new JSONObject();
// List<Object> xAxis = new ArrayList<>();
// List<Object> series = new ArrayList<>();
// data.forEach(jsonObject -> {
// jsonObject.forEach((s, o) -> {
// if ("xAxis".equals(s)) {
// xAxis.add(o);
// } else {
// series.add(o);
// }
// });
// });
//
// json.put("xAxis", xAxis);
// JSONArray objects = new JSONArray();
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("data", series);
// objects.add(jsonObject);
// json.put("series", objects);
// return json.toJSONString();
return data;
}
/*
* { "xAxis": [ "哈哈", "洗洗", "来了", "问问", "天天" ], "series": [ { "data": [ 1, 2, 3, 4, 5
* ] } ] }
*/
/* {
"xAxis": [
"哈哈",
"洗洗",
"来了",
"问问",
"天天"
],
"series": [
{
"data": [
1,
2,
3,
4,
5
]
}
]
}*/
}
@@ -8,72 +8,98 @@ import org.springframework.stereotype.Component;
import java.util.List;
/**
* 折柱图 Created by raodeming on 2021/4/26.
* 折柱图
* Created by raodeming on 2021/4/26.
*/
@Component
public class BarLineChartServiceImpl implements ChartStrategy {
/**
* 图表类型
*
* @return
*/
@Override
public String type() {
return "widget-barlinechart";
}
/**
* 图表类型
* @return
*/
@Override
public String type() {
return "widget-barlinechart";
}
/**
* 针对每种图表类型做单独的数据转换解析
*
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// JSONObject json = new JSONObject();
// List<Object> xAxis = new ArrayList<>();
// Map<String, List<Object>> series = new HashMap<>();
// data.forEach(jsonObject -> {
// jsonObject.forEach((s, o) -> {
// if ("xAxis".equals(s)) {
// xAxis.add(o);
// } else {
// List<Object> objects;
// if (series.containsKey(s)) {
// objects = series.get(s);
// } else {
// objects = new ArrayList<>();
//
// }
// objects.add(o);
// series.put(s, objects);
//
// }
// });
// });
//
// json.put("xAxis", xAxis);
// List<JSONObject> result = new ArrayList<>();
// series.forEach((s, objects) -> {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("name", s);
// if (s.endsWith("bar")) {
// jsonObject.put("type", "bar");
// } else {
// jsonObject.put("type", "line");
// }
// jsonObject.put("data", objects);
// result.add(jsonObject);
// });
// json.put("series", result);
// return json.toJSONString();
return data;
}
/**
* 针对每种图表类型做单独的数据转换解析
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// JSONObject json = new JSONObject();
// List<Object> xAxis = new ArrayList<>();
// Map<String, List<Object>> series = new HashMap<>();
// data.forEach(jsonObject -> {
// jsonObject.forEach((s, o) -> {
// if ("xAxis".equals(s)) {
// xAxis.add(o);
// } else {
// List<Object> objects;
// if (series.containsKey(s)) {
// objects = series.get(s);
// } else {
// objects = new ArrayList<>();
//
// }
// objects.add(o);
// series.put(s, objects);
//
// }
// });
// });
//
// json.put("xAxis", xAxis);
// List<JSONObject> result = new ArrayList<>();
// series.forEach((s, objects) -> {
// JSONObject jsonObject = new JSONObject();
// jsonObject.put("name", s);
// if (s.endsWith("bar")) {
// jsonObject.put("type", "bar");
// } else {
// jsonObject.put("type", "line");
// }
// jsonObject.put("data", objects);
// result.add(jsonObject);
// });
// json.put("series", result);
// return json.toJSONString();
return data;
}
/*
* { "xAxis": [ "1月", "2月", "3月" ], "series": [ { "name": "指标1", //暂时用不上 "type":
* "bar", //需要处理 "data": [ 2, 49, 2 ] }, { "name": "指标2", "type": "line",
* "yAxisIndex": 1, "data": [ 2, 32, 4 ] } ] }
*/
/*{
"xAxis": [
"1月",
"2月",
"3月"
],
"series": [
{
"name": "指标1", //暂时用不上
"type": "bar", //需要处理
"data": [
2,
49,
2
]
},
{
"name": "指标2",
"type": "line",
"yAxisIndex": 1,
"data": [
2,
32,
4
]
}
]
}*/
}
@@ -8,31 +8,36 @@ import org.springframework.stereotype.Component;
import java.util.List;
/**
* 饼图或者空心饼图或者漏斗图 Created by raodeming on 2021/4/26.
* 饼图或者空心饼图或者漏斗图
* Created by raodeming on 2021/4/26.
*/
@Component
public class GaugeChartServiceImpl implements ChartStrategy {
/**
* 图表类型
*
* @return
*/
@Override
public String type() {
return "widget-gauge";
}
/**
* 针对每种图表类型做单独的数据转换解析
*
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// return "{\"value\": 50, \"name\": \"名称1\", \"unit\": \"%\"}";
return data;
}
/**
* 图表类型
* @return
*/
@Override
public String type() {
return "widget-gauge";
}
/**
* 针对每种图表类型做单独的数据转换解析
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
// return "{\"value\": 50, \"name\": \"名称1\", \"unit\": \"%\"}";
return data;
}
}
@@ -8,34 +8,45 @@ import org.springframework.stereotype.Component;
import java.util.List;
/**
* 饼图或者空心饼图或者漏斗图 Created by raodeming on 2021/4/26.
* 饼图或者空心饼图或者漏斗图
* Created by raodeming on 2021/4/26.
*/
@Component
public class PieChartServiceImpl implements ChartStrategy {
/**
* 图表类型
*
* @return
*/
@Override
public String type() {
return "widget-piechart|widget-hollow-piechart|widget-funnel";
}
/**
* 图表类型
* @return
*/
@Override
public String type() {
return "widget-piechart|widget-hollow-piechart|widget-funnel";
}
/**
* 针对每种图表类型做单独的数据转换解析
*
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
/**
* 针对每种图表类型做单独的数据转换解析
* @param dto
* @param data
* @return
*/
@Override
public Object transform(ChartDto dto, List<JSONObject> data) {
return data;
}
/* [
{
"value": 11,
"name": "指标1"
},
{
"value": 10,
"name": "指标2"
}
]*/
return data;
}
/*
* [ { "value": 11, "name": "指标1" }, { "value": 10, "name": "指标2" } ]
*/
}
@@ -24,8 +24,10 @@ import com.anjiplus.template.gaea.business.modules.dataset.service.DataSetServic
import com.anjiplus.template.gaea.business.modules.file.entity.GaeaFile;
import com.anjiplus.template.gaea.business.modules.file.service.GaeaFileService;
import com.anjiplus.template.gaea.business.modules.file.util.FileUtils;
import com.anjiplus.template.gaea.business.modules.report.service.ReportService;
import com.anjiplus.template.gaea.business.util.DateUtil;
import com.anjiplus.template.gaea.business.util.FileUtil;
import com.anjiplus.template.gaea.business.util.RequestUtil;
import com.anjiplus.template.gaea.business.util.UuidUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
@@ -50,6 +52,7 @@ import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CompletableFuture;
/**
* @author Raod
@@ -58,490 +61,504 @@ import java.util.*;
**/
@Service
@Slf4j
// @RequiredArgsConstructor
//@RequiredArgsConstructor
public class ReportDashboardServiceImpl implements ReportDashboardService, InitializingBean, ApplicationContextAware {
@Autowired
private ReportDashboardMapper reportDashboardMapper;
@Autowired
private ReportDashboardMapper reportDashboardMapper;
@Autowired
private ReportDashboardWidgetService reportDashboardWidgetService;
@Autowired
private ReportDashboardWidgetService reportDashboardWidgetService;
@Autowired
private DataSetService dataSetService;
@Autowired
private DataSetService dataSetService;
@Autowired
private GaeaFileService gaeaFileService;
@Autowired
private GaeaFileService gaeaFileService;
@Value("${customer.file.downloadPath:''}")
private String fileDownloadPath;
@Autowired
private ReportService reportService;
@Value("${customer.file.dist-path:''}")
private String dictPath;
@Value("${customer.file.downloadPath:''}")
private String fileDownloadPath;
private final static String ZIP_PATH = "/zip/";
@Value("${customer.file.dist-path:''}")
private String dictPath;
private final static String JSON_PATH = "dashboard.json";
private final static String ZIP_PATH = "/zip/";
private final static String JSON_PATH = "dashboard.json";
private final Map<String, ChartStrategy> queryServiceImplMap = new HashMap<>();
private Map<String, ChartStrategy> queryServiceImplMap = new HashMap<>();
private ApplicationContext applicationContext;
private ApplicationContext applicationContext;
@Override
public GaeaBaseMapper<ReportDashboard> getMapper() {
return reportDashboardMapper;
}
@Override
public GaeaBaseMapper<ReportDashboard> getMapper() {
return reportDashboardMapper;
}
@Override
public ReportDashboardObjectDto getDetail(String reportCode) {
ReportDashboardObjectDto result = new ReportDashboardObjectDto();
ReportDashboardDto reportDashboardDto = new ReportDashboardDto();
ReportDashboard reportDashboard = this.selectOne("report_code", reportCode);
if (null == reportDashboard) {
return new ReportDashboardObjectDto();
}
GaeaBeanUtils.copyAndFormatter(reportDashboard, reportDashboardDto);
@Override
public ReportDashboardObjectDto getDetail(String reportCode) {
ReportDashboardObjectDto result = new ReportDashboardObjectDto();
ReportDashboardDto reportDashboardDto = new ReportDashboardDto();
ReportDashboard reportDashboard = this.selectOne("report_code", reportCode);
if (null == reportDashboard) {
return new ReportDashboardObjectDto();
}
GaeaBeanUtils.copyAndFormatter(reportDashboard, reportDashboardDto);
List<ReportDashboardWidget> list = reportDashboardWidgetService.list(
new QueryWrapper<ReportDashboardWidget>().lambda()
.eq(ReportDashboardWidget::getReportCode, reportCode)
.orderByAsc(ReportDashboardWidget::getSort)
);
List<ReportDashboardWidgetDto> reportDashboardWidgetDtoList = new ArrayList<>();
list.forEach(reportDashboardWidget -> {
ReportDashboardWidgetDto reportDashboardWidgetDto = new ReportDashboardWidgetDto();
ReportDashboardWidgetValueDto value = new ReportDashboardWidgetValueDto();
value.setSetup(StringUtils.isNotBlank(reportDashboardWidget.getSetup()) ? JSONObject.parseObject(reportDashboardWidget.getSetup()) : new JSONObject());
value.setData(StringUtils.isNotBlank(reportDashboardWidget.getData()) ? JSONObject.parseObject(reportDashboardWidget.getData()) : new JSONObject());
value.setPosition(StringUtils.isNotBlank(reportDashboardWidget.getPosition()) ? JSONObject.parseObject(reportDashboardWidget.getPosition()) : new JSONObject());
value.setCollapse(StringUtils.isNotBlank(reportDashboardWidget.getCollapse()) ? JSONObject.parseObject(reportDashboardWidget.getCollapse()) : new JSONObject());
List<ReportDashboardWidget> list = reportDashboardWidgetService.list(
new QueryWrapper<ReportDashboardWidget>().lambda().eq(ReportDashboardWidget::getReportCode, reportCode)
.orderByAsc(ReportDashboardWidget::getSort));
List<ReportDashboardWidgetDto> reportDashboardWidgetDtoList = new ArrayList<>();
list.forEach(reportDashboardWidget -> {
ReportDashboardWidgetDto reportDashboardWidgetDto = new ReportDashboardWidgetDto();
ReportDashboardWidgetValueDto value = new ReportDashboardWidgetValueDto();
value.setSetup(StringUtils.isNotBlank(reportDashboardWidget.getSetup())
? JSONObject.parseObject(reportDashboardWidget.getSetup()) : new JSONObject());
value.setData(StringUtils.isNotBlank(reportDashboardWidget.getData())
? JSONObject.parseObject(reportDashboardWidget.getData()) : new JSONObject());
value.setPosition(StringUtils.isNotBlank(reportDashboardWidget.getPosition())
? JSONObject.parseObject(reportDashboardWidget.getPosition()) : new JSONObject());
value.setCollapse(StringUtils.isNotBlank(reportDashboardWidget.getCollapse())
? JSONObject.parseObject(reportDashboardWidget.getCollapse()) : new JSONObject());
//实时数据的替换
analysisData(value);
reportDashboardWidgetDto.setType(reportDashboardWidget.getType());
reportDashboardWidgetDto.setValue(value);
reportDashboardWidgetDto.setOptions(JSONObject.parseObject(reportDashboardWidget.getOptions()));
reportDashboardWidgetDtoList.add(reportDashboardWidgetDto);
});
reportDashboardDto.setWidgets(reportDashboardWidgetDtoList);
result.setDashboard(reportDashboardDto);
result.setReportCode(reportCode);
return result;
}
// 实时数据的替换
analysisData(value);
reportDashboardWidgetDto.setType(reportDashboardWidget.getType());
reportDashboardWidgetDto.setValue(value);
reportDashboardWidgetDto.setOptions(JSONObject.parseObject(reportDashboardWidget.getOptions()));
reportDashboardWidgetDtoList.add(reportDashboardWidgetDto);
});
reportDashboardDto.setWidgets(reportDashboardWidgetDtoList);
result.setDashboard(reportDashboardDto);
result.setReportCode(reportCode);
return result;
}
/***
* 保存大屏设计
*
* @param dto
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void insertDashboard(ReportDashboardObjectDto dto) {
String reportCode = dto.getReportCode();
GaeaAssert.notEmpty(reportCode, ResponseCode.PARAM_IS_NULL, "reportCode");
//查询ReportDashboard
ReportDashboard reportDashboard = this.selectOne("report_code", reportCode);
ReportDashboard dashboard = new ReportDashboard();
GaeaBeanUtils.copyAndFormatter(dto.getDashboard(), dashboard);
BeanUtils.copyProperties(dto.getDashboard(), dashboard);
dashboard.setReportCode(reportCode);
if (null == reportDashboard) {
//新增
this.insert(dashboard);
} else {
//更新
dashboard.setId(reportDashboard.getId());
dashboard.setVersion(null);
this.update(dashboard);
}
/***
* 保存大屏设计
* @param dto
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void insertDashboard(ReportDashboardObjectDto dto) {
String reportCode = dto.getReportCode();
GaeaAssert.notEmpty(reportCode, ResponseCode.PARAM_IS_NULL, "reportCode");
// 查询ReportDashboard
ReportDashboard reportDashboard = this.selectOne("report_code", reportCode);
ReportDashboard dashboard = new ReportDashboard();
GaeaBeanUtils.copyAndFormatter(dto.getDashboard(), dashboard);
BeanUtils.copyProperties(dto.getDashboard(), dashboard);
dashboard.setReportCode(reportCode);
if (null == reportDashboard) {
// 新增
this.insert(dashboard);
}
else {
// 更新
dashboard.setId(reportDashboard.getId());
dashboard.setVersion(null);
this.update(dashboard);
}
//删除reportDashboardWidget
reportDashboardWidgetService.delete(new QueryWrapper<ReportDashboardWidget>()
.lambda().eq(ReportDashboardWidget::getReportCode, reportCode));
List<ReportDashboardWidgetDto> widgets = dto.getWidgets();
// 删除reportDashboardWidget
reportDashboardWidgetService.delete(new QueryWrapper<ReportDashboardWidget>().lambda()
.eq(ReportDashboardWidget::getReportCode, reportCode));
List<ReportDashboardWidgetDto> widgets = dto.getWidgets();
// List<ReportDashboardWidget> reportDashboardWidgetList = new ArrayList<>();
for (int i = 0; i < widgets.size(); i++) {
ReportDashboardWidget reportDashboardWidget = new ReportDashboardWidget();
ReportDashboardWidgetDto reportDashboardWidgetDto = widgets.get(i);
String type = reportDashboardWidgetDto.getType();
ReportDashboardWidgetValueDto value = reportDashboardWidgetDto.getValue();
reportDashboardWidget.setReportCode(reportCode);
reportDashboardWidget.setType(type);
reportDashboardWidget.setSetup(value.getSetup() != null ? JSONObject.toJSONString(value.getSetup()) : "");
reportDashboardWidget.setData(value.getData() != null ? JSONObject.toJSONString(value.getData()) : "");
reportDashboardWidget.setPosition(value.getPosition() != null ? JSONObject.toJSONString(value.getPosition()) : "");
reportDashboardWidget.setCollapse(value.getCollapse() != null ? JSONObject.toJSONString(value.getCollapse()) : "");
reportDashboardWidget.setOptions(reportDashboardWidgetDto.getOptions() != null ? JSONObject.toJSONString(reportDashboardWidgetDto.getOptions()) : "");
reportDashboardWidget.setEnableFlag(1);
reportDashboardWidget.setDeleteFlag(0);
reportDashboardWidget.setSort((long) (i + 1));
// List<ReportDashboardWidget> reportDashboardWidgetList = new ArrayList<>();
for (int i = 0; i < widgets.size(); i++) {
ReportDashboardWidget reportDashboardWidget = new ReportDashboardWidget();
ReportDashboardWidgetDto reportDashboardWidgetDto = widgets.get(i);
String type = reportDashboardWidgetDto.getType();
ReportDashboardWidgetValueDto value = reportDashboardWidgetDto.getValue();
reportDashboardWidget.setReportCode(reportCode);
reportDashboardWidget.setType(type);
reportDashboardWidget.setSetup(value.getSetup() != null ? JSONObject.toJSONString(value.getSetup()) : "");
reportDashboardWidget.setData(value.getData() != null ? JSONObject.toJSONString(value.getData()) : "");
reportDashboardWidget
.setPosition(value.getPosition() != null ? JSONObject.toJSONString(value.getPosition()) : "");
reportDashboardWidget
.setCollapse(value.getCollapse() != null ? JSONObject.toJSONString(value.getCollapse()) : "");
reportDashboardWidget.setOptions(reportDashboardWidgetDto.getOptions() != null
? JSONObject.toJSONString(reportDashboardWidgetDto.getOptions()) : "");
reportDashboardWidget.setEnableFlag(1);
reportDashboardWidget.setDeleteFlag(0);
reportDashboardWidget.setSort((long) (i + 1));
//兼容底层,不采用批量插入
reportDashboardWidgetService.insert(reportDashboardWidget);
// 兼容底层,不采用批量插入
reportDashboardWidgetService.insert(reportDashboardWidget);
}
// reportDashboardWidgetList.add(reportDashboardWidget);
}
// reportDashboardWidgetService.insertBatch(reportDashboardWidgetList);
}
}
@Override
public Object getChartData(ChartDto dto) {
// String chartType = dto.getChartType();
DataSetDto setDto = new DataSetDto();
setDto.setSetCode(dto.getSetCode());
setDto.setContextData(dto.getContextData());
OriginalDataDto result = dataSetService.getData(setDto);
List<JSONObject> data = result.getData();
// 处理时间轴
List<JSONObject> resultData = buildTimeLine(data, dto);
return resultData;
// return getTarget(chartType).transform(dto, result.getData());
}
@Override
public Object getChartData(ChartDto dto) {
// String chartType = dto.getChartType();
DataSetDto setDto = new DataSetDto();
setDto.setSetCode(dto.getSetCode());
setDto.setContextData(dto.getContextData());
OriginalDataDto result = dataSetService.getData(setDto);
List<JSONObject> data = result.getData();
//处理时间轴
List<JSONObject> resultData = buildTimeLine(data, dto);
return resultData;
// return getTarget(chartType).transform(dto, result.getData());
}
/**
* 导出大屏,zip文件
* @param request
* @param response
* @param reportCode
* @return
*/
@Override
public ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response,
String reportCode, Integer showDataSet) {
String userAgent = request.getHeader("User-Agent");
boolean isIeBrowser = userAgent.indexOf("MSIE") > 0;
/**
* 导出大屏,zip文件
*
* @param request
* @param response
* @param reportCode
* @return
*/
@Override
public ResponseEntity<byte[]> exportDashboard(HttpServletRequest request, HttpServletResponse response, String reportCode, Integer showDataSet) {
String userAgent = request.getHeader("User-Agent");
boolean isIeBrowser = userAgent.indexOf("MSIE") > 0;
ReportDashboardObjectDto detail = getDetail(reportCode);
List<ReportDashboardWidgetDto> widgets = detail.getDashboard().getWidgets();
detail.setWidgets(widgets);
detail.getDashboard().setWidgets(null);
ReportDashboardObjectDto detail = getDetail(reportCode);
List<ReportDashboardWidgetDto> widgets = detail.getDashboard().getWidgets();
detail.setWidgets(widgets);
detail.getDashboard().setWidgets(null);
// 1.组装临时目录,/app/disk/upload/zip/临时文件夹
String path = dictPath + ZIP_PATH + UuidUtil.generateShortUuid();
// 将涉及到的图片保存下来(1.背景图,2.组件为图片的)
String backgroundImage = detail.getDashboard().getBackgroundImage();
zipLoadImage(backgroundImage, path);
detail.getWidgets().stream()
.filter(reportDashboardWidgetDto -> "widget-image".equals(reportDashboardWidgetDto.getType()))
.forEach(reportDashboardWidgetDto -> {
String imageAddress = reportDashboardWidgetDto.getValue().getSetup().getString("imageAdress");
zipLoadImage(imageAddress, path);
});
//1.组装临时目录,/app/disk/upload/zip/临时文件夹
String path = dictPath + ZIP_PATH + UuidUtil.generateShortUuid();
// showDataSet == 0 代表不包含数据集
if (0 == showDataSet) {
detail.getWidgets().forEach(reportDashboardWidgetDto -> {
ReportDashboardWidgetValueDto value = reportDashboardWidgetDto.getValue();
JSONObject data = value.getData();
if (null != data && data.containsKey("dataType")) {
reportDashboardWidgetDto.getValue().getData().put("dataType", "staticData");
}
});
}
//将涉及到的图片保存下来(1.背景图,2.组件为图片的)
String backgroundImage = detail.getDashboard().getBackgroundImage();
zipLoadImage(backgroundImage, path);
detail.getWidgets().stream()
.filter(reportDashboardWidgetDto -> "widget-image".equals(reportDashboardWidgetDto.getType()))
.forEach(reportDashboardWidgetDto -> {
String imageAddress = reportDashboardWidgetDto.getValue().getSetup().getString("imageAdress");
zipLoadImage(imageAddress, path);
});
// 2.将大屏设计到的json文件保存
String jsonPath = path + "/" + JSON_PATH;
FileUtil.WriteStringToFile(jsonPath, JSONObject.toJSONString(detail));
//showDataSet == 0 代表不包含数据集
if (0 == showDataSet) {
detail.getWidgets().forEach(reportDashboardWidgetDto -> {
ReportDashboardWidgetValueDto value = reportDashboardWidgetDto.getValue();
JSONObject data = value.getData();
if (null != data && data.containsKey("dataType")) {
reportDashboardWidgetDto.getValue().getData().put("dataType", "staticData");
}
});
}
// 将path文件夹打包zip
String zipPath = path + ".zip";
FileUtil.compress(path, zipPath);
File file = new File(zipPath);
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
builder.contentLength(file.length());
// application/octet-stream 二进制数据流(最常见的文件下载)
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
if (isIeBrowser) {
builder.header("Content-Disposition", "attachment; filename=" + reportCode + ".zip");
}
else {
builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + reportCode + ".zip");
}
//2.将大屏设计到的json文件保存
String jsonPath = path + "/" + JSON_PATH;
FileUtil.WriteStringToFile(jsonPath, JSONObject.toJSONString(detail));
ResponseEntity<byte[]> body = builder.body(FileUtils.readFileToByteArray(file));
// 删除zip文件
file.delete();
// 删除path临时文件夹
FileUtil.delete(path);
log.info("删除临时文件:{},{}", zipPath, path);
//将path文件夹打包zip
String zipPath = path + ".zip";
FileUtil.compress(path, zipPath);
return body;
}
/**
* 导入大屏zip
* @param file
* @param reportCode
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void importDashboard(MultipartFile file, String reportCode) {
log.info("导入开始,{}", reportCode);
// 1.组装临时目录,/app/disk/upload/zip/临时文件夹
String path = dictPath + ZIP_PATH + UuidUtil.generateShortUuid();
// 2.解压
FileUtil.decompress(file, path);
// path/uuid/
File parentPath = new File(path);
// 获取打包的第一层目录
File firstFile = parentPath.listFiles()[0];
File file = new File(zipPath);
ResponseEntity.BodyBuilder builder = ResponseEntity.ok();
builder.contentLength(file.length());
//application/octet-stream 二进制数据流(最常见的文件下载)
builder.contentType(MediaType.APPLICATION_OCTET_STREAM);
if (isIeBrowser) {
builder.header("Content-Disposition", "attachment; filename=" + reportCode + ".zip");
} else {
builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + reportCode + ".zip");
}
File[] files = firstFile.listFiles();
ResponseEntity<byte[]> body = builder.body(FileUtils.readFileToByteArray(file));
// 定义map
Map<String, String> fileMap = new HashMap<>();
String content = "";
//删除zip文件
file.delete();
//删除path临时文件夹
FileUtil.delete(path);
log.info("删除临时文件:{},{}", zipPath, path);
for (int i = 0; i < files.length; i++) {
File childFile = files[i];
if (JSON_PATH.equals(childFile.getName())) {
// json文件
content = FileUtil.readFile(childFile);
}
else if ("image".equals(childFile.getName())) {
File[] imageFiles = childFile.listFiles();
// 所有需要上传的图片
for (File imageFile : imageFiles) {
// 查看是否存在此image
String fileName = imageFile.getName().split("\\.")[0];
// 根据fileId,从gaea_file中读出filePath
LambdaQueryWrapper<GaeaFile> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(GaeaFile::getFileId, fileName);
GaeaFile gaeaFile = gaeaFileService.selectOne(queryWrapper);
if (null == gaeaFile) {
GaeaFile upload = gaeaFileService.upload(imageFile, fileName);
log.info("存入图片: {}", upload.getFilePath());
fileMap.put(fileName, upload.getUrlPath());
}
}
}
//异步统计下载次数
CompletableFuture.runAsync(() -> {
log.info("=======>ip:{} 下载模板:{}", RequestUtil.getIpAddr(request), reportCode);
reportService.downloadStatistics(reportCode);
});
}
// 解析cotent
ReportDashboardObjectDto detail = JSONObject.parseObject(content, ReportDashboardObjectDto.class);
// 将涉及到的图片路径替换(1.背景图,2.组件为图片的)
String backgroundImage = detail.getDashboard().getBackgroundImage();
detail.getDashboard().setBackgroundImage(replaceUrl(backgroundImage, fileMap));
detail.getWidgets().stream()
.filter(reportDashboardWidgetDto -> "widget-image".equals(reportDashboardWidgetDto.getType()))
.forEach(reportDashboardWidgetDto -> {
String imageAddress = reportDashboardWidgetDto.getValue().getSetup().getString("imageAdress");
String address = replaceUrl(imageAddress, fileMap);
reportDashboardWidgetDto.getValue().getSetup().put("imageAdress", address);
reportDashboardWidgetDto.getOptions().getJSONArray("setup").getJSONObject(4).put("value", address);
});
// 将新的大屏编码赋值
detail.setReportCode(reportCode);
return body;
}
// 解析结束,删除临时文件夹
FileUtil.delete(path);
/**
* 导入大屏zip
*
* @param file
* @param reportCode
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public void importDashboard(MultipartFile file, String reportCode) {
log.info("导入开始,{}", reportCode);
//1.组装临时目录,/app/disk/upload/zip/临时文件夹
String path = dictPath + ZIP_PATH + UuidUtil.generateShortUuid();
//2.解压
FileUtil.decompress(file, path);
// path/uuid/
File parentPath = new File(path);
//获取打包的第一层目录
File firstFile = parentPath.listFiles()[0];
log.info("解析成功,开始存入数据库...");
insertDashboard(detail);
}
File[] files = firstFile.listFiles();
private String replaceUrl(String imageAddress, Map<String, String> fileMap) {
if (StringUtils.isBlank(imageAddress)) {
return "";
}
String fileId = imageAddress.substring(imageAddress.trim().length() - 36);
String orDefault = fileMap.getOrDefault(fileId, null);
if (StringUtils.isBlank(orDefault)) {
return imageAddress;
}
return orDefault;
}
//定义map
Map<String, String> fileMap = new HashMap<>();
String content = "";
/**
* 将大屏涉及到的图片存入指定文件夹
* @param imageAddress
* @param path
*/
private void zipLoadImage(String imageAddress, String path) {
// http://10.108.26.197:9095/file/download/1d9bcd35-82a1-4f08-9465-b66b930b6a8d
if (imageAddress.trim().startsWith(fileDownloadPath)) {
// 以fileDownloadPath为前缀的代表为上传的图片
String fileName = imageAddress.substring(fileDownloadPath.length() + 1);
// 根据fileId,从gaea_file中读出filePath
LambdaQueryWrapper<GaeaFile> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(GaeaFile::getFileId, fileName);
GaeaFile gaeaFile = gaeaFileService.selectOne(queryWrapper);
if (null != gaeaFile) {
String fileType = gaeaFile.getFileType();
path = path + "/image/" + fileName + "." + fileType;
// path = /app/disk/upload/zip/UUID/image
for (int i = 0; i < files.length; i++) {
File childFile = files[i];
if (JSON_PATH.equals(childFile.getName())) {
//json文件
content = FileUtil.readFile(childFile);
} else if ("image".equals(childFile.getName())) {
File[] imageFiles = childFile.listFiles();
//所有需要上传的图片
for (File imageFile : imageFiles) {
//查看是否存在此image
String fileName = imageFile.getName().split("\\.")[0];
//根据fileId,从gaea_file中读出filePath
LambdaQueryWrapper<GaeaFile> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(GaeaFile::getFileId, fileName);
GaeaFile gaeaFile = gaeaFileService.selectOne(queryWrapper);
String uploadPath;
if (null == gaeaFile) {
GaeaFile upload = gaeaFileService.upload(imageFile, fileName);
log.info("存入图片: {}", upload.getFilePath());
uploadPath = upload.getUrlPath();
}else {
uploadPath = gaeaFile.getUrlPath();
}
fileMap.put(fileName, uploadPath);
}
}
// 原始文件的路径
String filePath = gaeaFile.getFilePath();
FileUtil.copyFileUsingFileChannels(filePath, path);
}
}
}
}
public ChartStrategy getTarget(String type) {
for (String s : queryServiceImplMap.keySet()) {
if (s.contains(type)) {
return queryServiceImplMap.get(s);
}
}
throw BusinessExceptionBuilder.build(ResponseCode.RULE_CONTENT_NOT_EXIST);
}
//解析cotent
ReportDashboardObjectDto detail = JSONObject.parseObject(content, ReportDashboardObjectDto.class);
//将涉及到的图片路径替换(1.背景图,2.组件为图片的)
String backgroundImage = detail.getDashboard().getBackgroundImage();
detail.getDashboard().setBackgroundImage(replaceUrl(backgroundImage, fileMap));
detail.getWidgets().stream()
.filter(reportDashboardWidgetDto -> "widget-image".equals(reportDashboardWidgetDto.getType()))
.forEach(reportDashboardWidgetDto -> {
String imageAddress = reportDashboardWidgetDto.getValue().getSetup().getString("imageAdress");
String address = replaceUrl(imageAddress, fileMap);
reportDashboardWidgetDto.getValue().getSetup().put("imageAdress", address);
reportDashboardWidgetDto.getOptions().getJSONArray("setup").getJSONObject(4).put("value", address);
});
//将新的大屏编码赋值
detail.setReportCode(reportCode);
@Override
public void afterPropertiesSet() {
Map<String, ChartStrategy> beanMap = applicationContext.getBeansOfType(ChartStrategy.class);
// 遍历该接口的所有实现,将其放入map中
for (ChartStrategy serviceImpl : beanMap.values()) {
queryServiceImplMap.put(serviceImpl.type(), serviceImpl);
}
}
//解析结束,删除临时文件夹
FileUtil.delete(path);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
log.info("解析成功,开始存入数据库...");
insertDashboard(detail);
}
/**
* 解析图层数据
* @param dto
*/
public void analysisData(ReportDashboardWidgetValueDto dto) {
// if (StringUtils.isBlank(reportDashboardWidgetDto.getSetCode())) {
// return;
// }
// DataSetDto dto = new DataSetDto();
// dto.setSetCode(reportDashboardWidgetDto.getSetCode());
// if (reportDashboardWidgetDto.getContextData() != null &&
// reportDashboardWidgetDto.getContextData().size() > 0) {
// dto.setContextData(reportDashboardWidgetDto.getContextData());
// }
// OriginalDataDto data = dataSetService.getData(dto);
// reportDashboardWidgetDto.setData(JSONObject.toJSONString(data.getData()));
}
public List<JSONObject> buildTimeLine(List<JSONObject> data, ChartDto dto) {
Map<String, String> chartProperties = dto.getChartProperties();
if (null == chartProperties || chartProperties.size() < 1) {
return data;
}
Map<String, Object> contextData = dto.getContextData();
if (null == contextData || contextData.size() < 1) {
return data;
}
if (contextData.containsKey("startTime") && contextData.containsKey("endTime")) {
dto.setStartTime(contextData.get("startTime").toString());
dto.setEndTime(contextData.get("endTime").toString());
}
if (StringUtils.isBlank(dto.getStartTime()) || StringUtils.isBlank(dto.getEndTime())) {
return data;
}
// 获取时间轴字段和解析时间颗粒度
private String replaceUrl(String imageAddress, Map<String, String> fileMap) {
if (StringUtils.isBlank(imageAddress)) {
return "";
}
String fileId = imageAddress.substring(imageAddress.trim().length() - 36);
String orDefault = fileMap.getOrDefault(fileId, null);
if (StringUtils.isBlank(orDefault)) {
return imageAddress;
}
return orDefault;
}
for (Map.Entry<String, String> entry : chartProperties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
dto.setParticles(value);
setTimeLineFormat(dto);
if (StringUtils.isNotBlank(dto.getDataTimeFormat())) {
dto.setTimeLineFiled(key);
break;
}
/**
* 将大屏涉及到的图片存入指定文件夹
* @param imageAddress
* @param path
*/
private void zipLoadImage(String imageAddress, String path) {
//http://10.108.26.197:9095/file/download/1d9bcd35-82a1-4f08-9465-b66b930b6a8d
if (imageAddress.trim().startsWith(fileDownloadPath)) {
//以fileDownloadPath为前缀的代表为上传的图片
String fileName = imageAddress.substring(fileDownloadPath.length() + 1);
//根据fileId,从gaea_file中读出filePath
LambdaQueryWrapper<GaeaFile> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.eq(GaeaFile::getFileId, fileName);
GaeaFile gaeaFile = gaeaFileService.selectOne(queryWrapper);
if (null != gaeaFile) {
String fileType = gaeaFile.getFileType();
path = path + "/image/" + fileName + "." + fileType;
//path = /app/disk/upload/zip/UUID/image
}
//原始文件的路径
String filePath = gaeaFile.getFilePath();
FileUtil.copyFileUsingFileChannels(filePath, path);
}
}
if (StringUtils.isBlank(dto.getDataTimeFormat())) {
return data;
}
}
Date beginTime = DateUtil.parseHmsTime(dto.getStartTime());
Date endTime = DateUtil.parseHmsTime(dto.getEndTime());
SimpleDateFormat showFormat = new SimpleDateFormat(dto.getTimeLineFormat());
SimpleDateFormat dataFormat = new SimpleDateFormat(dto.getDataTimeFormat());
public ChartStrategy getTarget(String type) {
for (String s : queryServiceImplMap.keySet()) {
if (s.contains(type)) {
return queryServiceImplMap.get(s);
}
}
throw BusinessExceptionBuilder.build(ResponseCode.RULE_CONTENT_NOT_EXIST);
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(beginTime);
@Override
public void afterPropertiesSet() {
Map<String, ChartStrategy> beanMap = applicationContext.getBeansOfType(ChartStrategy.class);
//遍历该接口的所有实现,将其放入map中
for (ChartStrategy serviceImpl : beanMap.values()) {
queryServiceImplMap.put(serviceImpl.type(), serviceImpl);
}
}
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.setTime(endTime);
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
List<String> timeLine = new ArrayList<>();
List<String> dataTimeline = new ArrayList<>();
timeLine.add(showFormat.format(calendar.getTime()));
dataTimeline.add(dataFormat.format(calendar.getTime()));
// 添加时间轴数据
while (true) {
calendar.add(dto.getTimeUnit(), 1);
timeLine.add(showFormat.format(calendar.getTime()));
dataTimeline.add(dataFormat.format(calendar.getTime()));
if (showFormat.format(calendar.getTime()).equals(showFormat.format(calendarEnd.getTime()))) {
break;
}
}
/**
* 解析图层数据
*
* @param dto
*/
public void analysisData(ReportDashboardWidgetValueDto dto) {
// if (StringUtils.isBlank(reportDashboardWidgetDto.getSetCode())) {
// return;
// }
// DataSetDto dto = new DataSetDto();
// dto.setSetCode(reportDashboardWidgetDto.getSetCode());
// if (reportDashboardWidgetDto.getContextData() != null && reportDashboardWidgetDto.getContextData().size() > 0) {
// dto.setContextData(reportDashboardWidgetDto.getContextData());
// }
// OriginalDataDto data = dataSetService.getData(dto);
// reportDashboardWidgetDto.setData(JSONObject.toJSONString(data.getData()));
}
// 根据时间轴生成对应的时间线,数据不存在,补数据
List<JSONObject> result = new ArrayList<>();
JSONObject jsonDemo = data.get(0);
String timeLineFiled = dto.getTimeLineFiled();
for (String dateFormat : dataTimeline) {
boolean flag = true;
for (JSONObject datum : data) {
if (datum.containsKey(timeLineFiled) && datum.getString(timeLineFiled).equals(dateFormat)) {
result.add(datum);
flag = false;
}
}
if (flag) {
// 补数据
JSONObject json = new JSONObject();
jsonDemo.forEach((s, o) -> {
if (s.equals(timeLineFiled)) {
json.put(timeLineFiled, dateFormat);
}
else {
json.put(s, 0);
}
});
result.add(json);
}
}
return result;
}
public List<JSONObject> buildTimeLine(List<JSONObject> data, ChartDto dto) {
Map<String, String> chartProperties = dto.getChartProperties();
if (null == chartProperties || chartProperties.size() < 1) {
return data;
}
Map<String, Object> contextData = dto.getContextData();
if (null == contextData || contextData.size() < 1) {
return data;
}
if (contextData.containsKey("startTime") && contextData.containsKey("endTime")) {
dto.setStartTime(contextData.get("startTime").toString());
dto.setEndTime(contextData.get("endTime").toString());
}
if (StringUtils.isBlank(dto.getStartTime()) || StringUtils.isBlank(dto.getEndTime())) {
return data;
}
//获取时间轴字段和解析时间颗粒度
// 设置时间格式
private void setTimeLineFormat(ChartDto dto) {
String particles = dto.getParticles();
if ("xAxis-hour".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM-dd HH");
dto.setTimeLineFormat("MM-dd HH");
dto.setTimeUnit(Calendar.HOUR);
}
else if ("xAxis-day".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM-dd");
dto.setTimeLineFormat("yyyy-MM-dd");
dto.setTimeUnit(Calendar.DATE);
}
else if ("xAxis-month".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM");
dto.setTimeLineFormat("yyyy-MM");
dto.setTimeUnit(Calendar.MONTH);
}
else if ("xAxis-year".equals(particles)) {
dto.setDataTimeFormat("yyyy");
dto.setTimeLineFormat("yyyy");
dto.setTimeUnit(Calendar.YEAR);
}
}
for (Map.Entry<String, String> entry : chartProperties.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
dto.setParticles(value);
setTimeLineFormat(dto);
if (StringUtils.isNotBlank(dto.getDataTimeFormat())) {
dto.setTimeLineFiled(key);
break;
}
}
if (StringUtils.isBlank(dto.getDataTimeFormat())) {
return data;
}
Date beginTime = DateUtil.parseHmsTime(dto.getStartTime());
Date endTime = DateUtil.parseHmsTime(dto.getEndTime());
SimpleDateFormat showFormat = new SimpleDateFormat(dto.getTimeLineFormat());
SimpleDateFormat dataFormat = new SimpleDateFormat(dto.getDataTimeFormat());
Calendar calendar = Calendar.getInstance();
calendar.setTime(beginTime);
Calendar calendarEnd = Calendar.getInstance();
calendarEnd.setTime(endTime);
List<String> timeLine = new ArrayList<>();
List<String> dataTimeline = new ArrayList<>();
timeLine.add(showFormat.format(calendar.getTime()));
dataTimeline.add(dataFormat.format(calendar.getTime()));
//添加时间轴数据
while (true) {
calendar.add(dto.getTimeUnit(), 1);
timeLine.add(showFormat.format(calendar.getTime()));
dataTimeline.add(dataFormat.format(calendar.getTime()));
if (showFormat.format(calendar.getTime()).equals(showFormat.format(calendarEnd.getTime()))) {
break;
}
}
//根据时间轴生成对应的时间线,数据不存在,补数据
List<JSONObject> result = new ArrayList<>();
JSONObject jsonDemo = data.get(0);
String timeLineFiled = dto.getTimeLineFiled();
for (String dateFormat : dataTimeline) {
boolean flag = true;
for (JSONObject datum : data) {
if (datum.containsKey(timeLineFiled) && datum.getString(timeLineFiled).equals(dateFormat)) {
result.add(datum);
flag = false;
}
}
if (flag) {
//补数据
JSONObject json = new JSONObject();
jsonDemo.forEach((s, o) -> {
if (s.equals(timeLineFiled)) {
json.put(timeLineFiled, dateFormat);
} else {
json.put(s, 0);
}
});
result.add(json);
}
}
return result;
}
//设置时间格式
private void setTimeLineFormat(ChartDto dto) {
String particles = dto.getParticles();
if ("xAxis-hour".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM-dd HH");
dto.setTimeLineFormat("MM-dd HH");
dto.setTimeUnit(Calendar.HOUR);
} else if ("xAxis-day".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM-dd");
dto.setTimeLineFormat("yyyy-MM-dd");
dto.setTimeUnit(Calendar.DATE);
} else if ("xAxis-month".equals(particles)) {
dto.setDataTimeFormat("yyyy-MM");
dto.setTimeLineFormat("yyyy-MM");
dto.setTimeUnit(Calendar.MONTH);
} else if ("xAxis-year".equals(particles)) {
dto.setDataTimeFormat("yyyy");
dto.setTimeLineFormat("yyyy");
dto.setTimeUnit(Calendar.YEAR);
}
}
}
@@ -6,27 +6,29 @@ import lombok.Data;
import java.io.Serializable;
/**
* @description 大屏看板数据渲染 dto
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
*
* @description 大屏看板数据渲染 dto
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@Data
public class ReportDashboardWidgetDto implements Serializable {
/**
* 组件类型参考字典DASHBOARD_PANEL_TYPE
*/
private String type;
/**
* 组件类型参考字典DASHBOARD_PANEL_TYPE
*/
private String type;
/**
* value
*/
private ReportDashboardWidgetValueDto value;
/**
* value
*/
private ReportDashboardWidgetValueDto value;
/**
* options
*/
private JSONObject options;
/**
* options
*/
private JSONObject options;
}
@@ -6,41 +6,42 @@ import lombok.Data;
import java.io.Serializable;
/**
* @description 大屏看板数据渲染 dto,已弃用
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
*
* @description 大屏看板数据渲染 dto,已弃用
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@Data
public class ReportDashboardWidgetValueDto implements Serializable {
/** 报表编码 */
private String reportCode;
/** 报表编码 */
private String reportCode;
/** 组件的渲染属性json */
private JSONObject setup;
/** 组件的渲染属性json */
private JSONObject setup;
/** 组件的数据属性json */
private JSONObject data;
/** 组件的数据属性json */
private JSONObject data;
/** 组件的配置属性json */
private JSONObject collapse;
/** 组件的配置属性json */
private JSONObject collapse;
/** 组件的大小位置属性json */
private JSONObject position;
/** 组件的大小位置属性json */
private JSONObject position;
private String options;
private String options;
/** 自动刷新间隔秒 */
private Integer refreshSeconds;
/** 自动刷新间隔秒 */
private Integer refreshSeconds;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */
private Integer deleteFlag;
/** 排序,图层的概念 */
private Long sort;
/** 排序,图层的概念 */
private Long sort;
}
@@ -1,17 +1,20 @@
/**/
package com.anjiplus.template.gaea.business.modules.dashboardwidget.controller.param;
import com.anji.plus.gaea.curd.params.PageParam;
import lombok.Data;
import java.io.Serializable;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
import java.util.List;
/**
* @desc ReportDashboardWidget 大屏看板数据渲染查询输入类
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
* @desc ReportDashboardWidget 大屏看板数据渲染查询输入类
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@Data
public class ReportDashboardWidgetParam extends PageParam implements Serializable {
public class ReportDashboardWidgetParam extends PageParam implements Serializable{
}
@@ -1,15 +1,15 @@
package com.anjiplus.template.gaea.business.modules.dashboardwidget.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.entity.ReportDashboardWidget;
import org.apache.ibatis.annotations.Mapper;
/**
* ReportDashboardWidget Mapper
*
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
* ReportDashboardWidget Mapper
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@Mapper
public interface ReportDashboardWidgetMapper extends GaeaBaseMapper<ReportDashboardWidget> {
@@ -7,44 +7,44 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 大屏看板数据渲染 entity
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_dashboard_widget")
* @description 大屏看板数据渲染 entity
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_dashboard_widget")
@Data
public class ReportDashboardWidget extends GaeaBaseEntity {
@ApiModelProperty(value = "报表编码")
private String reportCode;
@ApiModelProperty(value = "报表编码")
private String reportCode;
@ApiModelProperty(value = "组件类型参考字典DASHBOARD_PANEL_TYPE")
private String type;
@ApiModelProperty(value = "组件类型参考字典DASHBOARD_PANEL_TYPE")
private String type;
@ApiModelProperty(value = "组件的渲染属性json")
private String setup;
@ApiModelProperty(value = "组件的渲染属性json")
private String setup;
@ApiModelProperty(value = "组件的数据属性json")
private String data;
@ApiModelProperty(value = "组件的数据属性json")
private String data;
@ApiModelProperty(value = "组件的配置属性json")
private String collapse;
@ApiModelProperty(value = "组件的配置属性json")
private String collapse;
@ApiModelProperty(value = "组件的大小位置属性json")
private String position;
@ApiModelProperty(value = "组件的大小位置属性json")
private String position;
private String options;
private String options;
@ApiModelProperty(value = "自动刷新间隔秒")
private Integer refreshSeconds;
@ApiModelProperty(value = "自动刷新间隔秒")
private Integer refreshSeconds;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "排序,图层的概念")
private Long sort;
@ApiModelProperty(value = "排序,图层的概念")
private Long sort;
}
@@ -1,22 +1,21 @@
package com.anjiplus.template.gaea.business.modules.dashboardwidget.service;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.controller.param.ReportDashboardWidgetParam;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.entity.ReportDashboardWidget;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
/**
* @desc ReportDashboardWidget 大屏看板数据渲染服务接口
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
public interface ReportDashboardWidgetService
extends GaeaBaseService<ReportDashboardWidgetParam, ReportDashboardWidget> {
/***
* 查询详情
* @param id
*/
ReportDashboardWidget getDetail(Long id);
* @desc ReportDashboardWidget 大屏看板数据渲染服务接口
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
public interface ReportDashboardWidgetService extends GaeaBaseService<ReportDashboardWidgetParam, ReportDashboardWidget> {
/***
* 查询详情
*
* @param id
*/
ReportDashboardWidget getDetail(Long id);
}
@@ -2,33 +2,33 @@
package com.anjiplus.template.gaea.business.modules.dashboardwidget.service.impl;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.ReportDashboardWidgetMapper;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.entity.ReportDashboardWidget;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.service.ReportDashboardWidgetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.entity.ReportDashboardWidget;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.service.ReportDashboardWidgetService;
import com.anjiplus.template.gaea.business.modules.dashboardwidget.dao.ReportDashboardWidgetMapper;
/**
* @desc ReportDashboardWidget 大屏看板数据渲染服务实现
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
* @desc ReportDashboardWidget 大屏看板数据渲染服务实现
* @author Raod
* @date 2021-04-12 15:12:43.724
**/
@Service
// @RequiredArgsConstructor
//@RequiredArgsConstructor
public class ReportDashboardWidgetServiceImpl implements ReportDashboardWidgetService {
@Autowired
private ReportDashboardWidgetMapper reportDashboardWidgetMapper;
@Autowired
private ReportDashboardWidgetMapper reportDashboardWidgetMapper;
@Override
public GaeaBaseMapper<ReportDashboardWidget> getMapper() {
return reportDashboardWidgetMapper;
}
@Override
public ReportDashboardWidget getDetail(Long id) {
ReportDashboardWidget reportDashboardWidget = this.selectOne(id);
return reportDashboardWidget;
}
@Override
public GaeaBaseMapper<ReportDashboardWidget> getMapper() {
return reportDashboardWidgetMapper;
}
@Override
public ReportDashboardWidget getDetail(Long id) {
ReportDashboardWidget reportDashboardWidget = this.selectOne(id);
return reportDashboardWidget;
}
}
@@ -21,111 +21,125 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @desc 数据集 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* @desc 数据集 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@RestController
@Api(tags = "数据集管理")
@Permission(code = "resultsetManage", name = "数据集管理")
@RequestMapping("/dataSet")
public class DataSetController extends GaeaBaseController<DataSetParam, DataSet, DataSetDto> {
@Autowired
private DataSetService dataSetService;
@Autowired
private DataSetService dataSetService;
@Override
public GaeaBaseService<DataSetParam, DataSet> getService() {
return dataSetService;
}
@Override
public GaeaBaseService<DataSetParam, DataSet> getService() {
return dataSetService;
}
@Override
public DataSet getEntity() {
return new DataSet();
}
@Override
public DataSet getEntity() {
return new DataSet();
}
@Override
public DataSetDto getDTO() {
return new DataSetDto();
}
@Override
public DataSetDto getDTO() {
return new DataSetDto();
}
@GetMapping("/detailBysetId/{id}")
@Permission(code = "query", name = "明细")
public ResponseBean detailBysetId(@PathVariable("id") Long id) {
this.logger.info("{}根据ID查询服务开始,id为:{}", this.getClass().getSimpleName(), id);
ResponseBean responseBean = this.responseSuccessWithData(dataSetService.detailSet(id));
this.logger.info("{}根据ID查询结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean));
return responseBean;
}
@GetMapping("/detailBysetId/{id}")
@Permission( code = "query", name = "明细" )
public ResponseBean detailBysetId(@PathVariable("id") Long id) {
this.logger.info("{}根据ID查询服务开始,id为:{}", this.getClass().getSimpleName(), id);
ResponseBean responseBean = this.responseSuccessWithData(dataSetService.detailSet(id));
this.logger.info("{}根据ID查询结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean));
return responseBean;
}
@GetMapping({ "/detailBysetCode/{setCode}" })
@Permission(code = "query", name = "明细")
@AccessKey
public ResponseBean detailBysetCode(@PathVariable("setCode") String setCode) {
this.logger.info("{}根据setCode查询服务开始,setCode为:{}", this.getClass().getSimpleName(), setCode);
ResponseBean responseBean = this.responseSuccessWithData(dataSetService.detailSet(setCode));
this.logger.info("{}根据setCode查询结束,结果:{}", this.getClass().getSimpleName(),
GaeaUtils.toJSONString(responseBean));
return responseBean;
}
@GetMapping({"/detailBysetCode/{setCode}"})
@Permission( code = "query", name = "明细" )
@AccessKey
public ResponseBean detailBysetCode(@PathVariable("setCode") String setCode) {
this.logger.info("{}根据setCode查询服务开始,setCode为:{}", this.getClass().getSimpleName(), setCode);
ResponseBean responseBean = this.responseSuccessWithData(dataSetService.detailSet(setCode));
this.logger.info("{}根据setCode查询结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean));
return responseBean;
}
@PostMapping
@Permission(code = "insert", name = "新增")
@GaeaAuditLog(pageTitle = "新增")
@Override
public ResponseBean insert(@RequestBody DataSetDto dto) {
this.logger.info("{}新增服务开始,参数:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(dto));
DataSetDto dataSetDto = dataSetService.insertSet(dto);
this.logger.info("{}新增服务结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(dataSetDto));
return ResponseBean.builder().data(dataSetDto).build();
}
@PostMapping
@Permission(
code = "insert",
name = "新增"
)
@GaeaAuditLog(
pageTitle = "新增"
)
@Override
public ResponseBean insert(@RequestBody DataSetDto dto) {
this.logger.info("{}新增服务开始,参数:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(dto));
DataSetDto dataSetDto = dataSetService.insertSet(dto);
this.logger.info("{}新增服务结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(dataSetDto));
return ResponseBean.builder().data(dataSetDto).build();
}
@PutMapping
@Permission(code = "update", name = "更新")
@GaeaAuditLog(pageTitle = "修改")
@Override
public ResponseBean update(@RequestBody DataSetDto dto) {
String username = UserContentHolder.getContext().getUsername();
this.logger.info("{}更新服务开始,更新人:{},参数:{}", this.getClass().getSimpleName(), username,
GaeaUtils.toJSONString(dto));
ResponseBean responseBean = this.responseSuccess();
dataSetService.updateSet(dto);
this.logger.info("{}更新服务结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean));
return this.responseSuccess();
}
@PutMapping
@Permission(
code = "update",
name = "更新"
)
@GaeaAuditLog(
pageTitle = "修改"
)
@Override
public ResponseBean update(@RequestBody DataSetDto dto) {
String username = UserContentHolder.getContext().getUsername();
this.logger.info("{}更新服务开始,更新人:{},参数:{}", this.getClass().getSimpleName(), username, GaeaUtils.toJSONString(dto));
ResponseBean responseBean = this.responseSuccess();
dataSetService.updateSet(dto);
this.logger.info("{}更新服务结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean));
return this.responseSuccess();
}
@DeleteMapping({ "/{id}" })
@Permission(code = "delete", name = "删除")
@GaeaAuditLog(pageTitle = "删除")
@Override
public ResponseBean deleteById(@PathVariable("id") Long id) {
this.logger.info("{}删除服务开始,参数ID:{}", this.getClass().getSimpleName(), id);
dataSetService.deleteSet(id);
this.logger.info("{}删除服务结束", this.getClass().getSimpleName());
return this.responseSuccess();
}
@DeleteMapping({"/{id}"})
@Permission(
code = "delete",
name = "删除"
)
@GaeaAuditLog(
pageTitle = "删除"
)
@Override
public ResponseBean deleteById(@PathVariable("id") Long id) {
this.logger.info("{}删除服务开始,参数ID:{}", this.getClass().getSimpleName(), id);
dataSetService.deleteSet(id);
this.logger.info("{}删除服务结束", this.getClass().getSimpleName());
return this.responseSuccess();
}
/**
* 测试 数据转换是否正确
* @param param
* @return
*/
@PostMapping("/testTransform")
@Permission(code = "query", name = "明细")
public ResponseBean testTransform(@Validated @RequestBody DataSetTestTransformParam param) {
DataSetDto dto = new DataSetDto();
BeanUtils.copyProperties(param, dto);
return responseSuccessWithData(dataSetService.testTransform(dto));
}
/**
* 测试 数据转换是否正确
* @param param
* @return
*/
@PostMapping("/testTransform")
@Permission( code = "query", name = "明细" )
public ResponseBean testTransform(@Validated @RequestBody DataSetTestTransformParam param) {
DataSetDto dto = new DataSetDto();
BeanUtils.copyProperties(param, dto);
return responseSuccessWithData(dataSetService.testTransform(dto));
}
/**
* 获取所有数据集
* @return
*/
@GetMapping("/queryAllDataSet")
public ResponseBean queryAllDataSet() {
return responseSuccessWithData(dataSetService.queryAllDataSet());
}
/**
* 获取所有数据集
* @return
*/
@GetMapping("/queryAllDataSet")
public ResponseBean queryAllDataSet() {
return responseSuccessWithData(dataSetService.queryAllDataSet());
}
}
@@ -11,50 +11,55 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @description 数据集 dto
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
*
* @description 数据集 dto
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@Data
public class DataSetDto extends GaeaBaseDTO implements Serializable {
/** 数据集编码 */
private String setCode;
/** 数据集编码 */
private String setCode;
/** 数据集名称 */
private String setName;
/** 数据集名称 */
private String setName;
/** 数据集描述 */
private String setDesc;
/** 数据集描述 */
private String setDesc;
/** 数据集类型 */
private String setType;
/** 数据源编码 */
private String sourceCode;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 数据源编码 */
private String sourceCode;
/** 结果案例 */
private String caseResult;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 结果案例 */
private String caseResult;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 请求参数集合 */
private List<DataSetParamDto> dataSetParamDtoList;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/** 数据转换集合 */
private List<DataSetTransformDto> dataSetTransformDtoList;
/** 请求参数集合 */
private List<DataSetParamDto> dataSetParamDtoList;
/** 传入的自定义参数 */
private Map<String, Object> contextData;
/** 数据转换集合 */
private List<DataSetTransformDto> dataSetTransformDtoList;
private Set<String> setParamList;
/** 传入的自定义参数*/
private Map<String, Object> contextData;
/** 指定字段 */
private String fieldLabel;
private Set<String> setParamList;
/**指定字段*/
private String fieldLabel;
}
@@ -12,22 +12,21 @@ import java.util.List;
@Data
public class OriginalDataDto implements Serializable {
/** 总数 */
private long total;
/**总数*/
private long total;
/** 获取的数据详情 */
private List<JSONObject> data;
/**获取的数据详情*/
private List<JSONObject> data;
public OriginalDataDto(List<JSONObject> data) {
this.data = data;
}
public OriginalDataDto(List<JSONObject> data) {
this.data = data;
}
public OriginalDataDto(long total, List<JSONObject> data) {
this.total = total;
this.data = data;
}
public OriginalDataDto() {
}
public OriginalDataDto(long total, List<JSONObject> data) {
this.total = total;
this.data = data;
}
public OriginalDataDto() {
}
}
@@ -8,24 +8,27 @@ import lombok.Data;
import java.io.Serializable;
/**
* @desc DataSet 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* @desc DataSet 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@Data
public class DataSetParam extends PageParam implements Serializable {
public class DataSetParam extends PageParam implements Serializable{
/** 数据集编码 */
@Query(QueryEnum.LIKE)
private String setCode;
/** 数据集编码 */
@Query(QueryEnum.LIKE)
private String setCode;
/** 数据集名称 */
@Query(QueryEnum.LIKE)
private String setName;
/** 数据集名称 */
@Query(QueryEnum.LIKE)
private String setName;
/** 数据源编码 */
@Query(QueryEnum.EQ)
private String sourceCode;
/** 数据源编码 */
@Query(QueryEnum.EQ)
private String sourceCode;
/** 数据集类型 */
@Query(QueryEnum.EQ)
private String setType;
}
@@ -5,29 +5,31 @@ import com.anjiplus.template.gaea.business.modules.datasetparam.controller.dto.D
import com.anjiplus.template.gaea.business.modules.datasettransform.controller.dto.DataSetTransformDto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.List;
/**
* @desc DataSet 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* @desc DataSet 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@Data
public class DataSetTestTransformParam implements Serializable {
public class DataSetTestTransformParam implements Serializable{
/** 数据源编码 */
@NotBlank(message = "sourceCode not empty")
private String sourceCode;
/** 数据源编码 */
private String sourceCode;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 请求参数集合 */
private List<DataSetParamDto> dataSetParamDtoList;
/** 数据集类型 */
private String setType;
/** 数据转换集合 */
private List<DataSetTransformDto> dataSetTransformDtoList;
/** 请求参数集合 */
private List<DataSetParamDto> dataSetParamDtoList;
/** 数据转换集合 */
private List<DataSetTransformDto> dataSetTransformDtoList;
}
@@ -1,15 +1,15 @@
package com.anjiplus.template.gaea.business.modules.dataset.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.dataset.dao.entity.DataSet;
import org.apache.ibatis.annotations.Mapper;
/**
* DataSet Mapper
*
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* DataSet Mapper
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@Mapper
public interface DataSetMapper extends GaeaBaseMapper<DataSet> {
@@ -9,37 +9,40 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 数据集 entity
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_data_set")
* @description 数据集 entity
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_data_set")
@Data
public class DataSet extends GaeaBaseEntity {
@ApiModelProperty(value = "数据集编码")
@Unique(code = ResponseCode.SET_CODE_ISEXIST)
private String setCode;
@ApiModelProperty(value = "数据集编码")
@Unique(code = ResponseCode.SET_CODE_ISEXIST)
private String setCode;
@ApiModelProperty(value = "数据集名称")
private String setName;
@ApiModelProperty(value = "数据集名称")
private String setName;
@ApiModelProperty(value = "数据集描述")
private String setDesc;
@ApiModelProperty(value = "数据集描述")
private String setDesc;
@ApiModelProperty(value = "数据集类型")
private String setType;
@ApiModelProperty(value = "数据源编码")
private String sourceCode;
@ApiModelProperty(value = "数据源编码")
private String sourceCode;
@ApiModelProperty(value = "动态查询sql或者接口中的请求体")
private String dynSentence;
@ApiModelProperty(value = "动态查询sql或者接口中的请求体")
private String dynSentence;
@ApiModelProperty(value = "结果案例")
private String caseResult;
@ApiModelProperty(value = "结果案例")
private String caseResult;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
}
@@ -10,61 +10,61 @@ import com.anjiplus.template.gaea.business.modules.dataset.dao.entity.DataSet;
import java.util.List;
/**
* @desc DataSet 数据集服务接口
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* @desc DataSet 数据集服务接口
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
public interface DataSetService extends GaeaBaseService<DataSetParam, DataSet> {
/**
* 单条详情
* @param id
* @return
*/
DataSetDto detailSet(Long id);
/**
* 单条详情
* @param id
* @return
*/
DataSetDto detailSet(Long id);
/**
* 单条详情
* @param setCode
* @return
*/
DataSetDto detailSet(String setCode);
/**
* 单条详情
* @param setCode
* @return
*/
DataSetDto detailSet(String setCode);
/**
* 新增数据集、添加查询参数、数据转换
* @param dto
*/
DataSetDto insertSet(DataSetDto dto);
/**
* 新增数据集、添加查询参数、数据转换
* @param dto
*/
DataSetDto insertSet(DataSetDto dto);
/**
* 更新数据集、添加查询参数、数据转换
* @param dto
*/
void updateSet(DataSetDto dto);
/**
* 更新数据集、添加查询参数、数据转换
* @param dto
*/
void updateSet(DataSetDto dto);
/**
* 删除数据集、添加查询参数、数据转换
* @param id
*/
void deleteSet(Long id);
/**
* 删除数据集、添加查询参数、数据转换
* @param id
*/
void deleteSet(Long id);
/**
* 获取数据
* @param dto
* @return
*/
OriginalDataDto getData(DataSetDto dto);
/**
* 获取数据
* @param dto
* @return
*/
OriginalDataDto getData(DataSetDto dto);
/**
* @param dto
* @return
*/
OriginalDataDto testTransform(DataSetDto dto);
/**
* 获取所有数据集
* @return
*/
List<DataSet> queryAllDataSet();
/**
*
* @param dto
* @return
*/
OriginalDataDto testTransform(DataSetDto dto);
/**
* 获取所有数据集
* @return
*/
List<DataSet> queryAllDataSet();
}
@@ -8,8 +8,9 @@ import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anji.plus.gaea.utils.GaeaBeanUtils;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.DataSetDto;
import com.anjiplus.template.gaea.business.enums.SetTypeEnum;
import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.OriginalDataDto;
import com.anjiplus.template.gaea.business.modules.dataset.controller.dto.DataSetDto;
import com.anjiplus.template.gaea.business.modules.dataset.dao.DataSetMapper;
import com.anjiplus.template.gaea.business.modules.dataset.dao.entity.DataSet;
import com.anjiplus.template.gaea.business.modules.dataset.service.DataSetService;
@@ -22,6 +23,7 @@ import com.anjiplus.template.gaea.business.modules.datasettransform.service.Data
import com.anjiplus.template.gaea.business.modules.datasource.controller.dto.DataSourceDto;
import com.anjiplus.template.gaea.business.modules.datasource.dao.entity.DataSource;
import com.anjiplus.template.gaea.business.modules.datasource.service.DataSourceService;
import com.anjiplus.template.gaea.business.util.JdbcConstants;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -33,288 +35,372 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @desc DataSet 数据集服务实现
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
* @desc DataSet 数据集服务实现
* @author Raod
* @date 2021-03-18 12:11:31.150755900
**/
@Service
// @RequiredArgsConstructor
//@RequiredArgsConstructor
@Slf4j
public class DataSetServiceImpl implements DataSetService {
@Autowired
private DataSetMapper dataSetMapper;
@Autowired
private DataSetMapper dataSetMapper;
@Autowired
private DataSetParamService dataSetParamService;
@Autowired
private DataSetParamService dataSetParamService;
@Autowired
private DataSetTransformService dataSetTransformService;
@Autowired
private DataSetTransformService dataSetTransformService;
@Autowired
private DataSourceService dataSourceService;
@Autowired
private DataSourceService dataSourceService;
@Override
public GaeaBaseMapper<DataSet> getMapper() {
return dataSetMapper;
}
@Override
public GaeaBaseMapper<DataSet> getMapper() {
return dataSetMapper;
}
/**
* 单条详情
* @param id
* @return
*/
@Override
public DataSetDto detailSet(Long id) {
DataSetDto dto = new DataSetDto();
DataSet result = selectOne(id);
String setCode = result.getSetCode();
GaeaBeanUtils.copyAndFormatter(result, dto);
return getDetailSet(dto, setCode);
}
/**
* 单条详情
*
* @param id
* @return
*/
@Override
public DataSetDto detailSet(Long id) {
DataSetDto dto = new DataSetDto();
DataSet result = selectOne(id);
String setCode = result.getSetCode();
GaeaBeanUtils.copyAndFormatter(result, dto);
return getDetailSet(dto, setCode);
}
/**
* 单条详情
* @param setCode
* @return
*/
@Override
public DataSetDto detailSet(String setCode) {
DataSetDto dto = new DataSetDto();
DataSet result = selectOne("set_code", setCode);
GaeaBeanUtils.copyAndFormatter(result, dto);
return getDetailSet(dto, setCode);
}
/**
* 单条详情
*
* @param setCode
* @return
*/
@Override
public DataSetDto detailSet(String setCode) {
DataSetDto dto = new DataSetDto();
DataSet result = selectOne("set_code", setCode);
GaeaBeanUtils.copyAndFormatter(result, dto);
return getDetailSet(dto, setCode);
}
public DataSetDto getDetailSet(DataSetDto dto, String setCode) {
// 查询参数
List<DataSetParam> dataSetParamList = dataSetParamService
.list(new QueryWrapper<DataSetParam>().lambda().eq(DataSetParam::getSetCode, setCode));
List<DataSetParamDto> dataSetParamDtoList = new ArrayList<>();
dataSetParamList.forEach(dataSetParam -> {
DataSetParamDto dataSetParamDto = new DataSetParamDto();
GaeaBeanUtils.copyAndFormatter(dataSetParam, dataSetParamDto);
dataSetParamDtoList.add(dataSetParamDto);
});
dto.setDataSetParamDtoList(dataSetParamDtoList);
public DataSetDto getDetailSet(DataSetDto dto, String setCode) {
//查询参数
List<DataSetParam> dataSetParamList = dataSetParamService.list(
new QueryWrapper<DataSetParam>()
.lambda()
.eq(DataSetParam::getSetCode, setCode)
);
List<DataSetParamDto> dataSetParamDtoList = new ArrayList<>();
dataSetParamList.forEach(dataSetParam -> {
DataSetParamDto dataSetParamDto = new DataSetParamDto();
GaeaBeanUtils.copyAndFormatter(dataSetParam, dataSetParamDto);
dataSetParamDtoList.add(dataSetParamDto);
});
dto.setDataSetParamDtoList(dataSetParamDtoList);
// 数据转换
//数据转换
List<DataSetTransform> dataSetTransformList = dataSetTransformService.list(new QueryWrapper<DataSetTransform>()
.lambda().eq(DataSetTransform::getSetCode, setCode).orderByAsc(DataSetTransform::getOrderNum));
List<DataSetTransformDto> dataSetTransformDtoList = new ArrayList<>();
dataSetTransformList.forEach(dataSetTransform -> {
DataSetTransformDto dataSetTransformDto = new DataSetTransformDto();
GaeaBeanUtils.copyAndFormatter(dataSetTransform, dataSetTransformDto);
dataSetTransformDtoList.add(dataSetTransformDto);
});
dto.setDataSetTransformDtoList(dataSetTransformDtoList);
List<DataSetTransform> dataSetTransformList = dataSetTransformService.list(
new QueryWrapper<DataSetTransform>()
.lambda()
.eq(DataSetTransform::getSetCode, setCode)
.orderByAsc(DataSetTransform::getOrderNum)
);
List<DataSetTransformDto> dataSetTransformDtoList = new ArrayList<>();
dataSetTransformList.forEach(dataSetTransform -> {
DataSetTransformDto dataSetTransformDto = new DataSetTransformDto();
GaeaBeanUtils.copyAndFormatter(dataSetTransform, dataSetTransformDto);
dataSetTransformDtoList.add(dataSetTransformDto);
});
dto.setDataSetTransformDtoList(dataSetTransformDtoList);
if (StringUtils.isNotBlank(dto.getCaseResult())) {
try {
JSONArray jsonArray = JSONArray.parseArray(dto.getCaseResult());
JSONObject jsonObject = jsonArray.getJSONObject(0);
dto.setSetParamList(jsonObject.keySet());
}
catch (Exception e) {
log.error("error", e);
}
}
return dto;
}
if (StringUtils.isNotBlank(dto.getCaseResult())) {
try {
JSONArray jsonArray = JSONArray.parseArray(dto.getCaseResult());
JSONObject jsonObject = jsonArray.getJSONObject(0);
dto.setSetParamList(jsonObject.keySet());
} catch (Exception e) {
log.error("error",e);
}
}
return dto;
}
/**
* 新增数据集、添加查询参数、数据转换
* @param dto
*/
@Override
@Transactional
public DataSetDto insertSet(DataSetDto dto) {
List<DataSetParamDto> dataSetParamDtoList = dto.getDataSetParamDtoList();
List<DataSetTransformDto> dataSetTransformDtoList = dto.getDataSetTransformDtoList();
// 1.新增数据集
DataSet dataSet = new DataSet();
BeanUtils.copyProperties(dto, dataSet);
insert(dataSet);
// 2.更新查询参数
dataSetParamBatch(dataSetParamDtoList, dto.getSetCode());
/**
* 新增数据集、添加查询参数、数据转换
*
* @param dto
*/
@Override
@Transactional
public DataSetDto insertSet(DataSetDto dto) {
List<DataSetParamDto> dataSetParamDtoList = dto.getDataSetParamDtoList();
List<DataSetTransformDto> dataSetTransformDtoList = dto.getDataSetTransformDtoList();
// 3.更新数据转换
dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode());
return dto;
}
//1.新增数据集
DataSet dataSet = new DataSet();
BeanUtils.copyProperties(dto, dataSet);
insert(dataSet);
//2.更新查询参数
dataSetParamBatch(dataSetParamDtoList, dto.getSetCode());
/**
* 更新数据集、添加查询参数、数据转换
* @param dto
*/
@Override
@Transactional
public void updateSet(DataSetDto dto) {
List<DataSetParamDto> dataSetParamDtoList = dto.getDataSetParamDtoList();
List<DataSetTransformDto> dataSetTransformDtoList = dto.getDataSetTransformDtoList();
// 1.更新数据集
DataSet dataSet = new DataSet();
BeanUtils.copyProperties(dto, dataSet);
update(dataSet);
//3.更新数据转换
dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode());
return dto;
}
// 2.更新查询参数
dataSetParamBatch(dataSetParamDtoList, dto.getSetCode());
/**
* 更新数据集、添加查询参数、数据转换
*
* @param dto
*/
@Override
@Transactional
public void updateSet(DataSetDto dto) {
List<DataSetParamDto> dataSetParamDtoList = dto.getDataSetParamDtoList();
List<DataSetTransformDto> dataSetTransformDtoList = dto.getDataSetTransformDtoList();
//1.更新数据集
DataSet dataSet = new DataSet();
BeanUtils.copyProperties(dto, dataSet);
update(dataSet);
// 3.更新数据转换
dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode());
}
//2.更新查询参数
dataSetParamBatch(dataSetParamDtoList, dto.getSetCode());
/**
* 删除数据集、添加查询参数、数据转换
* @param id
*/
@Override
public void deleteSet(Long id) {
DataSet dataSet = selectOne(id);
String setCode = dataSet.getSetCode();
// 1.删除数据集
deleteById(id);
//3.更新数据转换
dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode());
}
// 2.删除查询参数
dataSetParamService.delete(new QueryWrapper<DataSetParam>().lambda().eq(DataSetParam::getSetCode, setCode));
// 3.删除数据转换
dataSetTransformService
.delete(new QueryWrapper<DataSetTransform>().lambda().eq(DataSetTransform::getSetCode, setCode));
}
/**
* 删除数据集、添加查询参数、数据转换
*
* @param id
*/
@Override
public void deleteSet(Long id) {
DataSet dataSet = selectOne(id);
String setCode = dataSet.getSetCode();
//1.删除数据集
deleteById(id);
/**
* 获取数据
* @param dto
* @return
*/
@Override
public OriginalDataDto getData(DataSetDto dto) {
OriginalDataDto originalDataDto = new OriginalDataDto();
String setCode = dto.getSetCode();
// 1.获取数据集、参数替换、数据转换
DataSetDto dataSetDto = detailSet(setCode);
// 2.获取数据源
DataSource dataSource = dataSourceService.selectOne("source_code", dataSetDto.getSourceCode());
// 3.参数替换
// 3.1参数校验
log.debug("参数校验替换前:{}", dto.getContextData());
boolean verification = dataSetParamService.verification(dataSetDto.getDataSetParamDtoList(),
dto.getContextData());
if (!verification) {
throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR);
}
String dynSentence = dataSetParamService.transform(dto.getContextData(), dataSetDto.getDynSentence());
log.debug("参数校验替换后:{}", dto.getContextData());
// 4.获取数据
DataSourceDto dataSourceDto = new DataSourceDto();
BeanUtils.copyProperties(dataSource, dataSourceDto);
dataSourceDto.setDynSentence(dynSentence);
dataSourceDto.setContextData(dto.getContextData());
// 获取total,判断contextData中是否传入分页参数
if (null != dto.getContextData() && dto.getContextData().containsKey("pageNumber")
&& dto.getContextData().containsKey("pageSize")) {
long total = dataSourceService.total(dataSourceDto, dto);
originalDataDto.setTotal(total);
}
List<JSONObject> data = dataSourceService.execute(dataSourceDto);
// 5.数据转换
List<JSONObject> transform = dataSetTransformService.transform(dataSetDto.getDataSetTransformDtoList(), data);
originalDataDto.setData(transform);
return originalDataDto;
}
//2.删除查询参数
dataSetParamService.delete(
new QueryWrapper<DataSetParam>()
.lambda()
.eq(DataSetParam::getSetCode, setCode)
);
/**
* @param dto
* @return
*/
@Override
public OriginalDataDto testTransform(DataSetDto dto) {
OriginalDataDto originalDataDto = new OriginalDataDto();
String sourceCode = dto.getSourceCode();
// 1.获取数据源
DataSource dataSource = dataSourceService.selectOne("source_code", sourceCode);
// 3.参数替换
// 3.1参数校验
boolean verification = dataSetParamService.verification(dto.getDataSetParamDtoList(), null);
if (!verification) {
throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR);
}
//3.删除数据转换
dataSetTransformService.delete(
new QueryWrapper<DataSetTransform>()
.lambda()
.eq(DataSetTransform::getSetCode, setCode)
);
}
String dynSentence = dataSetParamService.transform(dto.getDataSetParamDtoList(), dto.getDynSentence());
// 4.获取数据
DataSourceDto dataSourceDto = new DataSourceDto();
BeanUtils.copyProperties(dataSource, dataSourceDto);
dataSourceDto.setDynSentence(dynSentence);
dataSourceDto.setContextData(dto.getContextData());
/**
* 获取数据
*
* @param dto
* @return
*/
@Override
public OriginalDataDto getData(DataSetDto dto) {
// 获取total,判断DataSetParamDtoList中是否传入分页参数
Map<String, Object> collect = dto.getDataSetParamDtoList().stream()
.collect(Collectors.toMap(DataSetParamDto::getParamName, DataSetParamDto::getSampleItem));
if (collect.containsKey("pageNumber") && collect.containsKey("pageSize")) {
dto.setContextData(collect);
long total = dataSourceService.total(dataSourceDto, dto);
originalDataDto.setTotal(total);
}
OriginalDataDto originalDataDto = new OriginalDataDto();
String setCode = dto.getSetCode();
//1.获取数据集、参数替换、数据转换
DataSetDto dataSetDto = detailSet(setCode);
String dynSentence = dataSetDto.getDynSentence();
//2.获取数据源
DataSource dataSource;
if (StringUtils.isNotBlank(dataSetDto.getSetType())
&& dataSetDto.getSetType().equals(SetTypeEnum.HTTP.getCodeValue())) {
//http不需要数据源,兼容已有的逻辑,将http所需要的数据塞进DataSource
dataSource = new DataSource();
dataSource.setSourceConfig(dynSentence);
dataSource.setSourceType(JdbcConstants.HTTP);
String body = JSONObject.parseObject(dynSentence).getString("body");
if (StringUtils.isNotBlank(body)) {
dynSentence = body;
}else {
dynSentence = "{}";
}
List<JSONObject> data = dataSourceService.execute(dataSourceDto);
// 5.数据转换
List<JSONObject> transform = dataSetTransformService.transform(dto.getDataSetTransformDtoList(), data);
originalDataDto.setData(transform);
return originalDataDto;
}
}else {
dataSource = dataSourceService.selectOne("source_code", dataSetDto.getSourceCode());
}
/**
* 获取所有数据集
* @return
*/
@Override
public List<DataSet> queryAllDataSet() {
LambdaQueryWrapper<DataSet> wrapper = Wrappers.lambdaQuery();
wrapper.select(DataSet::getSetCode, DataSet::getSetName, DataSet::getSetDesc, DataSet::getId)
.eq(DataSet::getEnableFlag, Enabled.YES.getValue());
wrapper.orderByDesc(DataSet::getUpdateTime);
return dataSetMapper.selectList(wrapper);
}
//3.参数替换
//3.1参数校验
log.debug("参数校验替换前:{}", dto.getContextData());
boolean verification = dataSetParamService.verification(dataSetDto.getDataSetParamDtoList(), dto.getContextData());
if (!verification) {
throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR);
}
dynSentence = dataSetParamService.transform(dto.getContextData(), dynSentence);
log.debug("参数校验替换后:{}", dto.getContextData());
//4.获取数据
DataSourceDto dataSourceDto = new DataSourceDto();
BeanUtils.copyProperties(dataSource, dataSourceDto);
dataSourceDto.setDynSentence(dynSentence);
dataSourceDto.setContextData(dto.getContextData());
//获取total,判断contextData中是否传入分页参数
if (null != dto.getContextData()
&& dto.getContextData().containsKey("pageNumber")
&& dto.getContextData().containsKey("pageSize")) {
long total = dataSourceService.total(dataSourceDto, dto);
originalDataDto.setTotal(total);
}
List<JSONObject> data = dataSourceService.execute(dataSourceDto);
//5.数据转换
List<JSONObject> transform = dataSetTransformService.transform(dataSetDto.getDataSetTransformDtoList(), data);
originalDataDto.setData(transform);
return originalDataDto;
}
public void dataSetParamBatch(List<DataSetParamDto> dataSetParamDtoList, String setCode) {
dataSetParamService.delete(new QueryWrapper<DataSetParam>().lambda().eq(DataSetParam::getSetCode, setCode));
if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) {
return;
}
// List<DataSetParam> dataSetParamList = new ArrayList<>();
dataSetParamDtoList.forEach(dataSetParamDto -> {
DataSetParam dataSetParam = new DataSetParam();
BeanUtils.copyProperties(dataSetParamDto, dataSetParam);
dataSetParam.setSetCode(setCode);
// 不采用批量
dataSetParamService.insert(dataSetParam);
});
/**
* @param dto
* @return
*/
@Override
public OriginalDataDto testTransform(DataSetDto dto) {
String dynSentence = dto.getDynSentence();
}
OriginalDataDto originalDataDto = new OriginalDataDto();
String sourceCode = dto.getSourceCode();
//1.获取数据源
DataSource dataSource;
if (dto.getSetType().equals(SetTypeEnum.HTTP.getCodeValue())) {
//http不需要数据源,兼容已有的逻辑,将http所需要的数据塞进DataSource
dataSource = new DataSource();
dataSource.setSourceConfig(dynSentence);
dataSource.setSourceType(JdbcConstants.HTTP);
String body = JSONObject.parseObject(dynSentence).getString("body");
if (StringUtils.isNotBlank(body)) {
dynSentence = body;
}else {
dynSentence = "{}";
}
public void dataSetTransformBatch(List<DataSetTransformDto> dataSetTransformDtoList, String setCode) {
dataSetTransformService
.delete(new QueryWrapper<DataSetTransform>().lambda().eq(DataSetTransform::getSetCode, setCode));
if (null == dataSetTransformDtoList || dataSetTransformDtoList.size() <= 0) {
return;
}
// List<DataSetTransform> dataSetTransformList = new ArrayList<>();
for (int i = 0; i < dataSetTransformDtoList.size(); i++) {
DataSetTransform dataSetTransform = new DataSetTransform();
BeanUtils.copyProperties(dataSetTransformDtoList.get(i), dataSetTransform);
dataSetTransform.setOrderNum(i + 1);
dataSetTransform.setSetCode(setCode);
// 不采用批量
dataSetTransformService.insert(dataSetTransform);
}
}
}else {
dataSource = dataSourceService.selectOne("source_code", sourceCode);
}
//3.参数替换
//3.1参数校验
boolean verification = dataSetParamService.verification(dto.getDataSetParamDtoList(), null);
if (!verification) {
throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR);
}
dynSentence = dataSetParamService.transform(dto.getDataSetParamDtoList(), dynSentence);
//4.获取数据
DataSourceDto dataSourceDto = new DataSourceDto();
BeanUtils.copyProperties(dataSource, dataSourceDto);
dataSourceDto.setDynSentence(dynSentence);
dataSourceDto.setContextData(setContextData(dto.getDataSetParamDtoList()));
//获取total,判断DataSetParamDtoList中是否传入分页参数
Map<String, Object> collect = dto.getDataSetParamDtoList().stream().collect(Collectors.toMap(DataSetParamDto::getParamName, DataSetParamDto::getSampleItem));
if (collect.containsKey("pageNumber") && collect.containsKey("pageSize")) {
dto.setContextData(collect);
long total = dataSourceService.total(dataSourceDto, dto);
originalDataDto.setTotal(total);
}
List<JSONObject> data = dataSourceService.execute(dataSourceDto);
//5.数据转换
List<JSONObject> transform = dataSetTransformService.transform(dto.getDataSetTransformDtoList(), data);
originalDataDto.setData(transform);
return originalDataDto;
}
/**
* 获取所有数据集
*
* @return
*/
@Override
public List<DataSet> queryAllDataSet() {
LambdaQueryWrapper<DataSet> wrapper = Wrappers.lambdaQuery();
wrapper.select(DataSet::getSetCode, DataSet::getSetName, DataSet::getSetDesc, DataSet::getId)
.eq(DataSet::getEnableFlag, Enabled.YES.getValue());
wrapper.orderByDesc(DataSet::getUpdateTime);
return dataSetMapper.selectList(wrapper);
}
public void dataSetParamBatch(List<DataSetParamDto> dataSetParamDtoList,String setCode){
dataSetParamService.delete(
new QueryWrapper<DataSetParam>()
.lambda()
.eq(DataSetParam::getSetCode, setCode)
);
if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) {
return;
}
// List<DataSetParam> dataSetParamList = new ArrayList<>();
dataSetParamDtoList.forEach(dataSetParamDto -> {
DataSetParam dataSetParam = new DataSetParam();
BeanUtils.copyProperties(dataSetParamDto, dataSetParam);
dataSetParam.setSetCode(setCode);
//不采用批量
dataSetParamService.insert(dataSetParam);
// dataSetParamList.add(dataSetParam);
});
// dataSetParamService.insertBatch(dataSetParamList);
}
public void dataSetTransformBatch(List<DataSetTransformDto> dataSetTransformDtoList,String setCode){
dataSetTransformService.delete(
new QueryWrapper<DataSetTransform>()
.lambda()
.eq(DataSetTransform::getSetCode, setCode)
);
if (null == dataSetTransformDtoList || dataSetTransformDtoList.size() <= 0) {
return;
}
// List<DataSetTransform> dataSetTransformList = new ArrayList<>();
for (int i = 0; i < dataSetTransformDtoList.size(); i++) {
DataSetTransform dataSetTransform = new DataSetTransform();
BeanUtils.copyProperties(dataSetTransformDtoList.get(i), dataSetTransform);
dataSetTransform.setOrderNum(i + 1);
dataSetTransform.setSetCode(setCode);
//不采用批量
dataSetTransformService.insert(dataSetTransform);
// dataSetTransformList.add(dataSetTransform);
}
// dataSetTransformService.insertBatch(dataSetTransformList);
}
/**
* dataSetParamDtoList转map
* @param dataSetParamDtoList
* @return
*/
public Map<String, Object> setContextData(List<DataSetParamDto> dataSetParamDtoList){
Map<String, Object> map = new HashMap<>();
if (null != dataSetParamDtoList && dataSetParamDtoList.size() > 0) {
dataSetParamDtoList.forEach(dataSetParamDto -> map.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem()));
}
return map;
}
}
@@ -18,45 +18,44 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @desc 数据集动态参数 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
* @desc 数据集动态参数 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@RestController
@Api(tags = "数据集动态参数管理")
@RequestMapping("/dataSetParam")
public class DataSetParamController extends GaeaBaseController<DataSetParamParam, DataSetParam, DataSetParamDto> {
@Autowired
private DataSetParamService dataSetParamService;
@Autowired
private DataSetParamService dataSetParamService;
@Override
public GaeaBaseService<DataSetParamParam, DataSetParam> getService() {
return dataSetParamService;
}
@Override
public GaeaBaseService<DataSetParamParam, DataSetParam> getService() {
return dataSetParamService;
}
@Override
public DataSetParam getEntity() {
return new DataSetParam();
}
@Override
public DataSetParam getEntity() {
return new DataSetParam();
}
@Override
public DataSetParamDto getDTO() {
return new DataSetParamDto();
}
/**
* 测试 查询参数是否正确
* @param param
* @return
*/
@PostMapping("/verification")
public ResponseBean verification(@Validated @RequestBody DataSetParamValidationParam param) {
DataSetParamDto dto = new DataSetParamDto();
dto.setSampleItem(param.getSampleItem());
dto.setValidationRules(param.getValidationRules());
return responseSuccessWithData(dataSetParamService.verification(dto));
}
@Override
public DataSetParamDto getDTO() {
return new DataSetParamDto();
}
/**
* 测试 查询参数是否正确
* @param param
* @return
*/
@PostMapping("/verification")
public ResponseBean verification(@Validated @RequestBody DataSetParamValidationParam param) {
DataSetParamDto dto = new DataSetParamDto();
dto.setSampleItem(param.getSampleItem());
dto.setValidationRules(param.getValidationRules());
return responseSuccessWithData(dataSetParamService.verification(dto));
}
}
@@ -6,42 +6,43 @@ import lombok.Data;
import java.io.Serializable;
/**
* @description 数据集动态参数 dto
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
*
* @description 数据集动态参数 dto
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@Data
public class DataSetParamDto extends GaeaBaseDTO implements Serializable {
/** 数据集编码 */
private String setCode;
/** 数据集编码 */
private String setCode;
/** 参数名 */
private String paramName;
/** 参数名 */
private String paramName;
/** 参数描述 */
private String paramDesc;
/** 参数描述 */
private String paramDesc;
/** 参数类型,字典= */
private String paramType;
/** 参数类型,字典= */
private String paramType;
/** 参数示例项 */
private String sampleItem;
/** 参数示例项 */
private String sampleItem;
/** 0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG */
private Integer requiredFlag;
/** 0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG */
private Integer requiredFlag;
/** js校验字段值规则,满足校验返回 true */
private String validationRules;
/** js校验字段值规则,满足校验返回 true */
private String validationRules;
/** 排序 */
private Integer orderNum;
/** 排序 */
private Integer orderNum;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
}
@@ -6,12 +6,12 @@ import lombok.Data;
import java.io.Serializable;
/**
* @desc DataSetParam 数据集动态参数查询输入类
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@Data
public class DataSetParamParam extends PageParam implements Serializable {
/**
* @desc DataSetParam 数据集动态参数查询输入类
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@Data
public class DataSetParamParam extends PageParam implements Serializable{
}
@@ -11,12 +11,12 @@ import java.io.Serializable;
@Data
public class DataSetParamValidationParam implements Serializable {
/** 参数示例项 */
@NotBlank(message = "sampleItem not empty")
private String sampleItem;
/** 参数示例项 */
@NotBlank(message = "sampleItem not empty")
private String sampleItem;
/** js校验字段值规则,满足校验返回 true */
@NotBlank(message = "validationRules not empty")
private String validationRules;
/** js校验字段值规则,满足校验返回 true */
@NotBlank(message = "validationRules not empty")
private String validationRules;
}
@@ -5,11 +5,10 @@ import com.anjiplus.template.gaea.business.modules.datasetparam.dao.entity.DataS
import org.apache.ibatis.annotations.Mapper;
/**
* DataSetParam Mapper
*
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
* DataSetParam Mapper
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@Mapper
public interface DataSetParamMapper extends GaeaBaseMapper<DataSetParam> {
@@ -7,42 +7,42 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 数据集动态参数 entity
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_data_set_param")
* @description 数据集动态参数 entity
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_data_set_param")
@Data
public class DataSetParam extends GaeaBaseEntity {
@ApiModelProperty(value = "数据集编码")
private String setCode;
@ApiModelProperty(value = "数据集编码")
private String setCode;
@ApiModelProperty(value = "参数名")
private String paramName;
@ApiModelProperty(value = "参数名")
private String paramName;
@ApiModelProperty(value = "参数描述")
private String paramDesc;
@ApiModelProperty(value = "参数描述")
private String paramDesc;
@ApiModelProperty(value = "参数类型,字典=")
private String paramType;
@ApiModelProperty(value = "参数类型,字典=")
private String paramType;
@ApiModelProperty(value = "参数示例项")
private String sampleItem;
@ApiModelProperty(value = "参数示例项")
private String sampleItem;
@ApiModelProperty(value = "0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG")
private Integer requiredFlag;
@ApiModelProperty(value = "0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG")
private Integer requiredFlag;
@ApiModelProperty(value = "js校验字段值规则,满足校验返回 true")
private String validationRules;
@ApiModelProperty(value = "js校验字段值规则,满足校验返回 true")
private String validationRules;
@ApiModelProperty(value = "排序")
private Integer orderNum;
@ApiModelProperty(value = "排序")
private Integer orderNum;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
}
@@ -16,34 +16,36 @@ import java.util.Map;
**/
public interface DataSetParamService extends GaeaBaseService<DataSetParamParam, DataSetParam> {
/**
* 参数替换
* @param contextData
* @param dynSentence
* @return
*/
String transform(Map<String, Object> contextData, String dynSentence);
/**
* 参数替换
*
* @param contextData
* @param dynSentence
* @return
*/
String transform(Map<String, Object> contextData, String dynSentence);
/**
* 参数替换
* @param dataSetParamDtoList
* @param dynSentence
* @return
*/
String transform(List<DataSetParamDto> dataSetParamDtoList, String dynSentence);
/**
* 参数替换
*
* @param dataSetParamDtoList
* @param dynSentence
* @return
*/
String transform(List<DataSetParamDto> dataSetParamDtoList, String dynSentence);
/**
* 参数校验 js脚本
* @param dataSetParamDto
* @return
*/
Object verification(DataSetParamDto dataSetParamDto);
/**
* 参数校验 js脚本
* @param dataSetParamDtoList
* @return
*/
boolean verification(List<DataSetParamDto> dataSetParamDtoList, Map<String, Object> contextData);
/**
* 参数校验 js脚本
* @param dataSetParamDto
* @return
*/
Object verification(DataSetParamDto dataSetParamDto);
/**
* 参数校验 js脚本
*
* @param dataSetParamDtoList
* @return
*/
boolean verification(List<DataSetParamDto> dataSetParamDtoList, Map<String, Object> contextData);
}
@@ -3,12 +3,12 @@ package com.anjiplus.template.gaea.business.modules.datasetparam.service.impl;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.datasetparam.controller.dto.DataSetParamDto;
import com.anjiplus.template.gaea.business.modules.datasetparam.dao.DataSetParamMapper;
import com.anjiplus.template.gaea.business.modules.datasetparam.dao.entity.DataSetParam;
import com.anjiplus.template.gaea.business.modules.datasetparam.service.DataSetParamService;
import com.anjiplus.template.gaea.business.modules.datasetparam.util.ParamsResolverHelper;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
@@ -23,135 +23,135 @@ import java.util.List;
import java.util.Map;
/**
* @desc DataSetParam 数据集动态参数服务实现
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
* @desc DataSetParam 数据集动态参数服务实现
* @author Raod
* @date 2021-03-18 12:12:33.108033200
**/
@Service
// @RequiredArgsConstructor
//@RequiredArgsConstructor
@Slf4j
public class DataSetParamServiceImpl implements DataSetParamService {
private ScriptEngine engine;
private ScriptEngine engine;
{
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript");
}
{
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript");
}
@Autowired
private DataSetParamMapper dataSetParamMapper;
@Autowired
private DataSetParamMapper dataSetParamMapper;
@Override
public GaeaBaseMapper<DataSetParam> getMapper() {
return dataSetParamMapper;
}
@Override
public GaeaBaseMapper<DataSetParam> getMapper() {
return dataSetParamMapper;
}
/**
* 参数替换
*
* @param contextData
* @param dynSentence
* @return
*/
@Override
public String transform(Map<String, Object> contextData, String dynSentence) {
if (StringUtils.isBlank(dynSentence)) {
return dynSentence;
}
if (dynSentence.contains("${")) {
dynSentence = ParamsResolverHelper.resolveParams(contextData, dynSentence);
}
if (dynSentence.contains("${")) {
throw BusinessExceptionBuilder.build(ResponseCode.INCOMPLETE_PARAMETER_REPLACEMENT_VALUES, dynSentence);
}
return dynSentence;
}
/**
* 参数替换
* @param contextData
* @param dynSentence
* @return
*/
@Override
public String transform(Map<String, Object> contextData, String dynSentence) {
if (StringUtils.isBlank(dynSentence)) {
return dynSentence;
}
if (dynSentence.contains("${")) {
dynSentence = ParamsResolverHelper.resolveParams(contextData, dynSentence);
}
if (dynSentence.contains("${")) {
throw BusinessExceptionBuilder.build(ResponseCode.INCOMPLETE_PARAMETER_REPLACEMENT_VALUES, dynSentence);
}
return dynSentence;
}
/**
* 参数替换
*
* @param dataSetParamDtoList
* @param dynSentence
* @return
*/
@Override
public String transform(List<DataSetParamDto> dataSetParamDtoList, String dynSentence) {
Map<String, Object> contextData = new HashMap<>();
if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) {
return dynSentence;
}
dataSetParamDtoList.forEach(dataSetParamDto -> {
contextData.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem());
});
return transform(contextData, dynSentence);
}
/**
* 参数替换
* @param dataSetParamDtoList
* @param dynSentence
* @return
*/
@Override
public String transform(List<DataSetParamDto> dataSetParamDtoList, String dynSentence) {
Map<String, Object> contextData = new HashMap<>();
if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) {
return dynSentence;
}
dataSetParamDtoList.forEach(dataSetParamDto -> {
contextData.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem());
});
return transform(contextData, dynSentence);
}
/**
* 参数校验 js脚本
*
* @param dataSetParamDto
* @return
*/
@Override
public Object verification(DataSetParamDto dataSetParamDto) {
/**
* 参数校验 js脚本
* @param dataSetParamDto
* @return
*/
@Override
public Object verification(DataSetParamDto dataSetParamDto) {
String validationRules = dataSetParamDto.getValidationRules();
if (StringUtils.isNotBlank(validationRules)) {
try {
engine.eval(validationRules);
if(engine instanceof Invocable){
Invocable invocable = (Invocable) engine;
Object exec = invocable.invokeFunction("verification", dataSetParamDto);
ObjectMapper objectMapper = new ObjectMapper();
if (exec instanceof Boolean) {
return objectMapper.convertValue(exec, Boolean.class);
}else {
return objectMapper.convertValue(exec, String.class);
}
String validationRules = dataSetParamDto.getValidationRules();
if (StringUtils.isNotBlank(validationRules)) {
try {
engine.eval(validationRules);
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
Object exec = invocable.invokeFunction("verification", dataSetParamDto);
ObjectMapper objectMapper = new ObjectMapper();
if (exec instanceof Boolean) {
return objectMapper.convertValue(exec, Boolean.class);
}
else {
return objectMapper.convertValue(exec, String.class);
}
}
}
} catch (Exception ex) {
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage());
}
}
catch (Exception ex) {
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage());
}
}
return true;
}
}
return true;
}
/**
* 参数校验 js脚本
*
* @param dataSetParamDtoList
* @return
*/
@Override
public boolean verification(List<DataSetParamDto> dataSetParamDtoList, Map<String, Object> contextData) {
if (null == dataSetParamDtoList || dataSetParamDtoList.size() == 0) {
return true;
}
/**
* 参数校验 js脚本
* @param dataSetParamDtoList
* @return
*/
@Override
public boolean verification(List<DataSetParamDto> dataSetParamDtoList, Map<String, Object> contextData) {
if (null == dataSetParamDtoList || dataSetParamDtoList.size() == 0) {
return true;
}
for (DataSetParamDto dataSetParamDto : dataSetParamDtoList) {
if (null != contextData) {
String value = contextData.getOrDefault(dataSetParamDto.getParamName(), "").toString();
dataSetParamDto.setSampleItem(value);
}
for (DataSetParamDto dataSetParamDto : dataSetParamDtoList) {
if (null != contextData) {
String value = contextData.getOrDefault(dataSetParamDto.getParamName(), "").toString();
dataSetParamDto.setSampleItem(value);
}
Object verification = verification(dataSetParamDto);
if (verification instanceof Boolean) {
if (!(Boolean) verification) {
return false;
}
}else {
//将得到的值重新赋值给contextData
if (null != contextData) {
contextData.put(dataSetParamDto.getParamName(), verification);
}
dataSetParamDto.setSampleItem(verification.toString());
}
Object verification = verification(dataSetParamDto);
if (verification instanceof Boolean) {
if (!(Boolean) verification) {
return false;
}
}
else {
// 将得到的值重新赋值给contextData
if (null != contextData) {
contextData.put(dataSetParamDto.getParamName(), verification);
}
dataSetParamDto.setSampleItem(verification.toString());
}
}
return true;
}
}
return true;
}
}
@@ -12,28 +12,25 @@ import java.util.regex.Pattern;
* Created by raodeming on 2021/3/23.
*/
public class ParamsResolverHelper {
private static String placeholderPrefix = "${";
private static String placeholderSuffix = "}";
private static PropertyPlaceholderHelper helper =
new PropertyPlaceholderHelper(placeholderPrefix, placeholderSuffix);
private static String placeholderPrefix = "${";
public static String resolveParams(final Map<String, Object> param, String con) {
con = helper.replacePlaceholders(con, (key -> param.get(key) + ""));
return con;
}
private static String placeholderSuffix = "}";
private static Pattern key = Pattern.compile("\\$\\{(.*?)\\}");
private static PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(placeholderPrefix,
placeholderSuffix);
public static String resolveParams(final Map<String, Object> param, String con) {
con = helper.replacePlaceholders(con, (key -> param.get(key) + ""));
return con;
}
private static Pattern key = Pattern.compile("\\$\\{(.*?)\\}");
public static List<String> findParamKeys(String con) {
Matcher m = key.matcher(con);
List ret = new ArrayList();
while (m.find()) {
ret.add(m.group(1));
}
return ret;
}
public static List<String> findParamKeys(String con) {
Matcher m = key.matcher(con);
List ret = new ArrayList();
while (m.find()) {
ret.add(m.group(1));
}
return ret;
}
}
@@ -13,33 +13,32 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @desc 数据集数据转换 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
* @desc 数据集数据转换 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@RestController
@Api(tags = "数据集数据转换管理")
@RequestMapping("/dataSetTransform")
public class DataSetTransformController
extends GaeaBaseController<DataSetTransformParam, DataSetTransform, DataSetTransformDto> {
public class DataSetTransformController extends GaeaBaseController<DataSetTransformParam, DataSetTransform, DataSetTransformDto> {
@Autowired
private DataSetTransformService dataSetTransformService;
@Autowired
private DataSetTransformService dataSetTransformService;
@Override
public GaeaBaseService<DataSetTransformParam, DataSetTransform> getService() {
return dataSetTransformService;
}
@Override
public GaeaBaseService<DataSetTransformParam, DataSetTransform> getService() {
return dataSetTransformService;
}
@Override
public DataSetTransform getEntity() {
return new DataSetTransform();
}
@Override
public DataSetTransform getEntity() {
return new DataSetTransform();
}
@Override
public DataSetTransformDto getDTO() {
return new DataSetTransformDto();
}
@Override
public DataSetTransformDto getDTO() {
return new DataSetTransformDto();
}
}
@@ -6,30 +6,31 @@ import lombok.Data;
import java.io.Serializable;
/**
* @description 数据集数据转换 dto
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
*
* @description 数据集数据转换 dto
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@Data
public class DataSetTransformDto extends GaeaBaseDTO implements Serializable {
/** 数据集编码 */
private String setCode;
/** 数据集编码 */
private String setCode;
/** 数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换 */
private String transformType;
/** 数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换 */
private String transformType;
/** 数据转换script,处理逻辑 */
private String transformScript;
/** 数据转换script,处理逻辑 */
private String transformScript;
/** 排序,执行数据转换顺序 */
private Integer orderNum;
/** 排序,执行数据转换顺序 */
private Integer orderNum;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
}
@@ -6,12 +6,12 @@ import lombok.Data;
import java.io.Serializable;
/**
* @desc DataSetTransform 数据集数据转换查询输入类
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@Data
public class DataSetTransformParam extends PageParam implements Serializable {
/**
* @desc DataSetTransform 数据集数据转换查询输入类
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@Data
public class DataSetTransformParam extends PageParam implements Serializable{
}
@@ -5,11 +5,10 @@ import com.anjiplus.template.gaea.business.modules.datasettransform.dao.entity.D
import org.apache.ibatis.annotations.Mapper;
/**
* DataSetTransform Mapper
*
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
* DataSetTransform Mapper
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@Mapper
public interface DataSetTransformMapper extends GaeaBaseMapper<DataSetTransform> {
@@ -7,30 +7,30 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 数据集数据转换 entity
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_data_set_transform")
* @description 数据集数据转换 entity
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_data_set_transform")
@Data
public class DataSetTransform extends GaeaBaseEntity {
@ApiModelProperty(value = "数据集编码")
private String setCode;
@ApiModelProperty(value = "数据集编码")
private String setCode;
@ApiModelProperty(value = "数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换")
private String transformType;
@ApiModelProperty(value = "数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换")
private String transformType;
@ApiModelProperty(value = "数据转换script,处理逻辑")
private String transformScript;
@ApiModelProperty(value = "数据转换script,处理逻辑")
private String transformScript;
@ApiModelProperty(value = "排序,执行数据转换顺序")
private Integer orderNum;
@ApiModelProperty(value = "排序,执行数据转换顺序")
private Integer orderNum;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
}
@@ -10,12 +10,12 @@ import com.anjiplus.template.gaea.business.modules.datasettransform.dao.entity.D
import java.util.List;
/**
* @desc DataSetTransform 数据集数据转换服务接口
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
* @desc DataSetTransform 数据集数据转换服务接口
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
public interface DataSetTransformService extends GaeaBaseService<DataSetTransformParam, DataSetTransform> {
List<JSONObject> transform(List<DataSetTransformDto> dataSetTransformDtoList, List<JSONObject> data);
List<JSONObject> transform(List<DataSetTransformDto> dataSetTransformDtoList, List<JSONObject> data);
}
@@ -9,19 +9,17 @@ import java.util.List;
* Created by raodeming on 2021/3/23.
*/
public interface TransformStrategy {
/**
* 数据清洗转换 类型
* @return
*/
String type();
/**
* 数据清洗转换 类型
* @return
*/
String type();
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data);
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data);
}
@@ -20,54 +20,52 @@ import java.util.List;
import java.util.Map;
/**
* @desc DataSetTransform 数据集数据转换服务实现
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
* @desc DataSetTransform 数据集数据转换服务实现
* @author Raod
* @date 2021-03-18 12:13:15.591309400
**/
@Service
// @RequiredArgsConstructor
//@RequiredArgsConstructor
public class DataSetTransformServiceImpl implements DataSetTransformService, InitializingBean, ApplicationContextAware {
private final Map<String, TransformStrategy> queryServiceImplMap = new HashMap<>();
private final Map<String, TransformStrategy> queryServiceImplMap = new HashMap<>();
private ApplicationContext applicationContext;
private ApplicationContext applicationContext;
@Autowired
private DataSetTransformMapper dataSetTransformMapper;
@Autowired
private DataSetTransformMapper dataSetTransformMapper;
@Override
public GaeaBaseMapper<DataSetTransform> getMapper() {
return dataSetTransformMapper;
}
@Override
public GaeaBaseMapper<DataSetTransform> getMapper() {
return dataSetTransformMapper;
}
public TransformStrategy getTarget(String type) {
return queryServiceImplMap.get(type);
}
public TransformStrategy getTarget(String type) {
return queryServiceImplMap.get(type);
}
@Override
public void afterPropertiesSet() {
Map<String, TransformStrategy> beanMap = applicationContext.getBeansOfType(TransformStrategy.class);
//遍历该接口的所有实现,将其放入map中
for (TransformStrategy serviceImpl : beanMap.values()) {
queryServiceImplMap.put(serviceImpl.type(), serviceImpl);
}
}
@Override
public void afterPropertiesSet() {
Map<String, TransformStrategy> beanMap = applicationContext.getBeansOfType(TransformStrategy.class);
// 遍历该接口的所有实现,将其放入map中
for (TransformStrategy serviceImpl : beanMap.values()) {
queryServiceImplMap.put(serviceImpl.type(), serviceImpl);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public List<JSONObject> transform(List<DataSetTransformDto> dataSetTransformDtoList, List<JSONObject> data) {
if (dataSetTransformDtoList == null || dataSetTransformDtoList.size() <= 0) {
return data;
}
for (DataSetTransformDto dataSetTransformDto : dataSetTransformDtoList) {
data = getTarget(dataSetTransformDto.getTransformType()).transform(dataSetTransformDto, data);
}
return data;
}
@Override
public List<JSONObject> transform(List<DataSetTransformDto> dataSetTransformDtoList, List<JSONObject> data) {
if (dataSetTransformDtoList == null || dataSetTransformDtoList.size() <= 0) {
return data;
}
for (DataSetTransformDto dataSetTransformDto : dataSetTransformDtoList) {
data = getTarget(dataSetTransformDto.getTransformType()).transform(dataSetTransformDto, data);
}
return data;
}
}
@@ -11,45 +11,46 @@ import java.util.List;
import java.util.Set;
/**
* 字典转换 Created by raodeming on 2021/3/29.
* 字典转换
* Created by raodeming on 2021/3/29.
*/
@Component
@Slf4j
public class DictTransformServiceImpl implements TransformStrategy {
/**
* 数据清洗转换 类型
* @return
*/
@Override
public String type() {
return "dict";
}
/**
* 数据清洗转换 类型
*
* @return
*/
@Override
public String type() {
return "dict";
}
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
@Override
public List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data) {
String transformScript = def.getTransformScript();
if (StringUtils.isBlank(transformScript)) {
return data;
}
JSONObject jsonObject = JSONObject.parseObject(transformScript);
Set<String> keys = jsonObject.keySet();
data.forEach(dataDetail -> dataDetail.forEach((key, value) -> {
if (keys.contains(key)) {
String string = jsonObject.getJSONObject(key).getString(value.toString());
if (StringUtils.isNotBlank(string)) {
dataDetail.put(key, string);
}
}
}));
return data;
}
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
@Override
public List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data) {
String transformScript = def.getTransformScript();
if (StringUtils.isBlank(transformScript)) {
return data;
}
JSONObject jsonObject = JSONObject.parseObject(transformScript);
Set<String> keys = jsonObject.keySet();
data.forEach(dataDetail -> dataDetail.forEach((key, value) -> {
if (keys.contains(key)) {
String string = jsonObject.getJSONObject(key).getString(value.toString());
if (StringUtils.isNotBlank(string)) {
dataDetail.put(key, string);
}
}
}));
return data;
}
}
@@ -5,6 +5,7 @@ import com.anji.plus.gaea.exception.BusinessExceptionBuilder;
import com.anjiplus.template.gaea.business.code.ResponseCode;
import com.anjiplus.template.gaea.business.modules.datasettransform.controller.dto.DataSetTransformDto;
import com.anjiplus.template.gaea.business.modules.datasettransform.service.TransformStrategy;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@@ -20,47 +21,45 @@ import java.util.List;
@Slf4j
public class JsTransformServiceImpl implements TransformStrategy {
private ScriptEngine engine;
private ScriptEngine engine;
{
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript");
}
{
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("JavaScript");
}
/**
* 数据清洗转换 类型
*
* @return
*/
@Override
public String type() {
return "js";
}
/**
* 数据清洗转换 类型
* @return
*/
@Override
public String type() {
return "js";
}
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
@Override
public List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data) {
return getValueFromJs(def,data);
}
/***
* 清洗转换算法接口
* @param def
* @param data
* @return
*/
@Override
public List<JSONObject> transform(DataSetTransformDto def, List<JSONObject> data) {
return getValueFromJs(def, data);
}
private List<JSONObject> getValueFromJs(DataSetTransformDto def, List<JSONObject> data) {
String js = def.getTransformScript();
try {
engine.eval(js);
if (engine instanceof Invocable) {
Invocable invocable = (Invocable) engine;
return (List<JSONObject>) invocable.invokeFunction("dataTransform", data);
}
}
catch (Exception ex) {
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage());
}
return null;
}
private List<JSONObject> getValueFromJs(DataSetTransformDto def, List<JSONObject> data) {
String js = def.getTransformScript();
try {
engine.eval(js);
if(engine instanceof Invocable){
Invocable invocable = (Invocable) engine;
return (List<JSONObject>) invocable.invokeFunction("dataTransform", data);
}
} catch (Exception ex) {
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage());
}
return null;
}
}
@@ -47,168 +47,168 @@ import java.util.*;
@Configuration
@Slf4j
public class HttpClientConfig {
@Autowired
private HttpClientPoolConfig httpClientPoolConfig;
@Autowired
private HttpClientPoolConfig httpClientPoolConfig;
/**
* 创建HTTP客户端工厂
*/
@Bean(name = "clientHttpRequestFactory")
public ClientHttpRequestFactory clientHttpRequestFactory() {
/**
* maxTotalConnection 和 maxConnectionPerRoute 必须要配
*/
if (httpClientPoolConfig.getMaxTotalConnect() <= 0) {
throw new IllegalArgumentException("invalid maxTotalConnection: " + httpClientPoolConfig.getMaxTotalConnect());
}
if (httpClientPoolConfig.getMaxConnectPerRoute() <= 0) {
throw new IllegalArgumentException("invalid maxConnectionPerRoute: " + httpClientPoolConfig.getMaxConnectPerRoute());
}
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
// 连接超时
clientHttpRequestFactory.setConnectTimeout(httpClientPoolConfig.getConnectTimeout());
// 数据读取超时时间,即SocketTimeout
clientHttpRequestFactory.setReadTimeout(httpClientPoolConfig.getReadTimeout());
// 从连接池获取请求连接的超时时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
clientHttpRequestFactory.setConnectionRequestTimeout(httpClientPoolConfig.getConnectionRequestTimout());
return clientHttpRequestFactory;
}
/**
* 创建HTTP客户端工厂
*/
@Bean(name = "clientHttpRequestFactory")
public ClientHttpRequestFactory clientHttpRequestFactory() {
/**
* maxTotalConnection 和 maxConnectionPerRoute 必须要配
*/
if (httpClientPoolConfig.getMaxTotalConnect() <= 0) {
throw new IllegalArgumentException(
"invalid maxTotalConnection: " + httpClientPoolConfig.getMaxTotalConnect());
}
if (httpClientPoolConfig.getMaxConnectPerRoute() <= 0) {
throw new IllegalArgumentException(
"invalid maxConnectionPerRoute: " + httpClientPoolConfig.getMaxConnectPerRoute());
}
HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(
httpClient());
// 连接超时
clientHttpRequestFactory.setConnectTimeout(httpClientPoolConfig.getConnectTimeout());
// 数据读取超时时间,即SocketTimeout
clientHttpRequestFactory.setReadTimeout(httpClientPoolConfig.getReadTimeout());
// 从连接池获取请求连接的超时时间,不宜过长,必须设置,比如连接不够用时,时间过长将是灾难性的
clientHttpRequestFactory.setConnectionRequestTimeout(httpClientPoolConfig.getConnectionRequestTimout());
return clientHttpRequestFactory;
}
/**
* 初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理
*/
@Bean(name = "dataSourceRestTemplate")
public RestTemplate restTemplate(@Qualifier("clientHttpRequestFactory") ClientHttpRequestFactory factory) {
return createRestTemplate(factory);
}
/**
* 初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理
*/
@Bean(name = "dataSourceRestTemplate")
public RestTemplate restTemplate(@Qualifier("clientHttpRequestFactory") ClientHttpRequestFactory factory) {
return createRestTemplate(factory);
}
/**
* 配置httpClient
*
* @return
*/
@Bean
public HttpClient httpClient() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try {
//设置信任ssl访问
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
/**
* 配置httpClient
* @return
*/
@Bean
public HttpClient httpClient() {
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
try {
// 设置信任ssl访问
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();
httpClientBuilder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
// 注册http和https请求
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
httpClientBuilder.setSSLContext(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
// 注册http和https请求
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", sslConnectionSocketFactory).build();
//使用Httpclient连接池的方式配置(推荐),同时支持netty,okHttp以及其他http框架
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// 最大连接数
poolingHttpClientConnectionManager.setMaxTotal(httpClientPoolConfig.getMaxTotalConnect());
// 同路由并发数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientPoolConfig.getMaxConnectPerRoute());
//配置连接池
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
// 重试次数
httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(httpClientPoolConfig.getRetryTimes(), true));
// 使用Httpclient连接池的方式配置(推荐),同时支持netty,okHttp以及其他http框架
PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
// 最大连接数
poolingHttpClientConnectionManager.setMaxTotal(httpClientPoolConfig.getMaxTotalConnect());
// 同路由并发数
poolingHttpClientConnectionManager.setDefaultMaxPerRoute(httpClientPoolConfig.getMaxConnectPerRoute());
// 配置连接池
httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);
// 重试次数
httpClientBuilder
.setRetryHandler(new DefaultHttpRequestRetryHandler(httpClientPoolConfig.getRetryTimes(), true));
//设置默认请求头
List<Header> headers = getDefaultHeaders();
httpClientBuilder.setDefaultHeaders(headers);
//设置长连接保持策略
httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy());
return httpClientBuilder.build();
} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("初始化HTTP连接池出错", e);
}
return null;
}
// 设置默认请求头
List<Header> headers = getDefaultHeaders();
httpClientBuilder.setDefaultHeaders(headers);
// 设置长连接保持策略
httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy());
return httpClientBuilder.build();
}
catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
log.error("初始化HTTP连接池出错", e);
}
return null;
}
/**
* 配置长连接保持策略
* @return
*/
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return (response, context) -> {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
log.info("HeaderElement:{}", JSON.toJSONString(he));
String param = he.getName();
String value = he.getValue();
if (value != null && "timeout".equalsIgnoreCase(param)) {
try {
return Long.parseLong(value) * 1000;
}
catch (NumberFormatException ignore) {
log.error("解析长连接过期时间异常", ignore);
}
}
}
HttpHost target = (HttpHost) context.getAttribute(HttpClientContext.HTTP_TARGET_HOST);
// 如果请求目标地址,单独配置了长连接保持时间,使用该配置
Optional<Map.Entry<String, Integer>> any = Optional
.ofNullable(httpClientPoolConfig.getKeepAliveTargetHost()).orElseGet(HashMap::new).entrySet()
.stream().filter(e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny();
// 否则使用默认长连接保持时间
return any.map(en -> en.getValue() * 1000L).orElse(httpClientPoolConfig.getKeepAliveTime() * 1000L);
};
}
/**
* 配置长连接保持策略
*
* @return
*/
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() {
return (response, context) -> {
// Honor 'keep-alive' header
HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
HeaderElement he = it.nextElement();
log.info("HeaderElement:{}", JSON.toJSONString(he));
String param = he.getName();
String value = he.getValue();
if (value != null && "timeout".equalsIgnoreCase(param)) {
try {
return Long.parseLong(value) * 1000;
} catch (NumberFormatException ignore) {
log.error("解析长连接过期时间异常", ignore);
}
}
}
HttpHost target = (HttpHost) context.getAttribute(
HttpClientContext.HTTP_TARGET_HOST);
//如果请求目标地址,单独配置了长连接保持时间,使用该配置
Optional<Map.Entry<String, Integer>> any = Optional.ofNullable(httpClientPoolConfig.getKeepAliveTargetHost()).orElseGet(HashMap::new)
.entrySet().stream().filter(
e -> e.getKey().equalsIgnoreCase(target.getHostName())).findAny();
//否则使用默认长连接保持时间
return any.map(en -> en.getValue() * 1000L).orElse(httpClientPoolConfig.getKeepAliveTime() * 1000L);
};
}
/**
* 设置请求头
* @return
*/
private List<Header> getDefaultHeaders() {
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
headers.add(new BasicHeader("Accept-Language", "zh-CN"));
headers.add(new BasicHeader("Connection", "Keep-Alive"));
return headers;
}
private RestTemplate createRestTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
/**
* 设置请求头
*
* @return
*/
private List<Header> getDefaultHeaders() {
List<Header> headers = new ArrayList<>();
headers.add(new BasicHeader("User-Agent",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
headers.add(new BasicHeader("Accept-Language", "zh-CN"));
headers.add(new BasicHeader("Connection", "Keep-Alive"));
return headers;
}
// 我们采用RestTemplate内部的MessageConverter
// 重新设置StringHttpMessageConverter字符集,解决中文乱码问题
modifyDefaultCharset(restTemplate);
// 设置错误处理器
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
private RestTemplate createRestTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
//我们采用RestTemplate内部的MessageConverter
//重新设置StringHttpMessageConverter字符集,解决中文乱码问题
modifyDefaultCharset(restTemplate);
/**
* 修改默认的字符集类型为utf-8
* @param restTemplate
*/
private void modifyDefaultCharset(RestTemplate restTemplate) {
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
Charset defaultCharset = Charset.forName(httpClientPoolConfig.getCharset());
converterList.add(1, new StringHttpMessageConverter(defaultCharset));
}
//设置错误处理器
restTemplate.setErrorHandler(new DefaultResponseErrorHandler());
return restTemplate;
}
/**
* 修改默认的字符集类型为utf-8
*
* @param restTemplate
*/
private void modifyDefaultCharset(RestTemplate restTemplate) {
List<HttpMessageConverter<?>> converterList = restTemplate.getMessageConverters();
HttpMessageConverter<?> converterTarget = null;
for (HttpMessageConverter<?> item : converterList) {
if (StringHttpMessageConverter.class == item.getClass()) {
converterTarget = item;
break;
}
}
if (null != converterTarget) {
converterList.remove(converterTarget);
}
Charset defaultCharset = Charset.forName(httpClientPoolConfig.getCharset());
converterList.add(1, new StringHttpMessageConverter(defaultCharset));
}
}
@@ -13,50 +13,41 @@ import java.util.Map;
@ConfigurationProperties(prefix = "spring.http-client.pool")
@Data
public class HttpClientPoolConfig {
/**
* java配置的优先级低于yml配置;如果yml配置不存在,会采用java配置
*/
/**
* 连接池的最大连接数
*/
private int maxTotalConnect = 1000;
/**
* 同路由的并发数
*/
private int maxConnectPerRoute = 200;
/**
* 客户端和服务器建立连接超时,默认2s
*/
private int connectTimeout = 2 * 1000;
/**
* 指客户端从服务器读取数据包的间隔超时时间,不是总读取时间,默认30s
*/
private int readTimeout = 30 * 1000;
/**
* java配置的优先级低于yml配置;如果yml配置不存在,会采用java配置
*/
/**
* 连接池的最大连接数
*/
private int maxTotalConnect = 1000;
/**
* 同路由的并发数
*/
private int maxConnectPerRoute = 200;
/**
* 客户端和服务器建立连接超时,默认2s
*/
private int connectTimeout = 2 * 1000;
/**
* 指客户端从服务器读取数据包的间隔超时时间,不是总读取时间,默认30s
*/
private int readTimeout = 30 * 1000;
private String charset = "UTF-8";
/**
* 重试次数,默认2次
*/
private int retryTimes = 2;
/**
* 从连接池获取连接的超时时间,不宜过长,单位ms
*/
private int connectionRequestTimout = 200;
/**
* 针对不同的地址,特别设置不同的长连接保持时间
*/
private Map<String, Integer> keepAliveTargetHost;
/**
* 针对不同的地址,特别设置不同的长连接保持时间,单位 s
*/
private int keepAliveTime = 60;
private String charset = "UTF-8";
/**
* 重试次数,默认2次
*/
private int retryTimes = 2;
/**
* 从连接池获取连接的超时时间,不宜过长,单位ms
*/
private int connectionRequestTimout = 200;
/**
* 针对不同的地址,特别设置不同的长连接保持时间
*/
private Map<String,Integer> keepAliveTargetHost;
/**
* 针对不同的地址,特别设置不同的长连接保持时间,单位 s
*/
private int keepAliveTime = 60;
}
@@ -16,53 +16,53 @@ import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
/**
* @desc 数据源 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
* @desc 数据源 controller
* @website https://gitee.com/anji-plus/gaea
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@RestController
@Api(tags = "数据源管理")
@Permission(code = "datasourceManage", name = "数据源管理")
@RequestMapping("/dataSource")
public class DataSourceController extends GaeaBaseController<DataSourceParam, DataSource, DataSourceDto> {
@Autowired
private DataSourceService dataSourceService;
@Autowired
private DataSourceService dataSourceService;
@Override
public GaeaBaseService<DataSourceParam, DataSource> getService() {
return dataSourceService;
}
@Override
public GaeaBaseService<DataSourceParam, DataSource> getService() {
return dataSourceService;
}
@Override
public DataSource getEntity() {
return new DataSource();
}
@Override
public DataSource getEntity() {
return new DataSource();
}
@Override
public DataSourceDto getDTO() {
return new DataSourceDto();
}
@Override
public DataSourceDto getDTO() {
return new DataSourceDto();
}
/**
* 获取所有数据源
* @return
*/
@GetMapping("/queryAllDataSource")
public ResponseBean queryAllDataSource() {
return responseSuccessWithData(dataSourceService.queryAllDataSource());
}
/**
* 获取所有数据源
* @return
*/
@GetMapping("/queryAllDataSource")
public ResponseBean queryAllDataSource() {
return responseSuccessWithData(dataSourceService.queryAllDataSource());
}
/**
* 测试 连接
* @param connectionParam
* @return
*/
@Permission(code = "query", name = "测试数据源")
@PostMapping("/testConnection")
public ResponseBean testConnection(@Validated @RequestBody ConnectionParam connectionParam) {
return responseSuccessWithData(dataSourceService.testConnection(connectionParam));
}
/**
* 测试 连接
* @param connectionParam
* @return
*/
@Permission( code = "query", name = "测试数据源")
@PostMapping("/testConnection")
public ResponseBean testConnection(@Validated @RequestBody ConnectionParam connectionParam) {
return responseSuccessWithData(dataSourceService.testConnection(connectionParam));
}
}
@@ -7,74 +7,68 @@ import lombok.Data;
import java.io.Serializable;
import java.util.Map;
/**
* @description 数据源 dto
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
*
* @description 数据源 dto
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@Data
public class DataSourceDto extends GaeaBaseDTO implements Serializable {
/** 数据源编码 */
private String sourceCode;
/** 数据源编码 */
private String sourceCode;
/** 数据源名称 */
private String sourceName;
/** 数据源名称 */
private String sourceName;
/** 数据源描述 */
private String sourceDesc;
/** 数据源描述 */
private String sourceDesc;
/** 数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 */
private String sourceType;
/**
* 数据源类型 DIC_NAME=SOURCE_TYPE;
* mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单
*/
private String sourceType;
/** 数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{ apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{"query":"select 1"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' } */
private String sourceConfig;
/**
* 数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{
* apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{"query":"select
* 1"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' }
*/
private String sourceConfig;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */
private Integer enableFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */
private Integer deleteFlag;
/**************************************************************/
/**关系型数据库jdbcUrl */
private String jdbcUrl;
/**************************************************************/
/** 关系型数据库jdbcUrl */
private String jdbcUrl;
/** 关系型数据库用户名 */
private String username;
/** 关系型数据库用户名 */
private String username;
/** 关系型数据库密码 */
private String password;
/** 关系型数据库密码 */
private String password;
/** 关系型数据库驱动类 */
private String driverName;
/** 关系型数据库驱动类 */
private String driverName;
/** 关系型数据库sql */
private String sql;
/** 关系型数据库sql */
private String sql;
/** http requestUrl */
private String apiUrl;
/** http requestUrl */
private String apiUrl;
/** http method */
private String method;
/** http method */
private String method;
/** http header */
private String header;
/** http header */
private String header;
/** http 请求体 */
private String body;
/** http 请求体 */
private String body;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 动态查询sql或者接口中的请求体 */
private String dynSentence;
/** 传入的自定义参数,解决url中存在的动态参数 */
private Map<String, Object> contextData;
/** 传入的自定义参数,解决url中存在的动态参数*/
private Map<String, Object> contextData;
}
@@ -11,19 +11,11 @@ import java.io.Serializable;
@Data
public class ConnectionParam implements Serializable {
/**
* 数据源类型 DIC_NAME=SOURCE_TYPE;
* mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单
*/
@NotBlank(message = "sourceType not empty")
private String sourceType;
/**
* 数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{
* apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{"query":"select
* 1"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' }
*/
@NotBlank(message = "sourceConfig not empty")
private String sourceConfig;
/** 数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 */
@NotBlank(message = "sourceType not empty")
private String sourceType;
/** 数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{ apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{"query":"select 1"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' } */
@NotBlank(message = "sourceConfig not empty")
private String sourceConfig;
}
@@ -8,27 +8,24 @@ import lombok.Data;
import java.io.Serializable;
/**
* @desc DataSource 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
* @desc DataSource 数据集查询输入类
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@Data
public class DataSourceParam extends PageParam implements Serializable {
public class DataSourceParam extends PageParam implements Serializable{
/** 数据源名称 */
@Query(QueryEnum.LIKE)
private String sourceName;
/** 数据源名称 */
@Query(QueryEnum.LIKE)
private String sourceName;
/** 数据源编码 */
@Query(QueryEnum.LIKE)
private String sourceCode;
/**
* 数据源类型 DIC_NAME=SOURCE_TYPE;
* mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单
*/
@Query(QueryEnum.EQ)
private String sourceType;
/** 数据源编码 */
@Query(QueryEnum.LIKE)
private String sourceCode;
/** 数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 */
@Query(QueryEnum.EQ)
private String sourceType;
}
@@ -1,15 +1,15 @@
package com.anjiplus.template.gaea.business.modules.datasource.dao;
import org.apache.ibatis.annotations.Mapper;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.datasource.dao.entity.DataSource;
import org.apache.ibatis.annotations.Mapper;
/**
* DataSource Mapper
*
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
* DataSource Mapper
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@Mapper
public interface DataSourceMapper extends GaeaBaseMapper<DataSource> {
@@ -9,36 +9,34 @@ import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
/**
* @description 数据源 entity
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@TableName(keepGlobalPrefix = true, value = "gaea_report_data_source")
* @description 数据源 entity
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
@TableName(keepGlobalPrefix=true, value="gaea_report_data_source")
@Data
public class DataSource extends GaeaBaseEntity {
@ApiModelProperty(value = "数据源编码")
@Unique(code = ResponseCode.SOURCE_CODE_ISEXIST)
private String sourceCode;
@ApiModelProperty(value = "数据源编码")
@Unique(code = ResponseCode.SOURCE_CODE_ISEXIST)
private String sourceCode;
@ApiModelProperty(value = "数据源名称")
private String sourceName;
@ApiModelProperty(value = "数据源名称")
private String sourceName;
@ApiModelProperty(value = "数据源描述")
private String sourceDesc;
@ApiModelProperty(value = "数据源描述")
private String sourceDesc;
@ApiModelProperty(value = "数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单")
private String sourceType;
@ApiModelProperty(
value = "数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单")
private String sourceType;
@ApiModelProperty(value = "数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{ apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{\"query\":\"select 1\"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' }")
private String sourceConfig;
@ApiModelProperty(
value = "数据源连接配置json:关系库{ jdbcUrl:'', username:'', password:'','driverName':''}ES-sql{ apiUrl:'http://127.0.0.1:9092/_xpack/sql?format=json','method':'POST','body':'{\"query\":\"select 1\"}' } 接口{ apiUrl:'http://ip:port/url', method:'' } javaBean{ beanNamw:'xxx' }")
private String sourceConfig;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG")
private Integer enableFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
@ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG")
private Integer deleteFlag;
}
@@ -12,38 +12,37 @@ import com.anjiplus.template.gaea.business.modules.datasource.dao.entity.DataSou
import java.util.List;
/**
* @desc DataSource 数据集服务接口
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
* @desc DataSource 数据集服务接口
* @author Raod
* @date 2021-03-18 12:09:57.728203200
**/
public interface DataSourceService extends GaeaBaseService<DataSourceParam, DataSource> {
/**
* 获取所有数据源
* @return
*/
List<DataSource> queryAllDataSource();
/**
* 获取所有数据源
* @return
*/
List<DataSource> queryAllDataSource();
/**
* 测试 连接
* @param connectionParam
* @return
*/
Boolean testConnection(ConnectionParam connectionParam);
/**
* 测试 连接
* @param connectionParam
* @return
*/
Boolean testConnection(ConnectionParam connectionParam);
/**
* 执行sql
* @param dto
* @return
*/
List<JSONObject> execute(DataSourceDto dto);
/**
* 执行sql,统计数据total
* @param dataSourceDto
* @param dto
* @return
*/
long total(DataSourceDto dataSourceDto, DataSetDto dto);
/**
* 执行sql
* @param dto
* @return
*/
List<JSONObject> execute(DataSourceDto dto);
/**
* 执行sql,统计数据total
* @param dataSourceDto
* @param dto
* @return
*/
long total(DataSourceDto dataSourceDto, DataSetDto dto);
}
@@ -10,27 +10,30 @@ import java.sql.SQLException;
*/
public interface JdbcService {
/**
* 删除数据库连接池
* @param id
*/
void removeJdbcConnectionPool(Long id);
/**
* 删除数据库连接池
*
* @param id
*/
void removeJdbcConnectionPool(Long id);
/**
* 获取连接
* @param dataSource
* @return
* @throws SQLException
*/
Connection getPooledConnection(DataSourceDto dataSource) throws SQLException;
/**
* 测试数据库连接 获取一个连接
* @param dataSource
* @return
* @throws ClassNotFoundException driverName不正确
* @throws SQLException
*/
Connection getUnPooledConnection(DataSourceDto dataSource) throws SQLException;
/**
* 获取连接
*
* @param dataSource
* @return
* @throws SQLException
*/
Connection getPooledConnection(DataSourceDto dataSource) throws SQLException;
/**
* 测试数据库连接 获取一个连接
*
* @param dataSource
* @return
* @throws ClassNotFoundException driverName不正确
* @throws SQLException
*/
Connection getUnPooledConnection(DataSourceDto dataSource) throws SQLException;
}
@@ -33,10 +33,7 @@ import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
@@ -51,410 +48,405 @@ import java.util.Map;
@Slf4j
public class DataSourceServiceImpl implements DataSourceService {
@Autowired
private DataSourceMapper dataSourceMapper;
@Autowired
private DataSourceMapper dataSourceMapper;
@Resource(name = "dataSourceRestTemplate")
private RestTemplate restTemplate;
@Resource(name = "dataSourceRestTemplate")
private RestTemplate restTemplate;
@Autowired
private DataSetParamService dataSetParamService;
@Autowired
private DataSetParamService dataSetParamService;
@Autowired
private JdbcService jdbcService;
@Autowired
private JdbcService jdbcService;
@Override
public GaeaBaseMapper<DataSource> getMapper() {
return dataSourceMapper;
}
@Override
public GaeaBaseMapper<DataSource> getMapper() {
return dataSourceMapper;
}
/**
* 获取所有数据源
* @return
*/
@Override
public List<DataSource> queryAllDataSource() {
LambdaQueryWrapper<DataSource> wrapper = Wrappers.lambdaQuery();
wrapper.select(DataSource::getSourceCode, DataSource::getSourceName).eq(DataSource::getEnableFlag,
Enabled.YES.getValue());
wrapper.orderByDesc(DataSource::getUpdateTime);
return dataSourceMapper.selectList(wrapper);
}
/**
* 测试 连接
* @param connectionParam
* @return
*/
@Override
public Boolean testConnection(ConnectionParam connectionParam) {
String sourceType = connectionParam.getSourceType();
String sourceConfig = connectionParam.getSourceConfig();
DataSourceDto dto = new DataSourceDto();
dto.setSourceConfig(sourceConfig);
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
testElasticsearchSqlConnection(dto);
break;
case JdbcConstants.MYSQL:
case JdbcConstants.KUDU_IMAPLA:
case JdbcConstants.ORACLE:
case JdbcConstants.SQL_SERVER:
case JdbcConstants.JDBC:
case JdbcConstants.POSTGRESQL:
testRelationalDb(dto);
break;
case JdbcConstants.HTTP:
testHttp(dto);
break;
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
log.info("测试连接成功:{}", JSONObject.toJSONString(connectionParam));
return true;
/**
* 获取所有数据源
* @return
*/
@Override
public List<DataSource> queryAllDataSource() {
LambdaQueryWrapper<DataSource> wrapper = Wrappers.lambdaQuery();
wrapper.select(DataSource::getSourceCode, DataSource::getSourceName)
.eq(DataSource::getEnableFlag, Enabled.YES.getValue());
wrapper.orderByDesc(DataSource::getUpdateTime);
return dataSourceMapper.selectList(wrapper);
}
}
/**
* 测试 连接
*
* @param connectionParam
* @return
*/
@Override
public Boolean testConnection(ConnectionParam connectionParam) {
String sourceType = connectionParam.getSourceType();
String sourceConfig = connectionParam.getSourceConfig();
DataSourceDto dto = new DataSourceDto();
dto.setSourceConfig(sourceConfig);
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
testElasticsearchSqlConnection(dto);
break;
case JdbcConstants.MYSQL:
case JdbcConstants.KUDU_IMAPLA:
case JdbcConstants.ORACLE:
case JdbcConstants.SQL_SERVER:
case JdbcConstants.JDBC:
case JdbcConstants.POSTGRESQL:
testRelationalDb(dto);
break;
case JdbcConstants.HTTP:
testHttp(dto);
break;
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
log.info("测试连接成功:{}", JSONObject.toJSONString(connectionParam));
return true;
@Override
public List<JSONObject> execute(DataSourceDto dto) {
String sourceType = dto.getSourceType();
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
return executeElasticsearchSql(dto);
case JdbcConstants.MYSQL:
case JdbcConstants.KUDU_IMAPLA:
case JdbcConstants.ORACLE:
case JdbcConstants.SQL_SERVER:
case JdbcConstants.JDBC:
case JdbcConstants.POSTGRESQL:
return executeRelationalDb(dto);
case JdbcConstants.HTTP:
return executeHttp(dto);
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
}
}
/**
* 执行sql,统计数据total
* @param dto
* @return
*/
@Override
public long total(DataSourceDto sourceDto, DataSetDto dto) {
// 区分数据类型
String sourceType = sourceDto.getSourceType();
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
return 0;
case JdbcConstants.MYSQL:
return mysqlTotal(sourceDto, dto);
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
@Override
public List<JSONObject> execute(DataSourceDto dto) {
String sourceType = dto.getSourceType();
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
return executeElasticsearchSql(dto);
case JdbcConstants.MYSQL:
case JdbcConstants.KUDU_IMAPLA:
case JdbcConstants.ORACLE:
case JdbcConstants.SQL_SERVER:
case JdbcConstants.JDBC:
case JdbcConstants.POSTGRESQL:
return executeRelationalDb(dto);
case JdbcConstants.HTTP:
return executeHttp(dto);
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
}
}
/**
* 执行sql,统计数据total
*
* @param dto
* @return
*/
@Override
public long total(DataSourceDto sourceDto, DataSetDto dto) {
//区分数据类型
String sourceType = sourceDto.getSourceType();
switch (sourceType) {
case JdbcConstants.ELASTIC_SEARCH_SQL:
return 0;
case JdbcConstants.MYSQL:
return mysqlTotal(sourceDto, dto);
default:
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_TYPE_DOES_NOT_MATCH_TEMPORARILY);
}
/**
* 获取mysql count 和添加limit分页信息
* @param sourceDto
* @param dto
* @return
*/
public long mysqlTotal(DataSourceDto sourceDto, DataSetDto dto) {
String dynSentence = sourceDto.getDynSentence();
String sql = "select count(1) as count from (" + dynSentence + ") as gaeaExecute";
sourceDto.setDynSentence(sql);
List<JSONObject> result = execute(sourceDto);
}
// sql 拼接 limit 分页信息
int pageNumber = Integer.parseInt(dto.getContextData().getOrDefault("pageNumber", "1").toString());
int pageSize = Integer.parseInt(dto.getContextData().getOrDefault("pageSize", "10").toString());
String sqlLimit = " limit " + (pageNumber - 1) * pageSize + "," + pageSize;
sourceDto.setDynSentence(dynSentence.concat(sqlLimit));
log.info("当前total:{}, 添加分页参数,sql语句:{}", JSONObject.toJSONString(result), sourceDto.getDynSentence());
return result.get(0).getLongValue("count");
}
/**
* 获取mysql count 和添加limit分页信息
* @param sourceDto
* @param dto
* @return
*/
public long mysqlTotal(DataSourceDto sourceDto, DataSetDto dto){
String dynSentence = sourceDto.getDynSentence();
String sql = "select count(1) as count from (" + dynSentence + ") as gaeaExecute";
sourceDto.setDynSentence(sql);
List<JSONObject> result = execute(sourceDto);
public List<JSONObject> executeElasticsearchSql(DataSourceDto dto) {
analysisHttpConfig(dto);
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(dto.getDynSentence(), headers);
ResponseEntity<JSONObject> exchange;
try {
exchange = restTemplate.exchange(dto.getApiUrl(), HttpMethod.valueOf(dto.getMethod()), entity,
JSONObject.class);
}
catch (Exception e) {
log.error("error", e);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
List<JSONObject> result;
try {
JSONObject body = exchange.getBody();
// 解析es sql数据
if (null == body) {
return null;
}
JSONArray columns = body.getJSONArray("columns");
JSONArray rows = body.getJSONArray("rows");
result = new ArrayList<>();
for (int i = 0; i < rows.size(); i++) {
JSONArray row = rows.getJSONArray(i);
JSONObject jsonObject = new JSONObject();
for (int j = 0; j < row.size(); j++) {
String name = columns.getJSONObject(j).getString("name");
String value = row.getString(j);
jsonObject.put(name, value);
}
result.add(jsonObject);
}
}
catch (Exception e) {
log.error("error", e);
throw BusinessExceptionBuilder.build(ResponseCode.ANALYSIS_DATA_ERROR, e.getMessage());
}
return result;
}
//sql 拼接 limit 分页信息
int pageNumber = Integer.parseInt(dto.getContextData().getOrDefault("pageNumber", "1").toString());
int pageSize = Integer.parseInt(dto.getContextData().getOrDefault("pageSize", "10").toString());
String sqlLimit = " limit " + (pageNumber - 1) * pageSize + "," + pageSize;
sourceDto.setDynSentence(dynSentence.concat(sqlLimit));
log.info("当前total:{}, 添加分页参数,sql语句:{}", JSONObject.toJSONString(result), sourceDto.getDynSentence());
return result.get(0).getLongValue("count");
}
public List<JSONObject> executeRelationalDb(DataSourceDto dto) {
analysisRelationalDbConfig(dto);
Connection pooledConnection = null;
try {
pooledConnection = jdbcService.getPooledConnection(dto);
PreparedStatement statement = pooledConnection.prepareStatement(dto.getDynSentence());
ResultSet rs = statement.executeQuery();
int columnCount = rs.getMetaData().getColumnCount();
public List<JSONObject> executeElasticsearchSql(DataSourceDto dto) {
analysisHttpConfig(dto);
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(dto.getDynSentence(), headers);
ResponseEntity<JSONObject> exchange;
try {
exchange = restTemplate.exchange(dto.getApiUrl(), HttpMethod.valueOf(dto.getMethod()), entity, JSONObject.class);
} catch (Exception e) {
log.error("error",e);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
List<JSONObject> result;
try {
JSONObject body = exchange.getBody();
//解析es sql数据
if (null == body) {
return null;
}
JSONArray columns = body.getJSONArray("columns");
JSONArray rows = body.getJSONArray("rows");
result = new ArrayList<>();
for (int i = 0; i < rows.size(); i++) {
JSONArray row = rows.getJSONArray(i);
JSONObject jsonObject = new JSONObject();
for (int j = 0; j < row.size(); j++) {
String name = columns.getJSONObject(j).getString("name");
String value = row.getString(j);
jsonObject.put(name, value);
}
result.add(jsonObject);
}
} catch (Exception e) {
log.error("error",e);
throw BusinessExceptionBuilder.build(ResponseCode.ANALYSIS_DATA_ERROR, e.getMessage());
}
return result;
}
List<String> columns = new ArrayList<>();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnLabel(i);
columns.add(columnName);
}
List<JSONObject> list = new ArrayList<>();
while (rs.next()) {
JSONObject jo = new JSONObject();
columns.forEach(t -> {
try {
Object value = rs.getObject(t);
// 数据类型转换
Object result = dealResult(value);
jo.put(t, result);
}
catch (SQLException throwable) {
log.error("error", throwable);
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_SQL_ERROR, throwable.getMessage());
}
});
list.add(jo);
}
return list;
}
catch (Exception throwable) {
log.error("error", throwable);
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_SQL_ERROR, throwable.getMessage());
}
finally {
try {
if (pooledConnection != null) {
pooledConnection.close();
}
}
catch (SQLException throwable) {
log.error("error", throwable);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED,
throwable.getMessage());
}
}
}
public List<JSONObject> executeRelationalDb(DataSourceDto dto) {
analysisRelationalDbConfig(dto);
Connection pooledConnection = null;
try {
pooledConnection = jdbcService.getPooledConnection(dto);
/**
* 解决sql返回值 类型问题 (through reference chain:
* java.util.HashMap["pageData"]->java.util.ArrayList[0]->java.util.HashMap["UPDATE_TIME"]->oracle.sql.TIMESTAMP["stream"])
* @param result
* @return
* @throws SQLException
*/
private Object dealResult(Object result) throws SQLException {
if (null == result) {
return result;
}
String type = result.getClass().getName();
if ("oracle.sql.TIMESTAMP".equals(type)) {
// oracle.sql.TIMESTAMP处理逻辑
return new Date((Long) JSONObject.toJSON(result));
}
PreparedStatement statement = pooledConnection.prepareStatement(dto.getDynSentence());
ResultSet rs = statement.executeQuery();
return result;
}
int columnCount = rs.getMetaData().getColumnCount();
/**
* http 执行获取数据
* @param dto
*/
public List<JSONObject> executeHttp(DataSourceDto dto) {
analysisHttpConfig(dto);
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(dto.getDynSentence(), headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(dto.getApiUrl(), HttpMethod.valueOf(dto.getMethod()), entity,
Object.class);
}
catch (Exception e) {
log.error("error", e);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
Object body = exchange.getBody();
String jsonStr = JSONObject.toJSONString(body);
List<JSONObject> result = new ArrayList<>();
if (jsonStr.trim().startsWith(BusinessConstant.LEFT_BIG_BOAST)
&& jsonStr.trim().endsWith(BusinessConstant.RIGTH_BIG_BOAST)) {
// JSONObject
result.add(JSONObject.parseObject(jsonStr));
}
else if (jsonStr.trim().startsWith(BusinessConstant.LEFT_MIDDLE_BOAST)
&& jsonStr.trim().endsWith(BusinessConstant.RIGHT_MIDDLE_BOAST)) {
// List
result = JSONArray.parseArray(jsonStr, JSONObject.class);
}
else {
result.add(new JSONObject());
}
return result;
}
List<String> columns = new ArrayList<>();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnLabel(i);
columns.add(columnName);
}
List<JSONObject> list = new ArrayList<>();
while (rs.next()) {
JSONObject jo = new JSONObject();
columns.forEach(t -> {
try {
Object value = rs.getObject(t);
//数据类型转换
Object result = dealResult(value);
jo.put(t, result);
} catch (SQLException throwable) {
log.error("error",throwable);
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_SQL_ERROR, throwable.getMessage());
}
});
list.add(jo);
}
return list;
} catch (Exception throwable) {
log.error("error",throwable);
throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_SQL_ERROR, throwable.getMessage());
} finally {
try {
if (pooledConnection != null) {
pooledConnection.close();
}
} catch (SQLException throwable) {
log.error("error",throwable);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, throwable.getMessage());
}
}
}
/**
* 关系型数据库 测试连接
* @param dto
*/
public void testRelationalDb(DataSourceDto dto) {
analysisRelationalDbConfig(dto);
try {
Connection unPooledConnection = jdbcService.getUnPooledConnection(dto);
String catalog = unPooledConnection.getCatalog();
log.info("数据库测试连接成功:{}", catalog);
unPooledConnection.close();
}
catch (SQLException e) {
log.error("error", e);
if (e.getCause() instanceof ClassNotFoundException) {
throw BusinessExceptionBuilder.build(ResponseCode.CLASS_NOT_FOUND, e.getCause().getMessage());
}
else {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
/**
* 解决sql返回值 类型问题
* (through reference chain: java.util.HashMap["pageData"]->java.util.ArrayList[0]->java.util.HashMap["UPDATE_TIME"]->oracle.sql.TIMESTAMP["stream"])
* @param result
* @return
* @throws SQLException
*/
private Object dealResult(Object result) throws SQLException {
if (null == result) {
return result;
}
String type = result.getClass().getName();
if ("oracle.sql.TIMESTAMP".equals(type)) {
//oracle.sql.TIMESTAMP处理逻辑
return new Date((Long) JSONObject.toJSON(result));
}
}
}
return result;
}
/**
* http 测试连接
* @param dto
*/
public void testHttp(DataSourceDto dto) {
analysisHttpConfig(dto);
String apiUrl = dto.getApiUrl();
String method = dto.getMethod();
String body = dto.getBody();
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(body, headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(apiUrl, HttpMethod.valueOf(method), entity, Object.class);
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
}
catch (RestClientException e) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
}
/**
* http 执行获取数据
*
* @param dto
*/
public List<JSONObject> executeHttp(DataSourceDto dto) {
analysisHttpConfig(dto);
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(dto.getDynSentence(), headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(dto.getApiUrl(), HttpMethod.valueOf(dto.getMethod()), entity, Object.class);
} catch (Exception e) {
log.error("error",e);
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
Object body = exchange.getBody();
String jsonStr = JSONObject.toJSONString(body);
List<JSONObject> result = new ArrayList<>();
if (jsonStr.trim().startsWith(BusinessConstant.LEFT_BIG_BOAST) && jsonStr.trim().endsWith(BusinessConstant.RIGTH_BIG_BOAST)) {
//JSONObject
result.add(JSONObject.parseObject(jsonStr));
} else if (jsonStr.trim().startsWith(BusinessConstant.LEFT_MIDDLE_BOAST) && jsonStr.trim().endsWith(BusinessConstant.RIGHT_MIDDLE_BOAST)) {
//List
result = JSONArray.parseArray(jsonStr, JSONObject.class);
} else {
result.add(new JSONObject());
}
return result;
}
/**
* 关系型数据库 测试连接
* @param dto
*/
public void testElasticsearchSqlConnection(DataSourceDto dto) {
analysisHttpConfig(dto);
String apiUrl = dto.getApiUrl();
String method = dto.getMethod();
String body = dto.getBody();
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(body, headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(apiUrl, HttpMethod.valueOf(method), entity, Object.class);
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
}
catch (RestClientException e) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
/**
* 关系型数据库 测试连接
*
* @param dto
*/
public void testRelationalDb(DataSourceDto dto) {
analysisRelationalDbConfig(dto);
try {
Connection unPooledConnection = jdbcService.getUnPooledConnection(dto);
String catalog = unPooledConnection.getCatalog();
log.info("数据库测试连接成功:{}", catalog);
unPooledConnection.close();
} catch (SQLException e) {
log.error("error",e);
if (e.getCause() instanceof ClassNotFoundException) {
throw BusinessExceptionBuilder.build(ResponseCode.CLASS_NOT_FOUND, e.getCause().getMessage());
} else {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
}
}
}
public void analysisRelationalDbConfig(DataSourceDto dto) {
JSONObject json = JSONObject.parseObject(dto.getSourceConfig());
GaeaAssert.isFalse(json.containsKey("jdbcUrl"), ResponseCode.PARAM_IS_NULL, "jdbcUrl not empty");
GaeaAssert.isFalse(json.containsKey("driverName"), ResponseCode.PARAM_IS_NULL, "driverName not empty");
String jdbcUrl = json.getString("jdbcUrl");
String username = json.getString("username");
String password = json.getString("password");
String driverName = json.getString("driverName");
dto.setJdbcUrl(jdbcUrl);
dto.setDriverName(driverName);
dto.setUsername(username);
dto.setPassword(password);
}
/**
* http 测试连接
*
* @param dto
*/
public void testHttp(DataSourceDto dto) {
analysisHttpConfig(dto);
String apiUrl = dto.getApiUrl();
String method = dto.getMethod();
String body = dto.getBody();
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(body, headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(apiUrl, HttpMethod.valueOf(method), entity, Object.class);
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
} catch (RestClientException e) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
}
/**
* es通过api获取数据
* @param dto
* @return
*/
public void analysisHttpConfig(DataSourceDto dto) {
JSONObject json = JSONObject.parseObject(dto.getSourceConfig());
GaeaAssert.isFalse(json.containsKey("apiUrl"), ResponseCode.PARAM_IS_NULL, "apiUrl not empty");
GaeaAssert.isFalse(json.containsKey("method"), ResponseCode.PARAM_IS_NULL, "method not empty");
GaeaAssert.isFalse(json.containsKey("header"), ResponseCode.PARAM_IS_NULL, "header not empty");
GaeaAssert.isFalse(json.containsKey("body"), ResponseCode.PARAM_IS_NULL, "body not empty");
String apiUrl = json.getString("apiUrl");
String method = json.getString("method");
String header = json.getString("header");
String body = json.getString("body");
// 解决url中存在的动态参数
apiUrl = dataSetParamService.transform(dto.getContextData(), apiUrl);
// 请求头中动态参数
header = dataSetParamService.transform(dto.getContextData(), header);
dto.setApiUrl(apiUrl);
dto.setMethod(method);
dto.setHeader(header);
dto.setBody(body);
}
/**
* 操作后续处理
* @param entity
* @param operationEnum 操作类型
* @throws BusinessException 阻止程序继续执行或回滚事务
*/
@Override
public void processAfterOperation(DataSource entity, BaseOperationEnum operationEnum) throws BusinessException {
jdbcService.removeJdbcConnectionPool(entity.getId());
}
/**
* 关系型数据库 测试连接
*
* @param dto
*/
public void testElasticsearchSqlConnection(DataSourceDto dto) {
analysisHttpConfig(dto);
String apiUrl = dto.getApiUrl();
String method = dto.getMethod();
String body = dto.getBody();
HttpHeaders headers = new HttpHeaders();
headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class));
HttpEntity<String> entity = new HttpEntity<>(body, headers);
ResponseEntity<Object> exchange;
try {
exchange = restTemplate.exchange(apiUrl, HttpMethod.valueOf(method), entity, Object.class);
if (exchange.getStatusCode().isError()) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, exchange.getBody());
}
} catch (RestClientException e) {
throw BusinessExceptionBuilder.build(ResponseCode.DATA_SOURCE_CONNECTION_FAILED, e.getMessage());
}
}
public void analysisRelationalDbConfig(DataSourceDto dto) {
JSONObject json = JSONObject.parseObject(dto.getSourceConfig());
GaeaAssert.isFalse(json.containsKey("jdbcUrl"), ResponseCode.PARAM_IS_NULL,"jdbcUrl not empty");
GaeaAssert.isFalse(json.containsKey("driverName"), ResponseCode.PARAM_IS_NULL,"driverName not empty");
String jdbcUrl = json.getString("jdbcUrl");
String username = json.getString("username");
String password = json.getString("password");
String driverName = json.getString("driverName");
dto.setJdbcUrl(jdbcUrl);
dto.setDriverName(driverName);
dto.setUsername(username);
dto.setPassword(password);
}
/**
* es通过api获取数据
*
* @param dto
* @return
*/
public void analysisHttpConfig(DataSourceDto dto) {
JSONObject json = JSONObject.parseObject(dto.getSourceConfig());
GaeaAssert.isFalse(json.containsKey("apiUrl"), ResponseCode.PARAM_IS_NULL,"apiUrl not empty");
GaeaAssert.isFalse(json.containsKey("method"), ResponseCode.PARAM_IS_NULL,"method not empty");
GaeaAssert.isFalse(json.containsKey("header"), ResponseCode.PARAM_IS_NULL,"header not empty");
GaeaAssert.isFalse(json.containsKey("body"), ResponseCode.PARAM_IS_NULL,"body not empty");
String apiUrl = json.getString("apiUrl");
String method = json.getString("method");
String header = json.getString("header");
String body = json.getString("body");
//解决url中存在的动态参数
apiUrl = dataSetParamService.transform(dto.getContextData(), apiUrl);
//请求头中动态参数
header = dataSetParamService.transform(dto.getContextData(), header);
dto.setApiUrl(apiUrl);
dto.setMethod(method);
dto.setHeader(header);
dto.setBody(body);
}
/**
* 操作后续处理
*
* @param entity
* @param operationEnum 操作类型
* @throws BusinessException 阻止程序继续执行或回滚事务
*/
@Override
public void processAfterOperation(DataSource entity, BaseOperationEnum operationEnum) throws BusinessException {
jdbcService.removeJdbcConnectionPool(entity.getId());
}
}
@@ -20,77 +20,77 @@ import java.util.concurrent.ConcurrentHashMap;
@Slf4j
public class JdbcServiceImpl implements JdbcService {
@Autowired
private DruidProperties druidProperties;
@Autowired
private DruidProperties druidProperties;
/**
* 所有数据源的连接池存在map里
*/
static Map<Long, DruidDataSource> map = new ConcurrentHashMap<>();
/**
* 所有数据源的连接池存在map里
*/
static Map<Long, DruidDataSource> map = new ConcurrentHashMap<>();
public DruidDataSource getJdbcConnectionPool(DataSourceDto dataSource) {
if (map.containsKey(dataSource.getId())) {
return map.get(dataSource.getId());
}
else {
try {
if (!map.containsKey(dataSource.getId())) {
DruidDataSource pool = druidProperties.dataSource(dataSource.getJdbcUrl(), dataSource.getUsername(),
dataSource.getPassword(), dataSource.getDriverName());
map.put(dataSource.getId(), pool);
log.info("创建连接池成功:{}", dataSource.getJdbcUrl());
}
return map.get(dataSource.getId());
}
finally {
}
}
}
public DruidDataSource getJdbcConnectionPool(DataSourceDto dataSource) {
if (map.containsKey(dataSource.getId())) {
return map.get(dataSource.getId());
} else {
try {
if (!map.containsKey(dataSource.getId())) {
DruidDataSource pool = druidProperties.dataSource(dataSource.getJdbcUrl(),
dataSource.getUsername(), dataSource.getPassword(), dataSource.getDriverName());
map.put(dataSource.getId(), pool);
log.info("创建连接池成功:{}", dataSource.getJdbcUrl());
}
return map.get(dataSource.getId());
} finally {
}
}
}
/**
* 删除数据库连接池
* @param id
*/
@Override
public void removeJdbcConnectionPool(Long id) {
try {
DruidDataSource pool = map.get(id);
if (pool != null) {
log.info("remove pool success, datasourceId:{}", id);
map.remove(id);
}
}
catch (Exception e) {
log.error("error", e);
}
finally {
}
}
/**
* 获取连接
* @param dataSource
* @return
* @throws SQLException
*/
@Override
public Connection getPooledConnection(DataSourceDto dataSource) throws SQLException {
DruidDataSource pool = getJdbcConnectionPool(dataSource);
return pool.getConnection();
}
/**
* 删除数据库连接池
*
* @param id
*/
@Override
public void removeJdbcConnectionPool(Long id) {
try {
DruidDataSource pool = map.get(id);
if (pool != null) {
log.info("remove pool success, datasourceId:{}", id);
map.remove(id);
}
} catch (Exception e) {
log.error("error", e);
} finally {
}
}
/**
* 测试数据库连接 获取一个连接
* @param dataSource
* @return
* @throws ClassNotFoundException driverName不正确
* @throws SQLException
*/
@Override
public Connection getUnPooledConnection(DataSourceDto dataSource) throws SQLException {
DruidDataSource druidDataSource = druidProperties.dataSource(dataSource.getJdbcUrl(), dataSource.getUsername(),
dataSource.getPassword(), dataSource.getDriverName());
return druidDataSource.getConnection();
}
/**
* 获取连接
*
* @param dataSource
* @return
* @throws SQLException
*/
@Override
public Connection getPooledConnection(DataSourceDto dataSource) throws SQLException{
DruidDataSource pool = getJdbcConnectionPool(dataSource);
return pool.getConnection();
}
/**
* 测试数据库连接 获取一个连接
*
* @param dataSource
* @return
* @throws ClassNotFoundException driverName不正确
* @throws SQLException
*/
@Override
public Connection getUnPooledConnection(DataSourceDto dataSource) throws SQLException {
DruidDataSource druidDataSource = druidProperties.dataSource(dataSource.getJdbcUrl(),
dataSource.getUsername(), dataSource.getPassword(), dataSource.getDriverName());
return druidDataSource.getConnection();
}
}
@@ -15,10 +15,7 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.*;
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.*;
/**
* (GaeaDict)实体类
@@ -31,89 +28,89 @@ import java.util.Map;
@Api(value = "/gaeaDict", tags = "")
public class GaeaDictController extends GaeaBaseController<GaeaDictParam, GaeaDict, GaeaDictDTO> {
@Autowired
private GaeaDictService gaeaDictService;
@Autowired
private GaeaDictService gaeaDictService;
@Autowired
private GaeaDictItemService gaeaDictItemService;
@Autowired
private GaeaDictItemService gaeaDictItemService;
@Override
public GaeaBaseService<GaeaDictParam, GaeaDict> getService() {
return gaeaDictService;
}
@Override
public GaeaBaseService<GaeaDictParam, GaeaDict> getService() {
return gaeaDictService;
}
@Override
public GaeaDict getEntity() {
return new GaeaDict();
}
@Override
public GaeaDict getEntity() {
return new GaeaDict();
}
@Override
public GaeaDictDTO getDTO() {
return new GaeaDictDTO();
}
@Override
public GaeaDictDTO getDTO() {
return new GaeaDictDTO();
}
/**
* 刷新指定字典项
* @return
*/
@PostMapping("/freshDict")
@Permission(code = "fresh", name = "刷新")
public ResponseBean refreshDict(@RequestBody List<String> dictCodes) {
// 刷新
gaeaDictService.refreshCache(dictCodes);
return responseSuccess();
}
/**
* 下拉菜单
* @return
*/
@GetMapping("/select/{dictCode}")
@Permission(code = "query", name = "下拉")
public ResponseBean select(@PathVariable("dictCode") String dictName) {
Locale locale = LocaleContextHolder.getLocale();
// 语言
String language = locale.getLanguage();
/**
* 刷新指定字典项
* @return
*/
@PostMapping("/freshDict")
@Permission(code = "fresh",name = "刷新")
public ResponseBean refreshDict(@RequestBody List<String> dictCodes) {
//刷新
gaeaDictService.refreshCache(dictCodes);
return responseSuccess();
}
List<KeyValue> keyValues = gaeaDictService.select(dictName, language);
return responseSuccessWithData(keyValues);
}
/**
* 下拉菜单
* @return
*/
@GetMapping("/select/{dictCode}")
@Permission(code = "query",name = "下拉")
public ResponseBean select(@PathVariable("dictCode") String dictName){
Locale locale = LocaleContextHolder.getLocale();
//语言
String language = locale.getLanguage();
/**
* 指定语言的字典项
* @return
*/
@GetMapping("/map/{dictCode}")
public ResponseBean dictItemByLang(@PathVariable("dictCode") String dictCode) {
return responseSuccessWithData(gaeaDictItemService.getItemMap(dictCode));
}
List<KeyValue> keyValues = gaeaDictService.select(dictName,language);
return responseSuccessWithData(keyValues);
}
/**
* 下拉菜单
* @return
*/
@GetMapping("/selectAll/{project}")
public ResponseBean selectTypecodes(@PathVariable String project) {
Locale locale = LocaleContextHolder.getLocale();
// 语言
String language = locale.getLanguage();
Collection<KeyValue> keyValues = gaeaDictService.selectTypeCode(project, language);
return responseSuccessWithData(keyValues);
}
/**
* 指定语言的字典项
* @return
*/
@GetMapping("/map/{dictCode}")
public ResponseBean dictItemByLang(@PathVariable("dictCode") String dictCode){
return responseSuccessWithData(gaeaDictItemService.getItemMap(dictCode));
}
/**
* 下拉菜单
* @return
*/
@GetMapping("/selectAll/{project}")
public ResponseBean selectTypecodes(@PathVariable String project){
Locale locale = LocaleContextHolder.getLocale();
//语言
String language = locale.getLanguage();
/**
* 获取所有字典
* @return
*/
@GetMapping("/all")
public ResponseBean all() {
Locale locale = LocaleContextHolder.getLocale();
// 语言
String language = locale.getLanguage();
Collection<KeyValue> keyValues = gaeaDictService.selectTypeCode(project,language);
return responseSuccessWithData(keyValues);
}
Map<String, List<KeyValue>> all = gaeaDictService.all(language);
return responseSuccessWithData(all);
}
/**
* 获取所有字典
* @return
*/
@GetMapping("/all")
public ResponseBean all(){
Locale locale = LocaleContextHolder.getLocale();
//语言
String language = locale.getLanguage();
Map<String, List<KeyValue>> all = gaeaDictService.all(language);
return responseSuccessWithData(all);
}
}
@@ -1,15 +1,15 @@
package com.anjiplus.template.gaea.business.modules.dict.controller;
import com.anji.plus.gaea.curd.controller.GaeaBaseController;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem;
import com.anjiplus.template.gaea.business.modules.dict.controller.dto.GaeaDictItemDTO;
import com.anjiplus.template.gaea.business.modules.dict.controller.param.GaeaDictItemParam;
import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem;
import com.anjiplus.template.gaea.business.modules.dict.service.GaeaDictItemService;
import com.anji.plus.gaea.curd.service.GaeaBaseService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
/**
* 数据字典项(GaeaDictItem)实体类
@@ -21,23 +21,21 @@ import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/gaeaDictItem")
@Api(value = "/gaeaDictItem", tags = "数据字典项")
public class GaeaDictItemController extends GaeaBaseController<GaeaDictItemParam, GaeaDictItem, GaeaDictItemDTO> {
@Autowired
private GaeaDictItemService gaeaDictItemService;
@Override
public GaeaBaseService<GaeaDictItemParam, GaeaDictItem> getService() {
return gaeaDictItemService;
}
@Autowired
private GaeaDictItemService gaeaDictItemService;
@Override
public GaeaDictItem getEntity() {
return new GaeaDictItem();
}
@Override
public GaeaBaseService<GaeaDictItemParam, GaeaDictItem> getService() {
return gaeaDictItemService;
}
@Override
public GaeaDictItem getEntity() {
return new GaeaDictItem();
}
@Override
public GaeaDictItemDTO getDTO() {
return new GaeaDictItemDTO();
}
}
@Override
public GaeaDictItemDTO getDTO() {
return new GaeaDictItemDTO();
}
}
@@ -16,23 +16,21 @@ import java.io.Serializable;
@ApiModel(value = "")
@Data
public class GaeaDictDTO extends GaeaBaseDTO implements Serializable {
/**
* 字典名称
*/
@ApiModelProperty(value = "字典名称")
private String dictName;
/**
* 字典编号
*/
@ApiModelProperty(value = "字典编号")
private String dictCode;
/**
* 字典描述
*/
@ApiModelProperty(value = "字典描述")
private String remark;
/**
* 字典名称
*/
@ApiModelProperty(value = "字典名称")
private String dictName;
/**
* 字典编号
*/
@ApiModelProperty(value = "字典编号")
private String dictCode;
/**
* 字典描述
*/
@ApiModelProperty(value = "字典描述")
private String remark;
}
@@ -16,52 +16,45 @@ import java.io.Serializable;
@ApiModel(value = "数据字典项")
@Data
public class GaeaDictItemDTO extends GaeaBaseDTO implements Serializable {
/**
* 数据字典编码
*/
@ApiModelProperty(value = "数据字典编码")
private String dictCode;
/**
* 字典项名称
*/
@ApiModelProperty(value = "字典项名称")
private String itemName;
/**
* 字典项值
*/
@ApiModelProperty(value = "字典项值")
private String itemValue;
/**
* 数据字典编码
*/
@ApiModelProperty(value = "数据字典编码")
private String dictCode;
/**
* 字典项名称
*/
@ApiModelProperty(value = "字典项名称")
private String itemName;
/**
* 字典项值
*/
@ApiModelProperty(value = "字典项值")
private String itemValue;
/**
* 字典项扩展
*/
@ApiModelProperty(value = "字典项扩展")
private String itemExtend;
/**
* 语言标识
*/
@ApiModelProperty(value = "语言标识")
private String locale;
/**
* 描述
*/
@ApiModelProperty(value = "描述")
private String remark;
/**
* 排序
*/
@ApiModelProperty(value = "排序")
private Integer sort;
/**
* 1:启用,0:禁用
*/
private Integer enabled;
/**
* 字典项扩展
*/
@ApiModelProperty(value = "字典项扩展")
private String itemExtend;
/**
* 语言标识
*/
@ApiModelProperty(value = "语言标识")
private String locale;
/**
* 描述
*/
@ApiModelProperty(value = "描述")
private String remark;
/**
* 排序
*/
@ApiModelProperty(value = "排序")
private Integer sort;
/**
* 1:启用,0:禁用
*/
private Integer enabled;
}
@@ -1,5 +1,6 @@
package com.anjiplus.template.gaea.business.modules.dict.controller.param;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
@@ -16,25 +17,23 @@ import java.io.Serializable;
@Data
public class GaeaDictItemParam extends PageParam implements Serializable {
/**
* 数据字典编码
*/
private String dictCode;
/**
* 数据字典编码
*/
private String dictCode;
/**
* 字典项名称
*/
@Query(QueryEnum.LIKE)
private String itemName;
/**
* 字典项名称
*/
@Query(QueryEnum.LIKE)
private String itemName;
/**
* 语言标识
*/
private String locale;
/**
* 1:启用,0:禁用
*/
private Integer enabled;
/**
* 语言标识
*/
private String locale;
/**
* 1:启用,0:禁用
*/
private Integer enabled;
}
@@ -1,5 +1,6 @@
package com.anjiplus.template.gaea.business.modules.dict.controller.param;
import com.anji.plus.gaea.annotation.Query;
import com.anji.plus.gaea.constant.QueryEnum;
import com.anji.plus.gaea.curd.params.PageParam;
@@ -15,17 +16,14 @@ import java.io.Serializable;
*/
@Data
public class GaeaDictParam extends PageParam implements Serializable {
/**
* 字典名称
*/
@Query(QueryEnum.LIKE)
private String dictName;
/**
* 字典编号
*/
@Query(QueryEnum.LIKE)
private String dictCode;
/**
* 字典名称
*/
@Query(QueryEnum.LIKE)
private String dictName;
/**
* 字典编号
*/
@Query(QueryEnum.LIKE)
private String dictCode;
}
@@ -1,7 +1,7 @@
package com.anjiplus.template.gaea.business.modules.dict.dao;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem;
import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper;
import org.apache.ibatis.annotations.Mapper;
/**
@@ -13,4 +13,5 @@ import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface GaeaDictItemMapper extends GaeaBaseMapper<GaeaDictItem> {
}
}
Loaded 100 of 211 files, more files were not shown because too many files have changed in this diff. Show more