diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/filter/CorsFilter.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/filter/CorsFilter.java index 243a7fd02..0f75d2311 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/filter/CorsFilter.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/filter/CorsFilter.java @@ -16,28 +16,29 @@ 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 destroy() { + } + + @Override + public void init(FilterConfig filterConfig) throws ServletException { + } - @Override - public void init(FilterConfig filterConfig) throws ServletException { - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/AccessAuthorityController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/AccessAuthorityController.java index 6da7ba073..36c34ed52 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/AccessAuthorityController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/AccessAuthorityController.java @@ -2,66 +2,63 @@ 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.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 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.context.i18n.LocaleContextHolder; -import org.springframework.web.bind.annotation.*; +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 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 java.util.List; -import java.util.Locale; -import java.util.Map; /** -* @desc 权限管理 controller -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * @desc 权限管理 controller + * @author 木子李·De + * @date 2019-02-17 08:50:10.009 + **/ @RestController @Api(tags = "权限管理管理") @RequestMapping("/accessAuthority") @Permission(code = "authorityManage", name = "权限管理") -public class AccessAuthorityController extends GaeaBaseController { +public class AccessAuthorityController + extends GaeaBaseController { - @Autowired - private AccessAuthorityService accessAuthorityService; + @Autowired + private AccessAuthorityService accessAuthorityService; - @Override - public GaeaBaseService getService() { - return accessAuthorityService; - } + @Override + public GaeaBaseService 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 parentTreeList = accessAuthorityService.getAuthorityTree(username, false); - return responseSuccessWithData(parentTreeList); - } -} \ No newline at end of file + /** + * 获取一二级菜单 + * @return + */ + @Permission(code = "query", name = "查询") + @GetMapping("/menuTree") + public ResponseBean menuTree() { + String username = UserContentHolder.getContext().getUsername(); + List parentTreeList = accessAuthorityService.getAuthorityTree(username, false); + return responseSuccessWithData(parentTreeList); + } + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/dto/AccessAuthorityDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/dto/AccessAuthorityDto.java index 77cc98f55..ad736a28a 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/dto/AccessAuthorityDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/dto/AccessAuthorityDto.java @@ -1,58 +1,56 @@ package com.anjiplus.template.gaea.business.modules.accessauthority.controller.dto; -import java.io.Serializable; -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; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; + /** -* -* @description 权限管理 dto -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * @description 权限管理 dto + * @author 木子李·De + * @date 2019-02-17 08:50:10.009 + **/ @Data public class AccessAuthorityDto extends GaeaBaseDTO implements Serializable { - /** 父菜单代码 */ - @ApiModelProperty(value = "父菜单代码") - private String parentTarget; - /** 目标菜单 */ - @ApiModelProperty(value = "菜单代码") - @NotEmpty(message = "6002") - private String target; + /** 父菜单代码 */ + @ApiModelProperty(value = "父菜单代码") + private String parentTarget; - /** 目标菜单名称 */ - @ApiModelProperty(value = "菜单名称") - @NotEmpty(message = "6002") - private String targetName; + /** 目标菜单 */ + @ApiModelProperty(value = "菜单代码") + @NotEmpty(message = "6002") + private String target; - /** 目标按钮 */ - @ApiModelProperty(value = "按钮代码") - @NotEmpty(message = "6002") - private String action; + /** 目标菜单名称 */ + @ApiModelProperty(value = "菜单名称") + @NotEmpty(message = "6002") + private String targetName; - /** 目标按钮名称 */ - @ApiModelProperty(value = "按钮名称") - @NotEmpty(message = "6002") - private String actionName; + /** 目标按钮 */ + @ApiModelProperty(value = "按钮代码") + @NotEmpty(message = "6002") + private String action; - /** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */ - @ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG") - private Integer deleteFlag; + /** 目标按钮名称 */ + @ApiModelProperty(value = "按钮名称") + @NotEmpty(message = "6002") + private String actionName; - /** 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; - @ApiModelProperty(value = "sort") - private Integer sort; -} \ No newline at end of file + /** 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; + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/param/AccessAuthorityParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/param/AccessAuthorityParam.java index 344a14c92..95b84a7e4 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/param/AccessAuthorityParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/controller/param/AccessAuthorityParam.java @@ -1,44 +1,43 @@ /**/ 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 java.util.List; +import lombok.Data; -import java.util.Date; +import java.io.Serializable; /** -* @desc AccessAuthority 权限管理查询输入类 -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * @desc AccessAuthority 权限管理查询输入类 + * @author 木子李·De + * @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; -} \ No newline at end of file + // 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG + @Query + private Integer enableFlag; + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/AccessAuthorityMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/AccessAuthorityMapper.java index 9395dd29c..3b8c8d58e 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/AccessAuthorityMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/AccessAuthorityMapper.java @@ -1,17 +1,16 @@ 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 java.util.List; +import org.apache.ibatis.annotations.Mapper; /** -* AccessAuthority Mapper -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * AccessAuthority Mapper + * + * @author 木子李·De + * @date 2019-02-17 08:50:10.009 + **/ @Mapper public interface AccessAuthorityMapper extends GaeaBaseMapper { -} \ No newline at end of file +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/entity/AccessAuthority.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/entity/AccessAuthority.java index 1d04d89f7..15392054b 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/entity/AccessAuthority.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/dao/entity/AccessAuthority.java @@ -1,43 +1,40 @@ 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 javax.validation.constraints.*; -import java.util.Date; +import lombok.Data; + /** -* @description 权限管理 entity -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ -@TableName(keepGlobalPrefix=true, value="access_authority") + * @description 权限管理 entity + * @author 木子李·De + * @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 target; + /** 父菜单代码 */ + private String parentTarget; - /** 菜单名称 */ - private String targetName; + /** 菜单代码 */ + private String target; - /** 按钮代码 */ - private String action; + /** 菜单名称 */ + private String targetName; - /** 按钮名称 */ - private String actionName; + /** 按钮代码 */ + private String action; - /** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */ - private Integer deleteFlag; + /** 按钮名称 */ + private String actionName; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; - - private Integer sort; + /** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */ + private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; + private Integer sort; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/AccessAuthorityService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/AccessAuthorityService.java index 0e3e0238e..d44b83d60 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/AccessAuthorityService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/AccessAuthorityService.java @@ -2,28 +2,29 @@ package com.anjiplus.template.gaea.business.modules.accessauthority.service; import com.anji.plus.gaea.bean.TreeNode; -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 com.anjiplus.template.gaea.business.modules.accessauthority.controller.param.AccessAuthorityParam; +import com.anjiplus.template.gaea.business.modules.accessauthority.dao.entity.AccessAuthority; import java.util.List; /** -* @desc AccessAuthority 权限管理服务接口 -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * @desc AccessAuthority 权限管理服务接口 + * @author 木子李·De + * @date 2019-02-17 08:50:10.009 + **/ public interface AccessAuthorityService extends GaeaBaseService { - /** - * @param loginName 当前登录的用户名 - * @param withActionNode 带第三层的按钮节点 - * @return - */ - List getAuthorityTree(String loginName, boolean withActionNode); + /** + * @param loginName 当前登录的用户名 + * @param withActionNode 带第三层的按钮节点 + * @return + */ + List getAuthorityTree(String loginName, boolean withActionNode); - /** - * 扫描所有mvc url的需要权限码,建立拦截体系 - */ - void scanGaeaSecurityAuthorities(); -} \ No newline at end of file + /** + * 扫描所有mvc url的需要权限码,建立拦截体系 + */ + void scanGaeaSecurityAuthorities(); + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/impl/AccessAuthorityServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/impl/AccessAuthorityServiceImpl.java index b26186230..b155b32b5 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/impl/AccessAuthorityServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessauthority/service/impl/AccessAuthorityServiceImpl.java @@ -1,16 +1,15 @@ 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; @@ -24,117 +23,116 @@ import java.util.Map; import java.util.stream.Collectors; /** -* @desc AccessAuthority 权限管理服务实现 -* @author 木子李·De -* @date 2019-02-17 08:50:10.009 -**/ + * @desc AccessAuthority 权限管理服务实现 + * @author 木子李·De + * @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 getMapper() { - return accessAuthorityMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return accessAuthorityMapper; + } - @Override - public List getAuthorityTree(String loginName, boolean withActionNode) { - // 查询出所有的菜单记录 - LambdaQueryWrapper 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 accessAuthorityList = getMapper().selectList(wrapper); + @Override + public List getAuthorityTree(String loginName, boolean withActionNode) { + // 查询出所有的菜单记录 + LambdaQueryWrapper 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 accessAuthorityList = getMapper().selectList(wrapper); - // 筛选出一级菜单 - List 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 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> targetActionsMap = accessAuthorityList.stream() - .filter(accessAuthority -> StringUtils.isNoneBlank(accessAuthority.getParentTarget())) - .collect(Collectors.groupingBy(AccessAuthority::getTarget)); + // 菜单-按钮的map + Map> targetActionsMap = accessAuthorityList.stream() + .filter(accessAuthority -> StringUtils.isNoneBlank(accessAuthority.getParentTarget())) + .collect(Collectors.groupingBy(AccessAuthority::getTarget)); - // 设置每个一级菜单的二菜单 - parentNodes.stream().forEach(parentNode -> { - List alreadyTargets = new ArrayList<>(); + // 设置每个一级菜单的二菜单 + parentNodes.stream().forEach(parentNode -> { + List 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 levelTwoMenuNode = new TreeNode(); + levelTwoMenuNode.setId(authority.getTarget()); + levelTwoMenuNode.setLabel(authority.getTargetName()); + levelTwoMenuNode.setChildren(new ArrayList()); - // 初始化二级菜单的按钮 - if(withActionNode){ - List 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 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 children = parentNode.getChildren(); - if(children == null){ - children = new ArrayList(); - } - children.add(levelTwoMenuNode); - parentNode.setChildren(children); + // 将上面找到的二级菜单加入到一菜单的子树中去 + List children = parentNode.getChildren(); + if (children == null) { + children = new ArrayList(); + } + 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 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 requestInfos = initRequestUrlMappings + .getRequestInfos(Enabled.YES.getValue()); - // key="GET#/accessAuthority/menuTree" value="authorityManage:query" - Map securityAuthorityMap = new HashMap(); - requestInfos.stream().forEach(requestInfo -> { - securityAuthorityMap.put(requestInfo.getPath(), requestInfo.getAuthCode()); - }); + // key="GET#/accessAuthority/menuTree" value="authorityManage:query" + Map securityAuthorityMap = new HashMap(); + requestInfos.stream().forEach(requestInfo -> { + securityAuthorityMap.put(requestInfo.getPath(), requestInfo.getAuthCode()); + }); - // 将key存入到缓存中 - cacheHelper.hashSet(BusinessConstant.GAEA_SECURITY_AUTHORITIES, securityAuthorityMap); - } -} \ No newline at end of file + // 将key存入到缓存中 + cacheHelper.hashSet(BusinessConstant.GAEA_SECURITY_AUTHORITIES, securityAuthorityMap); + } + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/AccessRoleController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/AccessRoleController.java index 5614a308a..2cc256104 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/AccessRoleController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/AccessRoleController.java @@ -2,74 +2,70 @@ 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.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 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.service.AccessRoleService; +import io.swagger.annotations.Api; 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 -* @date 2019-02-17 08:50:14.136 -**/ + * @desc 角色管理 controller + * @author 木子李·De + * @date 2019-02-17 08:50:14.136 + **/ @RestController @Api(tags = "角色管理管理") @RequestMapping("/accessRole") @Permission(code = "roleManage", name = "角色管理") public class AccessRoleController extends GaeaBaseController { - @Autowired - private AccessRoleService accessRoleService; + @Autowired + private AccessRoleService accessRoleService; - @Override - public GaeaBaseService getService() { - return accessRoleService; - } + @Override + public GaeaBaseService 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); - } -} \ No newline at end of file + /** + * 保存角色的权限 + * @return + */ + @Permission(code = "grantAuthority", name = "分配权限") + @PostMapping("/saveAuthorityTree") + public ResponseBean saveAuthorityTree(@RequestBody AccessRoleDto dto) { + Boolean data = accessRoleService.saveAuthorityTree(dto); + return responseSuccessWithData(data); + } + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/dto/AccessRoleDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/dto/AccessRoleDto.java index c7e106202..9f5b849e7 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/dto/AccessRoleDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/dto/AccessRoleDto.java @@ -1,46 +1,43 @@ package com.anjiplus.template.gaea.business.modules.accessrole.controller.dto; -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; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.io.Serializable; +import java.util.List; + /** -* -* @description 角色管理 dto -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ + * @description 角色管理 dto + * @author 木子李·De + * @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 authorityList; -} \ No newline at end of file + /** 角色保存的权限 */ + private List authorityList; + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/param/AccessRoleParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/param/AccessRoleParam.java index 5e5d59f66..60642990e 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/param/AccessRoleParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/controller/param/AccessRoleParam.java @@ -1,33 +1,31 @@ /**/ 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 java.util.List; +import lombok.Data; -import java.util.Date; +import java.io.Serializable; /** -* @desc AccessRole 角色管理查询输入类 -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ + * @desc AccessRole 角色管理查询输入类 + * @author 木子李·De + * @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; -} \ No newline at end of file +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleAuthorityMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleAuthorityMapper.java index 7fe9995ef..bf810efa5 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleAuthorityMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleAuthorityMapper.java @@ -5,10 +5,11 @@ import com.anjiplus.template.gaea.business.modules.accessrole.dao.entity.AccessR import org.apache.ibatis.annotations.Mapper; /** -* AccessRoleAuthority Mapper -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ + * AccessRoleAuthority Mapper + * + * @author 木子李·De + * @date 2019-02-17 08:50:14.136 + **/ @Mapper public interface AccessRoleAuthorityMapper extends GaeaBaseMapper { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleMapper.java index 9b78e95a7..c2fc8d55b 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/AccessRoleMapper.java @@ -1,22 +1,21 @@ 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 -* @date 2019-02-17 08:50:14.136 -**/ + * AccessRole Mapper + * + * @author 木子李·De + * @date 2019-02-17 08:50:14.136 + **/ @Mapper public interface AccessRoleMapper extends GaeaBaseMapper { - List checkedAuthoritys(@Param("roleCode")String roleCode); -} \ No newline at end of file + List checkedAuthoritys(@Param("roleCode") String roleCode); + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRole.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRole.java index e8e7b1ae5..165ff4de3 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRole.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRole.java @@ -1,30 +1,29 @@ 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 javax.validation.constraints.*; -import java.util.Date; +import lombok.Data; + /** -* @description 角色管理 entity -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ -@TableName(keepGlobalPrefix=true, value="access_role") + * @description 角色管理 entity + * @author 木子李·De + * @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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRoleAuthority.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRoleAuthority.java index cb20a8f24..31aa551d2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRoleAuthority.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/dao/entity/AccessRoleAuthority.java @@ -1,10 +1,8 @@ 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; @@ -14,31 +12,32 @@ import java.util.Date; * @author 木子李·De * @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 Date updateTime; + + @TableField(exist = false) + private Integer version; - @TableField(exist = false) - private Integer version; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/AccessRoleService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/AccessRoleService.java index 639fd1a25..f4aa02eba 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/AccessRoleService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/AccessRoleService.java @@ -1,34 +1,33 @@ package com.anjiplus.template.gaea.business.modules.accessrole.service; -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.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 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 java.util.Map; /** -* @desc AccessRole 角色管理服务接口 -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ + * @desc AccessRole 角色管理服务接口 + * @author 木子李·De + * @date 2019-02-17 08:50:14.136 + **/ public interface AccessRoleService extends GaeaBaseService { - /** 查询某角色的权限树 - * @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); -} \ No newline at end of file +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/impl/AccessRoleServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/impl/AccessRoleServiceImpl.java index dea1b15af..b0f347732 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/impl/AccessRoleServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessrole/service/impl/AccessRoleServiceImpl.java @@ -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,78 +24,81 @@ import java.util.Map; import java.util.stream.Collectors; /** -* @desc AccessRole 角色管理服务实现 -* @author 木子李·De -* @date 2019-02-17 08:50:14.136 -**/ + * @desc AccessRole 角色管理服务实现 + * @author 木子李·De + * @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 getMapper() { - return accessRoleMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return accessRoleMapper; + } - @Override - public Map getAuthorityTree(String roleCode, String operator) { - Map result = new HashMap(); + @Override + public Map getAuthorityTree(String roleCode, String operator) { + Map result = new HashMap(); - // 菜单按钮树 - List treeData = accessAuthorityService.getAuthorityTree(operator, true); + // 菜单按钮树 + List treeData = accessAuthorityService.getAuthorityTree(operator, true); - // 该角色已选中的菜单及按钮 -// List checkedKeys = accessRoleMapper.checkedAuthoritys(roleCode); + // 该角色已选中的菜单及按钮 + // List checkedKeys = accessRoleMapper.checkedAuthoritys(roleCode); - LambdaQueryWrapper accessRoleAuthorityWrapper = Wrappers.lambdaQuery(); - accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction); - accessRoleAuthorityWrapper.eq(AccessRoleAuthority::getRoleCode, roleCode); - List accessRoleAuthorities = accessRoleAuthorityMapper.selectList(accessRoleAuthorityWrapper); - List checkedKeys = accessRoleAuthorities.stream() - .map(accessRoleAuthority -> accessRoleAuthority.getTarget().concat("_").concat(accessRoleAuthority.getAction())).distinct().collect(Collectors.toList()); + LambdaQueryWrapper accessRoleAuthorityWrapper = Wrappers.lambdaQuery(); + accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction); + accessRoleAuthorityWrapper.eq(AccessRoleAuthority::getRoleCode, roleCode); + List accessRoleAuthorities = accessRoleAuthorityMapper + .selectList(accessRoleAuthorityWrapper); + List 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 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 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 wrapper = Wrappers.lambdaQuery(); - wrapper.eq(AccessRoleAuthority::getRoleCode, roleCode); - accessRoleAuthorityMapper.delete(wrapper); + // 先清除该角色已保存的权限 + LambdaQueryWrapper 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; + } - // 保存勾选的权限(菜单和按钮) - 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; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/AccessUserController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/AccessUserController.java index 4db42aa2c..9997f8bce 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/AccessUserController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/AccessUserController.java @@ -6,108 +6,101 @@ 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 com.anjiplus.template.gaea.business.modules.accessuser.controller.dto.AccessUserDto; -import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam; +import io.swagger.annotations.Api; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.annotation.Validated; -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 org.springframework.web.bind.annotation.*; import java.util.Map; /** -* @desc 用户管理 controller -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * @desc 用户管理 controller + * @author 木子李·De + * @date 2019-02-17 08:50:11.902 + **/ @RestController @Api(tags = "用户管理管理") @RequestMapping("/accessUser") @Permission(code = "userManage", name = "用户管理") public class AccessUserController extends GaeaBaseController { - @Autowired - private AccessUserService accessUserService; + @Autowired + private AccessUserService accessUserService; - @Override - public GaeaBaseService getService() { - return accessUserService; - } + @Override + public GaeaBaseService 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 = "分配角色") - @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 = "分配角色") - @PostMapping("/saveRoleTree") - public ResponseBean saveRoleTree(@RequestBody AccessUserDto dto){ - Boolean data = accessUserService.saveRoleTree(dto); - return responseSuccessWithData(data); - } + /** + * 重置密码 + * @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 - */ - @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)); - } + /** + * 修改自己的密码 + * @param dto + * @return + */ + @PostMapping("/updatePassword") + public ResponseBean updatePassword(@RequestBody UpdatePasswordDto dto) { + return responseSuccessWithData(accessUserService.updatePassword(dto)); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/AccessUserDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/AccessUserDto.java index 11d1fb952..fd3dee914 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/AccessUserDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/AccessUserDto.java @@ -1,66 +1,64 @@ package com.anjiplus.template.gaea.business.modules.accessuser.controller.dto; -import java.io.Serializable; +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 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.io.Serializable; import java.util.Date; import java.util.List; /** -* -* @description 用户管理 dto -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * @description 用户管理 dto + * @author 木子李·De + * @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; + /** 备注 */ + @ApiModelProperty(value = "备注") + private String remark; + + /** 用户勾选的角色 */ + private List roleCodeList; - /** 用户勾选的角色 */ - private List roleCodeList; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/GaeaUserDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/GaeaUserDto.java index 02a9d194e..1da9381dc 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/GaeaUserDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/GaeaUserDto.java @@ -11,20 +11,21 @@ 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 String token; + + /** 用户所拥有的权限合集 */ + private List authorities; - /** 用户所拥有的权限合集 */ - private List authorities; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/UpdatePasswordDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/UpdatePasswordDto.java index daf841755..4dec1569d 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/UpdatePasswordDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/dto/UpdatePasswordDto.java @@ -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 password; + + @ApiModelProperty(value = "密码") + @NotBlank + private String confirmPassword; - @ApiModelProperty(value = "密码") - @NotBlank - private String confirmPassword; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/param/AccessUserParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/param/AccessUserParam.java index 0005c14ca..763be8e9e 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/param/AccessUserParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/controller/param/AccessUserParam.java @@ -1,37 +1,35 @@ /**/ 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 java.util.List; +import lombok.Data; -import java.util.Date; +import java.io.Serializable; /** -* @desc AccessUser 用户管理查询输入类 -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * @desc AccessUser 用户管理查询输入类 + * @author 木子李·De + * @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; -} \ No newline at end of file +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserMapper.java index 0d8aa185a..47e8e57d4 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserMapper.java @@ -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 -* @date 2019-02-17 08:50:11.902 -**/ + * AccessUser Mapper + * + * @author 木子李·De + * @date 2019-02-17 08:50:11.902 + **/ @Mapper public interface AccessUserMapper extends GaeaBaseMapper { - /** 查询用户所拥有的所有角色下的权限 - * @param loginName - * @return - */ - List queryAuthoritiesByLoginName(@Param("loginName")String loginName); -} \ No newline at end of file + /** + * 查询用户所拥有的所有角色下的权限 + * @param loginName + * @return + */ + List queryAuthoritiesByLoginName(@Param("loginName") String loginName); + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserRoleMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserRoleMapper.java index 2e4e68764..088d8fac9 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserRoleMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/AccessUserRoleMapper.java @@ -5,10 +5,11 @@ import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessU import org.apache.ibatis.annotations.Mapper; /** -* AccessUser Mapper -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * AccessUser Mapper + * + * @author 木子李·De + * @date 2019-02-17 08:50:11.902 + **/ @Mapper public interface AccessUserRoleMapper extends GaeaBaseMapper { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUser.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUser.java index 5cd38158a..66c1c9fa5 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUser.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUser.java @@ -1,48 +1,49 @@ 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 javax.validation.constraints.*; +import lombok.Data; + import java.util.Date; + /** -* @description 用户管理 entity -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ -@TableName(keepGlobalPrefix=true, value="access_user") + * @description 用户管理 entity + * @author 木子李·De + * @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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUserRole.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUserRole.java index a56be7ab9..b2050f836 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUserRole.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/dao/entity/AccessUserRole.java @@ -9,32 +9,33 @@ import lombok.Data; import java.util.Date; /** -* @description 用户--角色关联关系 entity -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ -@TableName(keepGlobalPrefix=true, value="access_user_role") + * @description 用户--角色关联关系 entity + * @author 木子李·De + * @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 Date updateTime; + + @TableField(exist = false) + private Integer version; - @TableField(exist = false) - private Integer version; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/AccessUserService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/AccessUserService.java index 900cee3a9..021f34da0 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/AccessUserService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/AccessUserService.java @@ -1,52 +1,56 @@ 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.dao.entity.AccessUser; import com.anjiplus.template.gaea.business.modules.accessuser.controller.param.AccessUserParam; -import com.anji.plus.gaea.curd.service.GaeaBaseService; +import com.anjiplus.template.gaea.business.modules.accessuser.dao.entity.AccessUser; import java.util.Map; /** -* @desc AccessUser 用户管理服务接口 -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * @desc AccessUser 用户管理服务接口 + * @author 木子李·De + * @date 2019-02-17 08:50:11.902 + **/ public interface AccessUserService extends GaeaBaseService { - /** 获取用户的角色树 - * @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 accessUserDto - * @return - */ - Boolean saveRoleTree(AccessUserDto accessUserDto); + /** + * 重置密码 + * @param gaeaUserDto + * @return + */ + Boolean resetPassword(GaeaUserDto gaeaUserDto); - /** 重置密码 - * @param gaeaUserDto - * @return - */ - Boolean resetPassword(GaeaUserDto gaeaUserDto); + /** + * 用户登录 + * @param gaeaUserDto + * @return + */ + GaeaUserDto login(GaeaUserDto gaeaUserDto); - /** 用户登录 - * @param gaeaUserDto - * @return - */ - GaeaUserDto login(GaeaUserDto gaeaUserDto); + /** + * 修改密码 + * @param dto + * @return + */ + Boolean updatePassword(UpdatePasswordDto dto); - /** - * 修改密码 - * @param dto - * @return - */ - Boolean updatePassword(UpdatePasswordDto dto); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/impl/AccessUserServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/impl/AccessUserServiceImpl.java index 966196033..ebe584478 100755 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/impl/AccessUserServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/accessuser/service/impl/AccessUserServiceImpl.java @@ -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,226 +37,228 @@ import java.util.*; import java.util.stream.Collectors; /** -* @desc AccessUser 用户管理服务实现 -* @author 木子李·De -* @date 2019-02-17 08:50:11.902 -**/ + * @desc AccessUser 用户管理服务实现 + * @author 木子李·De + * @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 getMapper() { - return accessUserMapper; - } + @Override + public GaeaBaseMapper 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 result = new HashMap(); - List treeData = new ArrayList<>(); - List checkedKeys = new ArrayList(); + @Override + public Map getRoleTree(String loginName, String operator) { + Map result = new HashMap(); + List treeData = new ArrayList<>(); + List checkedKeys = new ArrayList(); - // 角色树 - LambdaQueryWrapper roleQuery = Wrappers.lambdaQuery(); - roleQuery.select(AccessRole::getRoleCode, AccessRole::getRoleName); - // 按operator去筛选role 后面再加where - List 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 roleQuery = Wrappers.lambdaQuery(); + roleQuery.select(AccessRole::getRoleCode, AccessRole::getRoleName); + // 按operator去筛选role 后面再加where + List 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 queryWrapper = Wrappers.lambdaQuery(); - queryWrapper.select(AccessUserRole::getRoleCode) - .eq(AccessUserRole::getLoginName, loginName); - checkedKeys = accessUserRoleMapper.selectObjs(queryWrapper); + // 该用户已保存的角色 + LambdaQueryWrapper 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 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 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 wrapper = Wrappers.lambdaQuery(); - wrapper.eq(AccessUserRole::getLoginName, loginName); - accessUserRoleMapper.delete(wrapper); + // 先清除该用户已保存的角色 + LambdaQueryWrapper 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 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 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 authorities = accessUserMapper.queryAuthoritiesByLoginName(loginName); + // 为了兼容底层其他数据库,不再写自定义sql + // List authorities = + // accessUserMapper.queryAuthoritiesByLoginName(loginName); - //当前用户的roleCode集合 - LambdaQueryWrapper accessUserWrapper = Wrappers.lambdaQuery(); - accessUserWrapper.select(AccessUserRole::getRoleCode); - accessUserWrapper.eq(AccessUserRole::getLoginName, loginName); - List accessUserRoles = accessUserRoleMapper.selectList(accessUserWrapper); - Set roleCodeSet = accessUserRoles.stream().map(AccessUserRole::getRoleCode).collect(Collectors.toSet()); - if (roleCodeSet.size() < 1) { - gaeaUser.setAuthorities(new ArrayList<>()); - }else { - LambdaQueryWrapper accessRoleAuthorityWrapper = Wrappers.lambdaQuery(); - accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction); - accessRoleAuthorityWrapper.in(AccessRoleAuthority::getRoleCode, roleCodeSet); - List accessRoleAuthorities = accessRoleAuthorityMapper.selectList(accessRoleAuthorityWrapper); - List authorities = accessRoleAuthorities.stream() - .map(accessRoleAuthority -> accessRoleAuthority.getTarget().concat(":").concat(accessRoleAuthority.getAction())).distinct().collect(Collectors.toList()); - gaeaUser.setAuthorities(authorities); - } + // 当前用户的roleCode集合 + LambdaQueryWrapper accessUserWrapper = Wrappers.lambdaQuery(); + accessUserWrapper.select(AccessUserRole::getRoleCode); + accessUserWrapper.eq(AccessUserRole::getLoginName, loginName); + List accessUserRoles = accessUserRoleMapper.selectList(accessUserWrapper); + Set roleCodeSet = accessUserRoles.stream().map(AccessUserRole::getRoleCode).collect(Collectors.toSet()); + if (roleCodeSet.size() < 1) { + gaeaUser.setAuthorities(new ArrayList<>()); + } + else { + LambdaQueryWrapper accessRoleAuthorityWrapper = Wrappers.lambdaQuery(); + accessRoleAuthorityWrapper.select(AccessRoleAuthority::getTarget, AccessRoleAuthority::getAction); + accessRoleAuthorityWrapper.in(AccessRoleAuthority::getRoleCode, roleCodeSet); + List accessRoleAuthorities = accessRoleAuthorityMapper + .selectList(accessRoleAuthorityWrapper); + List 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 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())); - LambdaQueryWrapper 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; + } - accessUserMapper.updateById(accessUser); - return true; - } + /** + * 操作前处理 + * @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: - /** - * 操作前处理 - * - * @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; + } - break; - } + } - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/ReportDashboardController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/ReportDashboardController.java index 06e73ba27..a1da6fdc7 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/ReportDashboardController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/ReportDashboardController.java @@ -4,9 +4,9 @@ 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; @@ -20,89 +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; - @Autowired - private ReportShareService reportShareService; + @Autowired + private ReportShareService reportShareService; - /** - * 预览、查询大屏详情 - * @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 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 - @Permission(code = "design", name = "设计大屏") - @GaeaAuditLog(pageTitle = "新增") - public ResponseBean insert(@RequestBody ReportDashboardObjectDto dto) { - reportDashboardService.insertDashboard(dto); - return ResponseBean.builder().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 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("/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 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 reportCode - * @return - */ - @GetMapping("/export") - @Permission(code = "export", name = "导出大屏") - public ResponseEntity 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(); - } + @PostMapping("/share") + @GaeaAuditLog(pageTitle = "分享") + public ResponseBean share(@Validated @RequestBody ReportShareDto dto) { + return ResponseBean.builder().data(reportShareService.insertShare(dto)).build(); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ChartDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ChartDto.java index d6b67f871..90188c079 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ChartDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ChartDto.java @@ -6,46 +6,43 @@ 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 contextData; + /** 传入的自定义参数 */ + private Map contextData; - /**图表属性*/ - private Map chartProperties; + /** 图表属性 */ + private Map 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 endTime; + /** 时间区间 */ + private String startTime; + /** 时间区间 */ + private String endTime; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardDto.java index 681235241..276761a0f 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardDto.java @@ -8,48 +8,47 @@ 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 title; + /** 报表编码 */ + private String reportCode; - /** 宽度px */ - private Long width; + /** 看板标题 */ + private String title; - /** 高度px */ - private Long height; + /** 宽度px */ + private Long width; - /** 背景色 */ - private String backgroundColor; + /** 高度px */ + private Long height; - /** 背景图片 */ - private String backgroundImage; + /** 背景色 */ + private String backgroundColor; - /** 工作台中的辅助线 */ - private String presetLine; + /** 背景图片 */ + private String backgroundImage; - /** 自动刷新间隔秒,数据字典REFRESH_TYPE */ - private Integer refreshSeconds; + /** 工作台中的辅助线 */ + private String presetLine; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** 自动刷新间隔秒,数据字典REFRESH_TYPE */ + private Integer refreshSeconds; - /** 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=DEL_FLAG */ + private Integer deleteFlag; - private List widgets; + /** 排序,降序 */ + private Integer sort; + + private List widgets; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardObjectDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardObjectDto.java index cc4ca08ec..60486ea00 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardObjectDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/dto/ReportDashboardObjectDto.java @@ -7,26 +7,25 @@ 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 ReportDashboardDto dashboard; + /** 报表编码 */ + private String reportCode; - /** - * 大屏画布中的组件 - */ - private List widgets; + /** + * 报表编码 + */ + private ReportDashboardDto dashboard; + + /** + * 大屏画布中的组件 + */ + private List widgets; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/param/ReportDashboardParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/param/ReportDashboardParam.java index d044b9667..6b279558b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/param/ReportDashboardParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/controller/param/ReportDashboardParam.java @@ -1,20 +1,17 @@ /**/ package com.anjiplus.template.gaea.business.modules.dashboard.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; /** -* @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 { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/ReportDashboardMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/ReportDashboardMapper.java index 173e822b8..308042800 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/ReportDashboardMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/ReportDashboardMapper.java @@ -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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/entity/ReportDashboard.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/entity/ReportDashboard.java index 76ad6cb6b..d7eb14ffb 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/entity/ReportDashboard.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/dao/entity/ReportDashboard.java @@ -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 = "看板标题") - private String title; + @ApiModelProperty(value = "报表编码") + @Unique(code = ResponseCode.REPORT_CODE_ISEXIST) + private String reportCode; - @ApiModelProperty(value = "宽度px") - private Long width; + @ApiModelProperty(value = "看板标题") + private String title; - @ApiModelProperty(value = "高度px") - private Long height; + @ApiModelProperty(value = "宽度px") + private Long width; - @ApiModelProperty(value = "背景色") - private String backgroundColor; + @ApiModelProperty(value = "高度px") + private Long height; - @ApiModelProperty(value = "背景图片") - private String backgroundImage; + @ApiModelProperty(value = "背景色") + private String backgroundColor; - @ApiModelProperty(value = "工作台中的辅助线") - private String presetLine; + @ApiModelProperty(value = "背景图片") + private String backgroundImage; - @ApiModelProperty(value = "自动刷新间隔秒,数据字典REFRESH_TYPE") - private Integer refreshSeconds; + @ApiModelProperty(value = "工作台中的辅助线") + private String presetLine; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @ApiModelProperty(value = "自动刷新间隔秒,数据字典REFRESH_TYPE") + private Integer refreshSeconds; - @ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; - @ApiModelProperty(value = "排序,降序") - private Integer sort; + @ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG") + private Integer deleteFlag; + @ApiModelProperty(value = "排序,降序") + private Integer sort; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ChartStrategy.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ChartStrategy.java index ccaa4b047..bea7ee643 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ChartStrategy.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ChartStrategy.java @@ -10,17 +10,17 @@ import java.util.List; */ public interface ChartStrategy { - /** - * 图表类型 - * @return - */ - String type(); + /** + * 图表类型 + * @return + */ + String type(); + + /** + * 针对每种图表类型做单独的数据转换解析 + * @param dto + * @return + */ + Object transform(ChartDto dto, List data); - /** - * 针对每种图表类型做单独的数据转换解析 - * - * @param dto - * @return - */ - Object transform(ChartDto dto, List data); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ReportDashboardService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ReportDashboardService.java index 2b8c1e359..fd6924667 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ReportDashboardService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/ReportDashboardService.java @@ -13,49 +13,47 @@ 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 { - /*** - * 查询详情 - * - * @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); - /** - * 获取单个图表数据 - * @param dto - * @return - */ - Object getChartData(ChartDto dto); + /** + * 导出大屏,zip文件 + * @param request + * @param response + * @param reportCode + * @return + */ + ResponseEntity exportDashboard(HttpServletRequest request, HttpServletResponse response, String reportCode, + Integer showDataSet); + /** + * 导入大屏zip + * @param file + * @param reportCode + * @return + */ + void importDashboard(MultipartFile file, String reportCode); - /** - * 导出大屏,zip文件 - * @param request - * @param response - * @param reportCode - * @return - */ - ResponseEntity exportDashboard(HttpServletRequest request, HttpServletResponse response, String reportCode, Integer showDataSet); - - /** - * 导入大屏zip - * @param file - * @param reportCode - * @return - */ - void importDashboard(MultipartFile file, String reportCode); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarChartServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarChartServiceImpl.java index 7874721d5..83656301c 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarChartServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarChartServiceImpl.java @@ -8,72 +8,54 @@ 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"; - } - /** - * 针对每种图表类型做单独的数据转换解析 - * - * @param dto - * @param data - * @return - */ - @Override - public Object transform(ChartDto dto, List data) { -// JSONObject json = new JSONObject(); -// List xAxis = new ArrayList<>(); -// List 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; - } + /** + * 图表类型 + * @return + */ + @Override + public String type() { + return "widget-barchart|widget-linechart"; + } + /** + * 针对每种图表类型做单独的数据转换解析 + * @param dto + * @param data + * @return + */ + @Override + public Object transform(ChartDto dto, List data) { + // JSONObject json = new JSONObject(); + // List xAxis = new ArrayList<>(); + // List 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 - ] - } - ] - }*/ } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarLineChartServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarLineChartServiceImpl.java index 032620cfc..f5641488b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarLineChartServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/BarLineChartServiceImpl.java @@ -8,98 +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 BarLineChartServiceImpl implements ChartStrategy { - /** - * 图表类型 - * - * @return - */ - @Override - public String type() { - return "widget-barlinechart"; - } - /** - * 针对每种图表类型做单独的数据转换解析 - * - * @param dto - * @param data - * @return - */ - @Override - public Object transform(ChartDto dto, List data) { -// JSONObject json = new JSONObject(); -// List xAxis = new ArrayList<>(); -// Map> series = new HashMap<>(); -// data.forEach(jsonObject -> { -// jsonObject.forEach((s, o) -> { -// if ("xAxis".equals(s)) { -// xAxis.add(o); -// } else { -// List 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 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; - } + /** + * 图表类型 + * @return + */ + @Override + public String type() { + return "widget-barlinechart"; + } + /** + * 针对每种图表类型做单独的数据转换解析 + * @param dto + * @param data + * @return + */ + @Override + public Object transform(ChartDto dto, List data) { + // JSONObject json = new JSONObject(); + // List xAxis = new ArrayList<>(); + // Map> series = new HashMap<>(); + // data.forEach(jsonObject -> { + // jsonObject.forEach((s, o) -> { + // if ("xAxis".equals(s)) { + // xAxis.add(o); + // } else { + // List 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 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 ] } ] } + */ } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/GaugeChartServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/GaugeChartServiceImpl.java index 89fbe6f02..aead08a51 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/GaugeChartServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/GaugeChartServiceImpl.java @@ -8,36 +8,31 @@ 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 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 data) { + // return "{\"value\": 50, \"name\": \"名称1\", \"unit\": \"%\"}"; + return data; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/PieChartServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/PieChartServiceImpl.java index 5f1ffbf30..21f018fa3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/PieChartServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/PieChartServiceImpl.java @@ -8,45 +8,34 @@ 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"; - } - /** - * 针对每种图表类型做单独的数据转换解析 - * - * @param dto - * @param data - * @return - */ - @Override - public Object transform(ChartDto dto, List data) { + /** + * 图表类型 + * @return + */ + @Override + public String type() { + return "widget-piechart|widget-hollow-piechart|widget-funnel"; + } - return data; - } - -/* [ - { - "value": 11, - "name": "指标1" - }, - { - "value": 10, - "name": "指标2" - } - ]*/ + /** + * 针对每种图表类型做单独的数据转换解析 + * @param dto + * @param data + * @return + */ + @Override + public Object transform(ChartDto dto, List data) { + return data; + } + /* + * [ { "value": 11, "name": "指标1" }, { "value": 10, "name": "指标2" } ] + */ } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/ReportDashboardServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/ReportDashboardServiceImpl.java index 89b403b61..55b81e839 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/ReportDashboardServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboard/service/impl/ReportDashboardServiceImpl.java @@ -61,504 +61,507 @@ import java.util.concurrent.CompletableFuture; **/ @Service @Slf4j -//@RequiredArgsConstructor +// @RequiredArgsConstructor public class ReportDashboardServiceImpl implements ReportDashboardService, InitializingBean, ApplicationContextAware { - @Autowired - private ReportDashboardMapper reportDashboardMapper; - - @Autowired - private ReportDashboardWidgetService reportDashboardWidgetService; - - @Autowired - private DataSetService dataSetService; - - @Autowired - private GaeaFileService gaeaFileService; - - @Autowired - private ReportService reportService; - - @Value("${customer.file.downloadPath:''}") - private String fileDownloadPath; - - @Value("${customer.file.dist-path:''}") - private String dictPath; - - private final static String ZIP_PATH = "/zip/"; - private final static String JSON_PATH = "dashboard.json"; - - private Map queryServiceImplMap = new HashMap<>(); - private ApplicationContext applicationContext; - - @Override - public GaeaBaseMapper 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); - - List list = reportDashboardWidgetService.list( - new QueryWrapper().lambda() - .eq(ReportDashboardWidget::getReportCode, reportCode) - .orderByAsc(ReportDashboardWidget::getSort) - ); - List 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; - } - - /*** - * 保存大屏设计 - * - * @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() - .lambda().eq(ReportDashboardWidget::getReportCode, reportCode)); - List widgets = dto.getWidgets(); - -// List 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); - -// 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 data = result.getData(); - //处理时间轴 - List resultData = buildTimeLine(data, dto); - return resultData; -// return getTarget(chartType).transform(dto, result.getData()); - } - - /** - * 导出大屏,zip文件 - * - * @param request - * @param response - * @param reportCode - * @return - */ - @Override - public ResponseEntity 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 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); - }); - - //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"); - } - }); - } - - - //2.将大屏设计到的json文件保存 - String jsonPath = path + "/" + JSON_PATH; - FileUtil.WriteStringToFile(jsonPath, JSONObject.toJSONString(detail)); - - - //将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"); - } - - ResponseEntity body = builder.body(FileUtils.readFileToByteArray(file)); - - //删除zip文件 - file.delete(); - //删除path临时文件夹 - FileUtil.delete(path); - log.info("删除临时文件:{},{}", zipPath, path); - - //异步统计下载次数 - CompletableFuture.runAsync(() -> { - log.info("=======>ip:{} 下载模板:{}", RequestUtil.getIpAddr(request), reportCode); - reportService.downloadStatistics(reportCode); - }); - - - 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[] files = firstFile.listFiles(); - - //定义map - Map fileMap = new HashMap<>(); - String content = ""; - - 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 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); - } - } - - } - - - //解析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); - - //解析结束,删除临时文件夹 - FileUtil.delete(path); - - log.info("解析成功,开始存入数据库..."); - insertDashboard(detail); - } - - - private String replaceUrl(String imageAddress, Map 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; - } - - /** - * 将大屏涉及到的图片存入指定文件夹 - * @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 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); - } - } - - } - - 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); - } - - @Override - public void afterPropertiesSet() { - Map beanMap = applicationContext.getBeansOfType(ChartStrategy.class); - //遍历该接口的所有实现,将其放入map中 - for (ChartStrategy serviceImpl : beanMap.values()) { - queryServiceImplMap.put(serviceImpl.type(), serviceImpl); - } - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } - - - /** - * 解析图层数据 - * - * @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 buildTimeLine(List data, ChartDto dto) { - Map chartProperties = dto.getChartProperties(); - if (null == chartProperties || chartProperties.size() < 1) { - return data; - } - Map 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; - } - //获取时间轴字段和解析时间颗粒度 - - for (Map.Entry 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 timeLine = new ArrayList<>(); - List 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 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); - } - } + @Autowired + private ReportDashboardMapper reportDashboardMapper; + + @Autowired + private ReportDashboardWidgetService reportDashboardWidgetService; + + @Autowired + private DataSetService dataSetService; + + @Autowired + private GaeaFileService gaeaFileService; + + @Autowired + private ReportService reportService; + + @Value("${customer.file.downloadPath:''}") + private String fileDownloadPath; + + @Value("${customer.file.dist-path:''}") + private String dictPath; + + private final static String ZIP_PATH = "/zip/"; + + private final static String JSON_PATH = "dashboard.json"; + + private Map queryServiceImplMap = new HashMap<>(); + + private ApplicationContext applicationContext; + + @Override + public GaeaBaseMapper 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); + + List list = reportDashboardWidgetService.list( + new QueryWrapper().lambda().eq(ReportDashboardWidget::getReportCode, reportCode) + .orderByAsc(ReportDashboardWidget::getSort)); + List 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; + } + + /*** + * 保存大屏设计 + * @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().lambda() + .eq(ReportDashboardWidget::getReportCode, reportCode)); + List widgets = dto.getWidgets(); + + // List 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); + + // 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 data = result.getData(); + // 处理时间轴 + List resultData = buildTimeLine(data, dto); + return resultData; + // return getTarget(chartType).transform(dto, result.getData()); + } + + /** + * 导出大屏,zip文件 + * @param request + * @param response + * @param reportCode + * @return + */ + @Override + public ResponseEntity 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 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); + }); + + // 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"); + } + }); + } + + // 2.将大屏设计到的json文件保存 + String jsonPath = path + "/" + JSON_PATH; + FileUtil.WriteStringToFile(jsonPath, JSONObject.toJSONString(detail)); + + // 将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"); + } + + ResponseEntity body = builder.body(FileUtils.readFileToByteArray(file)); + + // 删除zip文件 + file.delete(); + // 删除path临时文件夹 + FileUtil.delete(path); + log.info("删除临时文件:{},{}", zipPath, path); + + // 异步统计下载次数 + CompletableFuture.runAsync(() -> { + log.info("=======>ip:{} 下载模板:{}", RequestUtil.getIpAddr(request), reportCode); + reportService.downloadStatistics(reportCode); + }); + + 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[] files = firstFile.listFiles(); + + // 定义map + Map fileMap = new HashMap<>(); + String content = ""; + + 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 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); + } + } + + } + + // 解析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); + + // 解析结束,删除临时文件夹 + FileUtil.delete(path); + + log.info("解析成功,开始存入数据库..."); + insertDashboard(detail); + } + + private String replaceUrl(String imageAddress, Map 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; + } + + /** + * 将大屏涉及到的图片存入指定文件夹 + * @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 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); + } + } + + } + + 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); + } + + @Override + public void afterPropertiesSet() { + Map beanMap = applicationContext.getBeansOfType(ChartStrategy.class); + // 遍历该接口的所有实现,将其放入map中 + for (ChartStrategy serviceImpl : beanMap.values()) { + queryServiceImplMap.put(serviceImpl.type(), serviceImpl); + } + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + /** + * 解析图层数据 + * @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 buildTimeLine(List data, ChartDto dto) { + Map chartProperties = dto.getChartProperties(); + if (null == chartProperties || chartProperties.size() < 1) { + return data; + } + Map 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; + } + // 获取时间轴字段和解析时间颗粒度 + + for (Map.Entry 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 timeLine = new ArrayList<>(); + List 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 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); + } + } + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetDto.java index a8538c2cf..707f44c82 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetDto.java @@ -6,29 +6,27 @@ 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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetValueDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetValueDto.java index 51b660a20..a246c06a1 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetValueDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/dto/ReportDashboardWidgetValueDto.java @@ -6,42 +6,41 @@ 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; - /** 组件的渲染属性json */ - private JSONObject setup; + /** 报表编码 */ + private String reportCode; - /** 组件的数据属性json */ - private JSONObject data; + /** 组件的渲染属性json */ + private JSONObject setup; - /** 组件的配置属性json */ - private JSONObject collapse; + /** 组件的数据属性json */ + private JSONObject data; - /** 组件的大小位置属性json */ - private JSONObject position; + /** 组件的配置属性json */ + private JSONObject collapse; - private String options; + /** 组件的大小位置属性json */ + private JSONObject position; - /** 自动刷新间隔秒 */ - private Integer refreshSeconds; + private String options; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** 自动刷新间隔秒 */ + private Integer refreshSeconds; - /** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */ - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; - /** 排序,图层的概念 */ - private Long sort; + /** 0--未删除 1--已删除 DIC_NAME=DEL_FLAG */ + private Integer deleteFlag; + + /** 排序,图层的概念 */ + private Long sort; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/param/ReportDashboardWidgetParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/param/ReportDashboardWidgetParam.java index 09f54bff0..78d82999e 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/param/ReportDashboardWidgetParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/controller/param/ReportDashboardWidgetParam.java @@ -1,20 +1,17 @@ /**/ package com.anjiplus.template.gaea.business.modules.dashboardwidget.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; /** -* @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 { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/ReportDashboardWidgetMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/ReportDashboardWidgetMapper.java index 2570c7fd6..becc27780 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/ReportDashboardWidgetMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/ReportDashboardWidgetMapper.java @@ -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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/entity/ReportDashboardWidget.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/entity/ReportDashboardWidget.java index 2631236bd..c369d3d08 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/entity/ReportDashboardWidget.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/dao/entity/ReportDashboardWidget.java @@ -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 = "组件类型参考字典DASHBOARD_PANEL_TYPE") - private String type; + @ApiModelProperty(value = "报表编码") + private String reportCode; - @ApiModelProperty(value = "组件的渲染属性json") - private String setup; + @ApiModelProperty(value = "组件类型参考字典DASHBOARD_PANEL_TYPE") + private String type; - @ApiModelProperty(value = "组件的数据属性json") - private String data; + @ApiModelProperty(value = "组件的渲染属性json") + private String setup; - @ApiModelProperty(value = "组件的配置属性json") - private String collapse; + @ApiModelProperty(value = "组件的数据属性json") + private String data; - @ApiModelProperty(value = "组件的大小位置属性json") - private String position; + @ApiModelProperty(value = "组件的配置属性json") + private String collapse; - private String options; + @ApiModelProperty(value = "组件的大小位置属性json") + private String position; - @ApiModelProperty(value = "自动刷新间隔秒") - private Integer refreshSeconds; + private String options; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @ApiModelProperty(value = "自动刷新间隔秒") + private Integer refreshSeconds; - @ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; - @ApiModelProperty(value = "排序,图层的概念") - private Long sort; + @ApiModelProperty(value = " 0--未删除 1--已删除 DIC_NAME=DEL_FLAG") + private Integer deleteFlag; + @ApiModelProperty(value = "排序,图层的概念") + private Long sort; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/ReportDashboardWidgetService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/ReportDashboardWidgetService.java index 367030c81..54c3b9c6f 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/ReportDashboardWidgetService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/ReportDashboardWidgetService.java @@ -1,21 +1,22 @@ 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 { + * @desc ReportDashboardWidget 大屏看板数据渲染服务接口 + * @author Raod + * @date 2021-04-12 15:12:43.724 + **/ +public interface ReportDashboardWidgetService + extends GaeaBaseService { + + /*** + * 查询详情 + * @param id + */ + ReportDashboardWidget getDetail(Long id); - /*** - * 查询详情 - * - * @param id - */ - ReportDashboardWidget getDetail(Long id); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/impl/ReportDashboardWidgetServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/impl/ReportDashboardWidgetServiceImpl.java index 11f0a0681..bffc0eb99 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/impl/ReportDashboardWidgetServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dashboardwidget/service/impl/ReportDashboardWidgetServiceImpl.java @@ -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 getMapper() { - return reportDashboardWidgetMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return reportDashboardWidgetMapper; + } + + @Override + public ReportDashboardWidget getDetail(Long id) { + ReportDashboardWidget reportDashboardWidget = this.selectOne(id); + return reportDashboardWidget; + } - @Override - public ReportDashboardWidget getDetail(Long id) { - ReportDashboardWidget reportDashboardWidget = this.selectOne(id); - return reportDashboardWidget; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/DataSetController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/DataSetController.java index 88a24bf99..21b9b0291 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/DataSetController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/DataSetController.java @@ -21,125 +21,111 @@ 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 { - @Autowired - private DataSetService dataSetService; + @Autowired + private DataSetService dataSetService; - @Override - public GaeaBaseService getService() { - return dataSetService; - } + @Override + public GaeaBaseService 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)); - } - - /** - * 获取所有数据集 - * @return - */ - @GetMapping("/queryAllDataSet") - public ResponseBean queryAllDataSet() { - return responseSuccessWithData(dataSetService.queryAllDataSet()); - } + /** + * 测试 数据转换是否正确 + * @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()); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/DataSetDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/DataSetDto.java index 2647a91f7..6bd520bc3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/DataSetDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/DataSetDto.java @@ -11,55 +11,53 @@ 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 setName; + /** 数据集编码 */ + private String setCode; - /** 数据集描述 */ - private String setDesc; + /** 数据集名称 */ + private String setName; - /** 数据集类型 */ - private String setType; + /** 数据集描述 */ + private String setDesc; + /** 数据集类型 */ + private String setType; - /** 数据源编码 */ - private String sourceCode; + /** 数据源编码 */ + private String sourceCode; - /** 动态查询sql或者接口中的请求体 */ - private String dynSentence; + /** 动态查询sql或者接口中的请求体 */ + private String dynSentence; - /** 结果案例 */ - private String caseResult; + /** 结果案例 */ + private String caseResult; - /** 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; - /** 请求参数集合 */ - private List dataSetParamDtoList; + /** 请求参数集合 */ + private List dataSetParamDtoList; - /** 数据转换集合 */ - private List dataSetTransformDtoList; + /** 数据转换集合 */ + private List dataSetTransformDtoList; - /** 传入的自定义参数*/ - private Map contextData; + /** 传入的自定义参数 */ + private Map contextData; - private Set setParamList; + private Set setParamList; - /**指定字段*/ - private String fieldLabel; + /** 指定字段 */ + private String fieldLabel; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/OriginalDataDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/OriginalDataDto.java index c33d1feaf..572f2f01c 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/OriginalDataDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/dto/OriginalDataDto.java @@ -12,21 +12,22 @@ import java.util.List; @Data public class OriginalDataDto implements Serializable { - /**总数*/ - private long total; + /** 总数 */ + private long total; - /**获取的数据详情*/ - private List data; + /** 获取的数据详情 */ + private List data; - public OriginalDataDto(List data) { - this.data = data; - } + public OriginalDataDto(List data) { + this.data = data; + } - public OriginalDataDto(long total, List data) { - this.total = total; - this.data = data; - } + public OriginalDataDto(long total, List data) { + this.total = total; + this.data = data; + } + + public OriginalDataDto() { + } - public OriginalDataDto() { - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetParam.java index 9730302eb..aeec58425 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetParam.java @@ -8,27 +8,28 @@ 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{ - /** 数据集编码 */ - @Query(QueryEnum.LIKE) - private String setCode; +public class DataSetParam extends PageParam implements Serializable { - /** 数据集名称 */ - @Query(QueryEnum.LIKE) - private String setName; + /** 数据集编码 */ + @Query(QueryEnum.LIKE) + private String setCode; - /** 数据源编码 */ - @Query(QueryEnum.EQ) - private String sourceCode; + /** 数据集名称 */ + @Query(QueryEnum.LIKE) + private String setName; + + /** 数据源编码 */ + @Query(QueryEnum.EQ) + private String sourceCode; + + /** 数据集类型 */ + @Query(QueryEnum.EQ) + private String setType; - /** 数据集类型 */ - @Query(QueryEnum.EQ) - private String setType; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetTestTransformParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetTestTransformParam.java index b628e2074..2c047b004 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetTestTransformParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/controller/param/DataSetTestTransformParam.java @@ -8,28 +8,27 @@ import lombok.Data; 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 { - /** 数据源编码 */ - private String sourceCode; + /** 数据源编码 */ + private String sourceCode; - /** 动态查询sql或者接口中的请求体 */ - private String dynSentence; + /** 动态查询sql或者接口中的请求体 */ + private String dynSentence; - /** 数据集类型 */ - private String setType; + /** 数据集类型 */ + private String setType; - /** 请求参数集合 */ - private List dataSetParamDtoList; + /** 请求参数集合 */ + private List dataSetParamDtoList; - /** 数据转换集合 */ - private List dataSetTransformDtoList; + /** 数据转换集合 */ + private List dataSetTransformDtoList; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/DataSetMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/DataSetMapper.java index d8514e480..96bdd838d 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/DataSetMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/DataSetMapper.java @@ -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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/entity/DataSet.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/entity/DataSet.java index d9313b519..37ac3baad 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/entity/DataSet.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/dao/entity/DataSet.java @@ -9,40 +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 = "数据集名称") - private String setName; + @ApiModelProperty(value = "数据集编码") + @Unique(code = ResponseCode.SET_CODE_ISEXIST) + private String setCode; - @ApiModelProperty(value = "数据集描述") - private String setDesc; + @ApiModelProperty(value = "数据集名称") + private String setName; - @ApiModelProperty(value = "数据集类型") - private String setType; + @ApiModelProperty(value = "数据集描述") + private String setDesc; - @ApiModelProperty(value = "数据源编码") - private String sourceCode; + @ApiModelProperty(value = "数据集类型") + private String setType; - @ApiModelProperty(value = "动态查询sql或者接口中的请求体") - private String dynSentence; + @ApiModelProperty(value = "数据源编码") + private String sourceCode; - @ApiModelProperty(value = "结果案例") - private String caseResult; + @ApiModelProperty(value = "动态查询sql或者接口中的请求体") + private String dynSentence; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @ApiModelProperty(value = "结果案例") + private String caseResult; - @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; + @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/DataSetService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/DataSetService.java index 8d37e3fae..73d92e244 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/DataSetService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/DataSetService.java @@ -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 { - /** - * 单条详情 - * @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); + /** + * @param dto + * @return + */ + OriginalDataDto testTransform(DataSetDto dto); + + /** + * 获取所有数据集 + * @return + */ + List queryAllDataSet(); - /** - * 获取所有数据集 - * @return - */ - List queryAllDataSet(); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/impl/DataSetServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/impl/DataSetServiceImpl.java index b4ef25e84..624f03cbb 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/impl/DataSetServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dataset/service/impl/DataSetServiceImpl.java @@ -9,8 +9,8 @@ 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.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.controller.dto.OriginalDataDto; 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; @@ -41,366 +41,342 @@ 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 getMapper() { - return dataSetMapper; - } + @Override + public GaeaBaseMapper 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 dataSetParamList = dataSetParamService.list( - new QueryWrapper() - .lambda() - .eq(DataSetParam::getSetCode, setCode) - ); - List 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 dataSetParamList = dataSetParamService + .list(new QueryWrapper().lambda().eq(DataSetParam::getSetCode, setCode)); + List dataSetParamDtoList = new ArrayList<>(); + dataSetParamList.forEach(dataSetParam -> { + DataSetParamDto dataSetParamDto = new DataSetParamDto(); + GaeaBeanUtils.copyAndFormatter(dataSetParam, dataSetParamDto); + dataSetParamDtoList.add(dataSetParamDto); + }); + dto.setDataSetParamDtoList(dataSetParamDtoList); - //数据转换 + // 数据转换 - List dataSetTransformList = dataSetTransformService.list( - new QueryWrapper() - .lambda() - .eq(DataSetTransform::getSetCode, setCode) - .orderByAsc(DataSetTransform::getOrderNum) - ); - List dataSetTransformDtoList = new ArrayList<>(); - dataSetTransformList.forEach(dataSetTransform -> { - DataSetTransformDto dataSetTransformDto = new DataSetTransformDto(); - GaeaBeanUtils.copyAndFormatter(dataSetTransform, dataSetTransformDto); - dataSetTransformDtoList.add(dataSetTransformDto); - }); - dto.setDataSetTransformDtoList(dataSetTransformDtoList); + List dataSetTransformList = dataSetTransformService.list(new QueryWrapper() + .lambda().eq(DataSetTransform::getSetCode, setCode).orderByAsc(DataSetTransform::getOrderNum)); + List 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 dataSetParamDtoList = dto.getDataSetParamDtoList(); + List dataSetTransformDtoList = dto.getDataSetTransformDtoList(); - /** - * 新增数据集、添加查询参数、数据转换 - * - * @param dto - */ - @Override - @Transactional - public DataSetDto insertSet(DataSetDto dto) { - List dataSetParamDtoList = dto.getDataSetParamDtoList(); - List dataSetTransformDtoList = dto.getDataSetTransformDtoList(); + // 1.新增数据集 + DataSet dataSet = new DataSet(); + BeanUtils.copyProperties(dto, dataSet); + insert(dataSet); + // 2.更新查询参数 + dataSetParamBatch(dataSetParamDtoList, dto.getSetCode()); - //1.新增数据集 - DataSet dataSet = new DataSet(); - BeanUtils.copyProperties(dto, dataSet); - insert(dataSet); - //2.更新查询参数 - dataSetParamBatch(dataSetParamDtoList, dto.getSetCode()); + // 3.更新数据转换 + dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode()); + return dto; + } - //3.更新数据转换 - dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode()); - return dto; - } + /** + * 更新数据集、添加查询参数、数据转换 + * @param dto + */ + @Override + @Transactional + public void updateSet(DataSetDto dto) { + List dataSetParamDtoList = dto.getDataSetParamDtoList(); + List dataSetTransformDtoList = dto.getDataSetTransformDtoList(); + // 1.更新数据集 + DataSet dataSet = new DataSet(); + BeanUtils.copyProperties(dto, dataSet); + update(dataSet); - /** - * 更新数据集、添加查询参数、数据转换 - * - * @param dto - */ - @Override - @Transactional - public void updateSet(DataSetDto dto) { - List dataSetParamDtoList = dto.getDataSetParamDtoList(); - List dataSetTransformDtoList = dto.getDataSetTransformDtoList(); - //1.更新数据集 - DataSet dataSet = new DataSet(); - BeanUtils.copyProperties(dto, dataSet); - update(dataSet); + // 2.更新查询参数 + dataSetParamBatch(dataSetParamDtoList, dto.getSetCode()); - //2.更新查询参数 - dataSetParamBatch(dataSetParamDtoList, dto.getSetCode()); + // 3.更新数据转换 + dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode()); + } - //3.更新数据转换 - dataSetTransformBatch(dataSetTransformDtoList, dto.getSetCode()); - } + /** + * 删除数据集、添加查询参数、数据转换 + * @param id + */ + @Override + public void deleteSet(Long id) { + DataSet dataSet = selectOne(id); + String setCode = dataSet.getSetCode(); + // 1.删除数据集 + deleteById(id); + // 2.删除查询参数 + dataSetParamService.delete(new QueryWrapper().lambda().eq(DataSetParam::getSetCode, setCode)); - /** - * 删除数据集、添加查询参数、数据转换 - * - * @param id - */ - @Override - public void deleteSet(Long id) { - DataSet dataSet = selectOne(id); - String setCode = dataSet.getSetCode(); - //1.删除数据集 - deleteById(id); + // 3.删除数据转换 + dataSetTransformService + .delete(new QueryWrapper().lambda().eq(DataSetTransform::getSetCode, setCode)); + } - //2.删除查询参数 - dataSetParamService.delete( - new QueryWrapper() - .lambda() - .eq(DataSetParam::getSetCode, setCode) - ); + /** + * 获取数据 + * @param dto + * @return + */ + @Override + public OriginalDataDto getData(DataSetDto dto) { - //3.删除数据转换 - dataSetTransformService.delete( - new QueryWrapper() - .lambda() - .eq(DataSetTransform::getSetCode, setCode) - ); - } + 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 = "{}"; + } - /** - * 获取数据 - * - * @param dto - * @return - */ - @Override - public OriginalDataDto getData(DataSetDto dto) { + } + else { + dataSource = dataSourceService.selectOne("source_code", dataSetDto.getSourceCode()); + } - 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 = "{}"; - } + // 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 data = dataSourceService.execute(dataSourceDto); + // 5.数据转换 + List transform = dataSetTransformService.transform(dataSetDto.getDataSetTransformDtoList(), data); + originalDataDto.setData(transform); + return originalDataDto; + } - }else { - dataSource = dataSourceService.selectOne("source_code", dataSetDto.getSourceCode()); - } + /** + * @param dto + * @return + */ + @Override + public OriginalDataDto testTransform(DataSetDto dto) { + String dynSentence = dto.getDynSentence(); - //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 data = dataSourceService.execute(dataSourceDto); - //5.数据转换 - List transform = dataSetTransformService.transform(dataSetDto.getDataSetTransformDtoList(), data); - originalDataDto.setData(transform); - return originalDataDto; - } + 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 = "{}"; + } - /** - * @param dto - * @return - */ - @Override - public OriginalDataDto testTransform(DataSetDto dto) { - String dynSentence = dto.getDynSentence(); + } + else { + dataSource = dataSourceService.selectOne("source_code", sourceCode); + } - 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 = "{}"; - } + // 3.参数替换 + // 3.1参数校验 + boolean verification = dataSetParamService.verification(dto.getDataSetParamDtoList(), null); + if (!verification) { + throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR); + } - }else { - dataSource = dataSourceService.selectOne("source_code", sourceCode); - } + dynSentence = dataSetParamService.transform(dto.getDataSetParamDtoList(), dynSentence); + // 4.获取数据 + DataSourceDto dataSourceDto = new DataSourceDto(); + BeanUtils.copyProperties(dataSource, dataSourceDto); + dataSourceDto.setDynSentence(dynSentence); + dataSourceDto.setContextData(setContextData(dto.getDataSetParamDtoList())); - //3.参数替换 - //3.1参数校验 - boolean verification = dataSetParamService.verification(dto.getDataSetParamDtoList(), null); - if (!verification) { - throw BusinessExceptionBuilder.build(ResponseCode.RULE_FIELDS_CHECK_ERROR); - } + // 获取total,判断DataSetParamDtoList中是否传入分页参数 + Map 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); + } - dynSentence = dataSetParamService.transform(dto.getDataSetParamDtoList(), dynSentence); - //4.获取数据 - DataSourceDto dataSourceDto = new DataSourceDto(); - BeanUtils.copyProperties(dataSource, dataSourceDto); - dataSourceDto.setDynSentence(dynSentence); - dataSourceDto.setContextData(setContextData(dto.getDataSetParamDtoList())); + List data = dataSourceService.execute(dataSourceDto); + // 5.数据转换 + List transform = dataSetTransformService.transform(dto.getDataSetTransformDtoList(), data); + originalDataDto.setData(transform); + return originalDataDto; + } - //获取total,判断DataSetParamDtoList中是否传入分页参数 - Map 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); - } + /** + * 获取所有数据集 + * @return + */ + @Override + public List queryAllDataSet() { + LambdaQueryWrapper 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); + } - List data = dataSourceService.execute(dataSourceDto); - //5.数据转换 - List transform = dataSetTransformService.transform(dto.getDataSetTransformDtoList(), data); - originalDataDto.setData(transform); - return originalDataDto; - } + public void dataSetParamBatch(List dataSetParamDtoList, String setCode) { + dataSetParamService.delete(new QueryWrapper().lambda().eq(DataSetParam::getSetCode, setCode)); + if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) { + return; + } + // List 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); + } - /** - * 获取所有数据集 - * - * @return - */ - @Override - public List queryAllDataSet() { - LambdaQueryWrapper 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 dataSetTransformBatch(List dataSetTransformDtoList, String setCode) { + dataSetTransformService + .delete(new QueryWrapper().lambda().eq(DataSetTransform::getSetCode, setCode)); + if (null == dataSetTransformDtoList || dataSetTransformDtoList.size() <= 0) { + return; + } + // List 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); + } - public void dataSetParamBatch(List dataSetParamDtoList,String setCode){ - dataSetParamService.delete( - new QueryWrapper() - .lambda() - .eq(DataSetParam::getSetCode, setCode) - ); - if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) { - return; - } -// List 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 dataSetTransformDtoList,String setCode){ - dataSetTransformService.delete( - new QueryWrapper() - .lambda() - .eq(DataSetTransform::getSetCode, setCode) - ); - if (null == dataSetTransformDtoList || dataSetTransformDtoList.size() <= 0) { - return; - } -// List 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 setContextData(List dataSetParamDtoList){ - Map map = new HashMap<>(); - if (null != dataSetParamDtoList && dataSetParamDtoList.size() > 0) { - dataSetParamDtoList.forEach(dataSetParamDto -> map.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem())); - } - return map; - } + /** + * dataSetParamDtoList转map + * @param dataSetParamDtoList + * @return + */ + public Map setContextData(List dataSetParamDtoList) { + Map map = new HashMap<>(); + if (null != dataSetParamDtoList && dataSetParamDtoList.size() > 0) { + dataSetParamDtoList.forEach( + dataSetParamDto -> map.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem())); + } + return map; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/DataSetParamController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/DataSetParamController.java index 4a7e076e1..9afa3a343 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/DataSetParamController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/DataSetParamController.java @@ -18,44 +18,45 @@ 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 { - @Autowired - private DataSetParamService dataSetParamService; + @Autowired + private DataSetParamService dataSetParamService; - @Override - public GaeaBaseService getService() { - return dataSetParamService; - } + @Override + public GaeaBaseService getService() { + return dataSetParamService; + } - @Override - public DataSetParam getEntity() { - return new DataSetParam(); - } + @Override + public DataSetParam getEntity() { + return new DataSetParam(); + } - @Override - public DataSetParamDto getDTO() { - return new DataSetParamDto(); - } + @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)); + } - /** - * 测试 查询参数是否正确 - * @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)); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/dto/DataSetParamDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/dto/DataSetParamDto.java index 81c5659f8..134e7ec74 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/dto/DataSetParamDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/dto/DataSetParamDto.java @@ -6,43 +6,42 @@ 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 paramName; + /** 数据集编码 */ + private String setCode; - /** 参数描述 */ - private String paramDesc; + /** 参数名 */ + private String paramName; - /** 参数类型,字典= */ - private String paramType; + /** 参数描述 */ + private String paramDesc; - /** 参数示例项 */ - private String sampleItem; + /** 参数类型,字典= */ + private String paramType; - /** 0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG */ - private Integer requiredFlag; + /** 参数示例项 */ + private String sampleItem; - /** js校验字段值规则,满足校验返回 true */ - private String validationRules; + /** 0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG */ + private Integer requiredFlag; - /** 排序 */ - private Integer orderNum; + /** js校验字段值规则,满足校验返回 true */ + private String validationRules; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** 排序 */ + private Integer orderNum; - /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; + + /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamParam.java index 6ad9882d1..1228f9637 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamParam.java @@ -6,12 +6,12 @@ import lombok.Data; import java.io.Serializable; - /** -* @desc DataSetParam 数据集动态参数查询输入类 -* @author Raod -* @date 2021-03-18 12:12:33.108033200 -**/ + * @desc DataSetParam 数据集动态参数查询输入类 + * @author Raod + * @date 2021-03-18 12:12:33.108033200 + **/ @Data -public class DataSetParamParam extends PageParam implements Serializable{ +public class DataSetParamParam extends PageParam implements Serializable { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamValidationParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamValidationParam.java index d2d9c0e84..e9fb4144d 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamValidationParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/controller/param/DataSetParamValidationParam.java @@ -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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/DataSetParamMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/DataSetParamMapper.java index c4f776c70..de3c635e8 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/DataSetParamMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/DataSetParamMapper.java @@ -5,10 +5,11 @@ 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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/entity/DataSetParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/entity/DataSetParam.java index 96a1648fc..022da663c 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/entity/DataSetParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/dao/entity/DataSetParam.java @@ -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 paramName; + @ApiModelProperty(value = "数据集编码") + private String setCode; - @ApiModelProperty(value = "参数描述") - private String paramDesc; + @ApiModelProperty(value = "参数名") + private String paramName; - @ApiModelProperty(value = "参数类型,字典=") - private String paramType; + @ApiModelProperty(value = "参数描述") + private String paramDesc; - @ApiModelProperty(value = "参数示例项") - private String sampleItem; + @ApiModelProperty(value = "参数类型,字典=") + private String paramType; - @ApiModelProperty(value = "0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG") - private Integer requiredFlag; + @ApiModelProperty(value = "参数示例项") + private String sampleItem; - @ApiModelProperty(value = "js校验字段值规则,满足校验返回 true") - private String validationRules; + @ApiModelProperty(value = "0--非必填 1--必填 DIC_NAME=REQUIRED_FLAG") + private Integer requiredFlag; - @ApiModelProperty(value = "排序") - private Integer orderNum; + @ApiModelProperty(value = "js校验字段值规则,满足校验返回 true") + private String validationRules; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @ApiModelProperty(value = "排序") + private Integer orderNum; - @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; + @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/DataSetParamService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/DataSetParamService.java index b8afe47c5..028beab36 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/DataSetParamService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/DataSetParamService.java @@ -16,36 +16,34 @@ import java.util.Map; **/ public interface DataSetParamService extends GaeaBaseService { - /** - * 参数替换 - * - * @param contextData - * @param dynSentence - * @return - */ - String transform(Map contextData, String dynSentence); + /** + * 参数替换 + * @param contextData + * @param dynSentence + * @return + */ + String transform(Map contextData, String dynSentence); - /** - * 参数替换 - * - * @param dataSetParamDtoList - * @param dynSentence - * @return - */ - String transform(List dataSetParamDtoList, String dynSentence); + /** + * 参数替换 + * @param dataSetParamDtoList + * @param dynSentence + * @return + */ + String transform(List dataSetParamDtoList, String dynSentence); - /** - * 参数校验 js脚本 - * @param dataSetParamDto - * @return - */ - Object verification(DataSetParamDto dataSetParamDto); + /** + * 参数校验 js脚本 + * @param dataSetParamDto + * @return + */ + Object verification(DataSetParamDto dataSetParamDto); + + /** + * 参数校验 js脚本 + * @param dataSetParamDtoList + * @return + */ + boolean verification(List dataSetParamDtoList, Map contextData); - /** - * 参数校验 js脚本 - * - * @param dataSetParamDtoList - * @return - */ - boolean verification(List dataSetParamDtoList, Map contextData); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/impl/DataSetParamServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/impl/DataSetParamServiceImpl.java index e4679b879..a4f98e88b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/impl/DataSetParamServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/service/impl/DataSetParamServiceImpl.java @@ -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; - { - ScriptEngineManager manager = new ScriptEngineManager(); - engine = manager.getEngineByName("JavaScript"); - } + private ScriptEngine engine; - @Autowired - private DataSetParamMapper dataSetParamMapper; + { + ScriptEngineManager manager = new ScriptEngineManager(); + engine = manager.getEngineByName("JavaScript"); + } - @Override - public GaeaBaseMapper getMapper() { - return dataSetParamMapper; - } + @Autowired + private DataSetParamMapper dataSetParamMapper; - /** - * 参数替换 - * - * @param contextData - * @param dynSentence - * @return - */ - @Override - public String transform(Map 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; - } + @Override + public GaeaBaseMapper getMapper() { + return dataSetParamMapper; + } - /** - * 参数替换 - * - * @param dataSetParamDtoList - * @param dynSentence - * @return - */ - @Override - public String transform(List dataSetParamDtoList, String dynSentence) { - Map 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 contextData + * @param dynSentence + * @return + */ + @Override + public String transform(Map 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; + } - /** - * 参数校验 js脚本 - * - * @param dataSetParamDto - * @return - */ - @Override - public Object verification(DataSetParamDto dataSetParamDto) { + /** + * 参数替换 + * @param dataSetParamDtoList + * @param dynSentence + * @return + */ + @Override + public String transform(List dataSetParamDtoList, String dynSentence) { + Map contextData = new HashMap<>(); + if (null == dataSetParamDtoList || dataSetParamDtoList.size() <= 0) { + return dynSentence; + } + dataSetParamDtoList.forEach(dataSetParamDto -> { + contextData.put(dataSetParamDto.getParamName(), dataSetParamDto.getSampleItem()); + }); + return transform(contextData, dynSentence); + } - 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); - } + /** + * 参数校验 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); + } - } catch (Exception ex) { - throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage()); - } + } - } - return true; - } + } + catch (Exception ex) { + throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage()); + } - /** - * 参数校验 js脚本 - * - * @param dataSetParamDtoList - * @return - */ - @Override - public boolean verification(List dataSetParamDtoList, Map contextData) { - if (null == dataSetParamDtoList || dataSetParamDtoList.size() == 0) { - return true; - } + } + return true; + } - for (DataSetParamDto dataSetParamDto : dataSetParamDtoList) { - if (null != contextData) { - String value = contextData.getOrDefault(dataSetParamDto.getParamName(), "").toString(); - dataSetParamDto.setSampleItem(value); - } + /** + * 参数校验 js脚本 + * @param dataSetParamDtoList + * @return + */ + @Override + public boolean verification(List dataSetParamDtoList, Map contextData) { + if (null == dataSetParamDtoList || dataSetParamDtoList.size() == 0) { + return true; + } - 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()); - } + for (DataSetParamDto dataSetParamDto : dataSetParamDtoList) { + if (null != contextData) { + String value = contextData.getOrDefault(dataSetParamDto.getParamName(), "").toString(); + dataSetParamDto.setSampleItem(value); + } - } - return true; - } + 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; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/util/ParamsResolverHelper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/util/ParamsResolverHelper.java index 51aad489e..73e25443f 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/util/ParamsResolverHelper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasetparam/util/ParamsResolverHelper.java @@ -12,25 +12,28 @@ 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); - public static String resolveParams(final Map param, String con) { - con = helper.replacePlaceholders(con, (key -> param.get(key) + "")); - return con; - } + private static String placeholderPrefix = "${"; - private static Pattern key = Pattern.compile("\\$\\{(.*?)\\}"); + private static String placeholderSuffix = "}"; - public static List findParamKeys(String con) { - Matcher m = key.matcher(con); - List ret = new ArrayList(); - while (m.find()) { - ret.add(m.group(1)); - } - return ret; - } + private static PropertyPlaceholderHelper helper = new PropertyPlaceholderHelper(placeholderPrefix, + placeholderSuffix); + + public static String resolveParams(final Map param, String con) { + con = helper.replacePlaceholders(con, (key -> param.get(key) + "")); + return con; + } + + private static Pattern key = Pattern.compile("\\$\\{(.*?)\\}"); + + public static List findParamKeys(String con) { + Matcher m = key.matcher(con); + List ret = new ArrayList(); + while (m.find()) { + ret.add(m.group(1)); + } + return ret; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/DataSetTransformController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/DataSetTransformController.java index 047708cae..f9b583b13 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/DataSetTransformController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/DataSetTransformController.java @@ -13,32 +13,33 @@ 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 { +public class DataSetTransformController + extends GaeaBaseController { - @Autowired - private DataSetTransformService dataSetTransformService; + @Autowired + private DataSetTransformService dataSetTransformService; - @Override - public GaeaBaseService getService() { - return dataSetTransformService; - } + @Override + public GaeaBaseService 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(); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/dto/DataSetTransformDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/dto/DataSetTransformDto.java index 28db676f1..f66bdb197 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/dto/DataSetTransformDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/dto/DataSetTransformDto.java @@ -6,31 +6,30 @@ 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; - /** 数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换 */ - private String transformType; + /** 数据集编码 */ + private String setCode; - /** 数据转换script,处理逻辑 */ - private String transformScript; + /** 数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换 */ + private String transformType; - /** 排序,执行数据转换顺序 */ - private Integer orderNum; + /** 数据转换script,处理逻辑 */ + private String transformScript; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** 排序,执行数据转换顺序 */ + private Integer orderNum; - /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; + + /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/param/DataSetTransformParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/param/DataSetTransformParam.java index 07ec30a06..8122d26ec 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/param/DataSetTransformParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/controller/param/DataSetTransformParam.java @@ -6,12 +6,12 @@ import lombok.Data; import java.io.Serializable; - /** -* @desc DataSetTransform 数据集数据转换查询输入类 -* @author Raod -* @date 2021-03-18 12:13:15.591309400 -**/ + * @desc DataSetTransform 数据集数据转换查询输入类 + * @author Raod + * @date 2021-03-18 12:13:15.591309400 + **/ @Data -public class DataSetTransformParam extends PageParam implements Serializable{ +public class DataSetTransformParam extends PageParam implements Serializable { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/DataSetTransformMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/DataSetTransformMapper.java index 209303b7f..d0be38afd 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/DataSetTransformMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/DataSetTransformMapper.java @@ -5,10 +5,11 @@ 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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/entity/DataSetTransform.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/entity/DataSetTransform.java index e81ad2934..a3ef052de 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/entity/DataSetTransform.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/dao/entity/DataSetTransform.java @@ -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 = "数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换") - private String transformType; + @ApiModelProperty(value = "数据集编码") + private String setCode; - @ApiModelProperty(value = "数据转换script,处理逻辑") - private String transformScript; + @ApiModelProperty(value = "数据转换类型,DIC_NAME=TRANSFORM_TYPE; js,javaBean,字典转换") + private String transformType; - @ApiModelProperty(value = "排序,执行数据转换顺序") - private Integer orderNum; + @ApiModelProperty(value = "数据转换script,处理逻辑") + private String transformScript; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @ApiModelProperty(value = "排序,执行数据转换顺序") + private Integer orderNum; - @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; + @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/DataSetTransformService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/DataSetTransformService.java index 92a3bb82a..5c8fac9d0 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/DataSetTransformService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/DataSetTransformService.java @@ -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 { - List transform(List dataSetTransformDtoList, List data); + List transform(List dataSetTransformDtoList, List data); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/TransformStrategy.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/TransformStrategy.java index ff8f35f8e..a3ba2aed1 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/TransformStrategy.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/TransformStrategy.java @@ -9,17 +9,19 @@ import java.util.List; * Created by raodeming on 2021/3/23. */ public interface TransformStrategy { - /** - * 数据清洗转换 类型 - * @return - */ - String type(); - /*** - * 清洗转换算法接口 - * @param def - * @param data - * @return - */ - List transform(DataSetTransformDto def, List data); + /** + * 数据清洗转换 类型 + * @return + */ + String type(); + + /*** + * 清洗转换算法接口 + * @param def + * @param data + * @return + */ + List transform(DataSetTransformDto def, List data); + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DataSetTransformServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DataSetTransformServiceImpl.java index ec2ca5b5b..1f49dcbf8 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DataSetTransformServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DataSetTransformServiceImpl.java @@ -20,52 +20,54 @@ 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 queryServiceImplMap = new HashMap<>(); - private ApplicationContext applicationContext; + private final Map queryServiceImplMap = new HashMap<>(); - @Autowired - private DataSetTransformMapper dataSetTransformMapper; + private ApplicationContext applicationContext; - @Override - public GaeaBaseMapper getMapper() { - return dataSetTransformMapper; - } + @Autowired + private DataSetTransformMapper dataSetTransformMapper; - public TransformStrategy getTarget(String type) { - return queryServiceImplMap.get(type); - } + @Override + public GaeaBaseMapper getMapper() { + return dataSetTransformMapper; + } - @Override - public void afterPropertiesSet() { - Map beanMap = applicationContext.getBeansOfType(TransformStrategy.class); - //遍历该接口的所有实现,将其放入map中 - for (TransformStrategy serviceImpl : beanMap.values()) { - queryServiceImplMap.put(serviceImpl.type(), serviceImpl); - } - } + public TransformStrategy getTarget(String type) { + return queryServiceImplMap.get(type); + } - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } + @Override + public void afterPropertiesSet() { + Map beanMap = applicationContext.getBeansOfType(TransformStrategy.class); + // 遍历该接口的所有实现,将其放入map中 + for (TransformStrategy serviceImpl : beanMap.values()) { + queryServiceImplMap.put(serviceImpl.type(), serviceImpl); + } + } - @Override - public List transform(List dataSetTransformDtoList, List data) { - if (dataSetTransformDtoList == null || dataSetTransformDtoList.size() <= 0) { - return data; - } + @Override + public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { + this.applicationContext = applicationContext; + } + + @Override + public List transform(List dataSetTransformDtoList, List data) { + if (dataSetTransformDtoList == null || dataSetTransformDtoList.size() <= 0) { + return data; + } + + for (DataSetTransformDto dataSetTransformDto : dataSetTransformDtoList) { + data = getTarget(dataSetTransformDto.getTransformType()).transform(dataSetTransformDto, data); + } + return data; + } - for (DataSetTransformDto dataSetTransformDto : dataSetTransformDtoList) { - data = getTarget(dataSetTransformDto.getTransformType()).transform(dataSetTransformDto, data); - } - return data; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DictTransformServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DictTransformServiceImpl.java index c7a583904..f3280abf8 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DictTransformServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/DictTransformServiceImpl.java @@ -11,46 +11,45 @@ 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 transform(DataSetTransformDto def, List data) { - String transformScript = def.getTransformScript(); - if (StringUtils.isBlank(transformScript)) { - return data; - } - JSONObject jsonObject = JSONObject.parseObject(transformScript); - Set keys = jsonObject.keySet(); + /*** + * 清洗转换算法接口 + * @param def + * @param data + * @return + */ + @Override + public List transform(DataSetTransformDto def, List data) { + String transformScript = def.getTransformScript(); + if (StringUtils.isBlank(transformScript)) { + return data; + } + JSONObject jsonObject = JSONObject.parseObject(transformScript); + Set 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; + } - 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; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/JsTransformServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/JsTransformServiceImpl.java index 082a2796b..70d939f76 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/JsTransformServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasettransform/service/impl/JsTransformServiceImpl.java @@ -5,7 +5,6 @@ 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; @@ -21,45 +20,47 @@ import java.util.List; @Slf4j public class JsTransformServiceImpl implements TransformStrategy { - private ScriptEngine engine; - { - ScriptEngineManager manager = new ScriptEngineManager(); - engine = manager.getEngineByName("JavaScript"); - } + private ScriptEngine engine; - /** - * 数据清洗转换 类型 - * - * @return - */ - @Override - public String type() { - return "js"; - } + { + ScriptEngineManager manager = new ScriptEngineManager(); + engine = manager.getEngineByName("JavaScript"); + } - /*** - * 清洗转换算法接口 - * @param def - * @param data - * @return - */ - @Override - public List transform(DataSetTransformDto def, List data) { - return getValueFromJs(def,data); - } + /** + * 数据清洗转换 类型 + * @return + */ + @Override + public String type() { + return "js"; + } - private List getValueFromJs(DataSetTransformDto def, List data) { - String js = def.getTransformScript(); - try { - engine.eval(js); - if(engine instanceof Invocable){ - Invocable invocable = (Invocable) engine; - return (List) invocable.invokeFunction("dataTransform", data); - } + /*** + * 清洗转换算法接口 + * @param def + * @param data + * @return + */ + @Override + public List transform(DataSetTransformDto def, List data) { + return getValueFromJs(def, data); + } + + private List getValueFromJs(DataSetTransformDto def, List data) { + String js = def.getTransformScript(); + try { + engine.eval(js); + if (engine instanceof Invocable) { + Invocable invocable = (Invocable) engine; + return (List) invocable.invokeFunction("dataTransform", data); + } + + } + catch (Exception ex) { + throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage()); + } + return null; + } - } catch (Exception ex) { - throw BusinessExceptionBuilder.build(ResponseCode.EXECUTE_JS_ERROR, ex.getMessage()); - } - return null; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientConfig.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientConfig.java index e1c8f2b66..7fa7ad9bb 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientConfig.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientConfig.java @@ -47,168 +47,168 @@ import java.util.*; @Configuration @Slf4j public class HttpClientConfig { - @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; - } + @Autowired + private HttpClientPoolConfig httpClientPoolConfig; - /** - * 初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理 - */ - @Bean(name = "dataSourceRestTemplate") - public RestTemplate restTemplate(@Qualifier("clientHttpRequestFactory") ClientHttpRequestFactory factory) { - return createRestTemplate(factory); - } + /** + * 创建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; + } - /** - * 配置httpClient - * - * @return - */ - @Bean - public HttpClient httpClient() { - HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); - try { - //设置信任ssl访问 - SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); + /** + * 初始化RestTemplate,并加入spring的Bean工厂,由spring统一管理 + */ + @Bean(name = "dataSourceRestTemplate") + public RestTemplate restTemplate(@Qualifier("clientHttpRequestFactory") ClientHttpRequestFactory factory) { + return createRestTemplate(factory); + } - httpClientBuilder.setSSLContext(sslContext); - HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; - SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); - Registry socketFactoryRegistry = RegistryBuilder.create() - // 注册http和https请求 - .register("http", PlainConnectionSocketFactory.getSocketFactory()) - .register("https", sslConnectionSocketFactory).build(); + /** + * 配置httpClient + * @return + */ + @Bean + public HttpClient httpClient() { + HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); + try { + // 设置信任ssl访问 + SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).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)); + httpClientBuilder.setSSLContext(sslContext); + HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE; + SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, + hostnameVerifier); + Registry socketFactoryRegistry = RegistryBuilder.create() + // 注册http和https请求 + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", sslConnectionSocketFactory).build(); - //设置默认请求头 - List
headers = getDefaultHeaders(); - httpClientBuilder.setDefaultHeaders(headers); - //设置长连接保持策略 - httpClientBuilder.setKeepAliveStrategy(connectionKeepAliveStrategy()); - return httpClientBuilder.build(); - } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { - log.error("初始化HTTP连接池出错", e); - } - return null; - } + // 使用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
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> 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> 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
getDefaultHeaders() { + List
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; + } - /** - * 设置请求头 - * - * @return - */ - private List
getDefaultHeaders() { - List
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); + // 我们采用RestTemplate内部的MessageConverter + // 重新设置StringHttpMessageConverter字符集,解决中文乱码问题 + modifyDefaultCharset(restTemplate); - private RestTemplate createRestTemplate(ClientHttpRequestFactory factory) { - RestTemplate restTemplate = new RestTemplate(factory); + // 设置错误处理器 + restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); - //我们采用RestTemplate内部的MessageConverter - //重新设置StringHttpMessageConverter字符集,解决中文乱码问题 - modifyDefaultCharset(restTemplate); + return restTemplate; + } - //设置错误处理器 - restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); + /** + * 修改默认的字符集类型为utf-8 + * @param restTemplate + */ + private void modifyDefaultCharset(RestTemplate restTemplate) { + List> 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)); + } - return restTemplate; - } - - /** - * 修改默认的字符集类型为utf-8 - * - * @param restTemplate - */ - private void modifyDefaultCharset(RestTemplate restTemplate) { - List> 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)); - } } - diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientPoolConfig.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientPoolConfig.java index ad12493a7..41c1f9bd3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientPoolConfig.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/config/HttpClientPoolConfig.java @@ -13,41 +13,50 @@ 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; - private String charset = "UTF-8"; - /** - * 重试次数,默认2次 - */ - private int retryTimes = 2; - /** - * 从连接池获取连接的超时时间,不宜过长,单位ms - */ - private int connectionRequestTimout = 200; - /** - * 针对不同的地址,特别设置不同的长连接保持时间 - */ - private Map keepAliveTargetHost; - /** - * 针对不同的地址,特别设置不同的长连接保持时间,单位 s - */ - private int keepAliveTime = 60; + /** + * 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 keepAliveTargetHost; + + /** + * 针对不同的地址,特别设置不同的长连接保持时间,单位 s + */ + private int keepAliveTime = 60; + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/DataSourceController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/DataSourceController.java index ba6c3a4d8..47db1d24a 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/DataSourceController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/DataSourceController.java @@ -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 { - @Autowired - private DataSourceService dataSourceService; + @Autowired + private DataSourceService dataSourceService; - @Override - public GaeaBaseService getService() { - return dataSourceService; - } + @Override + public GaeaBaseService 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)); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/dto/DataSourceDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/dto/DataSourceDto.java index e22eea62a..85c9299f6 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/dto/DataSourceDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/dto/DataSourceDto.java @@ -7,68 +7,74 @@ 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 sourceName; + /** 数据源编码 */ + private String sourceCode; - /** 数据源描述 */ - private String sourceDesc; + /** 数据源名称 */ + private String sourceName; - /** 数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 */ - private String sourceType; + /** 数据源描述 */ + private String sourceDesc; - /** 数据源连接配置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; + /** + * 数据源类型 DIC_NAME=SOURCE_TYPE; + * mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 + */ + private String sourceType; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** + * 数据源连接配置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=DELETE_FLAG */ - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; - /**************************************************************/ - /**关系型数据库jdbcUrl */ - private String jdbcUrl; + /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ + private Integer deleteFlag; - /** 关系型数据库用户名 */ - private String username; + /**************************************************************/ + /** 关系型数据库jdbcUrl */ + private String jdbcUrl; - /** 关系型数据库密码 */ - private String password; + /** 关系型数据库用户名 */ + private String username; - /** 关系型数据库驱动类 */ - private String driverName; + /** 关系型数据库密码 */ + private String password; - /** 关系型数据库sql */ - private String sql; + /** 关系型数据库驱动类 */ + private String driverName; - /** http requestUrl */ - private String apiUrl; + /** 关系型数据库sql */ + private String sql; - /** http method */ - private String method; + /** http requestUrl */ + private String apiUrl; - /** http header */ - private String header; + /** http method */ + private String method; - /** http 请求体 */ - private String body; + /** http header */ + private String header; - /** 动态查询sql或者接口中的请求体 */ - private String dynSentence; + /** http 请求体 */ + private String body; - /** 传入的自定义参数,解决url中存在的动态参数*/ - private Map contextData; + /** 动态查询sql或者接口中的请求体 */ + private String dynSentence; + + /** 传入的自定义参数,解决url中存在的动态参数 */ + private Map contextData; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/ConnectionParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/ConnectionParam.java index ec97092c9..3b6925c59 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/ConnectionParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/ConnectionParam.java @@ -11,11 +11,19 @@ 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; + /** + * 数据源类型 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; - /** 数据源连接配置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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/DataSourceParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/DataSourceParam.java index f8d98e876..0e2bd1ffe 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/DataSourceParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/controller/param/DataSourceParam.java @@ -8,24 +8,27 @@ 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; + /** 数据源编码 */ + @Query(QueryEnum.LIKE) + private String sourceCode; + + /** + * 数据源类型 DIC_NAME=SOURCE_TYPE; + * mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 + */ + @Query(QueryEnum.EQ) + private String sourceType; - /** 数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单 */ - @Query(QueryEnum.EQ) - private String sourceType; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/DataSourceMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/DataSourceMapper.java index 3bcf882de..19743bb10 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/DataSourceMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/DataSourceMapper.java @@ -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 { diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/entity/DataSource.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/entity/DataSource.java index 79f1e5b33..d2e14d21e 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/entity/DataSource.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/dao/entity/DataSource.java @@ -9,34 +9,36 @@ 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 = "数据源名称") - private String sourceName; + @ApiModelProperty(value = "数据源编码") + @Unique(code = ResponseCode.SOURCE_CODE_ISEXIST) + private String sourceCode; - @ApiModelProperty(value = "数据源描述") - private String sourceDesc; + @ApiModelProperty(value = "数据源名称") + private String sourceName; - @ApiModelProperty(value = "数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单") - private String sourceType; + @ApiModelProperty(value = "数据源描述") + private String sourceDesc; - @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 = "数据源类型 DIC_NAME=SOURCE_TYPE; mysql,orace,sqlserver,elasticsearch,接口,javaBean,数据源类型字典中item-extend动态生成表单") + private String sourceType; - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + @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=DELETE_FLAG") - private Integer deleteFlag; + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; + @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") + private Integer deleteFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/DataSourceService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/DataSourceService.java index 17e318b1b..c72afc640 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/DataSourceService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/DataSourceService.java @@ -12,37 +12,38 @@ 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 { - /** - * 获取所有数据源 - * @return - */ - List queryAllDataSource(); + /** + * 获取所有数据源 + * @return + */ + List queryAllDataSource(); - /** - * 测试 连接 - * @param connectionParam - * @return - */ - Boolean testConnection(ConnectionParam connectionParam); + /** + * 测试 连接 + * @param connectionParam + * @return + */ + Boolean testConnection(ConnectionParam connectionParam); - /** - * 执行sql - * @param dto - * @return - */ - List execute(DataSourceDto dto); + /** + * 执行sql + * @param dto + * @return + */ + List execute(DataSourceDto dto); + + /** + * 执行sql,统计数据total + * @param dataSourceDto + * @param dto + * @return + */ + long total(DataSourceDto dataSourceDto, DataSetDto dto); - /** - * 执行sql,统计数据total - * @param dataSourceDto - * @param dto - * @return - */ - long total(DataSourceDto dataSourceDto, DataSetDto dto); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/JdbcService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/JdbcService.java index 56dadf96d..65e4cb7c1 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/JdbcService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/JdbcService.java @@ -10,30 +10,27 @@ 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 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 ClassNotFoundException driverName不正确 - * @throws SQLException - */ - Connection getUnPooledConnection(DataSourceDto dataSource) throws SQLException; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/DataSourceServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/DataSourceServiceImpl.java index 0485a2945..6e8ec81b2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/DataSourceServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/DataSourceServiceImpl.java @@ -33,7 +33,10 @@ import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; -import java.sql.*; +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; @@ -48,405 +51,410 @@ 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 getMapper() { - return dataSourceMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return dataSourceMapper; + } + /** + * 获取所有数据源 + * @return + */ + @Override + public List queryAllDataSource() { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.select(DataSource::getSourceCode, DataSource::getSourceName).eq(DataSource::getEnableFlag, + Enabled.YES.getValue()); + wrapper.orderByDesc(DataSource::getUpdateTime); + return dataSourceMapper.selectList(wrapper); + } - /** - * 获取所有数据源 - * @return - */ - @Override - public List queryAllDataSource() { - LambdaQueryWrapper 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; - /** - * 测试 连接 - * - * @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 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); + } + } - @Override - public List 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); + } - /** - * 执行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 result = execute(sourceDto); - /** - * 获取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 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"); + } - //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 executeElasticsearchSql(DataSourceDto dto) { + analysisHttpConfig(dto); + HttpHeaders headers = new HttpHeaders(); + headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class)); + HttpEntity entity = new HttpEntity<>(dto.getDynSentence(), headers); + ResponseEntity 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 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; + } + public List executeRelationalDb(DataSourceDto dto) { + analysisRelationalDbConfig(dto); + Connection pooledConnection = null; + try { + pooledConnection = jdbcService.getPooledConnection(dto); + PreparedStatement statement = pooledConnection.prepareStatement(dto.getDynSentence()); + ResultSet rs = statement.executeQuery(); - public List executeElasticsearchSql(DataSourceDto dto) { - analysisHttpConfig(dto); - HttpHeaders headers = new HttpHeaders(); - headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class)); - HttpEntity entity = new HttpEntity<>(dto.getDynSentence(), headers); - ResponseEntity 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 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; - } + int columnCount = rs.getMetaData().getColumnCount(); - public List executeRelationalDb(DataSourceDto dto) { - analysisRelationalDbConfig(dto); - Connection pooledConnection = null; - try { - pooledConnection = jdbcService.getPooledConnection(dto); + List columns = new ArrayList<>(); + for (int i = 1; i <= columnCount; i++) { + String columnName = rs.getMetaData().getColumnLabel(i); + columns.add(columnName); + } + List 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()); + } + } + } - PreparedStatement statement = pooledConnection.prepareStatement(dto.getDynSentence()); - ResultSet rs = statement.executeQuery(); + /** + * 解决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)); + } - int columnCount = rs.getMetaData().getColumnCount(); + return result; + } - List columns = new ArrayList<>(); - for (int i = 1; i <= columnCount; i++) { - String columnName = rs.getMetaData().getColumnLabel(i); - columns.add(columnName); - } - List 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()); - } - } - } + /** + * http 执行获取数据 + * @param dto + */ + public List executeHttp(DataSourceDto dto) { + analysisHttpConfig(dto); + HttpHeaders headers = new HttpHeaders(); + headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class)); + HttpEntity entity = new HttpEntity<>(dto.getDynSentence(), headers); + ResponseEntity 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 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; + } - /** - * 解决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)); - } + /** + * 关系型数据库 测试连接 + * @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()); + } - return result; - } + } + } - /** - * http 执行获取数据 - * - * @param dto - */ - public List executeHttp(DataSourceDto dto) { - analysisHttpConfig(dto); - HttpHeaders headers = new HttpHeaders(); - headers.setAll(JSONObject.parseObject(dto.getHeader(), Map.class)); - HttpEntity entity = new HttpEntity<>(dto.getDynSentence(), headers); - ResponseEntity 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 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; - } + /** + * 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 entity = new HttpEntity<>(body, headers); + ResponseEntity 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()); - } + /** + * 关系型数据库 测试连接 + * @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 entity = new HttpEntity<>(body, headers); + ResponseEntity 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 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 entity = new HttpEntity<>(body, headers); - ResponseEntity 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 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 entity = new HttpEntity<>(body, headers); - ResponseEntity 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 entity + * @param operationEnum 操作类型 + * @throws BusinessException 阻止程序继续执行或回滚事务 + */ + @Override + public void processAfterOperation(DataSource entity, BaseOperationEnum operationEnum) throws BusinessException { + jdbcService.removeJdbcConnectionPool(entity.getId()); + } - } - - - 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()); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/JdbcServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/JdbcServiceImpl.java index 694aa2fd0..8bae27023 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/JdbcServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/datasource/service/impl/JdbcServiceImpl.java @@ -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 map = new ConcurrentHashMap<>(); + /** + * 所有数据源的连接池存在map里 + */ + static Map 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 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 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(); - } + /** + * 测试数据库连接 获取一个连接 + * @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(); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictController.java index e7c0fc731..549e53a0c 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictController.java @@ -15,7 +15,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.i18n.LocaleContextHolder; import org.springframework.web.bind.annotation.*; -import java.util.*; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Map; /** * (GaeaDict)实体类 @@ -28,89 +31,89 @@ import java.util.*; @Api(value = "/gaeaDict", tags = "") public class GaeaDictController extends GaeaBaseController { - @Autowired - private GaeaDictService gaeaDictService; + @Autowired + private GaeaDictService gaeaDictService; - @Autowired - private GaeaDictItemService gaeaDictItemService; + @Autowired + private GaeaDictItemService gaeaDictItemService; - @Override - public GaeaBaseService getService() { - return gaeaDictService; - } + @Override + public GaeaBaseService 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 dictCodes) { + // 刷新 + gaeaDictService.refreshCache(dictCodes); + return responseSuccess(); + } - /** - * 刷新指定字典项 - * @return - */ - @PostMapping("/freshDict") - @Permission(code = "fresh",name = "刷新") - public ResponseBean refreshDict(@RequestBody List 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 - */ - @GetMapping("/select/{dictCode}") - @Permission(code = "query",name = "下拉") - public ResponseBean select(@PathVariable("dictCode") String dictName){ - Locale locale = LocaleContextHolder.getLocale(); - //语言 - String language = locale.getLanguage(); + List keyValues = gaeaDictService.select(dictName, language); + return responseSuccessWithData(keyValues); + } - List keyValues = gaeaDictService.select(dictName,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("/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(); + Collection keyValues = gaeaDictService.selectTypeCode(project, language); + return responseSuccessWithData(keyValues); + } - Collection keyValues = gaeaDictService.selectTypeCode(project,language); - return responseSuccessWithData(keyValues); - } + /** + * 获取所有字典 + * @return + */ + @GetMapping("/all") + public ResponseBean all() { + Locale locale = LocaleContextHolder.getLocale(); + // 语言 + String language = locale.getLanguage(); - /** - * 获取所有字典 - * @return - */ - @GetMapping("/all") - public ResponseBean all(){ - Locale locale = LocaleContextHolder.getLocale(); - //语言 - String language = locale.getLanguage(); + Map> all = gaeaDictService.all(language); + return responseSuccessWithData(all); + } - Map> all = gaeaDictService.all(language); - return responseSuccessWithData(all); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictItemController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictItemController.java index 92a431d34..cb78a1dfb 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictItemController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/GaeaDictItemController.java @@ -1,15 +1,15 @@ package com.anjiplus.template.gaea.business.modules.dict.controller; import com.anji.plus.gaea.curd.controller.GaeaBaseController; -import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem; +import com.anji.plus.gaea.curd.service.GaeaBaseService; 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,21 +21,23 @@ import org.springframework.beans.factory.annotation.Autowired; @RequestMapping("/gaeaDictItem") @Api(value = "/gaeaDictItem", tags = "数据字典项") public class GaeaDictItemController extends GaeaBaseController { - @Autowired - private GaeaDictItemService gaeaDictItemService; - - @Override - public GaeaBaseService getService() { - return gaeaDictItemService; - } - @Override - public GaeaDictItem getEntity() { - return new GaeaDictItem(); - } + @Autowired + private GaeaDictItemService gaeaDictItemService; - @Override - public GaeaDictItemDTO getDTO() { - return new GaeaDictItemDTO(); - } -} \ No newline at end of file + @Override + public GaeaBaseService getService() { + return gaeaDictItemService; + } + + @Override + public GaeaDictItem getEntity() { + return new GaeaDictItem(); + } + + @Override + public GaeaDictItemDTO getDTO() { + return new GaeaDictItemDTO(); + } + +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictDTO.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictDTO.java index e4c5830f3..eb49a4972 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictDTO.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictDTO.java @@ -16,21 +16,23 @@ 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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictItemDTO.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictItemDTO.java index ef4cabb02..ccd4acbc2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictItemDTO.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/dto/GaeaDictItemDTO.java @@ -16,45 +16,52 @@ 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 itemExtend; - /** - * 语言标识 - */ - @ApiModelProperty(value = "语言标识") - private String locale; - /** - * 描述 - */ - @ApiModelProperty(value = "描述") - private String remark; - /** - * 排序 - */ - @ApiModelProperty(value = "排序") - private Integer sort; + /** + * 数据字典编码 + */ + @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; - /** - * 1:启用,0:禁用 - */ - private Integer enabled; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictItemParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictItemParam.java index 1b148e867..56052b1dc 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictItemParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictItemParam.java @@ -1,6 +1,5 @@ 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; @@ -17,23 +16,25 @@ import java.io.Serializable; @Data public class GaeaDictItemParam extends PageParam implements Serializable { - /** - * 数据字典编码 - */ - private String dictCode; - /** - * 字典项名称 - */ - @Query(QueryEnum.LIKE) - private String itemName; + /** + * 数据字典编码 + */ + private String dictCode; - /** - * 语言标识 - */ - private String locale; + /** + * 字典项名称 + */ + @Query(QueryEnum.LIKE) + private String itemName; + + /** + * 语言标识 + */ + private String locale; + + /** + * 1:启用,0:禁用 + */ + private Integer enabled; - /** - * 1:启用,0:禁用 - */ - private Integer enabled; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictParam.java index 5e23591c5..a9deb4c98 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/controller/param/GaeaDictParam.java @@ -1,6 +1,5 @@ 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,14 +15,17 @@ 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; + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictItemMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictItemMapper.java index 26451825e..5e89919f7 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictItemMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictItemMapper.java @@ -1,7 +1,7 @@ package com.anjiplus.template.gaea.business.modules.dict.dao; -import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem; import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper; +import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDictItem; import org.apache.ibatis.annotations.Mapper; /** @@ -13,5 +13,4 @@ import org.apache.ibatis.annotations.Mapper; @Mapper public interface GaeaDictItemMapper extends GaeaBaseMapper { - -} \ No newline at end of file +} diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictMapper.java index cfd7b4a45..458dc7211 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/GaeaDictMapper.java @@ -1,7 +1,7 @@ package com.anjiplus.template.gaea.business.modules.dict.dao; -import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDict; import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper; +import com.anjiplus.template.gaea.business.modules.dict.dao.entity.GaeaDict; import org.apache.ibatis.annotations.Mapper; /** @@ -13,5 +13,4 @@ import org.apache.ibatis.annotations.Mapper; @Mapper public interface GaeaDictMapper extends GaeaBaseMapper { - } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDict.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDict.java index 0bae69024..cd52c21cc 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDict.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDict.java @@ -13,44 +13,47 @@ import java.io.Serializable; * @author lr * @since 2021-02-23 10:01:02 */ -@TableName(keepGlobalPrefix=true, value = "gaea_dict") +@TableName(keepGlobalPrefix = true, value = "gaea_dict") public class GaeaDict extends GaeaBaseEntity implements Serializable { - /** - * 字典名称 - */ - private String dictName; - /** - * 字典编码 - */ - @Unique(code = ResponseCode.DICCODE_ISEXIST) - private String dictCode; - /** - * 字典描述 - */ - private String remark; + /** + * 字典名称 + */ + private String dictName; - public String getDictName() { - return dictName; - } + /** + * 字典编码 + */ + @Unique(code = ResponseCode.DICCODE_ISEXIST) + private String dictCode; - public void setDictName(String dictName) { - this.dictName = dictName; - } + /** + * 字典描述 + */ + private String remark; - public String getDictCode() { - return dictCode; - } + public String getDictName() { + return dictName; + } - public void setDictCode(String dictCode) { - this.dictCode = dictCode; - } + public void setDictName(String dictName) { + this.dictName = dictName; + } - public String getRemark() { - return remark; - } + public String getDictCode() { + return dictCode; + } + + public void setDictCode(String dictCode) { + this.dictCode = dictCode; + } + + public String getRemark() { + return remark; + } + + public void setRemark(String remark) { + this.remark = remark; + } - public void setRemark(String remark) { - this.remark = remark; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDictItem.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDictItem.java index 37f75c2c6..417fde483 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDictItem.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/dao/entity/GaeaDictItem.java @@ -2,8 +2,8 @@ package com.anjiplus.template.gaea.business.modules.dict.dao.entity; import com.anji.plus.gaea.annotation.UnionUnique; import com.anji.plus.gaea.annotation.UnionUniqueCode; -import com.anjiplus.template.gaea.business.code.*; import com.anji.plus.gaea.curd.entity.GaeaBaseEntity; +import com.anjiplus.template.gaea.business.code.ResponseCode; import com.anjiplus.template.gaea.business.constant.BusinessConstant; import com.baomidou.mybatisplus.annotation.TableName; @@ -15,109 +15,115 @@ import java.io.Serializable; * @author lirui * @since 2021-03-09 15:52:41 */ -@TableName(keepGlobalPrefix=true,value = "gaea_dict_item") +@TableName(keepGlobalPrefix = true, value = "gaea_dict_item") @UnionUniqueCode(group = BusinessConstant.DICT_ITEM_EXIST_GROUP, code = ResponseCode.DICT_ITEM_REPEAT) public class GaeaDictItem extends GaeaBaseEntity implements Serializable { - /** - * 数据字典编码 - */ - @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) - private String dictCode; - /** - * 字典项名称 - */ - private String itemName; - /** - * 字典项值 - */ - @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) - private String itemValue; + /** + * 数据字典编码 + */ + @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) + private String dictCode; - /** - * 字典项扩展 - */ - private String itemExtend; - /** - * 语言标识 - */ - @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) - private String locale; + /** + * 字典项名称 + */ + private String itemName; - /** - * 1:启用,0:禁用 - */ - private Integer enabled; - /** - * 描述 - */ - private String remark; - /** - * 排序 - */ - private Integer sort; + /** + * 字典项值 + */ + @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) + private String itemValue; - public String getDictCode() { - return dictCode; - } + /** + * 字典项扩展 + */ + private String itemExtend; - public void setDictCode(String dictCode) { - this.dictCode = dictCode; - } + /** + * 语言标识 + */ + @UnionUnique(group = BusinessConstant.DICT_ITEM_EXIST_GROUP) + private String locale; - public String getItemName() { - return itemName; - } + /** + * 1:启用,0:禁用 + */ + private Integer enabled; - public void setItemName(String itemName) { - this.itemName = itemName; - } + /** + * 描述 + */ + private String remark; - public String getItemValue() { - return itemValue; - } + /** + * 排序 + */ + private Integer sort; - public void setItemValue(String itemValue) { - this.itemValue = itemValue; - } + public String getDictCode() { + return dictCode; + } - public String getLocale() { - return locale; - } + public void setDictCode(String dictCode) { + this.dictCode = dictCode; + } - public void setLocale(String locale) { - this.locale = locale; - } + public String getItemName() { + return itemName; + } - public String getRemark() { - return remark; - } + public void setItemName(String itemName) { + this.itemName = itemName; + } - public void setRemark(String remark) { - this.remark = remark; - } + public String getItemValue() { + return itemValue; + } - public Integer getSort() { - return sort; - } + public void setItemValue(String itemValue) { + this.itemValue = itemValue; + } - public void setSort(Integer sort) { - this.sort = sort; - } + public String getLocale() { + return locale; + } - public Integer getEnabled() { - return enabled; - } + public void setLocale(String locale) { + this.locale = locale; + } - public void setEnabled(Integer enabled) { - this.enabled = enabled; - } + public String getRemark() { + return remark; + } - public String getItemExtend() { - return itemExtend; - } + public void setRemark(String remark) { + this.remark = remark; + } + + public Integer getSort() { + return sort; + } + + public void setSort(Integer sort) { + this.sort = sort; + } + + public Integer getEnabled() { + return enabled; + } + + public void setEnabled(Integer enabled) { + this.enabled = enabled; + } + + public String getItemExtend() { + return itemExtend; + } + + public void setItemExtend(String itemExtend) { + this.itemExtend = itemExtend; + } - public void setItemExtend(String itemExtend) { - this.itemExtend = itemExtend; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictItemService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictItemService.java index 462915441..bb9a23b99 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictItemService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictItemService.java @@ -14,10 +14,11 @@ import java.util.Map; */ public interface GaeaDictItemService extends GaeaBaseService { - /** - * 根据字典编码获取字典项 - * @param dictCode - * @return - */ - Map getItemMap(String dictCode); + /** + * 根据字典编码获取字典项 + * @param dictCode + * @return + */ + Map getItemMap(String dictCode); + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictService.java index 1649a4b58..c4a882502 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/GaeaDictService.java @@ -18,39 +18,39 @@ import java.util.Map; */ public interface GaeaDictService extends GaeaBaseService { - /** - * 刷新全部缓存 - * @param dictCodes - */ - void refreshCache(List dictCodes); + /** + * 刷新全部缓存 + * @param dictCodes + */ + void refreshCache(List dictCodes); + /** + * 获取指定字典code下拉 + * @param dictCode + * @param language + * @return + */ + List select(String dictCode, String language); - /** - * 获取指定字典code下拉 - * @param dictCode - * @param language - * @return - */ - List select(String dictCode, String language); + /** + * 获取所有字典项 + * @return + */ + List findItems(List dictCodes); - /** - * 获取所有字典项 - * @return - */ - List findItems(List dictCodes); - /** - * 获取所有 typecode - * @param system - * @param language - * @return - */ - Collection selectTypeCode(String system, String language); + /** + * 获取所有 typecode + * @param system + * @param language + * @return + */ + Collection selectTypeCode(String system, String language); + /** + * 获取所有数据字典 + * @param language + * @return + */ + Map> all(String language); - /** - * 获取所有数据字典 - * @param language - * @return - */ - Map> all(String language); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictItemServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictItemServiceImpl.java index 414af7eaa..5d4823cd2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictItemServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictItemServiceImpl.java @@ -30,69 +30,71 @@ import java.util.stream.Collectors; */ @Service public class GaeaDictItemServiceImpl implements GaeaDictItemService { - @Autowired - private GaeaDictItemMapper gaeaDictItemMapper; - @Autowired - private CacheHelper cacheHelper; + @Autowired + private GaeaDictItemMapper gaeaDictItemMapper; - @Override - public GaeaBaseMapper getMapper() { - return gaeaDictItemMapper; - } + @Autowired + private CacheHelper cacheHelper; + @Override + public GaeaBaseMapper getMapper() { + return gaeaDictItemMapper; + } - @Override - public void processAfterOperation(GaeaDictItem entity, BaseOperationEnum operationEnum) throws BusinessException { - String dictCode = entity.getDictCode(); - String locale = entity.getLocale(); + @Override + public void processAfterOperation(GaeaDictItem entity, BaseOperationEnum operationEnum) throws BusinessException { + String dictCode = entity.getDictCode(); + String locale = entity.getLocale(); - String key = GaeaKeyConstant.DICT_PREFIX + locale + GaeaConstant.REDIS_SPLIT + dictCode; - switch (operationEnum) { - case INSERT: - case UPDATE: - cacheHelper.hashSet(key, entity.getItemValue(), entity.getItemName()); - break; - case DELETE: - cacheHelper.hashDel(key, entity.getItemValue()); - default: - } - } + String key = GaeaKeyConstant.DICT_PREFIX + locale + GaeaConstant.REDIS_SPLIT + dictCode; + switch (operationEnum) { + case INSERT: + case UPDATE: + cacheHelper.hashSet(key, entity.getItemValue(), entity.getItemName()); + break; + case DELETE: + cacheHelper.hashDel(key, entity.getItemValue()); + default: + } + } - @Override - public void processBatchAfterOperation(List entities, BaseOperationEnum operationEnum) throws BusinessException { - if (CollectionUtils.isEmpty(entities)) { - return; - } + @Override + public void processBatchAfterOperation(List entities, BaseOperationEnum operationEnum) + throws BusinessException { + if (CollectionUtils.isEmpty(entities)) { + return; + } - Map> dictItemMap = entities.stream() - .collect(Collectors.groupingBy(item -> item.getLocale() + GaeaConstant.REDIS_SPLIT +item.getDictCode(), - Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName,(v1,v2)-> v2))); + Map> dictItemMap = entities.stream() + .collect(Collectors.groupingBy(item -> item.getLocale() + GaeaConstant.REDIS_SPLIT + item.getDictCode(), + Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName, (v1, v2) -> v2))); - switch (operationEnum) { - case DELETE_BATCH: - //遍历并保持到Redis中 - dictItemMap.entrySet().stream().forEach(entry -> { - String key = GaeaKeyConstant.DICT_PREFIX + entry.getKey(); - Set hashKeys = entry.getValue().keySet(); - cacheHelper.hashBatchDel(key, hashKeys); - }); - break; - default: - } - } + switch (operationEnum) { + case DELETE_BATCH: + // 遍历并保持到Redis中 + dictItemMap.entrySet().stream().forEach(entry -> { + String key = GaeaKeyConstant.DICT_PREFIX + entry.getKey(); + Set hashKeys = entry.getValue().keySet(); + cacheHelper.hashBatchDel(key, hashKeys); + }); + break; + default: + } + } - @Override - public Map getItemMap(String dictCode) { - Locale locale = LocaleContextHolder.getLocale(); + @Override + public Map getItemMap(String dictCode) { + Locale locale = LocaleContextHolder.getLocale(); - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); - wrapper.eq(GaeaDictItem::getDictCode, dictCode); - wrapper.eq(GaeaDictItem::getLocale, locale.getLanguage()); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.eq(GaeaDictItem::getDictCode, dictCode); + wrapper.eq(GaeaDictItem::getLocale, locale.getLanguage()); - List list = list(wrapper); - Map data = list.stream().collect(Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName, (v1, v2) -> v2)); - return data; - } + List list = list(wrapper); + Map data = list.stream() + .collect(Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName, (v1, v2) -> v2)); + return data; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictServiceImpl.java index 1216fe219..ea4fe4061 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/dict/service/impl/GaeaDictServiceImpl.java @@ -31,154 +31,144 @@ import java.util.stream.Collectors; @Service public class GaeaDictServiceImpl implements GaeaDictService { - @Autowired - private GaeaDictMapper gaeaDictMapper; + @Autowired + private GaeaDictMapper gaeaDictMapper; - @Autowired - private GaeaDictItemMapper gaeaDictItemMapper; + @Autowired + private GaeaDictItemMapper gaeaDictItemMapper; - @Autowired - private CacheHelper cacheHelper; + @Autowired + private CacheHelper cacheHelper; - @Override - public GaeaBaseMapper getMapper() { - return gaeaDictMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return gaeaDictMapper; + } - /** - * 刷新全部缓存 - * @param dictCodes - */ - @Override - public void refreshCache(List dictCodes) { + /** + * 刷新全部缓存 + * @param dictCodes + */ + @Override + public void refreshCache(List dictCodes) { - //查询指定字典项 - List gaeaDictItems = findItems(dictCodes); + // 查询指定字典项 + List gaeaDictItems = findItems(dictCodes); - //对数据字典项进行分组,分组key=语言标识:字典编码 - Map> dictItemMap = gaeaDictItems.stream() - .collect(Collectors - .groupingBy(item -> item.getLocale() + GaeaConstant.REDIS_SPLIT +item.getDictCode(), - Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName,(v1,v2)-> v2))); + // 对数据字典项进行分组,分组key=语言标识:字典编码 + Map> dictItemMap = gaeaDictItems.stream() + .collect(Collectors.groupingBy(item -> item.getLocale() + GaeaConstant.REDIS_SPLIT + item.getDictCode(), + Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemName, (v1, v2) -> v2))); - //遍历并保持到Redis中 - dictItemMap.entrySet().stream().forEach(entry -> { - String key = GaeaKeyConstant.DICT_PREFIX + entry.getKey(); - cacheHelper.delete(key); - cacheHelper.hashSet(key, entry.getValue()); - }); - } + // 遍历并保持到Redis中 + dictItemMap.entrySet().stream().forEach(entry -> { + String key = GaeaKeyConstant.DICT_PREFIX + entry.getKey(); + cacheHelper.delete(key); + cacheHelper.hashSet(key, entry.getValue()); + }); + } - /** - * 根据国际化语言查询指定字典编码下拉列表 - * 先从Redis中获取 - * @param dictCode 字典名称 - * @param language 语言 - * @return - */ - @Override - public List select(String dictCode, String language) { + /** + * 根据国际化语言查询指定字典编码下拉列表 先从Redis中获取 + * @param dictCode 字典名称 + * @param language 语言 + * @return + */ + @Override + public List select(String dictCode, String language) { - //缓存字典Key - String dictKey = GaeaKeyConstant.DICT_PREFIX + language + GaeaConstant.REDIS_SPLIT + dictCode; + // 缓存字典Key + String dictKey = GaeaKeyConstant.DICT_PREFIX + language + GaeaConstant.REDIS_SPLIT + dictCode; - Map dictMap = cacheHelper.hashGet(dictKey); + Map dictMap = cacheHelper.hashGet(dictKey); - //当查询的字典为空时 - if (CollectionUtils.isEmpty(dictMap)) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); - wrapper.eq(GaeaDictItem::getDictCode, dictCode) - .eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()) - .eq(GaeaDictItem::getLocale, language) - .orderByAsc(GaeaDictItem::getSort); + // 当查询的字典为空时 + if (CollectionUtils.isEmpty(dictMap)) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.eq(GaeaDictItem::getDictCode, dictCode).eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()) + .eq(GaeaDictItem::getLocale, language).orderByAsc(GaeaDictItem::getSort); - List list = gaeaDictItemMapper.selectList(wrapper); + List list = gaeaDictItemMapper.selectList(wrapper); - List keyValues = list.stream() - .map(dictItemEntity -> new KeyValue(dictItemEntity.getItemValue(), dictItemEntity.getItemName(), dictItemEntity.getItemExtend())) - .collect(Collectors.toList()); - //当缓存不存在时,刷新缓存 - List dictCodes = new ArrayList<>(); - dictCodes.add(dictCode); - refreshCache(dictCodes); - return keyValues; - } + List keyValues = list.stream().map(dictItemEntity -> new KeyValue(dictItemEntity.getItemValue(), + dictItemEntity.getItemName(), dictItemEntity.getItemExtend())).collect(Collectors.toList()); + // 当缓存不存在时,刷新缓存 + List dictCodes = new ArrayList<>(); + dictCodes.add(dictCode); + refreshCache(dictCodes); + return keyValues; + } - List keyValues = GaeaUtils.formatKeyValue(dictMap); + List keyValues = GaeaUtils.formatKeyValue(dictMap); - //添加扩展字段 - LambdaQueryWrapper gaeaDictItemWrapper = Wrappers.lambdaQuery(); - gaeaDictItemWrapper.eq(GaeaDictItem::getDictCode, dictCode); - gaeaDictItemWrapper.isNotNull(GaeaDictItem::getItemExtend); + // 添加扩展字段 + LambdaQueryWrapper gaeaDictItemWrapper = Wrappers.lambdaQuery(); + gaeaDictItemWrapper.eq(GaeaDictItem::getDictCode, dictCode); + gaeaDictItemWrapper.isNotNull(GaeaDictItem::getItemExtend); - Map extendMap = gaeaDictItemMapper.selectList(gaeaDictItemWrapper).stream() - .filter(gaeaDictItem -> StringUtils.isNotBlank(gaeaDictItem.getItemExtend())) - .collect(Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemExtend, (v1, v2) -> v2)); - if (!CollectionUtils.isEmpty(extendMap)) { - keyValues.stream().forEach(keyValue -> keyValue.setExtend(extendMap.get(keyValue.getId()))); - } - return keyValues; - } + Map extendMap = gaeaDictItemMapper.selectList(gaeaDictItemWrapper).stream() + .filter(gaeaDictItem -> StringUtils.isNotBlank(gaeaDictItem.getItemExtend())) + .collect(Collectors.toMap(GaeaDictItem::getItemValue, GaeaDictItem::getItemExtend, (v1, v2) -> v2)); + if (!CollectionUtils.isEmpty(extendMap)) { + keyValues.stream().forEach(keyValue -> keyValue.setExtend(extendMap.get(keyValue.getId()))); + } + return keyValues; + } - @Override - public List findItems(List dictCodes) { + @Override + public List findItems(List dictCodes) { - LambdaQueryWrapper gaeaDictItemQueryWrapper = Wrappers.lambdaQuery(); - gaeaDictItemQueryWrapper.eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()); - if (!CollectionUtils.isEmpty(dictCodes)) { - gaeaDictItemQueryWrapper.in(GaeaDictItem::getDictCode, dictCodes); - } - return gaeaDictItemMapper.selectList(gaeaDictItemQueryWrapper); - } + LambdaQueryWrapper gaeaDictItemQueryWrapper = Wrappers.lambdaQuery(); + gaeaDictItemQueryWrapper.eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()); + if (!CollectionUtils.isEmpty(dictCodes)) { + gaeaDictItemQueryWrapper.in(GaeaDictItem::getDictCode, dictCodes); + } + return gaeaDictItemMapper.selectList(gaeaDictItemQueryWrapper); + } + @Override + public Collection selectTypeCode(String system, String language) { - @Override - public Collection selectTypeCode(String system, String language) { + // 缓存字典Key + String dictKey = GaeaKeyConstant.DICT_PREFIX + language + GaeaConstant.REDIS_SPLIT + system; - //缓存字典Key - String dictKey = GaeaKeyConstant.DICT_PREFIX + language + GaeaConstant.REDIS_SPLIT + system; + Map dictMap = cacheHelper.hashGet(dictKey); - Map dictMap = cacheHelper.hashGet(dictKey); + // 当查询的字典为空时 + if (CollectionUtils.isEmpty(dictMap)) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + // wrapper.eq(GaeaDict::getLocale, language).orderByAsc(GaeaDict::getSort); - //当查询的字典为空时 - if (CollectionUtils.isEmpty(dictMap)) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); - //wrapper.eq(GaeaDict::getLocale, language).orderByAsc(GaeaDict::getSort); + List list = getMapper().selectList(wrapper); - List list = getMapper().selectList(wrapper); + Set keyValues = list.stream() + .map(dictItemEntity -> new KeyValue(dictItemEntity.getDictCode(), dictItemEntity.getDictName())) + .collect(Collectors.toSet()); + return keyValues; + } - Set keyValues = list.stream() - .map(dictItemEntity -> new KeyValue(dictItemEntity.getDictCode(), - dictItemEntity.getDictName())) - .collect(Collectors.toSet()); - return keyValues; - } + return GaeaUtils.formatKeyValue(dictMap); + } - return GaeaUtils.formatKeyValue(dictMap); - } + @Override + public Map> all(String language) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()).eq(GaeaDictItem::getLocale, language) + .orderByAsc(GaeaDictItem::getSort); - - @Override - public Map> all(String language) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); - wrapper.eq(GaeaDictItem::getEnabled, Enabled.YES.getValue()) - .eq(GaeaDictItem::getLocale, language) - .orderByAsc(GaeaDictItem::getSort); - - List list = gaeaDictItemMapper.selectList(wrapper); - Map> all = list.stream().collect( - Collectors.groupingBy( - GaeaDictItem::getDictCode, - Collectors.mapping(dictItemEntity -> { - Object itemValue = null; - try{ - itemValue = Integer.parseInt(dictItemEntity.getItemValue()); - }catch (Exception e){ - itemValue = dictItemEntity.getItemValue(); - } - return new KeyValue(itemValue, dictItemEntity.getItemName(), dictItemEntity.getItemExtend()); - },Collectors.toList()))); - return all; - } + List list = gaeaDictItemMapper.selectList(wrapper); + Map> all = list.stream() + .collect(Collectors.groupingBy(GaeaDictItem::getDictCode, Collectors.mapping(dictItemEntity -> { + Object itemValue = null; + try { + itemValue = Integer.parseInt(dictItemEntity.getItemValue()); + } + catch (Exception e) { + itemValue = dictItemEntity.getItemValue(); + } + return new KeyValue(itemValue, dictItemEntity.getItemName(), dictItemEntity.getItemExtend()); + }, Collectors.toList()))); + return all; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/GaeaFileController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/GaeaFileController.java index d0d45afc1..57ceffd00 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/GaeaFileController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/GaeaFileController.java @@ -27,47 +27,47 @@ import javax.servlet.http.HttpServletResponse; @RequestMapping("/file") @Api(value = "/file", tags = "") public class GaeaFileController extends BaseController { - @Autowired - private GaeaFileService gaeaFileService; - @PostMapping("/upload") - @Permission(code = "upload", name = "文件上传") - public ResponseBean upload(@RequestParam("file") MultipartFile file) { - return ResponseBean.builder().message("success").data((gaeaFileService.upload(file))).build(); - } + @Autowired + private GaeaFileService gaeaFileService; - @GetMapping(value = "/download/{fileId}") - public ResponseEntity download(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileId") String fileId) { - return gaeaFileService.download(request, response, fileId); - } + @PostMapping("/upload") + @Permission(code = "upload", name = "文件上传") + public ResponseBean upload(@RequestParam("file") MultipartFile file) { + return ResponseBean.builder().message("success").data((gaeaFileService.upload(file))).build(); + } - /** - * 获取实际服务类 - * - * @return - */ - @Override - public GaeaBaseService getService() { - return gaeaFileService; - } + @GetMapping(value = "/download/{fileId}") + public ResponseEntity download(HttpServletRequest request, HttpServletResponse response, + @PathVariable("fileId") String fileId) { + return gaeaFileService.download(request, response, fileId); + } - /** - * 获取当前Controller数据库实体Entity - * - * @return - */ - @Override - public GaeaFile getEntity() { - return new GaeaFile(); - } + /** + * 获取实际服务类 + * @return + */ + @Override + public GaeaBaseService getService() { + return gaeaFileService; + } + + /** + * 获取当前Controller数据库实体Entity + * @return + */ + @Override + public GaeaFile getEntity() { + return new GaeaFile(); + } + + /** + * 获取当前Controller数据传输DTO + * @return + */ + @Override + public GaeaFileDTO getDTO() { + return new GaeaFileDTO(); + } - /** - * 获取当前Controller数据传输DTO - * - * @return - */ - @Override - public GaeaFileDTO getDTO() { - return new GaeaFileDTO(); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/dto/GaeaFileDTO.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/dto/GaeaFileDTO.java index 86a735cbb..4ec87654b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/dto/GaeaFileDTO.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/dto/GaeaFileDTO.java @@ -1,8 +1,6 @@ package com.anjiplus.template.gaea.business.modules.file.controller.dto; import com.anji.plus.gaea.curd.dto.GaeaBaseDTO; -import io.swagger.annotations.ApiModel; -import io.swagger.annotations.ApiModelProperty; import lombok.Data; /** @@ -14,18 +12,19 @@ import lombok.Data; @Data public class GaeaFileDTO extends GaeaBaseDTO { - /** 文件标识 */ - private String fileId; + /** 文件标识 */ + private String fileId; - /** 文件类型 */ - private String fileType; + /** 文件类型 */ + private String fileType; - /** 文件路径 */ - private String filePath; + /** 文件路径 */ + private String filePath; - /** url路径 */ - private String urlPath; + /** url路径 */ + private String urlPath; + + /** 内容说明 */ + private String fileInstruction; - /** 内容说明 */ - private String fileInstruction; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/param/GaeaFileParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/param/GaeaFileParam.java index 7d6bd8350..21c8d5485 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/param/GaeaFileParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/controller/param/GaeaFileParam.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.file.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,11 +14,12 @@ import java.io.Serializable; */ public class GaeaFileParam extends PageParam implements Serializable { - /** 模糊查询 */ - @Query(value = QueryEnum.LIKE) - private String filePath; + /** 模糊查询 */ + @Query(value = QueryEnum.LIKE) + private String filePath; + + /** 模糊查询 */ + @Query(value = QueryEnum.EQ) + private String fileType; - /** 模糊查询 */ - @Query(value = QueryEnum.EQ) - private String fileType; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/dao/GaeaFileMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/dao/GaeaFileMapper.java index dabb1d35e..45db750e5 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/dao/GaeaFileMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/dao/GaeaFileMapper.java @@ -13,5 +13,4 @@ import org.apache.ibatis.annotations.Mapper; @Mapper public interface GaeaFileMapper extends GaeaBaseMapper { - } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/entity/GaeaFile.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/entity/GaeaFile.java index 49a973431..c07d81818 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/entity/GaeaFile.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/entity/GaeaFile.java @@ -1,7 +1,7 @@ package com.anjiplus.template.gaea.business.modules.file.entity; -import com.baomidou.mybatisplus.annotation.TableName; import com.anji.plus.gaea.curd.entity.GaeaBaseEntity; +import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @@ -13,22 +13,23 @@ import java.io.Serializable; * @author peiyanni * @since 2021-02-18 14:48:20 */ -@TableName(keepGlobalPrefix=true, value = "gaea_file") +@TableName(keepGlobalPrefix = true, value = "gaea_file") @Data public class GaeaFile extends GaeaBaseEntity implements Serializable { - @ApiModelProperty(value = "文件标识") - private String fileId; + @ApiModelProperty(value = "文件标识") + private String fileId; - @ApiModelProperty(value = "文件类型") - private String fileType; + @ApiModelProperty(value = "文件类型") + private String fileType; - @ApiModelProperty(value = "文件路径") - private String filePath; + @ApiModelProperty(value = "文件路径") + private String filePath; - @ApiModelProperty(value = "url路径") - private String urlPath; + @ApiModelProperty(value = "url路径") + private String urlPath; + + @ApiModelProperty(value = "内容说明") + private String fileInstruction; - @ApiModelProperty(value = "内容说明") - private String fileInstruction; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/GaeaFileService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/GaeaFileService.java index 4082ca7ea..218fa60fe 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/GaeaFileService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/GaeaFileService.java @@ -1,8 +1,8 @@ package com.anjiplus.template.gaea.business.modules.file.service; import com.anji.plus.gaea.curd.service.GaeaBaseService; -import com.anjiplus.template.gaea.business.modules.file.entity.GaeaFile; import com.anjiplus.template.gaea.business.modules.file.controller.param.GaeaFileParam; +import com.anjiplus.template.gaea.business.modules.file.entity.GaeaFile; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; @@ -18,40 +18,37 @@ import java.io.File; */ public interface GaeaFileService extends GaeaBaseService { - /** - * 文件上传 - * - * @param multipartFile 文件 - * @param file 文件 - * @param customFileName 自定义文件名,默认给null - * @return - */ - GaeaFile upload(MultipartFile multipartFile, File file, String customFileName); + /** + * 文件上传 + * @param multipartFile 文件 + * @param file 文件 + * @param customFileName 自定义文件名,默认给null + * @return + */ + GaeaFile upload(MultipartFile multipartFile, File file, String customFileName); - /** - * 文件上传 - * - * @param multipartFile 文件 - * @return - */ - GaeaFile upload(MultipartFile multipartFile); + /** + * 文件上传 + * @param multipartFile 文件 + * @return + */ + GaeaFile upload(MultipartFile multipartFile); + /** + * 文件上传 + * @param file 二选一 + * @param customFileName 自定义文件名 + * @return + */ + GaeaFile upload(File file, String customFileName); + + /** + * 根据fileId显示图片或者下载文件 + * @param request + * @param response + * @param fileId + * @return + */ + ResponseEntity download(HttpServletRequest request, HttpServletResponse response, String fileId); - /** - * 文件上传 - * - * @param file 二选一 - * @param customFileName 自定义文件名 - * @return - */ - GaeaFile upload(File file, String customFileName); - /** - * 根据fileId显示图片或者下载文件 - * - * @param request - * @param response - * @param fileId - * @return - */ - ResponseEntity download(HttpServletRequest request, HttpServletResponse response, String fileId); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/impl/GaeaFileServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/impl/GaeaFileServiceImpl.java index fed436890..89d271e71 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/impl/GaeaFileServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/service/impl/GaeaFileServiceImpl.java @@ -45,178 +45,184 @@ import java.util.stream.Collectors; @Slf4j public class GaeaFileServiceImpl implements GaeaFileService { - @Value("${customer.file.dist-path:''}") - private String dictPath; + @Value("${customer.file.dist-path:''}") + private String dictPath; - @Value("${customer.file.white-list:''}") - private String whiteList; + @Value("${customer.file.white-list:''}") + private String whiteList; - @Value("${customer.file.excelSuffix:''}") - private String excelSuffix; + @Value("${customer.file.excelSuffix:''}") + private String excelSuffix; - @Value("${customer.file.downloadPath:''}") - private String fileDownloadPath; + @Value("${customer.file.downloadPath:''}") + private String fileDownloadPath; - @Autowired - private GaeaFileMapper gaeaFileMapper; + @Autowired + private GaeaFileMapper gaeaFileMapper; - @Override - public GaeaBaseMapper getMapper() { - return gaeaFileMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return gaeaFileMapper; + } + @Override + @Transactional(rollbackFor = Exception.class) + public GaeaFile upload(MultipartFile multipartFile, File file, String customFileName) { + try { + String fileName = ""; + if (null != multipartFile) { + fileName = multipartFile.getOriginalFilename(); + } + else { + fileName = file.getName(); + } - @Override - @Transactional(rollbackFor = Exception.class) - public GaeaFile upload(MultipartFile multipartFile, File file, String customFileName) { - try { - String fileName = ""; - if (null != multipartFile) { - fileName = multipartFile.getOriginalFilename(); - }else { - fileName = file.getName(); - } + if (StringUtils.isBlank(fileName)) { + throw BusinessExceptionBuilder.build(ResponseCode.FILE_EMPTY_FILENAME); + } - if (StringUtils.isBlank(fileName)) { - throw BusinessExceptionBuilder.build(ResponseCode.FILE_EMPTY_FILENAME); - } + String suffixName = fileName.substring(fileName.lastIndexOf(".")); + String fileInstruction = fileName.substring(0, fileName.lastIndexOf(".")); + // 白名单校验(不区分大小写) + List list = new ArrayList<>(Arrays.asList(whiteList.split("\\|"))); + list.addAll(list.stream().map(String::toUpperCase).collect(Collectors.toList())); + if (!list.contains(suffixName)) { + throw BusinessExceptionBuilder.build(ResponseCode.FILE_SUFFIX_UNSUPPORTED); + } + // 生成文件唯一性标识 + String fileId; + if (StringUtils.isBlank(customFileName)) { + fileId = UUID.randomUUID().toString(); + } + else { + fileId = customFileName; + } + String newFileName = fileId + suffixName; + // 本地文件保存路径 + String filePath = dictPath + newFileName; + String urlPath = fileDownloadPath + "/" + fileId; - String suffixName = fileName.substring(fileName.lastIndexOf(".")); - String fileInstruction = fileName.substring(0, fileName.lastIndexOf(".")); - //白名单校验(不区分大小写) - List list = new ArrayList<>(Arrays.asList(whiteList.split("\\|"))); - list.addAll(list.stream().map(String::toUpperCase).collect(Collectors.toList())); - if (!list.contains(suffixName)) { - throw BusinessExceptionBuilder.build(ResponseCode.FILE_SUFFIX_UNSUPPORTED); - } - // 生成文件唯一性标识 - String fileId; - if (StringUtils.isBlank(customFileName)) { - fileId = UUID.randomUUID().toString(); - } else { - fileId = customFileName; - } - String newFileName = fileId + suffixName; - // 本地文件保存路径 - String filePath = dictPath + newFileName; - String urlPath = fileDownloadPath + "/" + fileId; + GaeaFile gaeaFile = new GaeaFile(); + gaeaFile.setFilePath(filePath); + gaeaFile.setFileId(fileId); + gaeaFile.setUrlPath(urlPath); + gaeaFile.setFileType(suffixName.replace(".", "")); + gaeaFile.setFileInstruction(fileInstruction); + gaeaFileMapper.insert(gaeaFile); - GaeaFile gaeaFile = new GaeaFile(); - gaeaFile.setFilePath(filePath); - gaeaFile.setFileId(fileId); - gaeaFile.setUrlPath(urlPath); - gaeaFile.setFileType(suffixName.replace(".", "")); - gaeaFile.setFileInstruction(fileInstruction); - gaeaFileMapper.insert(gaeaFile); + // 写文件 将文件保存/app/dictPath/upload/下 + java.io.File dest = new java.io.File(dictPath + newFileName); + java.io.File parentFile = dest.getParentFile(); + if (!parentFile.exists()) { + parentFile.mkdirs(); + } + if (null != multipartFile) { + multipartFile.transferTo(dest); + } + else { + FileUtil.copyFileUsingFileChannels(file, dest); + } + // 将完整的http访问路径返回 + return gaeaFile; + } + catch (Exception e) { + TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); + log.error("file upload error: {}", e); + throw BusinessExceptionBuilder.build(ResponseCode.FILE_UPLOAD_ERROR); + } + } - //写文件 将文件保存/app/dictPath/upload/下 - java.io.File dest = new java.io.File(dictPath + newFileName); - java.io.File parentFile = dest.getParentFile(); - if (!parentFile.exists()) { - parentFile.mkdirs(); - } - if (null != multipartFile) { - multipartFile.transferTo(dest); - }else { - FileUtil.copyFileUsingFileChannels(file, dest); - } - // 将完整的http访问路径返回 - return gaeaFile; - } catch (Exception e) { - TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); - log.error("file upload error: {}", e); - throw BusinessExceptionBuilder.build(ResponseCode.FILE_UPLOAD_ERROR); - } - } + /** + * 文件上传 + * @param multipartFile 文件 + * @return + */ + @Override + public GaeaFile upload(MultipartFile multipartFile) { + return upload(multipartFile, null, null); + } - /** - * 文件上传 - * - * @param multipartFile 文件 - * @return - */ - @Override - public GaeaFile upload(MultipartFile multipartFile) { - return upload(multipartFile, null, null); - } + /** + * 文件上传 + * @param file 文件 + * @param customFileName 自定义文件名 + * @return + */ + @Override + public GaeaFile upload(File file, String customFileName) { + return upload(null, file, customFileName); + } - /** - * 文件上传 - * - * @param file 文件 - * @param customFileName 自定义文件名 - * @return - */ - @Override - public GaeaFile upload(File file, String customFileName) { - return upload(null, file, customFileName); - } + @Override + public ResponseEntity download(HttpServletRequest request, HttpServletResponse response, String fileId) { + try { + String userAgent = request.getHeader("User-Agent"); + boolean isIeBrowser = userAgent.indexOf("MSIE") > 0; + // 根据fileId,从gaea_file中读出filePath + LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); + queryWrapper.eq(GaeaFile::getFileId, fileId); + GaeaFile gaeaFile = gaeaFileMapper.selectOne(queryWrapper); + if (null == gaeaFile) { + throw BusinessExceptionBuilder.build(ResponseCode.FILE_ONT_EXSIT); + } + // 解析文件路径、文件名和后缀 + String filePath = gaeaFile.getFilePath(); + if (StringUtils.isBlank(filePath)) { + throw BusinessExceptionBuilder.build(ResponseCode.FILE_ONT_EXSIT); + } + String filename = filePath.substring(filePath.lastIndexOf(File.separator)); + String fileSuffix = filename.substring(filename.lastIndexOf(".")); - @Override - public ResponseEntity download(HttpServletRequest request, HttpServletResponse response, String fileId) { - try { - String userAgent = request.getHeader("User-Agent"); - boolean isIeBrowser = userAgent.indexOf("MSIE") > 0; - //根据fileId,从gaea_file中读出filePath - LambdaQueryWrapper queryWrapper = Wrappers.lambdaQuery(); - queryWrapper.eq(GaeaFile::getFileId, fileId); - GaeaFile gaeaFile = gaeaFileMapper.selectOne(queryWrapper); - if (null == gaeaFile) { - throw BusinessExceptionBuilder.build(ResponseCode.FILE_ONT_EXSIT); - } - //解析文件路径、文件名和后缀 - String filePath = gaeaFile.getFilePath(); - if (StringUtils.isBlank(filePath)) { - throw BusinessExceptionBuilder.build(ResponseCode.FILE_ONT_EXSIT); - } - String filename = filePath.substring(filePath.lastIndexOf(File.separator)); - String fileSuffix = filename.substring(filename.lastIndexOf(".")); + // 根据文件后缀来判断,是显示图片\视频\音频,还是下载文件 + File file = new File(filePath); + ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); + builder.contentLength(file.length()); + if (StringPatternUtil.stringMatchIgnoreCase(fileSuffix, "(.png|.jpg|.jpeg|.bmp|.gif|.icon)")) { + builder.cacheControl(CacheControl.noCache()).contentType(MediaType.IMAGE_PNG); + } + else if (StringPatternUtil.stringMatchIgnoreCase(fileSuffix, + "(.flv|.swf|.mkv|.avi|.rm|.rmvb|.mpeg|.mpg|.ogg|.ogv|.mov|.wmv|.mp4|.webm|.wav|.mid|.mp3|.aac)")) { + builder.header("Content-Type", "video/mp4; charset=UTF-8"); + } + else { + // application/octet-stream 二进制数据流(最常见的文件下载) + builder.contentType(MediaType.APPLICATION_OCTET_STREAM); + filename = URLEncoder.encode(filename, "UTF-8"); + if (isIeBrowser) { + builder.header("Content-Disposition", "attachment; filename=" + filename); + } + else { + builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + filename); + } + } + return builder.body(FileUtils.readFileToByteArray(file)); + } + catch (Exception e) { + log.error("file download error: {}", e); + return null; + } + } - //根据文件后缀来判断,是显示图片\视频\音频,还是下载文件 - File file = new File(filePath); - ResponseEntity.BodyBuilder builder = ResponseEntity.ok(); - builder.contentLength(file.length()); - if (StringPatternUtil.stringMatchIgnoreCase(fileSuffix, "(.png|.jpg|.jpeg|.bmp|.gif|.icon)")) { - builder.cacheControl(CacheControl.noCache()).contentType(MediaType.IMAGE_PNG); - } else if (StringPatternUtil.stringMatchIgnoreCase(fileSuffix, "(.flv|.swf|.mkv|.avi|.rm|.rmvb|.mpeg|.mpg|.ogg|.ogv|.mov|.wmv|.mp4|.webm|.wav|.mid|.mp3|.aac)")) { - builder.header("Content-Type", "video/mp4; charset=UTF-8"); - } else { - //application/octet-stream 二进制数据流(最常见的文件下载) - builder.contentType(MediaType.APPLICATION_OCTET_STREAM); - filename = URLEncoder.encode(filename, "UTF-8"); - if (isIeBrowser) { - builder.header("Content-Disposition", "attachment; filename=" + filename); - } else { - builder.header("Content-Disposition", "attacher; filename*=UTF-8''" + filename); - } - } - return builder.body(FileUtils.readFileToByteArray(file)); - } catch (Exception e) { - log.error("file download error: {}", e); - return null; - } - } + /** + * 批处理操作后续处理 删除本地已经存在的文件 + * @param entities + * @param operationEnum 操作类型 + * @throws BusinessException 阻止程序继续执行或回滚事务 + */ + @Override + public void processBatchAfterOperation(List entities, BaseOperationEnum operationEnum) + throws BusinessException { + if (operationEnum.equals(BaseOperationEnum.DELETE_BATCH)) { + // 删除本地文件 + entities.forEach(gaeaFile -> { + String filePath = gaeaFile.getFilePath(); + File file = new File(filePath); + if (file.exists()) { + file.delete(); + } + }); + } - /** - * 批处理操作后续处理 - * 删除本地已经存在的文件 - * - * @param entities - * @param operationEnum 操作类型 - * @throws BusinessException 阻止程序继续执行或回滚事务 - */ - @Override - public void processBatchAfterOperation(List entities, BaseOperationEnum operationEnum) throws BusinessException { - if (operationEnum.equals(BaseOperationEnum.DELETE_BATCH)) { - // 删除本地文件 - entities.forEach(gaeaFile -> { - String filePath = gaeaFile.getFilePath(); - File file = new File(filePath); - if (file.exists()) { - file.delete(); - } - }); - } + } - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/FileUtils.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/FileUtils.java index fca211bb8..c0750c5e8 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/FileUtils.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/FileUtils.java @@ -2,30 +2,35 @@ package com.anjiplus.template.gaea.business.modules.file.util; import lombok.extern.slf4j.Slf4j; -import java.io.*; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; /** * Created by raodeming on 2021/7/8. */ @Slf4j public class FileUtils { - public static byte[] readFileToByteArray(File file) { - byte[] buffer = null; - try { - FileInputStream fis = new FileInputStream(file); - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - byte[] b = new byte[1024]; - int n; - while ((n = fis.read(b)) != -1) { - bos.write(b, 0, n); - } - fis.close(); - bos.close(); - buffer = bos.toByteArray(); - } catch (IOException e) { - log.error("error", e); - } - return buffer; - } + + public static byte[] readFileToByteArray(File file) { + byte[] buffer = null; + try { + FileInputStream fis = new FileInputStream(file); + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + byte[] b = new byte[1024]; + int n; + while ((n = fis.read(b)) != -1) { + bos.write(b, 0, n); + } + fis.close(); + bos.close(); + buffer = bos.toByteArray(); + } + catch (IOException e) { + log.error("error", e); + } + return buffer; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/StringPatternUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/StringPatternUtil.java index 5741f5e8a..93c049abd 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/StringPatternUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/file/util/StringPatternUtil.java @@ -5,94 +5,99 @@ import org.apache.commons.lang3.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; - public class StringPatternUtil { + /** + * + *

+ * Discription:[查找源sourceStr中是否包含pattern,返回boolean] + *

+ * @author + * @update:[日期YYYY-MM-DD] [更改人姓名] + * @param sourceStr + * @param pattern + * @return + */ + public static boolean stringMatch(String sourceStr, String pattern) { + boolean result = false; + try { + if (StringUtils.isBlank(sourceStr) || StringUtils.isBlank(pattern)) { + return result; + } + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(sourceStr); + while (m.find()) { + // String aa=m.group(0); + result = true; + break; + } - /** - * - *

Discription:[查找源sourceStr中是否包含pattern,返回boolean]

- * @author - * @update:[日期YYYY-MM-DD] [更改人姓名] - * @param sourceStr - * @param pattern - * @return - */ - public static boolean stringMatch(String sourceStr, String pattern){ - boolean result=false; - try{ - if(StringUtils.isBlank(sourceStr)|| StringUtils.isBlank(pattern)){ - return result; - } - Pattern p = Pattern.compile(pattern); - Matcher m = p.matcher(sourceStr); - while (m.find()) { - //String aa=m.group(0); - result=true; - break ; - } + } + catch (Exception e) { + result = false; + } + return result; + } - }catch(Exception e){ - result=false; - } - return result; - } + public static boolean stringMatchIgnoreCase(String sourceStr, String pattern) { + boolean result = false; + try { + if (StringUtils.isBlank(sourceStr) || StringUtils.isBlank(pattern)) { + return result; + } + sourceStr = sourceStr.toLowerCase(); + pattern = pattern.toLowerCase(); + result = stringMatch(sourceStr, pattern); + } + catch (Exception e) { + result = false; + } + return result; + } - public static boolean stringMatchIgnoreCase(String sourceStr, String pattern){ - boolean result=false; - try{ - if(StringUtils.isBlank(sourceStr)|| StringUtils.isBlank(pattern)){ - return result; - } - sourceStr=sourceStr.toLowerCase(); - pattern=pattern.toLowerCase(); - result= stringMatch(sourceStr,pattern); - }catch(Exception e){ - result=false; - } - return result; - } + /** + *

+ * Discription:[查找源sourceStr中是否包含pattern,返回找到的字符串,未找到就返回空字符串] + *

+ * @author + * @update:[日期YYYY-MM-DD] [更改人姓名] + * @param sourceStr + * @param pattern + * @return + */ + public static String stringFind(String sourceStr, String pattern) { + String result = ""; + try { + if (StringUtils.isBlank(sourceStr) || StringUtils.isBlank(pattern)) { + return result; + } + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(sourceStr); + while (m.find()) { + result = m.group(0); + break; + } + } + catch (Exception e) { + result = ""; + } + return result; + } + public static String replace(String sourceStr, String pattern, String replaceStr) { + String result = ""; + try { + if (StringUtils.isBlank(sourceStr) || StringUtils.isBlank(pattern)) { + return result; + } + Pattern p = Pattern.compile(pattern); + Matcher m = p.matcher(sourceStr); + result = m.replaceAll(replaceStr); + } + catch (Exception e) { + result = ""; + } + return result; + } - - /** - *

Discription:[查找源sourceStr中是否包含pattern,返回找到的字符串,未找到就返回空字符串]

- * @author - * @update:[日期YYYY-MM-DD] [更改人姓名] - * @param sourceStr - * @param pattern - * @return - */ - public static String stringFind(String sourceStr, String pattern){ - String result=""; - try{ - if(StringUtils.isBlank(sourceStr)|| StringUtils.isBlank(pattern)){ - return result; - } - Pattern p = Pattern.compile(pattern); - Matcher m = p.matcher(sourceStr); - while (m.find()) { - result = m.group(0); - break; - } - }catch(Exception e){ - result=""; - } - return result; - } - - public static String replace(String sourceStr, String pattern, String replaceStr){ - String result=""; - try{ - if(StringUtils.isBlank(sourceStr)|| StringUtils.isBlank(pattern)){ - return result; - } - Pattern p = Pattern.compile(pattern); - Matcher m = p.matcher(sourceStr); - result = m.replaceAll(replaceStr); - }catch(Exception e){ - result=""; - } - return result; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/constant/ExpConstant.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/constant/ExpConstant.java index 9e17df5cc..2bac8fbbe 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/constant/ExpConstant.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/constant/ExpConstant.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.report.constant; - import java.util.ArrayList; import java.util.List; @@ -9,17 +8,18 @@ import java.util.List; */ public class ExpConstant { - public static final String[] FUNCTION = new String[]{"=SUM(", "=AVERAGE(", "=MAX(", "=MIN(", "=IF(", "=AND(", "=OR(", "=CONCAT("}; + public static final String[] FUNCTION = new String[] { "=SUM(", "=AVERAGE(", "=MAX(", "=MIN(", "=IF(", "=AND(", + "=OR(", "=CONCAT(" }; - public static List getExpFunction(String e) { - List counts = new ArrayList<>(); - for (int i = 0; i < FUNCTION.length; i++) { - if(e.contains(FUNCTION[i])){ - counts.add(i); - } - } + public static List getExpFunction(String e) { + List counts = new ArrayList<>(); + for (int i = 0; i < FUNCTION.length; i++) { + if (e.contains(FUNCTION[i])) { + counts.add(i); + } + } - return counts; - } + return counts; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/ReportController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/ReportController.java index 6269e7d0d..07c52896b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/ReportController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/ReportController.java @@ -28,29 +28,30 @@ import org.springframework.web.bind.annotation.RestController; @RequestMapping("/report") public class ReportController extends GaeaBaseController { - @Autowired - private ReportService reportService; + @Autowired + private ReportService reportService; - @Override - public GaeaBaseService getService() { - return reportService; - } + @Override + public GaeaBaseService getService() { + return reportService; + } - @Override - public Report getEntity() { - return new Report(); - } + @Override + public Report getEntity() { + return new Report(); + } - @Override - public ReportDto getDTO() { - return new ReportDto(); - } + @Override + public ReportDto getDTO() { + return new ReportDto(); + } + + @DeleteMapping("/delReport") + @Permission(code = "delete", name = "删除") + @GaeaAuditLog(pageTitle = "删除") + public ResponseBean delReport(@RequestBody ReportDto reportDto) { + reportService.delReport(reportDto); + return ResponseBean.builder().build(); + } - @DeleteMapping("/delReport") - @Permission(code = "delete", name = "删除") - @GaeaAuditLog(pageTitle = "删除") - public ResponseBean delReport(@RequestBody ReportDto reportDto) { - reportService.delReport(reportDto); - return ResponseBean.builder().build(); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/dto/ReportDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/dto/ReportDto.java index 84e8d1c3e..bfc43e56b 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/dto/ReportDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/dto/ReportDto.java @@ -6,54 +6,52 @@ import lombok.Data; import java.io.Serializable; /** - * * @author chenkening * @date 2021/3/26 10:34 */ @Data public class ReportDto extends GaeaBaseDTO implements Serializable { - /** 报表名称 */ - private String reportName; + /** 报表名称 */ + private String reportName; - /** 报表编码 */ - private String reportCode; + /** 报表编码 */ + private String reportCode; - /**数据集编码,以|分割*/ - private String setCodes; + /** 数据集编码,以|分割 */ + private String setCodes; - /** 分组 */ - private String reportGroup; + /** 分组 */ + private String reportGroup; - /** 备注 */ - private String reportDesc; + /** 备注 */ + private String reportDesc; - /** 数据集查询参数 */ - private String setParam; + /** 数据集查询参数 */ + private String setParam; - /** 报表json字符串 */ - private String jsonStr; + /** 报表json字符串 */ + private String jsonStr; - /** 报表类型 */ - private String reportType; + /** 报表类型 */ + private String reportType; - /** 数据总计 */ - private long total; + /** 数据总计 */ + private long total; - /** 报表缩略图 */ - private String reportImage; + /** 报表缩略图 */ + private String reportImage; - /** 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; + /** 报表作者 */ + private String reportAuthor; - /** 报表作者 */ - private String reportAuthor; - - /** 下载次数 */ - private Long downloadCount; + /** 下载次数 */ + private Long downloadCount; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/param/ReportParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/param/ReportParam.java index 87c066aa8..866845a61 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/param/ReportParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/controller/param/ReportParam.java @@ -14,23 +14,22 @@ import java.io.Serializable; * @date 2021/3/26 10:40 */ @Data -public class ReportParam extends PageParam implements Serializable{ +public class ReportParam extends PageParam implements Serializable { - /** 报表名称 */ - @Query(QueryEnum.LIKE) - private String reportName; + /** 报表名称 */ + @Query(QueryEnum.LIKE) + private String reportName; - /** 报表作者 */ - @Query(QueryEnum.LIKE) - private String reportAuthor; + /** 报表作者 */ + @Query(QueryEnum.LIKE) + private String reportAuthor; - /** 报表编码 */ - @Query(QueryEnum.LIKE) - private String reportCode; - - /** 报表类型 */ - @Query(QueryEnum.EQ) - private String reportType; + /** 报表编码 */ + @Query(QueryEnum.LIKE) + private String reportCode; + /** 报表类型 */ + @Query(QueryEnum.EQ) + private String reportType; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/ReportMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/ReportMapper.java index bfece32d9..24bce7961 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/ReportMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/ReportMapper.java @@ -10,4 +10,5 @@ import com.anjiplus.template.gaea.business.modules.report.dao.entity.Report; * @date 2021/3/26 10:19 */ public interface ReportMapper extends GaeaBaseMapper { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/entity/Report.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/entity/Report.java index 09ed5f6f0..c8c294db3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/entity/Report.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/dao/entity/Report.java @@ -13,38 +13,39 @@ import lombok.Data; * @author chenkening * @date 2021/3/26 10:20 */ -@TableName(keepGlobalPrefix=true, value="gaea_report") +@TableName(keepGlobalPrefix = true, value = "gaea_report") @Data public class Report extends GaeaBaseEntity { - @ApiModelProperty(value = "名称") - private String reportName; + @ApiModelProperty(value = "名称") + private String reportName; - @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 reportGroup; + @ApiModelProperty(value = "分组") + private String reportGroup; - @ApiModelProperty(value = "报表描述") - private String reportDesc; + @ApiModelProperty(value = "报表描述") + private String reportDesc; - @ApiModelProperty(value = "报表类型") - private String reportType; + @ApiModelProperty(value = "报表类型") + private String reportType; - @ApiModelProperty(value = "报表缩略图") - private String reportImage; + @ApiModelProperty(value = "报表缩略图") + private String reportImage; - @ApiModelProperty(value = "报表作者") - private String reportAuthor; + @ApiModelProperty(value = "报表作者") + private String reportAuthor; - @ApiModelProperty(value = "下载次数") - private Long downloadCount; + @ApiModelProperty(value = "下载次数") + private Long downloadCount; - @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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/ReportService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/ReportService.java index a09efd080..108139083 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/ReportService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/ReportService.java @@ -6,17 +6,17 @@ import com.anjiplus.template.gaea.business.modules.report.controller.param.Repor import com.anjiplus.template.gaea.business.modules.report.dao.entity.Report; /** - * * @author chenkening * @date 2021/3/26 10:35 */ public interface ReportService extends GaeaBaseService { - void delReport(ReportDto reportDto); + void delReport(ReportDto reportDto); + + /** + * 下载次数+1 + * @param reportCode + */ + void downloadStatistics(String reportCode); - /** - * 下载次数+1 - * @param reportCode - */ - void downloadStatistics(String reportCode); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/impl/ReportServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/impl/ReportServiceImpl.java index e5b32704b..d9aef36ab 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/impl/ReportServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/report/service/impl/ReportServiceImpl.java @@ -11,52 +11,51 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** - * * @author chenkening * @date 2021/3/26 10:35 */ @Service public class ReportServiceImpl implements ReportService { - @Autowired - private ReportMapper reportMapper; + @Autowired + private ReportMapper reportMapper; - @Override - public GaeaBaseMapper getMapper() { - return reportMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return reportMapper; + } + @Override + public void delReport(ReportDto reportDto) { + deleteById(reportDto.getId()); + // 删除gaea_report_excel、gaea_report_dashboard、gaea_report_dashboard_widget + // ... + } - @Override - public void delReport(ReportDto reportDto) { - deleteById(reportDto.getId()); - //删除gaea_report_excel、gaea_report_dashboard、gaea_report_dashboard_widget - //... - } + /** + * 下载次数+1 + * @param reportCode + */ + @Override + public void downloadStatistics(String reportCode) { + Report report = selectOne("report_code", reportCode); + if (null != report) { + Long downloadCount = report.getDownloadCount(); + if (null == downloadCount) { + downloadCount = 0L; + } + else { + downloadCount++; + } + report.setDownloadCount(downloadCount); + update(report); + } - /** - * 下载次数+1 - * - * @param reportCode - */ - @Override - public void downloadStatistics(String reportCode) { - Report report = selectOne("report_code", reportCode); - if (null != report) { - Long downloadCount = report.getDownloadCount(); - if (null == downloadCount) { - downloadCount = 0L; - }else { - downloadCount++; - } - report.setDownloadCount(downloadCount); - update(report); - } + } - } + @Override + public void processBeforeOperation(Report entity, BaseOperationEnum operationEnum) throws BusinessException { - @Override - public void processBeforeOperation(Report entity, BaseOperationEnum operationEnum) throws BusinessException { + } - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/ReportExcelController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/ReportExcelController.java index 21273693b..b515d9e76 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/ReportExcelController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/ReportExcelController.java @@ -24,55 +24,54 @@ import org.springframework.web.bind.annotation.*; @RequestMapping("/reportExcel") public class ReportExcelController extends GaeaBaseController { - @Autowired - private ReportExcelService reportExcelService; + @Autowired + private ReportExcelService reportExcelService; - @Override - public GaeaBaseService getService() { - return reportExcelService; - } + @Override + public GaeaBaseService getService() { + return reportExcelService; + } - @Override - public ReportExcel getEntity() { - return new ReportExcel(); - } + @Override + public ReportExcel getEntity() { + return new ReportExcel(); + } - @Override - public ReportExcelDto getDTO() { - return new ReportExcelDto(); - } + @Override + public ReportExcelDto getDTO() { + return new ReportExcelDto(); + } - @GetMapping("/detailByReportCode/{reportCode}") - @Permission(code = "query", name = "详情") - @GaeaAuditLog(pageTitle = "详情") - public ResponseBean detailByReportCode(@PathVariable String reportCode) { - ReportExcelDto reportExcelDto = reportExcelService.detailByReportCode(reportCode); - return ResponseBean.builder().data(reportExcelDto).build(); - } + @GetMapping("/detailByReportCode/{reportCode}") + @Permission(code = "query", name = "详情") + @GaeaAuditLog(pageTitle = "详情") + public ResponseBean detailByReportCode(@PathVariable String reportCode) { + ReportExcelDto reportExcelDto = reportExcelService.detailByReportCode(reportCode); + return ResponseBean.builder().data(reportExcelDto).build(); + } - @PostMapping("/preview") - @Permission(code = "view", name = "预览") - @GaeaAuditLog(pageTitle = "预览") - public ResponseBean preview(@RequestBody ReportExcelDto reportExcelDto) { - ReportExcelDto result = reportExcelService.preview(reportExcelDto); - return ResponseBean.builder().data(result).build(); - } + @PostMapping("/preview") + @Permission(code = "view", name = "预览") + @GaeaAuditLog(pageTitle = "预览") + public ResponseBean preview(@RequestBody ReportExcelDto reportExcelDto) { + ReportExcelDto result = reportExcelService.preview(reportExcelDto); + return ResponseBean.builder().data(result).build(); + } + @PostMapping("/exportExcel") + @Permission(code = "export", name = "导出") + @GaeaAuditLog(pageTitle = "报表导出") + public ResponseBean exportExcel(@RequestBody ReportExcelDto reportExcelDto) { - @PostMapping("/exportExcel") - @Permission(code = "export", name = "导出") - @GaeaAuditLog(pageTitle = "报表导出") - public ResponseBean exportExcel(@RequestBody ReportExcelDto reportExcelDto) { + return ResponseBean.builder().code(ResponseCode.SUCCESS_CODE) + .data(reportExcelService.exportExcel(reportExcelDto)).message("导出成功,请稍后在文件管理中查看").build(); + } - return ResponseBean.builder().code(ResponseCode.SUCCESS_CODE) - .data(reportExcelService.exportExcel(reportExcelDto)) - .message("导出成功,请稍后在文件管理中查看").build(); - } + // @PostMapping("/exportPdf") + // public ResponseBean exportPdf(@RequestBody ReportExcelDto reportExcelDto) { + // reportExcelService.exportPdf(reportExcelDto); + // return ResponseBean.builder().code(ResponseCode.SUCCESS_CODE) + // .build(); + // } -// @PostMapping("/exportPdf") -// public ResponseBean exportPdf(@RequestBody ReportExcelDto reportExcelDto) { -// reportExcelService.exportPdf(reportExcelDto); -// return ResponseBean.builder().code(ResponseCode.SUCCESS_CODE) -// .build(); -// } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/GridRecordDataModel.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/GridRecordDataModel.java index b7041439c..9e5262142 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/GridRecordDataModel.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/GridRecordDataModel.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.controller.dto; - import com.alibaba.fastjson.JSONObject; import lombok.Data; @@ -13,46 +12,55 @@ import java.util.List; */ @Data public class GridRecordDataModel { - /** - * 记录序列 - */ - Long id; - /** - * 文档ID - */ - String list_id; - /** - * 本记录的行_列 - */ - String row_col; - /** - * sheet序号 - */ - String index; - /** - * 状态是否当前sheet页 - */ - Integer status; - /** - * 块编号 第一块 fblock - */ - String block_id; - /** - * json串 - */ - JSONObject json_data; - /** - * 排序位置 - */ - Integer order; - /** - * 是否删除 - */ - Integer is_delete; - /** - * sheet页数据 未编号分组 - */ - List dataList; + /** + * 记录序列 + */ + Long id; + + /** + * 文档ID + */ + String list_id; + + /** + * 本记录的行_列 + */ + String row_col; + + /** + * sheet序号 + */ + String index; + + /** + * 状态是否当前sheet页 + */ + Integer status; + + /** + * 块编号 第一块 fblock + */ + String block_id; + + /** + * json串 + */ + JSONObject json_data; + + /** + * 排序位置 + */ + Integer order; + + /** + * 是否删除 + */ + Integer is_delete; + + /** + * sheet页数据 未编号分组 + */ + List dataList; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/ReportExcelDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/ReportExcelDto.java index df92b09f7..0846e69d3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/ReportExcelDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/dto/ReportExcelDto.java @@ -6,56 +6,56 @@ import lombok.Data; import java.io.Serializable; - /** * @author chenkening * @date 2021/4/13 15:12 */ @Data public class ReportExcelDto extends GaeaBaseDTO implements Serializable { - /** - * 报表名称 - */ - private String reportName; - /** - * 报表编码 - */ - private String reportCode; + /** + * 报表名称 + */ + private String reportName; - /** - * 数据集编码,以|分割 - */ - private String setCodes; + /** + * 报表编码 + */ + private String reportCode; - /** - * 分组 - */ - private String reportGroup; + /** + * 数据集编码,以|分割 + */ + private String setCodes; - /** - * 数据集查询参数 - */ - private String setParam; + /** + * 分组 + */ + private String reportGroup; - /** - * 报表json字符串 - */ - private String jsonStr; + /** + * 数据集查询参数 + */ + private String setParam; - /** - * 报表类型 - */ - private String reportType; + /** + * 报表json字符串 + */ + private String jsonStr; - /** - * 数据总计 - */ - private long total; + /** + * 报表类型 + */ + private String reportType; - /** - * 导出类型 - */ - private String exportType; + /** + * 数据总计 + */ + private long total; + + /** + * 导出类型 + */ + private String exportType; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/param/ReportExcelParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/param/ReportExcelParam.java index 13202587c..8156a8a02 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/param/ReportExcelParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/controller/param/ReportExcelParam.java @@ -6,7 +6,6 @@ import lombok.Data; import java.io.Serializable; - /** * @author chenkening * @date 2021/4/13 15:12 @@ -14,5 +13,4 @@ import java.io.Serializable; @Data public class ReportExcelParam extends PageParam implements Serializable { - } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/ReportExcelMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/ReportExcelMapper.java index 422b83f82..1622e6cc7 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/ReportExcelMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/ReportExcelMapper.java @@ -8,4 +8,5 @@ import com.anjiplus.template.gaea.business.modules.reportexcel.dao.entity.Report * @date 2021/4/13 15:11 */ public interface ReportExcelMapper extends GaeaBaseMapper { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/entity/ReportExcel.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/entity/ReportExcel.java index 2fa43ec7b..c563e79ca 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/entity/ReportExcel.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/dao/entity/ReportExcel.java @@ -13,21 +13,22 @@ import lombok.Data; @Data public class ReportExcel extends GaeaBaseEntity { - @ApiModelProperty(value = "报表编码") - private String reportCode; + @ApiModelProperty(value = "报表编码") + private String reportCode; - @ApiModelProperty(value = "数据集编码,以|分割") - private String setCodes; + @ApiModelProperty(value = "数据集编码,以|分割") + private String setCodes; - @ApiModelProperty(value = "数据集查询参数") - private String setParam; + @ApiModelProperty(value = "数据集查询参数") + private String setParam; - @ApiModelProperty(value = "报表json字符串") - private String jsonStr; + @ApiModelProperty(value = "报表json字符串") + private String jsonStr; - @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; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/ReportExcelService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/ReportExcelService.java index 0bceb4b3b..bc933fcf7 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/ReportExcelService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/ReportExcelService.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.service; - import com.anji.plus.gaea.curd.service.GaeaBaseService; import com.anjiplus.template.gaea.business.modules.reportexcel.controller.dto.ReportExcelDto; import com.anjiplus.template.gaea.business.modules.reportexcel.controller.param.ReportExcelParam; @@ -14,30 +13,27 @@ import com.anjiplus.template.gaea.business.modules.reportexcel.dao.entity.Report */ public interface ReportExcelService extends GaeaBaseService { - /** - * 根据报表编码查询详情 - * - * @param reportCode - * @return - */ - ReportExcelDto detailByReportCode(String reportCode); + /** + * 根据报表编码查询详情 + * @param reportCode + * @return + */ + ReportExcelDto detailByReportCode(String reportCode); - /** - * 报表预览 - * - * @param reportExcelDto - * @return - */ - ReportExcelDto preview(ReportExcelDto reportExcelDto); + /** + * 报表预览 + * @param reportExcelDto + * @return + */ + ReportExcelDto preview(ReportExcelDto reportExcelDto); + /** + * 导出为excel + * @param reportExcelDto + * @return + */ + Boolean exportExcel(ReportExcelDto reportExcelDto); - /** - * 导出为excel - * - * @param reportExcelDto - * @return - */ - Boolean exportExcel(ReportExcelDto reportExcelDto); + // Boolean exportPdf(ReportExcelDto reportExcelDto); -// Boolean exportPdf(ReportExcelDto reportExcelDto); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/impl/ReportExcelServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/impl/ReportExcelServiceImpl.java index 865dd7dd0..c109ecd1f 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/impl/ReportExcelServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/service/impl/ReportExcelServiceImpl.java @@ -23,7 +23,6 @@ import com.anjiplus.template.gaea.business.modules.reportexcel.dao.ReportExcelMa import com.anjiplus.template.gaea.business.modules.reportexcel.dao.entity.ReportExcel; import com.anjiplus.template.gaea.business.modules.reportexcel.service.ReportExcelService; import com.anjiplus.template.gaea.business.modules.reportexcel.util.CellType; -import com.anjiplus.template.gaea.business.modules.reportexcel.util.XlsSheetUtil; import com.anjiplus.template.gaea.business.modules.reportexcel.util.XlsUtil; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.apache.commons.lang3.StringUtils; @@ -34,7 +33,10 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; -import java.io.*; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.OutputStream; import java.util.*; /** @@ -46,605 +48,615 @@ import java.util.*; @Service public class ReportExcelServiceImpl implements ReportExcelService { - private Logger logger = LoggerFactory.getLogger(this.getClass()); + private Logger logger = LoggerFactory.getLogger(this.getClass()); - @Autowired - private ReportExcelMapper reportExcelMapper; + @Autowired + private ReportExcelMapper reportExcelMapper; - @Autowired - private DataSetService dataSetService; + @Autowired + private DataSetService dataSetService; + @Autowired + private ReportMapper reportMapper; - @Autowired - private ReportMapper reportMapper; + @Value("${customer.file.dist-path:''}") + private String dictPath; - @Value("${customer.file.dist-path:''}") - private String dictPath; + @Value("${customer.file.downloadPath:''}") + private String fileDownloadPath; - @Value("${customer.file.downloadPath:''}") - private String fileDownloadPath; + @Autowired + private GaeaFileMapper gaeaFileMapper; - @Autowired - private GaeaFileMapper gaeaFileMapper; + @Override + public GaeaBaseMapper getMapper() { + return reportExcelMapper; + } + @Override + public ReportExcelDto detailByReportCode(String reportCode) { + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("report_code", reportCode); + ReportExcel reportExcel = reportExcelMapper.selectOne(queryWrapper); + if (reportExcel != null) { + ReportExcelDto dto = new ReportExcelDto(); + BeanUtils.copyProperties(reportExcel, dto); + return dto; + } + return null; + } - @Override - public GaeaBaseMapper getMapper() { - return reportExcelMapper; - } + /** + * 操作前处理 + * @param entity 前端传递的对象 + * @param operationEnum 操作类型 + * @throws BusinessException 阻止程序继续执行或回滚事务 + */ + @Override + public void processBeforeOperation(ReportExcel entity, BaseOperationEnum operationEnum) throws BusinessException { + if (operationEnum.equals(BaseOperationEnum.INSERT)) { + String reportCode = entity.getReportCode(); + ReportExcel report = this.selectOne("report_code", reportCode); + if (null != report) { + this.deleteById(report.getId()); + } + } + } - @Override - public ReportExcelDto detailByReportCode(String reportCode) { - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("report_code", reportCode); - ReportExcel reportExcel = reportExcelMapper.selectOne(queryWrapper); - if (reportExcel != null) { - ReportExcelDto dto = new ReportExcelDto(); - BeanUtils.copyProperties(reportExcel, dto); - return dto; - } - return null; - } + /** + * 报表预览 + */ + @Override + public ReportExcelDto preview(ReportExcelDto reportExcelDto) { + // 根据id查询 报表详情 + ReportExcel reportExcel = selectOne("report_code", reportExcelDto.getReportCode()); + QueryWrapper queryWrapper = new QueryWrapper<>(); + queryWrapper.eq("report_code", reportExcelDto.getReportCode()); + Report report = reportMapper.selectOne(queryWrapper); + GaeaAssert.notNull(reportExcel, ResponseCode.RULE_CONTENT_NOT_EXIST, "reportExcel"); + String setParam = reportExcelDto.getSetParam(); - /** - * 操作前处理 - * - * @param entity 前端传递的对象 - * @param operationEnum 操作类型 - * @throws BusinessException 阻止程序继续执行或回滚事务 - */ - @Override - public void processBeforeOperation(ReportExcel entity, BaseOperationEnum operationEnum) throws BusinessException { - if (operationEnum.equals(BaseOperationEnum.INSERT)) { - String reportCode = entity.getReportCode(); - ReportExcel report = this.selectOne("report_code", reportCode); - if (null != report) { - this.deleteById(report.getId()); - } - } - } + GaeaBeanUtils.copyAndFormatter(reportExcel, reportExcelDto); + if (StringUtils.isNotBlank(setParam)) { + reportExcelDto.setSetParam(setParam); + } + reportExcelDto.setReportName(report.getReportName()); + // 数据集解析 + String jsonStr = analysisReportData(reportExcelDto); + reportExcelDto.setJsonStr(jsonStr); + // reportExcelDto.setTotal(jsonObject.getJSONObject("rows").size()); + return reportExcelDto; + } - /** - * 报表预览 - */ - @Override - public ReportExcelDto preview(ReportExcelDto reportExcelDto) { - // 根据id查询 报表详情 - ReportExcel reportExcel = selectOne("report_code", reportExcelDto.getReportCode()); - QueryWrapper queryWrapper = new QueryWrapper<>(); - queryWrapper.eq("report_code", reportExcelDto.getReportCode()); - Report report = reportMapper.selectOne(queryWrapper); - GaeaAssert.notNull(reportExcel, ResponseCode.RULE_CONTENT_NOT_EXIST, "reportExcel"); - String setParam = reportExcelDto.getSetParam(); + @Override + public Boolean exportExcel(ReportExcelDto reportExcelDto) { + String reportCode = reportExcelDto.getReportCode(); + String exportType = reportExcelDto.getExportType(); + logger.error("导出..."); + if (exportType.equals(ExportTypeEnum.GAEA_TEMPLATE_EXCEL.getCodeValue())) { + ReportExcelDto report = detailByReportCode(reportCode); + reportExcelDto.setJsonStr(report.getJsonStr()); + String jsonStr = analysisReportData(reportExcelDto); + List lists = (List) JSON.parse(jsonStr); + OutputStream out; + try { + String fileId = UUID.randomUUID().toString(); + String filePath = dictPath + File.separator + fileId + ".xlsx"; + String urlPath = fileDownloadPath + java.io.File.separator + fileId; - GaeaBeanUtils.copyAndFormatter(reportExcel, reportExcelDto); - if (StringUtils.isNotBlank(setParam)) { - reportExcelDto.setSetParam(setParam); - } - reportExcelDto.setReportName(report.getReportName()); - // 数据集解析 - String jsonStr = analysisReportData(reportExcelDto); - reportExcelDto.setJsonStr(jsonStr); -// reportExcelDto.setTotal(jsonObject.getJSONObject("rows").size()); - return reportExcelDto; - } + GaeaFile gaeaFile = new GaeaFile(); + gaeaFile.setFilePath(filePath); + gaeaFile.setFileId(fileId); + gaeaFile.setUrlPath(urlPath); + gaeaFile.setFileType("xlsx"); + gaeaFile.setFileInstruction(reportCode + ".xlsx"); - @Override - public Boolean exportExcel(ReportExcelDto reportExcelDto) { - String reportCode = reportExcelDto.getReportCode(); - String exportType = reportExcelDto.getExportType(); - logger.error("导出..."); - if (exportType.equals(ExportTypeEnum.GAEA_TEMPLATE_EXCEL.getCodeValue())) { - ReportExcelDto report = detailByReportCode(reportCode); - reportExcelDto.setJsonStr(report.getJsonStr()); - String jsonStr = analysisReportData(reportExcelDto); - List lists=(List ) JSON.parse(jsonStr); - OutputStream out; - try { - String fileId = UUID.randomUUID().toString(); - String filePath = dictPath + File.separator + fileId + ".xlsx"; - String urlPath = fileDownloadPath + java.io.File.separator + fileId; + out = new FileOutputStream(filePath); + XlsUtil.exportXlsFile(out, true, lists); - GaeaFile gaeaFile = new GaeaFile(); - gaeaFile.setFilePath(filePath); - gaeaFile.setFileId(fileId); - gaeaFile.setUrlPath(urlPath); - gaeaFile.setFileType("xlsx"); - gaeaFile.setFileInstruction(reportCode + ".xlsx"); + gaeaFileMapper.insert(gaeaFile); + logger.info("导出成功:{}", gaeaFile); + } + catch (IOException e) { + logger.error("导出失败", e); + } + } + return true; + } - out = new FileOutputStream(filePath); - XlsUtil.exportXlsFile(out, true, lists); + /** + * 解析报表数据,动态插入列表数据和对象数据 + */ + private String analysisReportData(ReportExcelDto reportExcelDto) { - gaeaFileMapper.insert(gaeaFile); - logger.info("导出成功:{}", gaeaFile); - } catch (IOException e) { - logger.error("导出失败", e); - } - } - return true; - } + String jsonStr = reportExcelDto.getJsonStr(); + String setParam = reportExcelDto.getSetParam(); + List dbObjectList = (List) JSON.parse(jsonStr); - /** - * 解析报表数据,动态插入列表数据和对象数据 - */ - private String analysisReportData(ReportExcelDto reportExcelDto) { + if (dbObjectList != null && dbObjectList.size() > 0) { + for (int x = 0; x < dbObjectList.size(); x++) { + analysisSheetCellData(dbObjectList.get(x), setParam); + } + } + // fastjson $ref 循环引用 + return JSONObject.toJSONString(dbObjectList, SerializerFeature.DisableCircularReferenceDetect); + } - String jsonStr = reportExcelDto.getJsonStr(); - String setParam = reportExcelDto.getSetParam(); - List dbObjectList = (List) JSON.parse(jsonStr); + /** + * 解析单sheet data + * @param dbObject + */ + private void analysisSheet(JSONObject dbObject, String setParma) { + // data是一个二维数组 + if (dbObject.containsKey("data") && null != dbObject.get("data")) { + List data = (List) dbObject.get("data"); - if (dbObjectList != null && dbObjectList.size() > 0) { - for (int x = 0; x < dbObjectList.size(); x++) { - analysisSheetCellData(dbObjectList.get(x), setParam); - } - } - //fastjson $ref 循环引用 - return JSONObject.toJSONString(dbObjectList, SerializerFeature.DisableCircularReferenceDetect); - } + // 行 + for (int r = 0; r < data.size(); r++) { + JSONArray jsonArray = data.get(r); + // 列 + for (int c = 0; c < jsonArray.size(); c++) { + // 单元格 + JSONObject cell = jsonArray.getJSONObject(c); + if (null != cell && cell.containsKey("v") && StringUtils.isNotBlank(cell.getString("v"))) { + String v = cell.getString("v"); + DataSetDto dataSet = getDataSet(v, setParma); + if (null != dataSet) { + OriginalDataDto originalDataDto = dataSetService.getData(dataSet); + if (null != originalDataDto.getData()) { + if (originalDataDto.getData().size() == 1) { + // 对象 + JSONObject jsonObject = originalDataDto.getData().get(0); + String fieldLabel = jsonObject.getString(dataSet.getFieldLabel()); - /** - * 解析单sheet data - * - * @param dbObject - */ - private void analysisSheet(JSONObject dbObject, String setParma) { - //data是一个二维数组 - if (dbObject.containsKey("data") && null != dbObject.get("data")) { - List data = (List) dbObject.get("data"); + String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".") + .concat(dataSet.getFieldLabel()).concat("}"), fieldLabel); + dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace); + dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace); + } + else { + // 集合 + JSONObject jsonObject = originalDataDto.getData().get(0); + String fieldLabel = jsonObject.getString(dataSet.getFieldLabel()); - //行 - for (int r = 0; r < data.size(); r++) { - JSONArray jsonArray = data.get(r); - //列 - for (int c = 0; c < jsonArray.size(); c++) { - //单元格 - JSONObject cell = jsonArray.getJSONObject(c); - if (null != cell && cell.containsKey("v") && StringUtils.isNotBlank(cell.getString("v"))) { - String v = cell.getString("v"); - DataSetDto dataSet = getDataSet(v, setParma); - if (null != dataSet) { - OriginalDataDto originalDataDto = dataSetService.getData(dataSet); - if (null != originalDataDto.getData()) { - if (originalDataDto.getData().size() == 1) { - //对象 - JSONObject jsonObject = originalDataDto.getData().get(0); - String fieldLabel = jsonObject.getString(dataSet.getFieldLabel()); + String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".") + .concat(dataSet.getFieldLabel()).concat("}"), fieldLabel); + dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace); + dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace); + } + } - String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), fieldLabel); - dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace); - dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace); + } + } - } else { - //集合 - JSONObject jsonObject = originalDataDto.getData().get(0); - String fieldLabel = jsonObject.getString(dataSet.getFieldLabel()); + } + } - String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), fieldLabel); - dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("v", replace); - dbObject.getJSONArray("data").getJSONArray(r).getJSONObject(c).put("m", replace); - } - } + System.out.println("aaaa"); - } - } + } + } + /** + * 解析单sheet celldata + * @param dbObject + */ + private void analysisSheetCellData(JSONObject dbObject, String setParam) { + // 清空data值 + dbObject.remove("data"); + // celldata是一个一维数组 + if (dbObject.containsKey("celldata") && null != dbObject.get("celldata")) { + List celldata = new ArrayList<>(); + celldata.addAll((List) dbObject.get("celldata")); - } - } + // 整理celldata数据,转换为map格式,方便后续使用单元格位置获取对应的cell对象 + Map cellDataMap = cellDataList2Map(celldata); + // 清除原有的数据 + dbObject.getJSONArray("celldata").clear(); + // 获取配置项中的合并属性 + JSONObject merge = dbObject.getJSONObject("config").getJSONObject("merge"); + if (merge != null) + merge.clear(); + // 定义存储每一列动态扩展的行数 + Map colAddCntMap = new HashMap<>(); + // 遍历已存在的单元格,查看是否存在动态参数 + for (int i = 0; i < celldata.size(); i++) { + // 单元格对象 + JSONObject cellObj = celldata.get(i); + // fastjson深拷贝问题 + String cellStr = cellObj.toJSONString(); + analysisCellData(cellObj, setParam, colAddCntMap, cellStr, merge, dbObject, cellDataMap); + } + } + } + /** + * 开始解析并渲染 cellData + * @param cellObject + */ + public void analysisCellData(JSONObject cellObject, String setParam, Map colAddCntMap, + String cellStr, JSONObject merge, JSONObject dbObject, Map cellDataMap) { + // 获取行号 + Integer cellR = cellObject.getInteger("r"); + // 获取列数 + Integer cellC = cellObject.getInteger("c"); + // 获取此行已经动态增加的行数,默认0行 + int cnt = colAddCntMap.get(cellC) == null ? 0 : colAddCntMap.get(cellC); + // 获取单元格类型 + CellType cellType = getCellType(cellObject); + switch (cellType) { + case BLACK: + // 空数据单元格不处理 + break; + case DYNAMIC_MERGE: + case DYNAMIC: + // 处理动态单元格 + String v = cellObject.getJSONObject("v").getString("v"); + DataSetDto dataSet = getDataSet(v, setParam); + handleDynamicCellObject(dataSet, v, cellStr, cnt, cellR, cellC, merge, dbObject, colAddCntMap); + break; + default: + // 处理静态单元格 + handleStaticCellObject(cellStr, dbObject, cnt, cellR, cellC, cellDataMap, setParam, merge, colAddCntMap, + cellType); + break; + } + } - System.out.println("aaaa"); + /** + * 处理动态数据单元格自动扩展 + * @param dataSet + * @param v + * @param cellStr + * @param cnt + * @param r + * @param c + * @param merge + * @param dbObject + * @param colAddCntMap + */ + public void handleDynamicCellObject(DataSetDto dataSet, String v, String cellStr, int cnt, int r, int c, + JSONObject merge, JSONObject dbObject, Map colAddCntMap) { + // 获取动态数据 + OriginalDataDto originalDataDto = dataSetService.getData(dataSet); + List cellDynamicData = originalDataDto.getData(); + if (cellDynamicData != null) { + // 循环数据赋值 + for (int j = 0; j < cellDynamicData.size(); j++) { + // 新增的行数据 + JSONObject addCell = cellDynamicData.get(j); + // 字段 + String fieldLabel = addCell.getString(dataSet.getFieldLabel()); + String replace = v.replace( + "#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), + fieldLabel); + // 转字符串,解决深拷贝问题 + JSONObject addCellData = JSONObject.parseObject(cellStr); - } + addCellData.put("r", cnt + r + j); // 行数增加 + addCellData.put("c", c); + addCellData.getJSONObject("v").put("v", replace); + addCellData.getJSONObject("v").put("m", replace); + JSONObject cellMc = addCellData.getJSONObject("v").getJSONObject("mc"); + // 判断是否是合并单元格 + if (null != cellMc) { + // 处理合并单元格 + Integer rs = cellMc.getInteger("rs"); + cellMc.put("r", cnt + r + rs * j); // 行数增加 + cellMc.put("c", c); + addCellData.put("r", cnt + r + rs * j); + // 合并单元格需要处理config.merge + merge.put(cellMc.getString("r") + "_" + cellMc.getString("c"), cellMc); + // 处理单元格扩展之后此列扩展的总行数 + colAddCntMap.put(c, cnt + rs * cellDynamicData.size() - 1); + } + else { + // 处理单元格扩展之后此列扩展的总行数 + colAddCntMap.put(c, cnt + cellDynamicData.size() - 1); + } + dbObject.getJSONArray("celldata").add(addCellData); + } + } + } + /** + * 处理静态单元格数据 + * @param cellStr + * @param dbObject + * @param cnt + * @param r + * @param c + * @param cellDataMap + * @param setParam + * @param merge + * @param colAddCntMap + * @param cellType + */ + public void handleStaticCellObject(String cellStr, JSONObject dbObject, int cnt, int r, int c, + Map cellDataMap, String setParam, JSONObject merge, Map colAddCntMap, + CellType cellType) { + // 转字符串,解决深拷贝问题 + JSONObject addCellData = JSONObject.parseObject(cellStr); + int rows = 0; + switch (cellType) { + case STATIC: + case STATIC_MERGE: + // 静态不扩展单元格只需要初始化位置就可以 + initCellPosition(addCellData, cnt, merge); + break; + case STATIC_AUTO: + // 获取静态单元格右侧动态单元格的总行数 + rows = getRightDynamicCellRows(addCellData, cellDataMap, setParam, rows, cellType); + initCellPosition(addCellData, cnt, merge); + if (rows > 1) { + // 需要把这个静态扩展单元格 改变为 静态合并扩展单元格,就是增加合并属性 mc 以及merge配置 + JSONObject mc = new JSONObject(); + mc.put("rs", rows); + mc.put("cs", 1); + mc.put("r", addCellData.getIntValue("r")); + mc.put("c", addCellData.getIntValue("c")); + addCellData.getJSONObject("v").put("mc", mc); + // 合并单元格需要处理config.merge + merge.put((mc.getInteger("r")) + "_" + mc.getString("c"), mc); + // 处理单元格扩展之后此列扩展的总行数 + colAddCntMap.put(c, cnt + rows - 1); + } + break; + case STATIC_MERGE_AUTO: + // 获取静态单元格右侧动态单元格的总行数 + rows = getRightDynamicCellRows(addCellData, cellDataMap, setParam, rows, cellType); + initCellPosition(addCellData, cnt, merge); + if (rows > 0) { + // 需要修改单元格mc中的rs + JSONObject cellMc = addCellData.getJSONObject("v").getJSONObject("mc"); + int addCnt = cellMc.getInteger("rs"); + cellMc.put("rs", rows); + // 合并单元格需要处理config.merge + merge.put((cellMc.getInteger("r")) + "_" + cellMc.getString("c"), cellMc); + // 处理单元格扩展之后此列扩展的总行数 + colAddCntMap.put(c, cnt + rows - addCnt); + } + break; + } + dbObject.getJSONArray("celldata").add(addCellData); + } - } + /** + * 初始化单元格位置,主要是这一列已经动态增加的行数 + * @param addCellData + * @param cnt + * @param merge + */ + public void initCellPosition(JSONObject addCellData, int cnt, JSONObject merge) { + addCellData.put("r", cnt + addCellData.getInteger("r"));// 行数增加 + // 是否是合并单元格 + JSONObject mc = addCellData.getJSONObject("v").getJSONObject("mc"); + if (mc != null) { + mc.put("r", addCellData.getInteger("r")); + initCellMerge(merge, mc); + } + } - /** - * 解析单sheet celldata - * - * @param dbObject - */ - private void analysisSheetCellData(JSONObject dbObject, String setParam) { - //清空data值 - dbObject.remove("data"); - //celldata是一个一维数组 - if (dbObject.containsKey("celldata") && null != dbObject.get("celldata")) { - List celldata = new ArrayList<>(); - celldata.addAll((List) dbObject.get("celldata")); + /** + * 初始化单元格合并属性的行数 + * @param merge + * @param mc + */ + public void initCellMerge(JSONObject merge, JSONObject mc) { + merge.put((mc.getInteger("r")) + "_" + mc.getString("c"), mc); + } - //整理celldata数据,转换为map格式,方便后续使用单元格位置获取对应的cell对象 - Map cellDataMap = cellDataList2Map(celldata); - //清除原有的数据 - dbObject.getJSONArray("celldata").clear(); - //获取配置项中的合并属性 - JSONObject merge = dbObject.getJSONObject("config").getJSONObject("merge"); - if(merge != null) merge.clear(); - //定义存储每一列动态扩展的行数 - Map colAddCntMap = new HashMap<>(); - // 遍历已存在的单元格,查看是否存在动态参数 - for (int i = 0; i < celldata.size(); i++) { - //单元格对象 - JSONObject cellObj = celldata.get(i); - //fastjson深拷贝问题 - String cellStr = cellObj.toJSONString(); - analysisCellData(cellObj,setParam,colAddCntMap,cellStr,merge, dbObject,cellDataMap); - } - } - } + /** + * 获取合并单元格右侧的动态扩展行数,用来设置当前单元格的实际 + * @param addCellData + * @param cellDataMap + * @param setParam + * @param sumRows + * @param cellType + * @return + */ + public int getRightDynamicCellRows(JSONObject addCellData, Map cellDataMap, String setParam, + int sumRows, CellType cellType) { + // 1、获取此单元格右侧关联的所有单元格 + List rightCellList = getRightDynamicCell(addCellData, cellDataMap, cellType); + // 2、循环获取每个单元格的扩展行数 + for (JSONObject rightCell : rightCellList) { + // 首先判断这个单元格是否也是【静态扩展单元格】 + CellType rightCellType = getCellType(rightCell); + switch (rightCellType) { + case STATIC_AUTO: + case STATIC_MERGE_AUTO: + // 递归查找 + sumRows = getRightDynamicCellRows(rightCell, cellDataMap, setParam, sumRows, rightCellType); + break; + case BLACK: + case STATIC: + sumRows++; + break; + case STATIC_MERGE: + sumRows += rightCell.getJSONObject("v").getJSONObject("mc").getInteger("rs"); + break; + default: + List cellDynamicData = getDynamicDataList(rightCell.getJSONObject("v").getString("v"), + setParam); + if (cellDynamicData != null && cellDynamicData.size() > 1) { + int size = cellDynamicData.size(); + sumRows += size; + } + else { + sumRows++; + } + break; + } + } + return sumRows; + } - /** - * 开始解析并渲染 cellData - * @param cellObject - */ - public void analysisCellData(JSONObject cellObject,String setParam,Map colAddCntMap,String cellStr, - JSONObject merge,JSONObject dbObject,Map cellDataMap){ - //获取行号 - Integer cellR = cellObject.getInteger("r"); - //获取列数 - Integer cellC = cellObject.getInteger("c"); - //获取此行已经动态增加的行数,默认0行 - int cnt = colAddCntMap.get(cellC) == null ? 0 : colAddCntMap.get(cellC); - //获取单元格类型 - CellType cellType = getCellType(cellObject); - switch (cellType){ - case BLACK: - //空数据单元格不处理 - break; - case DYNAMIC_MERGE: - case DYNAMIC: - //处理动态单元格 - String v = cellObject.getJSONObject("v").getString("v"); - DataSetDto dataSet = getDataSet(v, setParam); - handleDynamicCellObject(dataSet,v,cellStr,cnt,cellR,cellC,merge,dbObject,colAddCntMap); - break; - default: - //处理静态单元格 - handleStaticCellObject(cellStr,dbObject,cnt,cellR,cellC,cellDataMap,setParam,merge,colAddCntMap,cellType); - break; - } - } + /** + * 获取扩展单元格右侧相邻的所有单元格实体 + * @param addCellData + * @param cellDataMap + * @param cellType + * @return + */ + public List getRightDynamicCell(JSONObject addCellData, Map cellDataMap, + CellType cellType) { + // 静态数据合并单元格需要根据右侧的单元格进行自动向下扩展 + // 1、先获取右侧一列的关联的单元格,根据自身的位置,以及自己合并的合并的信息推断 + // 如果自己位置是 2,5,并且本身合并 行数2,列数3,则需要推断出两个单元格的位置 + // 分别是2,8 和 3,8 + Integer cellR = addCellData.getInteger("r"); + Integer cellC = addCellData.getInteger("c"); + Integer cellRs = 0; + Integer cellCs = 0; + switch (cellType) { + case STATIC_AUTO: + cellRs = 1; + cellCs = 1; + break; + case STATIC_MERGE_AUTO: + cellRs = addCellData.getJSONObject("v").getJSONObject("mc").getInteger("rs"); + cellCs = addCellData.getJSONObject("v").getJSONObject("mc").getInteger("cs"); + break; + } + List rightCells = new ArrayList<>(); + for (int nums = 0; nums < cellRs; nums++) { + int r = cellR + nums; + int c = cellC + cellCs; + String key = r + "," + c; + if (cellDataMap.containsKey(key)) { + JSONObject cellData = cellDataMap.get(r + "," + c); + rightCells.add(cellData); + } + } + return rightCells; + } - /** - * 处理动态数据单元格自动扩展 - * @param dataSet - * @param v - * @param cellStr - * @param cnt - * @param r - * @param c - * @param merge - * @param dbObject - * @param colAddCntMap - */ - public void handleDynamicCellObject(DataSetDto dataSet,String v,String cellStr,int cnt,int r,int c, - JSONObject merge,JSONObject dbObject,Map colAddCntMap){ - //获取动态数据 - OriginalDataDto originalDataDto = dataSetService.getData(dataSet); - List cellDynamicData = originalDataDto.getData(); + /** + * 判断单元格类型 + * @param cellObject + * @return + */ + public CellType getCellType(JSONObject cellObject) { + JSONObject cellV1 = cellObject.getJSONObject("v"); + if (null != cellV1 && cellV1.containsKey("v") && StringUtils.isNotBlank(cellV1.getString("v"))) { + String cellV2 = cellObject.getJSONObject("v").getString("v"); + String auto = cellObject.getJSONObject("v").getString("auto"); + JSONObject mc = cellObject.getJSONObject("v").getJSONObject("mc"); + if (cellV2.contains("#{") && cellV2.contains("}")) { + // 动态单元格 + if (mc != null) { + return CellType.DYNAMIC_MERGE; + } + else { + return CellType.DYNAMIC; + } + } + else { + // 静态单元格 + if (mc != null && "1".equals(auto)) { + return CellType.STATIC_MERGE_AUTO; + } + else { + if ("1".equals(auto)) { + return CellType.STATIC_AUTO; + } + else if (mc != null) { + return CellType.STATIC_MERGE; + } + else { + return CellType.STATIC; + } + } + } + } + else { + return CellType.BLACK; + } + } - if(cellDynamicData != null){ - //循环数据赋值 - for (int j = 0; j < cellDynamicData.size(); j++) { - //新增的行数据 - JSONObject addCell = cellDynamicData.get(j); - //字段 - String fieldLabel = addCell.getString(dataSet.getFieldLabel()); - String replace = v.replace("#{".concat(dataSet.getSetCode()).concat(".").concat(dataSet.getFieldLabel()).concat("}"), fieldLabel); - //转字符串,解决深拷贝问题 - JSONObject addCellData = JSONObject.parseObject(cellStr); + /** + * list转为map结构,方便使用行列号查找对应cell对象 + * @param cellDataList + * @return + */ + public Map cellDataList2Map(List cellDataList) { + Map cellDataMap = new HashMap<>(); + for (JSONObject cellData : cellDataList) { + String r = cellData.getString("r"); + String c = cellData.getString("c"); + cellDataMap.put(r + "," + c, cellData); + } + return cellDataMap; + } - addCellData.put("r", cnt + r + j); //行数增加 - addCellData.put("c", c); - addCellData.getJSONObject("v").put("v", replace); - addCellData.getJSONObject("v").put("m", replace); - JSONObject cellMc = addCellData.getJSONObject("v").getJSONObject("mc"); - //判断是否是合并单元格 - if(null != cellMc){ - //处理合并单元格 - Integer rs = cellMc.getInteger("rs"); - cellMc.put("r", cnt + r + rs*j); //行数增加 - cellMc.put("c", c); - addCellData.put("r", cnt + r + rs*j); - //合并单元格需要处理config.merge - merge.put(cellMc.getString("r")+"_"+cellMc.getString("c"),cellMc); - //处理单元格扩展之后此列扩展的总行数 - colAddCntMap.put(c,cnt + rs * cellDynamicData.size() - 1); - }else{ - //处理单元格扩展之后此列扩展的总行数 - colAddCntMap.put(c,cnt + cellDynamicData.size() - 1); - } - dbObject.getJSONArray("celldata").add(addCellData); - } - } - } + /** + * 解析 #{xxxx.xxxxx} 数据 + * @param v + * @return + */ + private DataSetDto getDataSet(String v, String setParam) { - /** - * 处理静态单元格数据 - * @param cellStr - * @param dbObject - * @param cnt - * @param r - * @param c - * @param cellDataMap - * @param setParam - * @param merge - * @param colAddCntMap - * @param cellType - */ - public void handleStaticCellObject(String cellStr,JSONObject dbObject,int cnt,int r,int c, - Map cellDataMap,String setParam, - JSONObject merge,Map colAddCntMap,CellType cellType){ - //转字符串,解决深拷贝问题 - JSONObject addCellData = JSONObject.parseObject(cellStr); - int rows = 0; - switch(cellType){ - case STATIC: - case STATIC_MERGE: - //静态不扩展单元格只需要初始化位置就可以 - initCellPosition(addCellData,cnt,merge); - break; - case STATIC_AUTO: - //获取静态单元格右侧动态单元格的总行数 - rows = getRightDynamicCellRows(addCellData,cellDataMap,setParam,rows,cellType); - initCellPosition(addCellData,cnt,merge); - if(rows > 1){ - //需要把这个静态扩展单元格 改变为 静态合并扩展单元格,就是增加合并属性 mc 以及merge配置 - JSONObject mc = new JSONObject(); - mc.put("rs",rows); - mc.put("cs",1); - mc.put("r",addCellData.getIntValue("r")); - mc.put("c",addCellData.getIntValue("c")); - addCellData.getJSONObject("v").put("mc",mc); - //合并单元格需要处理config.merge - merge.put((mc.getInteger("r")) + "_" + mc.getString("c"),mc); - //处理单元格扩展之后此列扩展的总行数 - colAddCntMap.put(c,cnt + rows - 1); - } - break; - case STATIC_MERGE_AUTO: - //获取静态单元格右侧动态单元格的总行数 - rows = getRightDynamicCellRows(addCellData,cellDataMap,setParam,rows,cellType); - initCellPosition(addCellData,cnt,merge); - if(rows > 0){ - //需要修改单元格mc中的rs - JSONObject cellMc = addCellData.getJSONObject("v").getJSONObject("mc"); - int addCnt = cellMc.getInteger("rs"); - cellMc.put("rs",rows); - //合并单元格需要处理config.merge - merge.put((cellMc.getInteger("r")) + "_" + cellMc.getString("c"),cellMc); - //处理单元格扩展之后此列扩展的总行数 - colAddCntMap.put(c,cnt + rows - addCnt); - } - break; - } - dbObject.getJSONArray("celldata").add(addCellData); - } + DataSetDto dto = new DataSetDto(); + if (v.contains("#{") && v.contains("}")) { + int start = v.indexOf("#{") + 2; + int end = v.indexOf("}"); + if (start < end) { + String substring = v.substring(start, end); + if (substring.contains(".")) { + String[] split = substring.split("\\."); + dto.setSetCode(split[0]); + dto.setFieldLabel(split[1]); + getContextData(setParam, dto); + return dto; + } + } + } + return null; + } - /** - * 初始化单元格位置,主要是这一列已经动态增加的行数 - * @param addCellData - * @param cnt - * @param merge - */ - public void initCellPosition(JSONObject addCellData,int cnt,JSONObject merge){ - addCellData.put("r", cnt + addCellData.getInteger("r"));//行数增加 - //是否是合并单元格 - JSONObject mc = addCellData.getJSONObject("v").getJSONObject("mc"); - if(mc != null){ - mc.put("r",addCellData.getInteger("r")); - initCellMerge(merge,mc); - } - } + /** + * 获取单元格对应的动态数据集 + * @param v + * @param setParam + * @return + */ + private List getDynamicDataList(String v, String setParam) { + if (StringUtils.isNotBlank(v)) { + DataSetDto dataSet = getDataSet(v, setParam); + if (dataSet != null) { + OriginalDataDto originalDataDto = dataSetService.getData(dataSet); + List cellDynamicData = originalDataDto.getData(); + return cellDynamicData; + } + else { + return null; + } + } + else { + return null; + } + } - /** - * 初始化单元格合并属性的行数 - * @param merge - * @param mc - */ - public void initCellMerge(JSONObject merge,JSONObject mc){ - merge.put((mc.getInteger("r"))+"_"+mc.getString("c"),mc); - } - - /** - * 获取合并单元格右侧的动态扩展行数,用来设置当前单元格的实际 - * @param addCellData - * @param cellDataMap - * @param setParam - * @param sumRows - * @param cellType - * @return - */ - public int getRightDynamicCellRows(JSONObject addCellData,Map cellDataMap,String setParam,int sumRows,CellType cellType){ - //1、获取此单元格右侧关联的所有单元格 - List rightCellList = getRightDynamicCell(addCellData,cellDataMap,cellType); - //2、循环获取每个单元格的扩展行数 - for (JSONObject rightCell : rightCellList) { - //首先判断这个单元格是否也是【静态扩展单元格】 - CellType rightCellType = getCellType(rightCell); - switch (rightCellType){ - case STATIC_AUTO: - case STATIC_MERGE_AUTO: - //递归查找 - sumRows = getRightDynamicCellRows(rightCell,cellDataMap,setParam,sumRows,rightCellType); - break; - case BLACK: - case STATIC: - sumRows++; - break; - case STATIC_MERGE: - sumRows += rightCell.getJSONObject("v").getJSONObject("mc").getInteger("rs"); - break; - default: - List cellDynamicData = getDynamicDataList(rightCell.getJSONObject("v").getString("v"),setParam); - if(cellDynamicData != null && cellDynamicData.size() > 1){ - int size = cellDynamicData.size(); - sumRows += size; - }else{ - sumRows++; - } - break; - } - } - return sumRows; - } - - /** - * 获取扩展单元格右侧相邻的所有单元格实体 - * @param addCellData - * @param cellDataMap - * @param cellType - * @return - */ - public List getRightDynamicCell(JSONObject addCellData,Map cellDataMap,CellType cellType){ - //静态数据合并单元格需要根据右侧的单元格进行自动向下扩展 - //1、先获取右侧一列的关联的单元格,根据自身的位置,以及自己合并的合并的信息推断 - //如果自己位置是 2,5,并且本身合并 行数2,列数3,则需要推断出两个单元格的位置 - //分别是2,8 和 3,8 - Integer cellR = addCellData.getInteger("r"); - Integer cellC = addCellData.getInteger("c"); - Integer cellRs = 0; - Integer cellCs = 0; - switch (cellType){ - case STATIC_AUTO: - cellRs = 1; - cellCs = 1; - break; - case STATIC_MERGE_AUTO: - cellRs = addCellData.getJSONObject("v").getJSONObject("mc").getInteger("rs"); - cellCs = addCellData.getJSONObject("v").getJSONObject("mc").getInteger("cs"); - break; - } - List rightCells = new ArrayList<>(); - for(int nums = 0;nums < cellRs;nums++){ - int r = cellR + nums; - int c = cellC + cellCs; - String key = r + "," + c; - if(cellDataMap.containsKey(key)){ - JSONObject cellData = cellDataMap.get(r + "," + c); - rightCells.add(cellData); - } - } - return rightCells; - } - - /** - * 判断单元格类型 - * @param cellObject - * @return - */ - public CellType getCellType(JSONObject cellObject){ - JSONObject cellV1 = cellObject.getJSONObject("v"); - if (null != cellV1 && cellV1.containsKey("v") && StringUtils.isNotBlank(cellV1.getString("v"))) { - String cellV2 = cellObject.getJSONObject("v").getString("v"); - String auto = cellObject.getJSONObject("v").getString("auto"); - JSONObject mc = cellObject.getJSONObject("v").getJSONObject("mc"); - if(cellV2.contains("#{") && cellV2.contains("}") ){ - //动态单元格 - if(mc != null){ - return CellType.DYNAMIC_MERGE; - }else{ - return CellType.DYNAMIC; - } - }else{ - //静态单元格 - if(mc != null && "1".equals(auto)){ - return CellType.STATIC_MERGE_AUTO; - }else { - if("1".equals(auto)){ - return CellType.STATIC_AUTO; - }else if(mc != null){ - return CellType.STATIC_MERGE; - }else{ - return CellType.STATIC; - } - } - } - }else{ - return CellType.BLACK; - } - } - - /** - * list转为map结构,方便使用行列号查找对应cell对象 - * @param cellDataList - * @return - */ - public Map cellDataList2Map(List cellDataList){ - Map cellDataMap = new HashMap<>(); - for (JSONObject cellData : cellDataList) { - String r = cellData.getString("r"); - String c = cellData.getString("c"); - cellDataMap.put(r + "," + c, cellData); - } - return cellDataMap; - } - - /** - * 解析 #{xxxx.xxxxx} 数据 - * @param v - * @return - */ - private DataSetDto getDataSet(String v, String setParam) { - - DataSetDto dto = new DataSetDto(); - if (v.contains("#{") && v.contains("}")) { - int start = v.indexOf("#{") + 2; - int end = v.indexOf("}"); - if (start < end) { - String substring = v.substring(start, end); - if (substring.contains(".")) { - String[] split = substring.split("\\."); - dto.setSetCode( split[0]); - dto.setFieldLabel(split[1]); - getContextData(setParam, dto); - return dto; - } - } - } - return null; - } - - /** - * 获取单元格对应的动态数据集 - * @param v - * @param setParam - * @return - */ - private List getDynamicDataList(String v, String setParam){ - if(StringUtils.isNotBlank(v)){ - DataSetDto dataSet = getDataSet(v,setParam); - if(dataSet != null){ - OriginalDataDto originalDataDto = dataSetService.getData(dataSet); - List cellDynamicData = originalDataDto.getData(); - return cellDynamicData; - }else{ - return null; - } - }else{ - return null; - } - } - - /** - * 动态参数替换 - * @param setParam - * @param dto - */ - private void getContextData(String setParam, DataSetDto dto) { - if (StringUtils.isNotBlank(setParam)) { - JSONObject setParamJson = JSONObject.parseObject(setParam); - Map map = new HashMap<>(); - // 查询条件 - if (setParamJson.containsKey(dto.getSetCode())) { - JSONObject paramCondition = setParamJson.getJSONObject(dto.getSetCode()); - paramCondition.forEach(map::put); - } - dto.setContextData(map); - } - } + /** + * 动态参数替换 + * @param setParam + * @param dto + */ + private void getContextData(String setParam, DataSetDto dto) { + if (StringUtils.isNotBlank(setParam)) { + JSONObject setParamJson = JSONObject.parseObject(setParam); + Map map = new HashMap<>(); + // 查询条件 + if (setParamJson.containsKey(dto.getSetCode())) { + JSONObject paramCondition = setParamJson.getJSONObject(dto.getSetCode()); + paramCondition.forEach(map::put); + } + dto.setContextData(map); + } + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/CellType.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/CellType.java index 0a86c3093..547f917bf 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/CellType.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/CellType.java @@ -4,36 +4,34 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.util; * 单元格类型 */ public enum CellType { - DYNAMIC_MERGE("DYNAMIC_MERGE","动态合并单元格"), - DYNAMIC("DYNAMIC","动态单元格"), - STATIC("STATIC","静态单元格"), - STATIC_AUTO("STATIC_AUTO","静态扩展单元格"), - STATIC_MERGE("STATIC_MERGE","静态合并单元格"), - STATIC_MERGE_AUTO("STATIC_MERGE_AUTO","静态合并扩展单元格"), - BLACK("BLACK","空白单元格"); - private String code; - private String name; + DYNAMIC_MERGE("DYNAMIC_MERGE", "动态合并单元格"), DYNAMIC("DYNAMIC", "动态单元格"), STATIC("STATIC", "静态单元格"), STATIC_AUTO( + "STATIC_AUTO", "静态扩展单元格"), STATIC_MERGE("STATIC_MERGE", + "静态合并单元格"), STATIC_MERGE_AUTO("STATIC_MERGE_AUTO", "静态合并扩展单元格"), BLACK("BLACK", "空白单元格"); - CellType(String code,String name) { - this.code = code; - this.name = name; - } + private String code; - public String getCode() { - return code; - } + private String name; - public String getName() { - return name; - } + CellType(String code, String name) { + this.code = code; + this.name = name; + } - public void setCode(String code) { - this.code = code; - } + public String getCode() { + return code; + } + + public String getName() { + return name; + } + + public void setCode(String code) { + this.code = code; + } + + public void setName(String name) { + this.name = name; + } - public void setName(String name) { - this.name = name; - } } - diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ColorUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ColorUtil.java index 5e9037e31..cb03bca95 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ColorUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ColorUtil.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.util; - import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.poi.hssf.usermodel.HSSFPalette; @@ -11,7 +10,6 @@ import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Color; import org.apache.poi.xssf.usermodel.XSSFColor; - /** * 来自:https://github.com/mengshukeji/LuckysheetServer * @@ -20,115 +18,120 @@ import org.apache.poi.xssf.usermodel.XSSFColor; @Slf4j public class ColorUtil { - private static final String S = "0123456789ABCDEF"; + private static final String S = "0123456789ABCDEF"; - public static Short getColorByStr(String colorStr) { - HSSFWorkbook workbook = new HSSFWorkbook(); - HSSFPalette palette = workbook.getCustomPalette(); + public static Short getColorByStr(String colorStr) { + HSSFWorkbook workbook = new HSSFWorkbook(); + HSSFPalette palette = workbook.getCustomPalette(); - if (colorStr.toLowerCase().startsWith("rgb")) { - colorStr = colorStr.toLowerCase().replace("rgb(", "").replace(")", ""); - String[] colors = colorStr.split(","); - if (colors.length == 3) { - try { - int red = Integer.parseInt(colors[0].trim(), 16); - int green = Integer.parseInt(colors[1].trim(), 16); - int blue = Integer.parseInt(colors[2].trim(), 16); + if (colorStr.toLowerCase().startsWith("rgb")) { + colorStr = colorStr.toLowerCase().replace("rgb(", "").replace(")", ""); + String[] colors = colorStr.split(","); + if (colors.length == 3) { + try { + int red = Integer.parseInt(colors[0].trim(), 16); + int green = Integer.parseInt(colors[1].trim(), 16); + int blue = Integer.parseInt(colors[2].trim(), 16); - HSSFColor hssfColor = palette.findSimilarColor(red, green, blue); - return hssfColor.getIndex(); - } catch (Exception ex) { - log.error(ex.toString()); - return null; - } - } - return null; - } + HSSFColor hssfColor = palette.findSimilarColor(red, green, blue); + return hssfColor.getIndex(); + } + catch (Exception ex) { + log.error(ex.toString()); + return null; + } + } + return null; + } - if (colorStr.equals("#000")) { - colorStr = "#000000"; - } - if (colorStr != null && colorStr.length() >= 6) { - try { - if (colorStr.length() == 8) { - colorStr = colorStr.substring(2); - } - if (colorStr.length() == 7) { - colorStr = colorStr.substring(1); - } - String str2 = colorStr.substring(0, 2); - String str3 = colorStr.substring(2, 4); - String str4 = colorStr.substring(4, 6); - int red = Integer.parseInt(str2, 16); - int green = Integer.parseInt(str3, 16); - int blue = Integer.parseInt(str4, 16); + if (colorStr.equals("#000")) { + colorStr = "#000000"; + } + if (colorStr != null && colorStr.length() >= 6) { + try { + if (colorStr.length() == 8) { + colorStr = colorStr.substring(2); + } + if (colorStr.length() == 7) { + colorStr = colorStr.substring(1); + } + String str2 = colorStr.substring(0, 2); + String str3 = colorStr.substring(2, 4); + String str4 = colorStr.substring(4, 6); + int red = Integer.parseInt(str2, 16); + int green = Integer.parseInt(str3, 16); + int blue = Integer.parseInt(str4, 16); - HSSFColor hssfColor = palette.findSimilarColor(red, green, blue); - return hssfColor.getIndex(); - } catch (Exception ex) { - log.error(ex.toString()); - return null; - } - } - return null; - } + HSSFColor hssfColor = palette.findSimilarColor(red, green, blue); + return hssfColor.getIndex(); + } + catch (Exception ex) { + log.error(ex.toString()); + return null; + } + } + return null; + } - /** - * RGB转换成十六进制 - * - * @param r - * @param g - * @param b - * @return - */ - public static String convertRGBToHex(short r, short g, short b) { - String hex = ""; - if (r >= 0 && r < 256 && g >= 0 && g < 256 && b >= 0 && b < 256) { - int x, y, z; - x = r % 16; - r = (short) ((r - x) / 16); - y = g % 16; - g = (short) ((g - y) / 16); - z = b % 16; - b = (short) ((b - z) / 16); - hex = "#" + S.charAt(r) + S.charAt(x) + S.charAt(g) + S.charAt(y) + S.charAt(b) + S.charAt(z); - } - return hex; - } + /** + * RGB转换成十六进制 + * @param r + * @param g + * @param b + * @return + */ + public static String convertRGBToHex(short r, short g, short b) { + String hex = ""; + if (r >= 0 && r < 256 && g >= 0 && g < 256 && b >= 0 && b < 256) { + int x, y, z; + x = r % 16; + r = (short) ((r - x) / 16); + y = g % 16; + g = (short) ((g - y) / 16); + z = b % 16; + b = (short) ((b - z) / 16); + hex = "#" + S.charAt(r) + S.charAt(x) + S.charAt(g) + S.charAt(y) + S.charAt(b) + S.charAt(z); + } + return hex; + } - /** - * @param cell 单元格 - * @return 转换RGB颜色值 - * @description tint转换RBG - * @author zhouhang - * @date 2021/4/26 - */ - public static String getFillColorHex(Cell cell) { - String fillColorString = null; - if (cell != null) { - CellStyle cellStyle = cell.getCellStyle(); - Color color = cellStyle.getFillForegroundColorColor(); - if (color instanceof XSSFColor) { - XSSFColor xssfColor = (XSSFColor) color; - byte[] argb = xssfColor.getARGB(); - fillColorString = convertRGBToHex((short) (argb[1] & 0xFF), (short) (argb[2] & 0xFF), (short) (argb[3] & 0xFF)); - // TODO: 2021/4/26 添加透明度 -// if (xssfColor.hasTint()) { -// fillColorString += " * " + xssfColor.getTint(); -// byte[] rgb = xssfColor.getRGBWithTint(); -// fillColorString += " = [" + (argb[0] & 0xFF) + ", " + (rgb[0] & 0xFF) + ", " + (rgb[1] & 0xFF) + ", " + (rgb[2] & 0xFF) + "]"; -// } - } else if (color instanceof HSSFColor) { - HSSFColor hssfColor = (HSSFColor) color; - short[] rgb = hssfColor.getTriplet(); - fillColorString = convertRGBToHex((short) (rgb[0] & 0xFF), (short) (rgb[1] & 0xFF), (short) (rgb[2] & 0xFF)); - //去除黑色背景 - if (StringUtils.equals("#000000", fillColorString)) { - return null; - } - } - } - return fillColorString; - } + /** + * @param cell 单元格 + * @return 转换RGB颜色值 + * @description tint转换RBG + * @author zhouhang + * @date 2021/4/26 + */ + public static String getFillColorHex(Cell cell) { + String fillColorString = null; + if (cell != null) { + CellStyle cellStyle = cell.getCellStyle(); + Color color = cellStyle.getFillForegroundColorColor(); + if (color instanceof XSSFColor) { + XSSFColor xssfColor = (XSSFColor) color; + byte[] argb = xssfColor.getARGB(); + fillColorString = convertRGBToHex((short) (argb[1] & 0xFF), (short) (argb[2] & 0xFF), + (short) (argb[3] & 0xFF)); + // TODO: 2021/4/26 添加透明度 + // if (xssfColor.hasTint()) { + // fillColorString += " * " + xssfColor.getTint(); + // byte[] rgb = xssfColor.getRGBWithTint(); + // fillColorString += " = [" + (argb[0] & 0xFF) + ", " + (rgb[0] & 0xFF) + + // ", " + (rgb[1] & 0xFF) + ", " + (rgb[2] & 0xFF) + "]"; + // } + } + else if (color instanceof HSSFColor) { + HSSFColor hssfColor = (HSSFColor) color; + short[] rgb = hssfColor.getTriplet(); + fillColorString = convertRGBToHex((short) (rgb[0] & 0xFF), (short) (rgb[1] & 0xFF), + (short) (rgb[2] & 0xFF)); + // 去除黑色背景 + if (StringUtils.equals("#000000", fillColorString)) { + return null; + } + } + } + return fillColorString; + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ConstantUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ConstantUtil.java index 29df40c57..4922fad43 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ConstantUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/ConstantUtil.java @@ -1,6 +1,5 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.util; - import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; @@ -14,300 +13,312 @@ import java.util.*; * @author cr */ public class ConstantUtil { - /** - * 导出。字体转换 - */ - public static Map ff_IntegerToName = new HashMap(); - /** - * 导入。字体转换 - */ - public static Map ff_NameToInteger = new HashMap(); - /** - * 导入 36种数字格式。注意官方文档的编号不是连续的,22后面直接是37,所以数组中间补14个空值 - */ - public static String[] number_type = null; - /** - * 导入 36种格式的定义字符串 - */ - public static String[] number_format = null; - /** - * 数据类型 - */ - public static Map number_format_map = new HashMap(); + /** + * 导出。字体转换 + */ + public static Map ff_IntegerToName = new HashMap(); - static { - //格式 - nf(); - //字体 - ff(); - } + /** + * 导入。字体转换 + */ + public static Map ff_NameToInteger = new HashMap(); - private static void nf() { - number_type = new String[]{ - "General", "Decimal", "Decimal", "Decimal", "Decimal", "Currency", "Currency", "Currency", "Currency", - "Percentage", "Percentage", "Scientific", "Fraction", "Fraction", "Date", "Date", "Date", "Date", - "Time", "Time", "Time", "Time", "Time", - "", "", "", "", "", "", "", "", "", "", "", "", "", "", - "Accounting", "Accounting", "Accounting", "Accounting", "Accounting", - "Currency", "Accounting", "Currency", "Time", "Time", "Time", "Scientific", "Text" - }; + /** + * 导入 36种数字格式。注意官方文档的编号不是连续的,22后面直接是37,所以数组中间补14个空值 + */ + public static String[] number_type = null; - number_format = new String[]{ - "General", "0", "0.00", "#,##0", "#,##0.00", "$#,##0;($#,##0)", "$#,##0;[Red]($#,##0)", "$#,##0.00;($#,##0.00)", "$#,##0.00;[Red]($#,##0.00)", - "0%", "0.00%", "0.00E+00", "# ?/?", "# ??/??", "m/d/yyyy", "d-mmm-yy", "d-mmm", "mmm-yy", - "h:mm AM/PM", "h:mm:ss AM/PM", "h:mm", "h:mm:ss", "m/d/yyyy h:mm", - "", "", "", "", "", "", "", "", "", "", "", "", "", "", - "#,##0;(#,##0)", "#,##0;[Red](#,##0)", "#,##0.00;(#,##0.00)", "#,##0.00;[Red](#,##0.00)", "_ * #,##0_ ;_ * (#,##0)_ ;_ * \"-\"_ ;_ @_", - "_ $* #,##0_ ;_ $* (#,##0)_ ;_ $* \"-\"_ ;_ @_", "_ * #,##0.00_ ;_ * (#,##0.00)_ ;_ * \"-\"??_ ;_ @_", "_ $* #,##0.00_ ;_ $* (#,##0.00)_ ;_ $* \"-\"??_ ;_ @_", "mm:ss", "[h]:mm:ss", "mm:ss.0", "##0.0E+00", "@" - }; - for (int x = 0; x < number_format.length; x++) { - if (number_format[x].length() > 0) { - number_format_map.put(number_format[x].toLowerCase(), x); - } - } - } + /** + * 导入 36种格式的定义字符串 + */ + public static String[] number_format = null; - private static void ff() { - //0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST Song)、 - // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana - ff_IntegerToName.put(0, "微软雅黑"); - ff_IntegerToName.put(1, "宋体"); - ff_IntegerToName.put(2, "黑体"); - ff_IntegerToName.put(3, "楷体"); - ff_IntegerToName.put(4, "仿宋"); - ff_IntegerToName.put(5, "新宋体"); - ff_IntegerToName.put(6, "华文新魏"); - ff_IntegerToName.put(7, "华文行楷"); - ff_IntegerToName.put(8, "华文隶书"); - ff_IntegerToName.put(9, "Arial"); - ff_IntegerToName.put(10, "Times New Roman"); - ff_IntegerToName.put(11, "Tahoma"); - ff_IntegerToName.put(12, "Verdana"); + /** + * 数据类型 + */ + public static Map number_format_map = new HashMap(); - //0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST Song)、 - // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana - ff_NameToInteger.put("微软雅黑", 0); - ff_NameToInteger.put("宋体", 1); - ff_NameToInteger.put("Song", 1); - ff_NameToInteger.put("黑体", 2); - ff_NameToInteger.put("ST Heiti", 2); - ff_NameToInteger.put("楷体", 3); - ff_NameToInteger.put("ST Kaiti", 3); - ff_NameToInteger.put("仿宋", 4); - ff_NameToInteger.put("ST FangSong", 4); - ff_NameToInteger.put("新宋体", 5); - ff_NameToInteger.put("ST Song", 5); - ff_NameToInteger.put("华文新魏", 6); - ff_NameToInteger.put("华文行楷", 7); - ff_NameToInteger.put("华文隶书", 8); - ff_NameToInteger.put("Arial", 9); - ff_NameToInteger.put("Times New Roman", 10); - ff_NameToInteger.put("Tahoma", 11); - ff_NameToInteger.put("Verdana", 12); - } + static { + // 格式 + nf(); + // 字体 + ff(); + } - private static void borderType() { - //"border-left" | "border-right" | "border-top" | "border-bottom" | "border-all" - // | "border-outside" | "border-inside" | "border-horizontal" | "border-vertical" | "border-none" - ff_IntegerToName.put(0, "微软雅黑"); - ff_IntegerToName.put(1, "宋体"); - ff_IntegerToName.put(2, "黑体"); - ff_IntegerToName.put(3, "楷体"); - ff_IntegerToName.put(4, "仿宋"); - ff_IntegerToName.put(5, "新宋体"); - ff_IntegerToName.put(6, "华文新魏"); - ff_IntegerToName.put(7, "华文行楷"); - ff_IntegerToName.put(8, "华文隶书"); - ff_IntegerToName.put(9, "Arial"); - ff_IntegerToName.put(10, "Times New Roman"); - ff_IntegerToName.put(11, "Tahoma"); - ff_IntegerToName.put(12, "Verdana"); + private static void nf() { + number_type = new String[] { "General", "Decimal", "Decimal", "Decimal", "Decimal", "Currency", "Currency", + "Currency", "Currency", "Percentage", "Percentage", "Scientific", "Fraction", "Fraction", "Date", + "Date", "Date", "Date", "Time", "Time", "Time", "Time", "Time", "", "", "", "", "", "", "", "", "", "", + "", "", "", "", "Accounting", "Accounting", "Accounting", "Accounting", "Accounting", "Currency", + "Accounting", "Currency", "Time", "Time", "Time", "Scientific", "Text" }; - //0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST Song)、 - // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana - ff_NameToInteger.put("微软雅黑", 0); - ff_NameToInteger.put("宋体", 1); - ff_NameToInteger.put("Song", 1); - ff_NameToInteger.put("黑体", 2); - ff_NameToInteger.put("ST Heiti", 2); - ff_NameToInteger.put("楷体", 3); - ff_NameToInteger.put("ST Kaiti", 3); - ff_NameToInteger.put("仿宋", 4); - ff_NameToInteger.put("ST FangSong", 4); - ff_NameToInteger.put("新宋体", 5); - ff_NameToInteger.put("ST Song", 5); - ff_NameToInteger.put("华文新魏", 6); - ff_NameToInteger.put("华文行楷", 7); - ff_NameToInteger.put("华文隶书", 8); - ff_NameToInteger.put("Arial", 9); - ff_NameToInteger.put("Times New Roman", 10); - ff_NameToInteger.put("Tahoma", 11); - ff_NameToInteger.put("Verdana", 12); - } + number_format = new String[] { "General", "0", "0.00", "#,##0", "#,##0.00", "$#,##0;($#,##0)", + "$#,##0;[Red]($#,##0)", "$#,##0.00;($#,##0.00)", "$#,##0.00;[Red]($#,##0.00)", "0%", "0.00%", + "0.00E+00", "# ?/?", "# ??/??", "m/d/yyyy", "d-mmm-yy", "d-mmm", "mmm-yy", "h:mm AM/PM", + "h:mm:ss AM/PM", "h:mm", "h:mm:ss", "m/d/yyyy h:mm", "", "", "", "", "", "", "", "", "", "", "", "", "", + "", "#,##0;(#,##0)", "#,##0;[Red](#,##0)", "#,##0.00;(#,##0.00)", "#,##0.00;[Red](#,##0.00)", + "_ * #,##0_ ;_ * (#,##0)_ ;_ * \"-\"_ ;_ @_", "_ $* #,##0_ ;_ $* (#,##0)_ ;_ $* \"-\"_ ;_ @_", + "_ * #,##0.00_ ;_ * (#,##0.00)_ ;_ * \"-\"??_ ;_ @_", + "_ $* #,##0.00_ ;_ $* (#,##0.00)_ ;_ $* \"-\"??_ ;_ @_", "mm:ss", "[h]:mm:ss", "mm:ss.0", "##0.0E+00", + "@" }; + for (int x = 0; x < number_format.length; x++) { + if (number_format[x].length() > 0) { + number_format_map.put(number_format[x].toLowerCase(), x); + } + } + } + private static void ff() { + // 0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST + // Song)、 + // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana + ff_IntegerToName.put(0, "微软雅黑"); + ff_IntegerToName.put(1, "宋体"); + ff_IntegerToName.put(2, "黑体"); + ff_IntegerToName.put(3, "楷体"); + ff_IntegerToName.put(4, "仿宋"); + ff_IntegerToName.put(5, "新宋体"); + ff_IntegerToName.put(6, "华文新魏"); + ff_IntegerToName.put(7, "华文行楷"); + ff_IntegerToName.put(8, "华文隶书"); + ff_IntegerToName.put(9, "Arial"); + ff_IntegerToName.put(10, "Times New Roman"); + ff_IntegerToName.put(11, "Tahoma"); + ff_IntegerToName.put(12, "Verdana"); - /** - * 按自定义格式 - * - * @param fa - * @return - */ - public static Integer getNumberFormatMap(String fa) { - if (number_format_map.containsKey(fa.toLowerCase())) { - return number_format_map.get(fa.toLowerCase()); - } - return -1; - } + // 0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST + // Song)、 + // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana + ff_NameToInteger.put("微软雅黑", 0); + ff_NameToInteger.put("宋体", 1); + ff_NameToInteger.put("Song", 1); + ff_NameToInteger.put("黑体", 2); + ff_NameToInteger.put("ST Heiti", 2); + ff_NameToInteger.put("楷体", 3); + ff_NameToInteger.put("ST Kaiti", 3); + ff_NameToInteger.put("仿宋", 4); + ff_NameToInteger.put("ST FangSong", 4); + ff_NameToInteger.put("新宋体", 5); + ff_NameToInteger.put("ST Song", 5); + ff_NameToInteger.put("华文新魏", 6); + ff_NameToInteger.put("华文行楷", 7); + ff_NameToInteger.put("华文隶书", 8); + ff_NameToInteger.put("Arial", 9); + ff_NameToInteger.put("Times New Roman", 10); + ff_NameToInteger.put("Tahoma", 11); + ff_NameToInteger.put("Verdana", 12); + } - /** - * 获取poi表格垂直对齐 0 中间、1 上、2下 - * - * @param i - * @return - */ - public static VerticalAlignment getVerticalType(int i) { - if (0 == i) { - return VerticalAlignment.CENTER; - } else if (1 == i) { - return VerticalAlignment.TOP; - } else if (2 == i) { - return VerticalAlignment.BOTTOM; - } - //默认居中 - return VerticalAlignment.CENTER; - } + private static void borderType() { + // "border-left" | "border-right" | "border-top" | "border-bottom" | "border-all" + // | "border-outside" | "border-inside" | "border-horizontal" | "border-vertical" + // | "border-none" + ff_IntegerToName.put(0, "微软雅黑"); + ff_IntegerToName.put(1, "宋体"); + ff_IntegerToName.put(2, "黑体"); + ff_IntegerToName.put(3, "楷体"); + ff_IntegerToName.put(4, "仿宋"); + ff_IntegerToName.put(5, "新宋体"); + ff_IntegerToName.put(6, "华文新魏"); + ff_IntegerToName.put(7, "华文行楷"); + ff_IntegerToName.put(8, "华文隶书"); + ff_IntegerToName.put(9, "Arial"); + ff_IntegerToName.put(10, "Times New Roman"); + ff_IntegerToName.put(11, "Tahoma"); + ff_IntegerToName.put(12, "Verdana"); - /** - * 获取poi表格水平对齐 0 居中、1 左、2右 - * - * @param i - * @return - */ - public static HorizontalAlignment getHorizontaltype(int i) { - if (2 == i) { - return HorizontalAlignment.RIGHT; - } else if (1 == i) { - return HorizontalAlignment.LEFT; - } else if (0 == i) { - return HorizontalAlignment.CENTER; - } - //默认右 - return HorizontalAlignment.RIGHT; - } + // 0 微软雅黑、1 宋体(Song)、2 黑体(ST Heiti)、3 楷体(ST Kaiti)、 4仿宋(ST FangSong)、 5 新宋体(ST + // Song)、 + // 6 华文新魏、 7华文行楷、 8 华文隶书、 9 Arial、 10 Times New Roman 、11 Tahoma 、12 Verdana + ff_NameToInteger.put("微软雅黑", 0); + ff_NameToInteger.put("宋体", 1); + ff_NameToInteger.put("Song", 1); + ff_NameToInteger.put("黑体", 2); + ff_NameToInteger.put("ST Heiti", 2); + ff_NameToInteger.put("楷体", 3); + ff_NameToInteger.put("ST Kaiti", 3); + ff_NameToInteger.put("仿宋", 4); + ff_NameToInteger.put("ST FangSong", 4); + ff_NameToInteger.put("新宋体", 5); + ff_NameToInteger.put("ST Song", 5); + ff_NameToInteger.put("华文新魏", 6); + ff_NameToInteger.put("华文行楷", 7); + ff_NameToInteger.put("华文隶书", 8); + ff_NameToInteger.put("Arial", 9); + ff_NameToInteger.put("Times New Roman", 10); + ff_NameToInteger.put("Tahoma", 11); + ff_NameToInteger.put("Verdana", 12); + } - /** - * 文字旋转 - * 文字旋转角度(0=0,1=45,2=-45,3=竖排文字,4=90,5=-90) - * - * @param i - * @return - */ - public static short getRotation(int i) { - short t = 0; - switch (i) { - case 1: - t = 45; - break; - case 2: - t = -45; - break; - case 3: - t = 255; - break; - case 4: - t = 90; - break; - case 5: - t = -90; - break; + /** + * 按自定义格式 + * @param fa + * @return + */ + public static Integer getNumberFormatMap(String fa) { + if (number_format_map.containsKey(fa.toLowerCase())) { + return number_format_map.get(fa.toLowerCase()); + } + return -1; + } - default: - t = 0; - } - return t; - } + /** + * 获取poi表格垂直对齐 0 中间、1 上、2下 + * @param i + * @return + */ + public static VerticalAlignment getVerticalType(int i) { + if (0 == i) { + return VerticalAlignment.CENTER; + } + else if (1 == i) { + return VerticalAlignment.TOP; + } + else if (2 == i) { + return VerticalAlignment.BOTTOM; + } + // 默认居中 + return VerticalAlignment.CENTER; + } + /** + * 获取poi表格水平对齐 0 居中、1 左、2右 + * @param i + * @return + */ + public static HorizontalAlignment getHorizontaltype(int i) { + if (2 == i) { + return HorizontalAlignment.RIGHT; + } + else if (1 == i) { + return HorizontalAlignment.LEFT; + } + else if (0 == i) { + return HorizontalAlignment.CENTER; + } + // 默认右 + return HorizontalAlignment.RIGHT; + } - private static SimpleDateFormat df_DateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); + /** + * 文字旋转 文字旋转角度(0=0,1=45,2=-45,3=竖排文字,4=90,5=-90) + * @param i + * @return + */ + public static short getRotation(int i) { + short t = 0; + switch (i) { + case 1: + t = 45; + break; + case 2: + t = -45; + break; + case 3: + t = 255; + break; + case 4: + t = 90; + break; + case 5: + t = -90; + break; - public static Date stringToDateTime(String date) { - if (date == null || date.length() == 0) { - return null; - } - try { - return df_DateTime.parse(date); - } catch (ParseException e) { - return null; - } - } + default: + t = 0; + } + return t; + } - private static SimpleDateFormat df_Date = new SimpleDateFormat("yyyy-MM-dd"); + private static SimpleDateFormat df_DateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - public static Date stringToDate(String date) { - if (date == null || date.length() == 0) { - return null; - } - try { - return df_Date.parse(date); - } catch (ParseException e) { - return null; - } - } + public static Date stringToDateTime(String date) { + if (date == null || date.length() == 0) { + return null; + } + try { + return df_DateTime.parse(date); + } + catch (ParseException e) { + return null; + } + } - public static Date toDate(String numberString) { - try { - Double _d = Double.parseDouble(numberString); - String _s = toDate(_d, "yyyy-MM-dd HH:mm:ss"); - if (numberString.indexOf(".") > -1) { - return stringToDate(_s); - } else { - return stringToDateTime(_s); - } + private static SimpleDateFormat df_Date = new SimpleDateFormat("yyyy-MM-dd"); - } catch (Exception ex) { - System.out.println(ex.toString() + " " + numberString); - } - return null; - } + public static Date stringToDate(String date) { + if (date == null || date.length() == 0) { + return null; + } + try { + return df_Date.parse(date); + } + catch (ParseException e) { + return null; + } + } - private static final int SECONDS_PER_MINUTE = 60; - private static final int MINUTES_PER_HOUR = 60; - private static final int HOURS_PER_DAY = 24; - private static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); - /** - * 一天的毫秒数 - **/ - private static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L; + public static Date toDate(String numberString) { + try { + Double _d = Double.parseDouble(numberString); + String _s = toDate(_d, "yyyy-MM-dd HH:mm:ss"); + if (numberString.indexOf(".") > -1) { + return stringToDate(_s); + } + else { + return stringToDateTime(_s); + } - /** - * 转换方法 - * - * @parma numberString 要转换的浮点数 - * @parma format 要获得的格式 例如"hh:mm:ss" - **/ - public static String toDate(double numberString, String format) { - SimpleDateFormat sdFormat = new SimpleDateFormat(format); - int wholeDays = (int) Math.floor(numberString); - int millisecondsInday = (int) ((numberString - wholeDays) * DAY_MILLISECONDS + 0.5); - Calendar calendar = new GregorianCalendar(); - setCalendar(calendar, wholeDays, millisecondsInday, false); - return sdFormat.format(calendar.getTime()); - } + } + catch (Exception ex) { + System.out.println(ex.toString() + " " + numberString); + } + return null; + } + + private static final int SECONDS_PER_MINUTE = 60; + + private static final int MINUTES_PER_HOUR = 60; + + private static final int HOURS_PER_DAY = 24; + + private static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); + + /** + * 一天的毫秒数 + **/ + private static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L; + + /** + * 转换方法 + * + * @parma numberString 要转换的浮点数 + * @parma format 要获得的格式 例如"hh:mm:ss" + **/ + public static String toDate(double numberString, String format) { + SimpleDateFormat sdFormat = new SimpleDateFormat(format); + int wholeDays = (int) Math.floor(numberString); + int millisecondsInday = (int) ((numberString - wholeDays) * DAY_MILLISECONDS + 0.5); + Calendar calendar = new GregorianCalendar(); + setCalendar(calendar, wholeDays, millisecondsInday, false); + return sdFormat.format(calendar.getTime()); + } + + private static void setCalendar(Calendar calendar, int wholeDays, int millisecondsInDay, boolean use1904windowing) { + int startYear = 1900; + int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't + if (use1904windowing) { + startYear = 1904; + dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day + } + else if (wholeDays < 61) { + // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists + // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation + dayAdjust = 0; + } + calendar.set(startYear, 0, wholeDays + dayAdjust, 0, 0, 0); + calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay); + } - private static void setCalendar(Calendar calendar, int wholeDays, - int millisecondsInDay, boolean use1904windowing) { - int startYear = 1900; - int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't - if (use1904windowing) { - startYear = 1904; - dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day - } else if (wholeDays < 61) { - // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists - // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation - dayAdjust = 0; - } - calendar.set(startYear, 0, wholeDays + dayAdjust, 0, 0, 0); - calendar.set(GregorianCalendar.MILLISECOND, millisecondsInDay); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/MSExcelUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/MSExcelUtil.java index 1e1d167e6..0a66679b9 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/MSExcelUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/MSExcelUtil.java @@ -1,28 +1,33 @@ package com.anjiplus.template.gaea.business.modules.reportexcel.util; public class MSExcelUtil { - public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static final short EXCEL_ROW_HEIGHT_FACTOR = 20; - public static final int UNIT_OFFSET_LENGTH = 7; - public static final int[] UNIT_OFFSET_MAP = new int[]{0, 36, 73, 109, 146, 182, 219}; - public static short pixel2WidthUnits(int pxs) { - short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH)); - widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; - return widthUnits; - } + public static final short EXCEL_COLUMN_WIDTH_FACTOR = 256; - public static int widthUnits2Pixel(short widthUnits) { - int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH; - int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; - pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } + public static final short EXCEL_ROW_HEIGHT_FACTOR = 20; + + public static final int UNIT_OFFSET_LENGTH = 7; + + public static final int[] UNIT_OFFSET_MAP = new int[] { 0, 36, 73, 109, 146, 182, 219 }; + + public static short pixel2WidthUnits(int pxs) { + short widthUnits = (short) (EXCEL_COLUMN_WIDTH_FACTOR * (pxs / UNIT_OFFSET_LENGTH)); + widthUnits += UNIT_OFFSET_MAP[(pxs % UNIT_OFFSET_LENGTH)]; + return widthUnits; + } + + public static int widthUnits2Pixel(short widthUnits) { + int pixels = (widthUnits / EXCEL_COLUMN_WIDTH_FACTOR) * UNIT_OFFSET_LENGTH; + int offsetWidthUnits = widthUnits % EXCEL_COLUMN_WIDTH_FACTOR; + pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_COLUMN_WIDTH_FACTOR / UNIT_OFFSET_LENGTH)); + return pixels; + } + + public static int heightUnits2Pixel(short heightUnits) { + int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR); + int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR; + pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH)); + return pixels; + } - public static int heightUnits2Pixel(short heightUnits) { - int pixels = (heightUnits / EXCEL_ROW_HEIGHT_FACTOR); - int offsetWidthUnits = heightUnits % EXCEL_ROW_HEIGHT_FACTOR; - pixels += Math.floor((float) offsetWidthUnits / ((float) EXCEL_ROW_HEIGHT_FACTOR / UNIT_OFFSET_LENGTH)); - return pixels; - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsSheetUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsSheetUtil.java index a436002aa..fbcfd0f38 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsSheetUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsSheetUtil.java @@ -9,852 +9,853 @@ import org.apache.poi.ss.util.CellRangeAddress; import java.util.*; /** - * 来自:https://github.com/mengshukeji/LuckysheetServer - * sheet操作 + * 来自:https://github.com/mengshukeji/LuckysheetServer sheet操作 * * @author Administrator */ @Slf4j public class XlsSheetUtil { - /** - * 导出sheet - * - * @param wb - * @param sheetNum - * @param dbObject - */ - public static void exportSheet(Workbook wb, int sheetNum, JSONObject dbObject) { - Sheet sheet = wb.createSheet(); - - //设置sheet位置,名称 - if (dbObject.containsKey("name") && dbObject.get("name") != null) { - wb.setSheetName(sheetNum, dbObject.get("name").toString()); - } else { - wb.setSheetName(sheetNum, "sheet" + sheetNum); - } - //是否隐藏 - if (dbObject.containsKey("hide") && dbObject.get("hide").toString().equals("1")) { - wb.setSheetHidden(sheetNum, true); - } - //是否当前选中页 - if (dbObject.containsKey("status") && dbObject.get("status").toString().equals("1")) { - sheet.setSelected(true); - } - - - //循环数据 - if (dbObject.containsKey("celldata") && dbObject.get("celldata") != null) { - //取到所有单元格集合 - List cells_json = (List) dbObject.get("celldata"); - Map> cellMap = cellGroup(cells_json); - //循环每一行 - for (Integer r : cellMap.keySet()) { - Row row = sheet.createRow(r); - //循环每一列 - for (JSONObject col : cellMap.get(r)) { - createCell(wb, sheet, row, col); - } - } - } - - if (dbObject.containsKey("config") && dbObject.getJSONObject("config").containsKey("borderInfo")) { - JSONArray borderInfo = dbObject.getJSONObject("config").getJSONArray("borderInfo"); - setCellBoard(wb, borderInfo, sheet); - } - - - setColumAndRow(dbObject, sheet); - - } - - /** - * 每一个单元格 - * - * @param row - * @param dbObject - */ - private static void createCell(Workbook wb, Sheet sheet, Row row, JSONObject dbObject) { - if (dbObject.containsKey("c")) { - Integer c = getStrToInt(dbObject.get("c")); - if (c != null) { - Cell cell = row.createCell(c); - //取单元格中的v_json - if (dbObject.containsKey("v")) { - //获取v对象 - Object obj = dbObject.get("v"); - if (obj == null) { - //没有内容 - return; - } - //如果v对象直接是字符串 - if (obj instanceof String) { - if (((String) obj).length() > 0) { - cell.setCellValue(obj.toString()); - } - return; - } - - //转换v为对象(v是一个对象) - JSONObject v_json = (JSONObject) obj; - //样式 - CellStyle style = wb.createCellStyle(); - cell.setCellStyle(style); - - - //合并单元格 - //参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列 - //CellRangeAddress region1 = new CellRangeAddress(rowNumber, rowNumber, (short) 0, (short) 11); - - //mc 合并单元格 - if (v_json.containsKey("mc")) { - //是合并的单元格 - JSONObject mc = v_json.getJSONObject("mc"); - if (mc.containsKey("rs") && mc.containsKey("cs")) { - //合并的第一个单元格 - if (mc.containsKey("r") && mc.containsKey("c")) { - Integer _rs = getIntByDBObject(mc, "rs") - 1; - Integer _cs = getIntByDBObject(mc, "cs") - 1; - Integer _r = getIntByDBObject(mc, "r"); - Integer _c = getIntByDBObject(mc, "c"); - - CellRangeAddress region = new CellRangeAddress(_r.shortValue(), (_r.shortValue() + _rs.shortValue()), _c.shortValue(), (_c.shortValue() + _cs.shortValue())); - sheet.addMergedRegion(region); - } - } else { - //不是合并的第一个单元格 - return; - } - } - - - //取v值 (在数据类型中处理) - //ct 单元格值格式 (fa,t) - setFormatByCt(wb, cell, style, v_json); - - //font设置 - setCellStyleFont(wb, style, v_json); - - //bg 背景颜色 - if (v_json.containsKey("bg")) { - String _v = getByDBObject(v_json, "bg"); - Short _color = ColorUtil.getColorByStr(_v); - if (_color != null) { - style.setFillForegroundColor(_color); - style.setFillPattern(FillPatternType.SOLID_FOREGROUND); - } - } - - //vt 垂直对齐 垂直对齐方式(0=居中,1=上,2=下) - if (v_json.containsKey("vt")) { - Integer _v = getIntByDBObject(v_json, "vt"); - if (_v != null && _v >= 0 && _v <= 2) { - style.setVerticalAlignment(ConstantUtil.getVerticalType(_v)); - } - } else { - //默认设置居中 - style.setVerticalAlignment(ConstantUtil.getVerticalType(0)); - } - - //ht 水平对齐 水平对齐方式(0=居中,1=左对齐,2=右对齐) - if (v_json.containsKey("ht")) { - Integer _v = getIntByDBObject(v_json, "ht"); - if (_v != null && _v >= 0 && _v <= 2) { - style.setAlignment(ConstantUtil.getHorizontaltype(_v)); - } - } else { - //默认设置左对齐 - style.setAlignment(ConstantUtil.getHorizontaltype(1)); - } - - //tr 文字旋转 文字旋转角度(0=0,1=45,2=-45,3=竖排文字,4=90,5=-90) - if (v_json.containsKey("tr")) { - Integer _v = getIntByDBObject(v_json, "tr"); - if (_v != null) { - style.setRotation(ConstantUtil.getRotation(_v)); - } - } - - //tb 文本换行 0 截断、1溢出、2 自动换行 - // 2:setTextWrapped 0和1:IsTextWrapped = true - if (v_json.containsKey("tb")) { - Integer _v = getIntByDBObject(v_json, "tb"); - if (_v != null) { - if (_v >= 0 && _v <= 1) { - style.setWrapText(false); - } else { - style.setWrapText(true); - } - } - } - - //f 公式 - if (v_json.containsKey("f")) { - String _v = getByDBObject(v_json, "f"); - if (_v.length() > 0) { - try { - if (_v.startsWith("=")) { - cell.setCellFormula(_v.substring(1)); - } else { - cell.setCellFormula(_v); - } - } catch (Exception ex) { - log.error("公式 {};Error:{}", _v, ex.toString()); - } - } - } - - - } - - } - } - } - - /** - * 设置边框 - * - * @param borderInfo - * @param sheet - */ - private static void setCellBoard(Workbook wb, JSONArray borderInfo, Sheet sheet) { - - - //一定要通过 cell.getCellStyle() 不然的话之前设置的样式会丢失 - //设置边框 - for (int i = 0; i < borderInfo.size(); i++) { - JSONObject borderInfoObject = (JSONObject) borderInfo.get(i); - if (borderInfoObject.get("rangeType").equals("cell")) {//单个单元格 - JSONObject borderValueObject = borderInfoObject.getJSONObject("value"); - - JSONObject l = borderValueObject.getJSONObject("l"); - JSONObject r = borderValueObject.getJSONObject("r"); - JSONObject t = borderValueObject.getJSONObject("t"); - JSONObject b = borderValueObject.getJSONObject("b"); - - - int row_ = borderValueObject.getInteger("row_index"); - int col_ = borderValueObject.getInteger("col_index"); - - Row row = sheet.getRow(row_); - if (null == row) { - row = sheet.createRow(row_); - } - Cell cell = row.getCell(col_); - CellStyle style; - if (null == cell) { - style = wb.createCellStyle(); - cell = row.createCell(col_); - cell.setCellStyle(style); - } else { - style = cell.getCellStyle(); - } - - - if (l != null) { - style.setBorderLeft(BorderStyle.valueOf(l.getShort("style"))); //左边框 - Short color = ColorUtil.getColorByStr(l.getString("color")); - if (null != color) { - style.setLeftBorderColor(color);//左边框颜色 - } - - } - if (r != null) { - style.setBorderRight(BorderStyle.valueOf(r.getShort("style"))); //右边框 - Short color = ColorUtil.getColorByStr(r.getString("color")); - if (null != color) { - style.setRightBorderColor(color);//右边框颜色 - } - - } - if (t != null) { - style.setBorderTop(BorderStyle.valueOf(t.getShort("style"))); //顶部边框 - Short _vcolor = ColorUtil.getColorByStr(t.getString("color")); - if (null != _vcolor) { - style.setTopBorderColor(_vcolor);//顶部边框颜色 - } - - } - if (b != null) { - style.setBorderBottom(BorderStyle.valueOf(b.getShort("style"))); //底部边框 - Short _vcolor = ColorUtil.getColorByStr(b.getString("color")); - if (_vcolor != null) { - //底部边框颜色 - style.setBottomBorderColor(_vcolor); - } - } - - } else if (borderInfoObject.get("rangeType").equals("range")) { - //选区 - Short style_ = borderInfoObject.getShort("style"); - String borderType = borderInfoObject.getString("borderType"); - Short color = ColorUtil.getColorByStr(borderInfoObject.getString("color")); - JSONObject rangObject = (JSONObject) ((JSONArray) (borderInfoObject.get("range"))).get(0); - - JSONArray rowList = rangObject.getJSONArray("row"); - JSONArray columnList = rangObject.getJSONArray("column"); - - - for (int row_ = rowList.getInteger(0); row_ < rowList.getInteger(rowList.size() - 1) + 1; row_++) { - for (int col_ = columnList.getInteger(0); col_ < columnList.getInteger(columnList.size() - 1) + 1; col_++) { - Row row = sheet.getRow(row_); - if (null == row) { - row = sheet.createRow(row_); - } - Cell cell = row.getCell(col_); - CellStyle style; - if (null == cell) { - style = wb.createCellStyle(); - cell = row.createCell(col_); - cell.setCellStyle(style); - } else { - style = cell.getCellStyle(); - } - - //"border-left" | "border-right" | "border-top" | "border-bottom" | "border-all" | "border-horizontal" | "border-vertical" - // "border-outside" | "border-inside" | | "border-none" - if ("border-left".equals(borderType) || "border-all".equals(borderType)) { - style.setBorderLeft(BorderStyle.valueOf(style_)); //左边框 - style.setLeftBorderColor(color);//左边框颜色 - } - if ("border-right".equals(borderType) || "border-all".equals(borderType)) { - style.setBorderRight(BorderStyle.valueOf(style_)); //右边框 - style.setRightBorderColor(color);//右边框颜色 - } - - if ("border-top".equals(borderType) || "border-all".equals(borderType)) { - style.setBorderTop(BorderStyle.valueOf(style_)); //顶部边框 - style.setTopBorderColor(color);//顶部边框颜色 - } - - if ("border-bottom".equals(borderType) || "border-all".equals(borderType)) { - style.setBorderBottom(BorderStyle.valueOf(style_)); //底部边框 - style.setBottomBorderColor(color);//底部边框颜色 } - } - - if ("border-outside".equals(borderType)) { - //外圈边框 - if (row_ == rowList.getInteger(0)) { - style.setBorderTop(BorderStyle.valueOf(style_)); //顶部边框 - style.setTopBorderColor(color);//顶部边框颜色 - } - if (col_ == columnList.getInteger(0)) { - style.setBorderLeft(BorderStyle.valueOf(style_)); //左边框 - style.setLeftBorderColor(color);//左边框颜色 - } - if (row_ == rowList.getInteger(rowList.size() - 1)) { - style.setBorderBottom(BorderStyle.valueOf(style_)); //底部边框 - style.setBottomBorderColor(color);//底部边框颜色 } - } - if (col_ == columnList.getInteger(columnList.size() - 1)) { - style.setBorderRight(BorderStyle.valueOf(style_)); //右边框 - style.setRightBorderColor(color);//右边框颜色 - } - - } - - if ("border-horizontal".equals(borderType) || "border-inside".equals(borderType)) { - //内部横线 - if (row_ >= rowList.getInteger(0) - && row_ < rowList.getInteger(rowList.size() - 1) - && col_ >= columnList.getInteger(0) - && col_ <= columnList.getInteger(columnList.size() - 1)) { - style.setBorderBottom(BorderStyle.valueOf(style_)); //底部边框 - style.setBottomBorderColor(color);//底部边框颜色 } - } - } - - if ("border-vertical".equals(borderType) || "border-inside".equals(borderType)) { - //内部竖线 - if (row_ >= rowList.getInteger(0) - && row_ <= rowList.getInteger(rowList.size() - 1) - && col_ >= columnList.getInteger(0) - && col_ < columnList.getInteger(columnList.size() - 1)) { - style.setBorderRight(BorderStyle.valueOf(style_)); //右边框 - style.setRightBorderColor(color);//右边框颜色 - } - } - - if ("border-none".equals(borderType)) { - style.setBorderLeft(BorderStyle.NONE); //左边框 - style.setBorderRight(BorderStyle.NONE); //左边框 - style.setBorderTop(BorderStyle.NONE); //左边框 - style.setBorderBottom(BorderStyle.NONE); //左边框 - } - - } - } - - - } - } - - } - - - /** - * 设置单元格,宽、高 - * - * @param dbObject - * @param sheet - */ - private static void setColumAndRow(JSONObject dbObject, Sheet sheet) { - if (dbObject.containsKey("config")) { - JSONObject config = dbObject.getJSONObject("config"); - - if (config.containsKey("columnlen")) { - JSONObject columnlen = config.getJSONObject("columnlen"); - if (columnlen != null) { - for (String k : columnlen.keySet()) { - Integer _i = getStrToInt(k); - Integer _v = getStrToInt(columnlen.get(k).toString()); - if (_i != null && _v != null) { -// sheet.setColumnWidth(_i, MSExcelUtil.heightUnits2Pixel(_v.shortValue())); - // TODO 乘以32,有待商榷 - sheet.setColumnWidth(_i, _v * 32); - } - } - } - } - if (config.containsKey("rowlen")) { - JSONObject rowlen = config.getJSONObject("rowlen"); - if (rowlen != null) { - for (String k : rowlen.keySet()) { - Integer _i = getStrToInt(k); - Integer _v = getStrToInt(rowlen.get(k).toString()); - if (_i != null && _v != null) { - Row row = sheet.getRow(_i); - if (row != null) { -// row.setHeightInPoints(MSExcelUtil.pixel2WidthUnits(_v.shortValue())); - row.setHeightInPoints(_v.shortValue()); - } - } - } - } - } - } - } - - /** - * 单元格字体相关样式 - * - * @param wb - * @param style - * @param dbObject - */ - private static void setCellStyleFont(Workbook wb, CellStyle style, JSONObject dbObject) { - Font font = wb.createFont(); - style.setFont(font); - - //ff 字体 - if (dbObject.containsKey("ff")) { - if (dbObject.get("ff") instanceof Integer) { - Integer _v = getIntByDBObject(dbObject, "ff"); - if (_v != null && ConstantUtil.ff_IntegerToName.containsKey(_v)) { - font.setFontName(ConstantUtil.ff_IntegerToName.get(_v)); - } - } else if (dbObject.get("ff") instanceof String) { - font.setFontName(getByDBObject(dbObject, "ff")); - } - } - //fc 字体颜色 - if (dbObject.containsKey("fc")) { - String _v = getByDBObject(dbObject, "fc"); - Short _color = ColorUtil.getColorByStr(_v); - if (_color != null) { - font.setColor(_color); - } - } - //bl 粗体 - if (dbObject.containsKey("bl")) { - Integer _v = getIntByDBObject(dbObject, "bl"); - if (_v != null) { - if (_v.equals(1)) { - //是否粗体显示 - font.setBold(true); - } else { - font.setBold(false); - } - } - } - //it 斜体 - if (dbObject.containsKey("it")) { - Integer _v = getIntByDBObject(dbObject, "it"); - if (_v != null) { - if (_v.equals(1)) { - font.setItalic(true); - } else { - font.setItalic(false); - } - } - } - //fs 字体大小 - if (dbObject.containsKey("fs")) { - Integer _v = getStrToInt(getObjectByDBObject(dbObject, "fs")); - if (_v != null) { - font.setFontHeightInPoints(_v.shortValue()); - } - } - //cl 删除线 (导入没有) 0 常规 、 1 删除线 - if (dbObject.containsKey("cl")) { - Integer _v = getIntByDBObject(dbObject, "cl"); - if (_v != null) { - if (_v.equals(1)) { - font.setStrikeout(true); - } - } - } - //ul 下划线 - if (dbObject.containsKey("ul")) { - Integer _v = getIntByDBObject(dbObject, "ul"); - if (_v != null) { - if (_v.equals(1)) { - font.setUnderline(Font.U_SINGLE); - } else { - font.setUnderline(Font.U_NONE); - } - } - } - - } - - /** - * 设置cell边框颜色样式 - * - * @param style 样式 - * @param dbObject json对象 - * @param bs 样式 - * @param bc 样式 - */ - private static void setBorderStyle(CellStyle style, JSONObject dbObject, String bs, String bc) { - //bs 边框样式 - if (dbObject.containsKey(bs)) { - Integer _v = getStrToInt(getByDBObject(dbObject, bs)); - if (_v != null) { - //边框没有,不作改变 - if (bs.equals("bs") || bs.equals("bs_t")) { - style.setBorderTop(BorderStyle.valueOf(_v.shortValue())); - } - if (bs.equals("bs") || bs.equals("bs_b")) { - style.setBorderBottom(BorderStyle.valueOf(_v.shortValue())); - } - if (bs.equals("bs") || bs.equals("bs_l")) { - style.setBorderLeft(BorderStyle.valueOf(_v.shortValue())); - } - if (bs.equals("bs") || bs.equals("bs_r")) { - style.setBorderRight(BorderStyle.valueOf(_v.shortValue())); - } - - //bc 边框颜色 - String _vcolor = getByDBObject(dbObject, bc); - if (_vcolor != null) { - Short _color = ColorUtil.getColorByStr(_vcolor); - if (_color != null) { - if (bc.equals("bc") || bc.equals("bc_t")) { - style.setTopBorderColor(_color); - } - if (bc.equals("bc") || bc.equals("bc_b")) { - style.setBottomBorderColor(_color); - } - if (bc.equals("bc") || bc.equals("bc_l")) { - style.setLeftBorderColor(_color); - } - if (bc.equals("bc") || bc.equals("bc_r")) { - style.setRightBorderColor(_color); - } - } - } - } - } - } - - - /** - * 设置单元格格式 ct 单元格值格式 (fa,t) - * - * @param cell - * @param style - * @param dbObject - */ - private static void setFormatByCt(Workbook wb, Cell cell, CellStyle style, JSONObject dbObject) { - - if (!dbObject.containsKey("v") && dbObject.containsKey("ct")) { - /* 处理以下数据结构 - { - "celldata": [{ - "c": 0, - "r": 8, - "v": { - "ct": { - "s": [{ - "v": "sdsdgdf\r\ndfgdfg\r\ndsfgdfgdf\r\ndsfgdfg" - }], - "t": "inlineStr", - "fa": "General" - } - } - }] - } - */ - JSONObject ct = dbObject.getJSONObject("ct"); - if (ct.containsKey("s")) { - Object s = ct.get("s"); - if (s instanceof List && ((List) s).size() > 0) { - JSONObject _s1 = (JSONObject) ((List) s).get(0); - if (_s1.containsKey("v") && _s1.get("v") instanceof String) { - dbObject.put("v", _s1.get("v")); - style.setWrapText(true); - } - } - - } - } - - //String v = ""; //初始化 - if (dbObject.containsKey("v")) { - //v = v_json.get("v").toString(); - //取到v后,存到poi单元格对象 - //设置该单元格值 - //cell.setValue(v); - - //String v=getByDBObject(v_json,"v"); - //cell.setValue(v); - Object obj = getObjectByDBObject(dbObject, "v"); - if (obj instanceof Number) { - cell.setCellValue(Double.valueOf(obj.toString())); - } else if (obj instanceof Double) { - cell.setCellValue((Double) obj); - } else if (obj instanceof Date) { - cell.setCellValue((Date) obj); - } else if (obj instanceof Calendar) { - cell.setCellValue((Calendar) obj); - } else if (obj instanceof RichTextString) { - cell.setCellValue((RichTextString) obj); - } else if (obj instanceof String) { - cell.setCellValue((String) obj); - } else { - cell.setCellValue(obj.toString()); - } - - } - - if (dbObject.containsKey("ct")) { - JSONObject ct = dbObject.getJSONObject("ct"); - if (ct.containsKey("fa") && ct.containsKey("t")) { - //t 0=bool,1=datetime,2=error,3=null,4=numeric,5=string,6=unknown - String fa = getByDBObject(ct, "fa"); //单元格格式format定义串 - String t = getByDBObject(ct, "t"); //单元格格式type类型 - - Integer _i = ConstantUtil.getNumberFormatMap(fa); - switch (t) { - case "s": { - //字符串 - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - style.setDataFormat((short) 0); - } - cell.setCellType(org.apache.poi.ss.usermodel.CellType.STRING); - break; - } - case "d": { - //日期 - Date _d = null; - String v = getByDBObject(dbObject, "m"); - if (v.length() == 0) { - v = getByDBObject(dbObject, "v"); - } - if (v.length() > 0) { - if (v.indexOf("-") > -1) { - if (v.indexOf(":") > -1) { - _d = ConstantUtil.stringToDateTime(v); - } else { - _d = ConstantUtil.stringToDate(v); - } - } else { - _d = ConstantUtil.toDate(v); - } - } - if (_d != null) { - //能转换为日期 - cell.setCellValue(_d); - DataFormat format = wb.createDataFormat(); - style.setDataFormat(format.getFormat(fa)); - - } else { - //不能转换为日期 - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - style.setDataFormat((short) 0); - } - } - break; - } - case "b": { - //逻辑 - cell.setCellType(org.apache.poi.ss.usermodel.CellType.BOOLEAN); - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - DataFormat format = wb.createDataFormat(); - style.setDataFormat(format.getFormat(fa)); - } - break; - } - case "n": { - //数值 -// cell.setCellType(CellType.NUMERIC); - //数字转字符串 - cell.setCellType(org.apache.poi.ss.usermodel.CellType.STRING); - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - DataFormat format = wb.createDataFormat(); - style.setDataFormat(format.getFormat(fa)); - } - break; - } - case "u": - case "g": { - //general 自动类型 - //cell.setCellType(CellType._NONE); - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - DataFormat format = wb.createDataFormat(); - style.setDataFormat(format.getFormat(fa)); - } - break; - } - case "e": { - //错误 - cell.setCellType(org.apache.poi.ss.usermodel.CellType.ERROR); - if (_i >= 0) { - style.setDataFormat(_i.shortValue()); - } else { - DataFormat format = wb.createDataFormat(); - style.setDataFormat(format.getFormat(fa)); - } - break; - } - - } - - } - - } - } - - /** - * 内容按行分组 - * - * @param cells - * @return - */ - private static Map> cellGroup(List cells) { - Map> cellMap = new HashMap<>(100); - for (JSONObject dbObject : cells) { - //行号 - if (dbObject.containsKey("r")) { - Integer r = getStrToInt(dbObject.get("r")); - if (r != null) { - if (cellMap.containsKey(r)) { - cellMap.get(r).add(dbObject); - } else { - List list = new ArrayList<>(10); - list.add(dbObject); - cellMap.put(r, list); - } - } - } - - } - return cellMap; - } - - - /** - * 获取一个k的值 - * - * @param b - * @param k - * @return - */ - public static String getByDBObject(JSONObject b, String k) { - if (b.containsKey(k)) { - if (b.get(k) != null && b.get(k) instanceof String) { - return b.getString(k); - } - } - return null; - } - - /** - * 获取一个k的值 - * - * @param b - * @param k - * @return - */ - public static Object getObjectByDBObject(JSONObject b, String k) { - if (b.containsKey(k)) { - if (b.get(k) != null) { - return b.get(k); - } - } - return ""; - } - - /** - * 没有/无法转换 返回null - * - * @param b - * @param k - * @return - */ - public static Integer getIntByDBObject(JSONObject b, String k) { - if (b.containsKey(k)) { - if (b.get(k) != null) { - try { - String _s = b.getString(k).replace("px", ""); - Double _d = Double.parseDouble(_s); - return _d.intValue(); - } catch (Exception ex) { - log.error(ex.getMessage()); - return null; - } - } - } - return null; - } - - /** - * 转int - * - * @param str - * @return - */ - private static Integer getStrToInt(Object str) { - try { - if (str != null) { - return Integer.parseInt(str.toString()); - } - return null; - } catch (Exception ex) { - log.error("String:{};Error:{}", str, ex.getMessage()); - return null; - } - } - - private static Short getStrToShort(Object str) { - try { - if (str != null) { - return Short.parseShort(str.toString()); - } - return null; - } catch (Exception ex) { - log.error("String:{};Error:{}", str, ex.getMessage()); - return null; - } - } + + /** + * 导出sheet + * @param wb + * @param sheetNum + * @param dbObject + */ + public static void exportSheet(Workbook wb, int sheetNum, JSONObject dbObject) { + Sheet sheet = wb.createSheet(); + + // 设置sheet位置,名称 + if (dbObject.containsKey("name") && dbObject.get("name") != null) { + wb.setSheetName(sheetNum, dbObject.get("name").toString()); + } + else { + wb.setSheetName(sheetNum, "sheet" + sheetNum); + } + // 是否隐藏 + if (dbObject.containsKey("hide") && dbObject.get("hide").toString().equals("1")) { + wb.setSheetHidden(sheetNum, true); + } + // 是否当前选中页 + if (dbObject.containsKey("status") && dbObject.get("status").toString().equals("1")) { + sheet.setSelected(true); + } + + // 循环数据 + if (dbObject.containsKey("celldata") && dbObject.get("celldata") != null) { + // 取到所有单元格集合 + List cells_json = (List) dbObject.get("celldata"); + Map> cellMap = cellGroup(cells_json); + // 循环每一行 + for (Integer r : cellMap.keySet()) { + Row row = sheet.createRow(r); + // 循环每一列 + for (JSONObject col : cellMap.get(r)) { + createCell(wb, sheet, row, col); + } + } + } + + if (dbObject.containsKey("config") && dbObject.getJSONObject("config").containsKey("borderInfo")) { + JSONArray borderInfo = dbObject.getJSONObject("config").getJSONArray("borderInfo"); + setCellBoard(wb, borderInfo, sheet); + } + + setColumAndRow(dbObject, sheet); + + } + + /** + * 每一个单元格 + * @param row + * @param dbObject + */ + private static void createCell(Workbook wb, Sheet sheet, Row row, JSONObject dbObject) { + if (dbObject.containsKey("c")) { + Integer c = getStrToInt(dbObject.get("c")); + if (c != null) { + Cell cell = row.createCell(c); + // 取单元格中的v_json + if (dbObject.containsKey("v")) { + // 获取v对象 + Object obj = dbObject.get("v"); + if (obj == null) { + // 没有内容 + return; + } + // 如果v对象直接是字符串 + if (obj instanceof String) { + if (((String) obj).length() > 0) { + cell.setCellValue(obj.toString()); + } + return; + } + + // 转换v为对象(v是一个对象) + JSONObject v_json = (JSONObject) obj; + // 样式 + CellStyle style = wb.createCellStyle(); + cell.setCellStyle(style); + + // 合并单元格 + // 参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列 + // CellRangeAddress region1 = new CellRangeAddress(rowNumber, + // rowNumber, (short) 0, (short) 11); + + // mc 合并单元格 + if (v_json.containsKey("mc")) { + // 是合并的单元格 + JSONObject mc = v_json.getJSONObject("mc"); + if (mc.containsKey("rs") && mc.containsKey("cs")) { + // 合并的第一个单元格 + if (mc.containsKey("r") && mc.containsKey("c")) { + Integer _rs = getIntByDBObject(mc, "rs") - 1; + Integer _cs = getIntByDBObject(mc, "cs") - 1; + Integer _r = getIntByDBObject(mc, "r"); + Integer _c = getIntByDBObject(mc, "c"); + + CellRangeAddress region = new CellRangeAddress(_r.shortValue(), + (_r.shortValue() + _rs.shortValue()), _c.shortValue(), + (_c.shortValue() + _cs.shortValue())); + sheet.addMergedRegion(region); + } + } + else { + // 不是合并的第一个单元格 + return; + } + } + + // 取v值 (在数据类型中处理) + // ct 单元格值格式 (fa,t) + setFormatByCt(wb, cell, style, v_json); + + // font设置 + setCellStyleFont(wb, style, v_json); + + // bg 背景颜色 + if (v_json.containsKey("bg")) { + String _v = getByDBObject(v_json, "bg"); + Short _color = ColorUtil.getColorByStr(_v); + if (_color != null) { + style.setFillForegroundColor(_color); + style.setFillPattern(FillPatternType.SOLID_FOREGROUND); + } + } + + // vt 垂直对齐 垂直对齐方式(0=居中,1=上,2=下) + if (v_json.containsKey("vt")) { + Integer _v = getIntByDBObject(v_json, "vt"); + if (_v != null && _v >= 0 && _v <= 2) { + style.setVerticalAlignment(ConstantUtil.getVerticalType(_v)); + } + } + else { + // 默认设置居中 + style.setVerticalAlignment(ConstantUtil.getVerticalType(0)); + } + + // ht 水平对齐 水平对齐方式(0=居中,1=左对齐,2=右对齐) + if (v_json.containsKey("ht")) { + Integer _v = getIntByDBObject(v_json, "ht"); + if (_v != null && _v >= 0 && _v <= 2) { + style.setAlignment(ConstantUtil.getHorizontaltype(_v)); + } + } + else { + // 默认设置左对齐 + style.setAlignment(ConstantUtil.getHorizontaltype(1)); + } + + // tr 文字旋转 文字旋转角度(0=0,1=45,2=-45,3=竖排文字,4=90,5=-90) + if (v_json.containsKey("tr")) { + Integer _v = getIntByDBObject(v_json, "tr"); + if (_v != null) { + style.setRotation(ConstantUtil.getRotation(_v)); + } + } + + // tb 文本换行 0 截断、1溢出、2 自动换行 + // 2:setTextWrapped 0和1:IsTextWrapped = true + if (v_json.containsKey("tb")) { + Integer _v = getIntByDBObject(v_json, "tb"); + if (_v != null) { + if (_v >= 0 && _v <= 1) { + style.setWrapText(false); + } + else { + style.setWrapText(true); + } + } + } + + // f 公式 + if (v_json.containsKey("f")) { + String _v = getByDBObject(v_json, "f"); + if (_v.length() > 0) { + try { + if (_v.startsWith("=")) { + cell.setCellFormula(_v.substring(1)); + } + else { + cell.setCellFormula(_v); + } + } + catch (Exception ex) { + log.error("公式 {};Error:{}", _v, ex.toString()); + } + } + } + + } + + } + } + } + + /** + * 设置边框 + * @param borderInfo + * @param sheet + */ + private static void setCellBoard(Workbook wb, JSONArray borderInfo, Sheet sheet) { + + // 一定要通过 cell.getCellStyle() 不然的话之前设置的样式会丢失 + // 设置边框 + for (int i = 0; i < borderInfo.size(); i++) { + JSONObject borderInfoObject = (JSONObject) borderInfo.get(i); + if (borderInfoObject.get("rangeType").equals("cell")) {// 单个单元格 + JSONObject borderValueObject = borderInfoObject.getJSONObject("value"); + + JSONObject l = borderValueObject.getJSONObject("l"); + JSONObject r = borderValueObject.getJSONObject("r"); + JSONObject t = borderValueObject.getJSONObject("t"); + JSONObject b = borderValueObject.getJSONObject("b"); + + int row_ = borderValueObject.getInteger("row_index"); + int col_ = borderValueObject.getInteger("col_index"); + + Row row = sheet.getRow(row_); + if (null == row) { + row = sheet.createRow(row_); + } + Cell cell = row.getCell(col_); + CellStyle style; + if (null == cell) { + style = wb.createCellStyle(); + cell = row.createCell(col_); + cell.setCellStyle(style); + } + else { + style = cell.getCellStyle(); + } + + if (l != null) { + style.setBorderLeft(BorderStyle.valueOf(l.getShort("style"))); // 左边框 + Short color = ColorUtil.getColorByStr(l.getString("color")); + if (null != color) { + style.setLeftBorderColor(color);// 左边框颜色 + } + + } + if (r != null) { + style.setBorderRight(BorderStyle.valueOf(r.getShort("style"))); // 右边框 + Short color = ColorUtil.getColorByStr(r.getString("color")); + if (null != color) { + style.setRightBorderColor(color);// 右边框颜色 + } + + } + if (t != null) { + style.setBorderTop(BorderStyle.valueOf(t.getShort("style"))); // 顶部边框 + Short _vcolor = ColorUtil.getColorByStr(t.getString("color")); + if (null != _vcolor) { + style.setTopBorderColor(_vcolor);// 顶部边框颜色 + } + + } + if (b != null) { + style.setBorderBottom(BorderStyle.valueOf(b.getShort("style"))); // 底部边框 + Short _vcolor = ColorUtil.getColorByStr(b.getString("color")); + if (_vcolor != null) { + // 底部边框颜色 + style.setBottomBorderColor(_vcolor); + } + } + + } + else if (borderInfoObject.get("rangeType").equals("range")) { + // 选区 + Short style_ = borderInfoObject.getShort("style"); + String borderType = borderInfoObject.getString("borderType"); + Short color = ColorUtil.getColorByStr(borderInfoObject.getString("color")); + JSONObject rangObject = (JSONObject) ((JSONArray) (borderInfoObject.get("range"))).get(0); + + JSONArray rowList = rangObject.getJSONArray("row"); + JSONArray columnList = rangObject.getJSONArray("column"); + + for (int row_ = rowList.getInteger(0); row_ < rowList.getInteger(rowList.size() - 1) + 1; row_++) { + for (int col_ = columnList.getInteger(0); col_ < columnList.getInteger(columnList.size() - 1) + + 1; col_++) { + Row row = sheet.getRow(row_); + if (null == row) { + row = sheet.createRow(row_); + } + Cell cell = row.getCell(col_); + CellStyle style; + if (null == cell) { + style = wb.createCellStyle(); + cell = row.createCell(col_); + cell.setCellStyle(style); + } + else { + style = cell.getCellStyle(); + } + + // "border-left" | "border-right" | "border-top" | "border-bottom" + // | "border-all" | "border-horizontal" | "border-vertical" + // "border-outside" | "border-inside" | | "border-none" + if ("border-left".equals(borderType) || "border-all".equals(borderType)) { + style.setBorderLeft(BorderStyle.valueOf(style_)); // 左边框 + style.setLeftBorderColor(color);// 左边框颜色 + } + if ("border-right".equals(borderType) || "border-all".equals(borderType)) { + style.setBorderRight(BorderStyle.valueOf(style_)); // 右边框 + style.setRightBorderColor(color);// 右边框颜色 + } + + if ("border-top".equals(borderType) || "border-all".equals(borderType)) { + style.setBorderTop(BorderStyle.valueOf(style_)); // 顶部边框 + style.setTopBorderColor(color);// 顶部边框颜色 + } + + if ("border-bottom".equals(borderType) || "border-all".equals(borderType)) { + style.setBorderBottom(BorderStyle.valueOf(style_)); // 底部边框 + style.setBottomBorderColor(color);// 底部边框颜色 } + } + + if ("border-outside".equals(borderType)) { + // 外圈边框 + if (row_ == rowList.getInteger(0)) { + style.setBorderTop(BorderStyle.valueOf(style_)); // 顶部边框 + style.setTopBorderColor(color);// 顶部边框颜色 + } + if (col_ == columnList.getInteger(0)) { + style.setBorderLeft(BorderStyle.valueOf(style_)); // 左边框 + style.setLeftBorderColor(color);// 左边框颜色 + } + if (row_ == rowList.getInteger(rowList.size() - 1)) { + style.setBorderBottom(BorderStyle.valueOf(style_)); // 底部边框 + style.setBottomBorderColor(color);// 底部边框颜色 } + } + if (col_ == columnList.getInteger(columnList.size() - 1)) { + style.setBorderRight(BorderStyle.valueOf(style_)); // 右边框 + style.setRightBorderColor(color);// 右边框颜色 + } + + } + + if ("border-horizontal".equals(borderType) || "border-inside".equals(borderType)) { + // 内部横线 + if (row_ >= rowList.getInteger(0) && row_ < rowList.getInteger(rowList.size() - 1) + && col_ >= columnList.getInteger(0) + && col_ <= columnList.getInteger(columnList.size() - 1)) { + style.setBorderBottom(BorderStyle.valueOf(style_)); // 底部边框 + style.setBottomBorderColor(color);// 底部边框颜色 } + } + } + + if ("border-vertical".equals(borderType) || "border-inside".equals(borderType)) { + // 内部竖线 + if (row_ >= rowList.getInteger(0) && row_ <= rowList.getInteger(rowList.size() - 1) + && col_ >= columnList.getInteger(0) + && col_ < columnList.getInteger(columnList.size() - 1)) { + style.setBorderRight(BorderStyle.valueOf(style_)); // 右边框 + style.setRightBorderColor(color);// 右边框颜色 + } + } + + if ("border-none".equals(borderType)) { + style.setBorderLeft(BorderStyle.NONE); // 左边框 + style.setBorderRight(BorderStyle.NONE); // 左边框 + style.setBorderTop(BorderStyle.NONE); // 左边框 + style.setBorderBottom(BorderStyle.NONE); // 左边框 + } + + } + } + + } + } + + } + + /** + * 设置单元格,宽、高 + * @param dbObject + * @param sheet + */ + private static void setColumAndRow(JSONObject dbObject, Sheet sheet) { + if (dbObject.containsKey("config")) { + JSONObject config = dbObject.getJSONObject("config"); + + if (config.containsKey("columnlen")) { + JSONObject columnlen = config.getJSONObject("columnlen"); + if (columnlen != null) { + for (String k : columnlen.keySet()) { + Integer _i = getStrToInt(k); + Integer _v = getStrToInt(columnlen.get(k).toString()); + if (_i != null && _v != null) { + // sheet.setColumnWidth(_i, + // MSExcelUtil.heightUnits2Pixel(_v.shortValue())); + // TODO 乘以32,有待商榷 + sheet.setColumnWidth(_i, _v * 32); + } + } + } + } + if (config.containsKey("rowlen")) { + JSONObject rowlen = config.getJSONObject("rowlen"); + if (rowlen != null) { + for (String k : rowlen.keySet()) { + Integer _i = getStrToInt(k); + Integer _v = getStrToInt(rowlen.get(k).toString()); + if (_i != null && _v != null) { + Row row = sheet.getRow(_i); + if (row != null) { + // row.setHeightInPoints(MSExcelUtil.pixel2WidthUnits(_v.shortValue())); + row.setHeightInPoints(_v.shortValue()); + } + } + } + } + } + } + } + + /** + * 单元格字体相关样式 + * @param wb + * @param style + * @param dbObject + */ + private static void setCellStyleFont(Workbook wb, CellStyle style, JSONObject dbObject) { + Font font = wb.createFont(); + style.setFont(font); + + // ff 字体 + if (dbObject.containsKey("ff")) { + if (dbObject.get("ff") instanceof Integer) { + Integer _v = getIntByDBObject(dbObject, "ff"); + if (_v != null && ConstantUtil.ff_IntegerToName.containsKey(_v)) { + font.setFontName(ConstantUtil.ff_IntegerToName.get(_v)); + } + } + else if (dbObject.get("ff") instanceof String) { + font.setFontName(getByDBObject(dbObject, "ff")); + } + } + // fc 字体颜色 + if (dbObject.containsKey("fc")) { + String _v = getByDBObject(dbObject, "fc"); + Short _color = ColorUtil.getColorByStr(_v); + if (_color != null) { + font.setColor(_color); + } + } + // bl 粗体 + if (dbObject.containsKey("bl")) { + Integer _v = getIntByDBObject(dbObject, "bl"); + if (_v != null) { + if (_v.equals(1)) { + // 是否粗体显示 + font.setBold(true); + } + else { + font.setBold(false); + } + } + } + // it 斜体 + if (dbObject.containsKey("it")) { + Integer _v = getIntByDBObject(dbObject, "it"); + if (_v != null) { + if (_v.equals(1)) { + font.setItalic(true); + } + else { + font.setItalic(false); + } + } + } + // fs 字体大小 + if (dbObject.containsKey("fs")) { + Integer _v = getStrToInt(getObjectByDBObject(dbObject, "fs")); + if (_v != null) { + font.setFontHeightInPoints(_v.shortValue()); + } + } + // cl 删除线 (导入没有) 0 常规 、 1 删除线 + if (dbObject.containsKey("cl")) { + Integer _v = getIntByDBObject(dbObject, "cl"); + if (_v != null) { + if (_v.equals(1)) { + font.setStrikeout(true); + } + } + } + // ul 下划线 + if (dbObject.containsKey("ul")) { + Integer _v = getIntByDBObject(dbObject, "ul"); + if (_v != null) { + if (_v.equals(1)) { + font.setUnderline(Font.U_SINGLE); + } + else { + font.setUnderline(Font.U_NONE); + } + } + } + + } + + /** + * 设置cell边框颜色样式 + * @param style 样式 + * @param dbObject json对象 + * @param bs 样式 + * @param bc 样式 + */ + private static void setBorderStyle(CellStyle style, JSONObject dbObject, String bs, String bc) { + // bs 边框样式 + if (dbObject.containsKey(bs)) { + Integer _v = getStrToInt(getByDBObject(dbObject, bs)); + if (_v != null) { + // 边框没有,不作改变 + if (bs.equals("bs") || bs.equals("bs_t")) { + style.setBorderTop(BorderStyle.valueOf(_v.shortValue())); + } + if (bs.equals("bs") || bs.equals("bs_b")) { + style.setBorderBottom(BorderStyle.valueOf(_v.shortValue())); + } + if (bs.equals("bs") || bs.equals("bs_l")) { + style.setBorderLeft(BorderStyle.valueOf(_v.shortValue())); + } + if (bs.equals("bs") || bs.equals("bs_r")) { + style.setBorderRight(BorderStyle.valueOf(_v.shortValue())); + } + + // bc 边框颜色 + String _vcolor = getByDBObject(dbObject, bc); + if (_vcolor != null) { + Short _color = ColorUtil.getColorByStr(_vcolor); + if (_color != null) { + if (bc.equals("bc") || bc.equals("bc_t")) { + style.setTopBorderColor(_color); + } + if (bc.equals("bc") || bc.equals("bc_b")) { + style.setBottomBorderColor(_color); + } + if (bc.equals("bc") || bc.equals("bc_l")) { + style.setLeftBorderColor(_color); + } + if (bc.equals("bc") || bc.equals("bc_r")) { + style.setRightBorderColor(_color); + } + } + } + } + } + } + + /** + * 设置单元格格式 ct 单元格值格式 (fa,t) + * @param cell + * @param style + * @param dbObject + */ + private static void setFormatByCt(Workbook wb, Cell cell, CellStyle style, JSONObject dbObject) { + + if (!dbObject.containsKey("v") && dbObject.containsKey("ct")) { + /* + * 处理以下数据结构 { "celldata": [{ "c": 0, "r": 8, "v": { "ct": { "s": [{ "v": + * "sdsdgdf\r\ndfgdfg\r\ndsfgdfgdf\r\ndsfgdfg" }], "t": "inlineStr", "fa": + * "General" } } }] } + */ + JSONObject ct = dbObject.getJSONObject("ct"); + if (ct.containsKey("s")) { + Object s = ct.get("s"); + if (s instanceof List && ((List) s).size() > 0) { + JSONObject _s1 = (JSONObject) ((List) s).get(0); + if (_s1.containsKey("v") && _s1.get("v") instanceof String) { + dbObject.put("v", _s1.get("v")); + style.setWrapText(true); + } + } + + } + } + + // String v = ""; //初始化 + if (dbObject.containsKey("v")) { + // v = v_json.get("v").toString(); + // 取到v后,存到poi单元格对象 + // 设置该单元格值 + // cell.setValue(v); + + // String v=getByDBObject(v_json,"v"); + // cell.setValue(v); + Object obj = getObjectByDBObject(dbObject, "v"); + if (obj instanceof Number) { + cell.setCellValue(Double.valueOf(obj.toString())); + } + else if (obj instanceof Double) { + cell.setCellValue((Double) obj); + } + else if (obj instanceof Date) { + cell.setCellValue((Date) obj); + } + else if (obj instanceof Calendar) { + cell.setCellValue((Calendar) obj); + } + else if (obj instanceof RichTextString) { + cell.setCellValue((RichTextString) obj); + } + else if (obj instanceof String) { + cell.setCellValue((String) obj); + } + else { + cell.setCellValue(obj.toString()); + } + + } + + if (dbObject.containsKey("ct")) { + JSONObject ct = dbObject.getJSONObject("ct"); + if (ct.containsKey("fa") && ct.containsKey("t")) { + // t 0=bool,1=datetime,2=error,3=null,4=numeric,5=string,6=unknown + String fa = getByDBObject(ct, "fa"); // 单元格格式format定义串 + String t = getByDBObject(ct, "t"); // 单元格格式type类型 + + Integer _i = ConstantUtil.getNumberFormatMap(fa); + switch (t) { + case "s": { + // 字符串 + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + style.setDataFormat((short) 0); + } + cell.setCellType(org.apache.poi.ss.usermodel.CellType.STRING); + break; + } + case "d": { + // 日期 + Date _d = null; + String v = getByDBObject(dbObject, "m"); + if (v.length() == 0) { + v = getByDBObject(dbObject, "v"); + } + if (v.length() > 0) { + if (v.indexOf("-") > -1) { + if (v.indexOf(":") > -1) { + _d = ConstantUtil.stringToDateTime(v); + } + else { + _d = ConstantUtil.stringToDate(v); + } + } + else { + _d = ConstantUtil.toDate(v); + } + } + if (_d != null) { + // 能转换为日期 + cell.setCellValue(_d); + DataFormat format = wb.createDataFormat(); + style.setDataFormat(format.getFormat(fa)); + + } + else { + // 不能转换为日期 + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + style.setDataFormat((short) 0); + } + } + break; + } + case "b": { + // 逻辑 + cell.setCellType(org.apache.poi.ss.usermodel.CellType.BOOLEAN); + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + DataFormat format = wb.createDataFormat(); + style.setDataFormat(format.getFormat(fa)); + } + break; + } + case "n": { + // 数值 + // cell.setCellType(CellType.NUMERIC); + // 数字转字符串 + cell.setCellType(org.apache.poi.ss.usermodel.CellType.STRING); + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + DataFormat format = wb.createDataFormat(); + style.setDataFormat(format.getFormat(fa)); + } + break; + } + case "u": + case "g": { + // general 自动类型 + // cell.setCellType(CellType._NONE); + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + DataFormat format = wb.createDataFormat(); + style.setDataFormat(format.getFormat(fa)); + } + break; + } + case "e": { + // 错误 + cell.setCellType(org.apache.poi.ss.usermodel.CellType.ERROR); + if (_i >= 0) { + style.setDataFormat(_i.shortValue()); + } + else { + DataFormat format = wb.createDataFormat(); + style.setDataFormat(format.getFormat(fa)); + } + break; + } + + } + + } + + } + } + + /** + * 内容按行分组 + * @param cells + * @return + */ + private static Map> cellGroup(List cells) { + Map> cellMap = new HashMap<>(100); + for (JSONObject dbObject : cells) { + // 行号 + if (dbObject.containsKey("r")) { + Integer r = getStrToInt(dbObject.get("r")); + if (r != null) { + if (cellMap.containsKey(r)) { + cellMap.get(r).add(dbObject); + } + else { + List list = new ArrayList<>(10); + list.add(dbObject); + cellMap.put(r, list); + } + } + } + + } + return cellMap; + } + + /** + * 获取一个k的值 + * @param b + * @param k + * @return + */ + public static String getByDBObject(JSONObject b, String k) { + if (b.containsKey(k)) { + if (b.get(k) != null && b.get(k) instanceof String) { + return b.getString(k); + } + } + return null; + } + + /** + * 获取一个k的值 + * @param b + * @param k + * @return + */ + public static Object getObjectByDBObject(JSONObject b, String k) { + if (b.containsKey(k)) { + if (b.get(k) != null) { + return b.get(k); + } + } + return ""; + } + + /** + * 没有/无法转换 返回null + * @param b + * @param k + * @return + */ + public static Integer getIntByDBObject(JSONObject b, String k) { + if (b.containsKey(k)) { + if (b.get(k) != null) { + try { + String _s = b.getString(k).replace("px", ""); + Double _d = Double.parseDouble(_s); + return _d.intValue(); + } + catch (Exception ex) { + log.error(ex.getMessage()); + return null; + } + } + } + return null; + } + + /** + * 转int + * @param str + * @return + */ + private static Integer getStrToInt(Object str) { + try { + if (str != null) { + return Integer.parseInt(str.toString()); + } + return null; + } + catch (Exception ex) { + log.error("String:{};Error:{}", str, ex.getMessage()); + return null; + } + } + + private static Short getStrToShort(Object str) { + try { + if (str != null) { + return Short.parseShort(str.toString()); + } + return null; + } + catch (Exception ex) { + log.error("String:{};Error:{}", str, ex.getMessage()); + return null; + } + } + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsUtil.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsUtil.java index 51ea0d3e1..e6eeb14e3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsUtil.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportexcel/util/XlsUtil.java @@ -22,432 +22,458 @@ import java.io.OutputStream; import java.util.*; /** - * 来自:https://github.com/mengshukeji/LuckysheetServer - * 使用poi导出xls + * 来自:https://github.com/mengshukeji/LuckysheetServer 使用poi导出xls * * @author Administrator */ public class XlsUtil { - private final static String MODEL = "{\"c\":0,\"r\":0,\"v\":{\"m\":\"模板\",\"v\":\"模板\",\"bl\":1,\"ct\":{\"t\":\"g\",\"fa\":\"General\"}}}"; - private final static String BORDER_MODEL = "{\"rangeType\":\"cell\",\"value\":{\"b\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"r\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"col_index\":5,\"t\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"row_index\":7,\"l\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1}}}"; - /** - * 默认行数 - */ - private static final int DEFAULT_ROW_INDEX = 84; - /** - * 默认列数 - */ - private static final int DEFAULT_COLUMN_INDEX = 64; + private final static String MODEL = "{\"c\":0,\"r\":0,\"v\":{\"m\":\"模板\",\"v\":\"模板\",\"bl\":1,\"ct\":{\"t\":\"g\",\"fa\":\"General\"}}}"; - /** - * 输出文件流 - * - * @param outputStream 流 - * @param isXlsx 是否是xlsx - * @param dbObjectList 数据 - */ - public static void exportXlsFile(OutputStream outputStream, Boolean isXlsx, List dbObjectList) throws IOException { - Workbook wb = null; - if (isXlsx) { - wb = new XSSFWorkbook(); - } else { - wb = new HSSFWorkbook(); - } - if (dbObjectList != null && dbObjectList.size() > 0) { - for (int x = 0; x < dbObjectList.size(); x++) { - XlsSheetUtil.exportSheet(wb, x, dbObjectList.get(x)); - } - } - wb.write(outputStream); - } + private final static String BORDER_MODEL = "{\"rangeType\":\"cell\",\"value\":{\"b\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"r\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"col_index\":5,\"t\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1},\"row_index\":7,\"l\":{\"color\":\"rgb(0, 0, 0)\",\"style\":1}}}"; - /** - * @param workbook 工作簿 - * @return Map - * @description 读取excel - * @author zhouhang - * @date 2021/4/20 - */ - public static List readExcel(Workbook workbook) { - List list = new ArrayList<>(); - Iterator sheetIterator = workbook.sheetIterator(); - int sheetIndex = 0; - while (sheetIterator.hasNext()) { - Sheet sheet = sheetIterator.next(); - //生成默认MODEL - GridRecordDataModel model; - if (Objects.equals(0, sheetIndex)) { - model = strToModel("", (sheetIndex + 1) + "", 1, sheetIndex); - } else { - model = strToModel("", (sheetIndex + 1) + "", 0, sheetIndex); - } - sheetIndex++; - //读取sheet页 - readSheet(sheet, model, workbook); - //设置sheet页名称 - model.getJson_data().put("name", sheet.getSheetName()); - list.add(model); - } - return list; - } + /** + * 默认行数 + */ + private static final int DEFAULT_ROW_INDEX = 84; - public static GridRecordDataModel strToModel(String list_id, String index, int status, int order) { - String strSheet = "{\"row\":84,\"name\":\"reSheetName\",\"chart\":[],\"color\":\"\",\"index\":\"reIndex\",\"order\":reOrder,\"column\":60,\"config\":{},\"status\":reStatus,\"celldata\":[],\"ch_width\":4748,\"rowsplit\":[],\"rh_height\":1790,\"scrollTop\":0,\"scrollLeft\":0,\"visibledatarow\":[],\"visibledatacolumn\":[],\"jfgird_select_save\":[],\"jfgrid_selection_range\":{}}"; - strSheet = strSheet.replace("reSheetName", "Sheet" + index).replace("reIndex", index).replace("reOrder", order + "").replace("reStatus", status + ""); + /** + * 默认列数 + */ + private static final int DEFAULT_COLUMN_INDEX = 64; - JSONObject bson = JSONObject.parseObject(strSheet); - GridRecordDataModel model = new GridRecordDataModel(); - model.setBlock_id("fblock"); - model.setRow_col("5_5"); - model.setIndex(index); - model.setIs_delete(0); - model.setJson_data(bson); - model.setStatus(status); - model.setOrder(order); - model.setList_id(list_id); - return model; - } + /** + * 输出文件流 + * @param outputStream 流 + * @param isXlsx 是否是xlsx + * @param dbObjectList 数据 + */ + public static void exportXlsFile(OutputStream outputStream, Boolean isXlsx, List dbObjectList) + throws IOException { + Workbook wb = null; + if (isXlsx) { + wb = new XSSFWorkbook(); + } + else { + wb = new HSSFWorkbook(); + } + if (dbObjectList != null && dbObjectList.size() > 0) { + for (int x = 0; x < dbObjectList.size(); x++) { + XlsSheetUtil.exportSheet(wb, x, dbObjectList.get(x)); + } + } + wb.write(outputStream); + } - /** - * @param sheet sheet页 - * @param model 数据存储 - * @param workbook excel - * @description 读取单个sheet页 - * @author zhouhang - * @date 2021/4/20 - */ - private static void readSheet(Sheet sheet, GridRecordDataModel model, Workbook workbook) { - //excel数据集合 - List dataList = new ArrayList<>(); - model.setDataList(dataList); - //获取行迭代器 - Iterator rowIterator = sheet.rowIterator(); - //获取合并单元格信息 - Map rangeMap = getRangeMap(sheet); - //记录最大列 - int maxCellNumber = 0; - int maxRowNumber = 0; - //列宽 - JSONObject columnLenObj = new JSONObject(); - //行高 - JSONObject rowLenObj = new JSONObject(); - //读取文档 - while (rowIterator.hasNext()) { - Row row = rowIterator.next(); - int rowLen = ((int) row.getHeight()) / 20; - if (rowLen == 0) { - rowLen = 30; - } - rowLenObj.put(row.getRowNum() + "", rowLen); - Iterator cellIterator = row.cellIterator(); - maxRowNumber = row.getRowNum(); - while (cellIterator.hasNext()) { - //"{\"c\":0,\"r\":0,\"v\":{\"m\":\"模板\",\"v\":\"模板\",\"bl\":1,\"ct\":{\"t\":\"g\",\"fa\":\"General\"}}}"; - JSONObject dataModel = JSONObject.parseObject(MODEL); - //初始化默认单元格内容 - Cell cell = cellIterator.next(); - int columnLen = sheet.getColumnWidth(cell.getColumnIndex()) / 25; - if (columnLen == 0) { - columnLen = 73; - } - columnLenObj.put(cell.getColumnIndex() + "", columnLen); - //修改最大列 - maxCellNumber = Math.max(cell.getColumnIndex(), maxCellNumber); - //设置行列 - dataModel.put("c", cell.getColumnIndex()); - dataModel.put("r", row.getRowNum()); - //获取单元格内容 - switch (cell.getCellType()) { - case STRING: - dataModel.getJSONObject("v").put("m", cell.getStringCellValue()); - dataModel.getJSONObject("v").put("v", cell.getStringCellValue()); - break; - case NUMERIC: - dataModel.getJSONObject("v").put("m", cell.getNumericCellValue()); - dataModel.getJSONObject("v").put("v", cell.getNumericCellValue()); - break; - case BLANK: - dataModel.getJSONObject("v").put("m", ""); - dataModel.getJSONObject("v").put("v", ""); - break; - case BOOLEAN: - dataModel.getJSONObject("v").put("m", cell.getBooleanCellValue()); - dataModel.getJSONObject("v").put("v", cell.getBooleanCellValue()); - break; - case ERROR: - dataModel.getJSONObject("v").put("m", cell.getErrorCellValue()); - dataModel.getJSONObject("v").put("v", cell.getErrorCellValue()); - break; - default: - dataModel.getJSONObject("v").put("m", ""); - dataModel.getJSONObject("v").put("v", ""); - } - //设置单元格合并标记 - dealWithCellMarge(rangeMap, row, cell, dataModel); - //设置单元格样式、合并单元格信息 - dealWithExcelStyle(model, dataModel, cell, sheet, workbook); - dataList.add(dataModel); - } - } - //设置最大行、列 - model.getJson_data().put("column", Math.max(maxCellNumber, DEFAULT_COLUMN_INDEX)); - model.getJson_data().put("row", Math.max(maxRowNumber, DEFAULT_ROW_INDEX)); - //设置行高、列宽 - model.getJson_data().getJSONObject("config").put("columnlen", columnLenObj); - model.getJson_data().getJSONObject("config").put("rowlen", rowLenObj); - } + /** + * @param workbook 工作簿 + * @return Map + * @description 读取excel + * @author zhouhang + * @date 2021/4/20 + */ + public static List readExcel(Workbook workbook) { + List list = new ArrayList<>(); + Iterator sheetIterator = workbook.sheetIterator(); + int sheetIndex = 0; + while (sheetIterator.hasNext()) { + Sheet sheet = sheetIterator.next(); + // 生成默认MODEL + GridRecordDataModel model; + if (Objects.equals(0, sheetIndex)) { + model = strToModel("", (sheetIndex + 1) + "", 1, sheetIndex); + } + else { + model = strToModel("", (sheetIndex + 1) + "", 0, sheetIndex); + } + sheetIndex++; + // 读取sheet页 + readSheet(sheet, model, workbook); + // 设置sheet页名称 + model.getJson_data().put("name", sheet.getSheetName()); + list.add(model); + } + return list; + } - /** - * @param sheet sheet页信息 - * @return Map 单元格合并信息 - * @description 获取合并单元格信息 所有合并单元的MAP - * @author zhouhang - * @date 2021/4/21 - */ - @NotNull - private static Map getRangeMap(Sheet sheet) { - List rangeAddressList = sheet.getMergedRegions(); - Map rangeMap = new HashMap<>(rangeAddressList.size() * 5); - for (CellRangeAddress cellAddresses : rangeAddressList) { - for (int i = cellAddresses.getFirstRow(); i <= cellAddresses.getLastRow(); i++) { - for (int j = cellAddresses.getFirstColumn(); j <= cellAddresses.getLastColumn(); j++) { - if (i == cellAddresses.getFirstRow() && j == cellAddresses.getFirstColumn()) { - //单元格合并初始值特殊标记 - rangeMap.put(i + "_" + j, cellAddresses.getFirstRow() + "_" + cellAddresses.getFirstColumn() + "_" + cellAddresses.getLastRow() + "_" + cellAddresses.getLastColumn()); - } else { - rangeMap.put(i + "_" + j, cellAddresses.getFirstRow() + "_" + cellAddresses.getFirstColumn()); - } - } - } - } - return rangeMap; - } + public static GridRecordDataModel strToModel(String list_id, String index, int status, int order) { + String strSheet = "{\"row\":84,\"name\":\"reSheetName\",\"chart\":[],\"color\":\"\",\"index\":\"reIndex\",\"order\":reOrder,\"column\":60,\"config\":{},\"status\":reStatus,\"celldata\":[],\"ch_width\":4748,\"rowsplit\":[],\"rh_height\":1790,\"scrollTop\":0,\"scrollLeft\":0,\"visibledatarow\":[],\"visibledatacolumn\":[],\"jfgird_select_save\":[],\"jfgrid_selection_range\":{}}"; + strSheet = strSheet.replace("reSheetName", "Sheet" + index).replace("reIndex", index) + .replace("reOrder", order + "").replace("reStatus", status + ""); - /** - * @param rangeMap 合并信息 - * @param row 行信息 - * @param cell 单元格 - * @param dataModel 单元格数据存储信息 - * @description 设置单元格合并标记 - * @author zhouhang - * @date 2021/4/21 - */ - private static void dealWithCellMarge(Map rangeMap, Row row, Cell cell, JSONObject dataModel) { - if (rangeMap.containsKey(row.getRowNum() + "_" + cell.getColumnIndex())) { - String margeValue = rangeMap.get(row.getRowNum() + "_" + cell.getColumnIndex()); - JSONObject mcData = new JSONObject(); - String[] s = margeValue.split("_"); - mcData.put("r", Integer.parseInt(s[0])); - mcData.put("c", Integer.parseInt(s[1])); - if (s.length == 4) { - mcData.put("rs", Integer.parseInt(s[2]) - Integer.parseInt(s[0]) + 1); - mcData.put("cs", Integer.parseInt(s[3]) - Integer.parseInt(s[1]) + 1); - } - dataModel.getJSONObject("v").put("mc", mcData); - } - } + JSONObject bson = JSONObject.parseObject(strSheet); + GridRecordDataModel model = new GridRecordDataModel(); + model.setBlock_id("fblock"); + model.setRow_col("5_5"); + model.setIndex(index); + model.setIs_delete(0); + model.setJson_data(bson); + model.setStatus(status); + model.setOrder(order); + model.setList_id(list_id); + return model; + } - /** - * @param model sheet页信息 - * @param dataModel 单元格信息 - * @param cell 单元格 - * @param sheet sheet页数据 - * @param workbook excel - * @description 获取单元格样式,设置单元格样式 - * @author zhouhang - * @date 2021/4/21 - */ - private static void dealWithExcelStyle(GridRecordDataModel model, JSONObject dataModel, Cell cell, Sheet sheet, Workbook workbook) { - //设置单元格合并信息 - dealWithExcelMerge(model, sheet); - //设置字体样式 - setFontStyle(dataModel, workbook, cell); - //设置单元格样式 - dealWithBorderStyle(model, cell, workbook); - } + /** + * @param sheet sheet页 + * @param model 数据存储 + * @param workbook excel + * @description 读取单个sheet页 + * @author zhouhang + * @date 2021/4/20 + */ + private static void readSheet(Sheet sheet, GridRecordDataModel model, Workbook workbook) { + // excel数据集合 + List dataList = new ArrayList<>(); + model.setDataList(dataList); + // 获取行迭代器 + Iterator rowIterator = sheet.rowIterator(); + // 获取合并单元格信息 + Map rangeMap = getRangeMap(sheet); + // 记录最大列 + int maxCellNumber = 0; + int maxRowNumber = 0; + // 列宽 + JSONObject columnLenObj = new JSONObject(); + // 行高 + JSONObject rowLenObj = new JSONObject(); + // 读取文档 + while (rowIterator.hasNext()) { + Row row = rowIterator.next(); + int rowLen = ((int) row.getHeight()) / 20; + if (rowLen == 0) { + rowLen = 30; + } + rowLenObj.put(row.getRowNum() + "", rowLen); + Iterator cellIterator = row.cellIterator(); + maxRowNumber = row.getRowNum(); + while (cellIterator.hasNext()) { + // "{\"c\":0,\"r\":0,\"v\":{\"m\":\"模板\",\"v\":\"模板\",\"bl\":1,\"ct\":{\"t\":\"g\",\"fa\":\"General\"}}}"; + JSONObject dataModel = JSONObject.parseObject(MODEL); + // 初始化默认单元格内容 + Cell cell = cellIterator.next(); + int columnLen = sheet.getColumnWidth(cell.getColumnIndex()) / 25; + if (columnLen == 0) { + columnLen = 73; + } + columnLenObj.put(cell.getColumnIndex() + "", columnLen); + // 修改最大列 + maxCellNumber = Math.max(cell.getColumnIndex(), maxCellNumber); + // 设置行列 + dataModel.put("c", cell.getColumnIndex()); + dataModel.put("r", row.getRowNum()); + // 获取单元格内容 + switch (cell.getCellType()) { + case STRING: + dataModel.getJSONObject("v").put("m", cell.getStringCellValue()); + dataModel.getJSONObject("v").put("v", cell.getStringCellValue()); + break; + case NUMERIC: + dataModel.getJSONObject("v").put("m", cell.getNumericCellValue()); + dataModel.getJSONObject("v").put("v", cell.getNumericCellValue()); + break; + case BLANK: + dataModel.getJSONObject("v").put("m", ""); + dataModel.getJSONObject("v").put("v", ""); + break; + case BOOLEAN: + dataModel.getJSONObject("v").put("m", cell.getBooleanCellValue()); + dataModel.getJSONObject("v").put("v", cell.getBooleanCellValue()); + break; + case ERROR: + dataModel.getJSONObject("v").put("m", cell.getErrorCellValue()); + dataModel.getJSONObject("v").put("v", cell.getErrorCellValue()); + break; + default: + dataModel.getJSONObject("v").put("m", ""); + dataModel.getJSONObject("v").put("v", ""); + } + // 设置单元格合并标记 + dealWithCellMarge(rangeMap, row, cell, dataModel); + // 设置单元格样式、合并单元格信息 + dealWithExcelStyle(model, dataModel, cell, sheet, workbook); + dataList.add(dataModel); + } + } + // 设置最大行、列 + model.getJson_data().put("column", Math.max(maxCellNumber, DEFAULT_COLUMN_INDEX)); + model.getJson_data().put("row", Math.max(maxRowNumber, DEFAULT_ROW_INDEX)); + // 设置行高、列宽 + model.getJson_data().getJSONObject("config").put("columnlen", columnLenObj); + model.getJson_data().getJSONObject("config").put("rowlen", rowLenObj); + } - /** - * @param model 在线表格存储单元 - * @param cell cell - * @param workbook workbook - * @description 设置单元格样式 - * @author zhouhang - * @date 2021/4/22 - */ - private static void dealWithBorderStyle(GridRecordDataModel model, Cell cell, Workbook workbook) { - CellStyle cellStyle = cell.getCellStyle(); - //判断是否存在边框 - if (cellStyle.getBorderTop().getCode() > 0 || cellStyle.getBorderBottom().getCode() > 0 || - cellStyle.getBorderLeft().getCode() > 0 || cellStyle.getBorderRight().getCode() > 0) { - JSONObject border = JSONObject.parseObject(BORDER_MODEL); - border.getJSONObject("value").put("row_index", cell.getRowIndex()); - border.getJSONObject("value").put("col_index", cell.getColumnIndex()); - //xlsx - if (cellStyle instanceof XSSFCellStyle) { - XSSFCellStyle xssfCellStyle = (XSSFCellStyle) cellStyle; - if (Objects.equals((short) 0, cellStyle.getBorderTop().getCode())) { - border.getJSONObject("value").remove("t"); - } else { - border.getJSONObject("value").getJSONObject("t").put("color", dealWithRbg(xssfCellStyle.getTopBorderXSSFColor().getRGB())); - } - if (Objects.equals((short) 0, cellStyle.getBorderRight().getCode())) { - border.getJSONObject("value").remove("r"); - } else { - border.getJSONObject("value").getJSONObject("r").put("color", dealWithRbg(xssfCellStyle.getRightBorderXSSFColor().getRGB())); - } - if (Objects.equals((short) 0, cellStyle.getBorderLeft().getCode())) { - border.getJSONObject("value").remove("l"); - } else { - border.getJSONObject("value").getJSONObject("l").put("color", dealWithRbg(xssfCellStyle.getLeftBorderXSSFColor().getRGB())); - } - if (Objects.equals((short) 0, cellStyle.getBorderBottom().getCode())) { - border.getJSONObject("value").remove("b"); - } else { - border.getJSONObject("value").getJSONObject("b").put("color", dealWithRbg(xssfCellStyle.getBottomBorderXSSFColor().getRGB())); - } - } else if (cellStyle instanceof HSSFCellStyle) { - //xls - HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook; - HSSFCellStyle hssfCellStyle = (HSSFCellStyle) cellStyle; - if (Objects.equals((short) 0, cellStyle.getBorderTop().getCode())) { - border.getJSONObject("value").remove("t"); - } else { - HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getTopBorderColor()); - border.getJSONObject("value").getJSONObject("t").put("color", dealWithRbgShort(color.getTriplet())); - } - if (Objects.equals((short) 0, cellStyle.getBorderRight().getCode())) { - border.getJSONObject("value").remove("r"); - } else { - HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getRightBorderColor()); - border.getJSONObject("value").getJSONObject("r").put("color", dealWithRbgShort(color.getTriplet())); - } - if (Objects.equals((short) 0, cellStyle.getBorderLeft().getCode())) { - border.getJSONObject("value").remove("l"); - } else { - HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getLeftBorderColor()); - border.getJSONObject("value").getJSONObject("l").put("color", dealWithRbgShort(color.getTriplet())); - } - if (Objects.equals((short) 0, cellStyle.getBorderBottom().getCode())) { - border.getJSONObject("value").remove("b"); - } else { - HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getBottomBorderColor()); - border.getJSONObject("value").getJSONObject("b").put("color", dealWithRbgShort(color.getTriplet())); - } - } - JSONArray borderInfo = model.getJson_data().getJSONObject("config").getJSONArray("borderInfo"); - if (Objects.isNull(borderInfo)) { - borderInfo = new JSONArray(); - model.getJson_data().getJSONObject("config").put("borderInfo", borderInfo); - } - borderInfo.add(border); - } - } + /** + * @param sheet sheet页信息 + * @return Map 单元格合并信息 + * @description 获取合并单元格信息 所有合并单元的MAP + * @author zhouhang + * @date 2021/4/21 + */ + @NotNull + private static Map getRangeMap(Sheet sheet) { + List rangeAddressList = sheet.getMergedRegions(); + Map rangeMap = new HashMap<>(rangeAddressList.size() * 5); + for (CellRangeAddress cellAddresses : rangeAddressList) { + for (int i = cellAddresses.getFirstRow(); i <= cellAddresses.getLastRow(); i++) { + for (int j = cellAddresses.getFirstColumn(); j <= cellAddresses.getLastColumn(); j++) { + if (i == cellAddresses.getFirstRow() && j == cellAddresses.getFirstColumn()) { + // 单元格合并初始值特殊标记 + rangeMap.put(i + "_" + j, cellAddresses.getFirstRow() + "_" + cellAddresses.getFirstColumn() + + "_" + cellAddresses.getLastRow() + "_" + cellAddresses.getLastColumn()); + } + else { + rangeMap.put(i + "_" + j, cellAddresses.getFirstRow() + "_" + cellAddresses.getFirstColumn()); + } + } + } + } + return rangeMap; + } - /** - * @param rgb RBG short - * @return rbg(0, 0, 0) - * @description 转换RBG rbg(0,0,0) - * @author zhouhang - * @date 2021/4/26 - */ - private static String dealWithRbgShort(short[] rgb) { - return getRbg(Objects.nonNull(rgb), rgb[0], rgb[1], rgb[2]); - } + /** + * @param rangeMap 合并信息 + * @param row 行信息 + * @param cell 单元格 + * @param dataModel 单元格数据存储信息 + * @description 设置单元格合并标记 + * @author zhouhang + * @date 2021/4/21 + */ + private static void dealWithCellMarge(Map rangeMap, Row row, Cell cell, JSONObject dataModel) { + if (rangeMap.containsKey(row.getRowNum() + "_" + cell.getColumnIndex())) { + String margeValue = rangeMap.get(row.getRowNum() + "_" + cell.getColumnIndex()); + JSONObject mcData = new JSONObject(); + String[] s = margeValue.split("_"); + mcData.put("r", Integer.parseInt(s[0])); + mcData.put("c", Integer.parseInt(s[1])); + if (s.length == 4) { + mcData.put("rs", Integer.parseInt(s[2]) - Integer.parseInt(s[0]) + 1); + mcData.put("cs", Integer.parseInt(s[3]) - Integer.parseInt(s[1]) + 1); + } + dataModel.getJSONObject("v").put("mc", mcData); + } + } - @NotNull - private static String getRbg(boolean b2, short r, short b, short g) { - if (b2) { - return "rgb(" + (r & 0xFF) + ", " + (b & 0xFF) + ", " + (g & 0xFF) + ")"; - } else { - return "rgb(0, 0, 0)"; - } - } + /** + * @param model sheet页信息 + * @param dataModel 单元格信息 + * @param cell 单元格 + * @param sheet sheet页数据 + * @param workbook excel + * @description 获取单元格样式,设置单元格样式 + * @author zhouhang + * @date 2021/4/21 + */ + private static void dealWithExcelStyle(GridRecordDataModel model, JSONObject dataModel, Cell cell, Sheet sheet, + Workbook workbook) { + // 设置单元格合并信息 + dealWithExcelMerge(model, sheet); + // 设置字体样式 + setFontStyle(dataModel, workbook, cell); + // 设置单元格样式 + dealWithBorderStyle(model, cell, workbook); + } - /** - * @param rgb RBG byte - * @return rbg(0, 0, 0) - * @description 转换RBG rbg(0,0,0) - * @author zhouhang - * @date 2021/4/26 - */ - private static String dealWithRbg(byte[] rgb) { - if (Objects.isNull(rgb)) { - return "rgb(0, 0, 0)"; - } - short[] shorts = new short[]{rgb[0], rgb[1], rgb[2]}; - return getRbg(true, shorts[0], shorts[1], shorts[2]); - } + /** + * @param model 在线表格存储单元 + * @param cell cell + * @param workbook workbook + * @description 设置单元格样式 + * @author zhouhang + * @date 2021/4/22 + */ + private static void dealWithBorderStyle(GridRecordDataModel model, Cell cell, Workbook workbook) { + CellStyle cellStyle = cell.getCellStyle(); + // 判断是否存在边框 + if (cellStyle.getBorderTop().getCode() > 0 || cellStyle.getBorderBottom().getCode() > 0 + || cellStyle.getBorderLeft().getCode() > 0 || cellStyle.getBorderRight().getCode() > 0) { + JSONObject border = JSONObject.parseObject(BORDER_MODEL); + border.getJSONObject("value").put("row_index", cell.getRowIndex()); + border.getJSONObject("value").put("col_index", cell.getColumnIndex()); + // xlsx + if (cellStyle instanceof XSSFCellStyle) { + XSSFCellStyle xssfCellStyle = (XSSFCellStyle) cellStyle; + if (Objects.equals((short) 0, cellStyle.getBorderTop().getCode())) { + border.getJSONObject("value").remove("t"); + } + else { + border.getJSONObject("value").getJSONObject("t").put("color", + dealWithRbg(xssfCellStyle.getTopBorderXSSFColor().getRGB())); + } + if (Objects.equals((short) 0, cellStyle.getBorderRight().getCode())) { + border.getJSONObject("value").remove("r"); + } + else { + border.getJSONObject("value").getJSONObject("r").put("color", + dealWithRbg(xssfCellStyle.getRightBorderXSSFColor().getRGB())); + } + if (Objects.equals((short) 0, cellStyle.getBorderLeft().getCode())) { + border.getJSONObject("value").remove("l"); + } + else { + border.getJSONObject("value").getJSONObject("l").put("color", + dealWithRbg(xssfCellStyle.getLeftBorderXSSFColor().getRGB())); + } + if (Objects.equals((short) 0, cellStyle.getBorderBottom().getCode())) { + border.getJSONObject("value").remove("b"); + } + else { + border.getJSONObject("value").getJSONObject("b").put("color", + dealWithRbg(xssfCellStyle.getBottomBorderXSSFColor().getRGB())); + } + } + else if (cellStyle instanceof HSSFCellStyle) { + // xls + HSSFWorkbook hssfWorkbook = (HSSFWorkbook) workbook; + HSSFCellStyle hssfCellStyle = (HSSFCellStyle) cellStyle; + if (Objects.equals((short) 0, cellStyle.getBorderTop().getCode())) { + border.getJSONObject("value").remove("t"); + } + else { + HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getTopBorderColor()); + border.getJSONObject("value").getJSONObject("t").put("color", dealWithRbgShort(color.getTriplet())); + } + if (Objects.equals((short) 0, cellStyle.getBorderRight().getCode())) { + border.getJSONObject("value").remove("r"); + } + else { + HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getRightBorderColor()); + border.getJSONObject("value").getJSONObject("r").put("color", dealWithRbgShort(color.getTriplet())); + } + if (Objects.equals((short) 0, cellStyle.getBorderLeft().getCode())) { + border.getJSONObject("value").remove("l"); + } + else { + HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getLeftBorderColor()); + border.getJSONObject("value").getJSONObject("l").put("color", dealWithRbgShort(color.getTriplet())); + } + if (Objects.equals((short) 0, cellStyle.getBorderBottom().getCode())) { + border.getJSONObject("value").remove("b"); + } + else { + HSSFColor color = hssfWorkbook.getCustomPalette().getColor(hssfCellStyle.getBottomBorderColor()); + border.getJSONObject("value").getJSONObject("b").put("color", dealWithRbgShort(color.getTriplet())); + } + } + JSONArray borderInfo = model.getJson_data().getJSONObject("config").getJSONArray("borderInfo"); + if (Objects.isNull(borderInfo)) { + borderInfo = new JSONArray(); + model.getJson_data().getJSONObject("config").put("borderInfo", borderInfo); + } + borderInfo.add(border); + } + } - /** - * @param dataModel 单元格内容 - * @param workbook workbook - * @param cell cell - * @description s设置字体样式 - * @author zhouhang - * @date 2021/4/21 - */ - private static void setFontStyle(JSONObject dataModel, Workbook workbook, Cell cell) { - CellStyle cellStyle = cell.getCellStyle(); - Font font = workbook.getFontAt(cellStyle.getFontIndexAsInt()); - JSONObject v = dataModel.getJSONObject("v"); - //ht 水平对齐 水平对齐方式(0=居中,1=左对齐,2=右对齐) excel:左:1 中:2 右:3 未设置:0 - v.put("ht", ExcelCenterStyleEnum.getExcelCenterStyleByExcelCenterCode(cellStyle.getAlignment().getCode()).getOnlineExcelCode()); - //bl 字体加粗设置 - v.put("bl", font.getBold() ? 1 : 0); - //lt 斜体 - v.put("it", font.getItalic() ? 1 : 0); - //ff 字体 - v.put("ff", font.getFontName()); - //fc 字体颜色 - if (font instanceof HSSFFont) { - HSSFFont hssfFont = (HSSFFont) font; - HSSFColor hssfColor = hssfFont.getHSSFColor((HSSFWorkbook) workbook); - if (Objects.nonNull(hssfColor)) { - v.put("fc", ColorUtil.convertRGBToHex(hssfColor.getTriplet()[0], hssfColor.getTriplet()[1], hssfColor.getTriplet()[2])); - } - } else { - XSSFFont xssfFont = (XSSFFont) font; - XSSFColor xssfColor = xssfFont.getXSSFColor(); - if (Objects.nonNull(xssfColor)) { - v.put("fc", "#" + xssfColor.getARGBHex().substring(2)); - } - } - //fs 字体大小 - v.put("fs", font.getFontHeightInPoints()); - //cl 删除线 - v.put("cl", font.getStrikeout() ? 1 : 0); - //ul 下划线 - v.put("un", font.getUnderline()); - //背景色 - String fillColorHex = ColorUtil.getFillColorHex(cell); - if (Objects.nonNull(fillColorHex)) { - v.put("bg", fillColorHex); - } - } + /** + * @param rgb RBG short + * @return rbg(0, 0, 0) + * @description 转换RBG rbg(0,0,0) + * @author zhouhang + * @date 2021/4/26 + */ + private static String dealWithRbgShort(short[] rgb) { + return getRbg(Objects.nonNull(rgb), rgb[0], rgb[1], rgb[2]); + } + + @NotNull + private static String getRbg(boolean b2, short r, short b, short g) { + if (b2) { + return "rgb(" + (r & 0xFF) + ", " + (b & 0xFF) + ", " + (g & 0xFF) + ")"; + } + else { + return "rgb(0, 0, 0)"; + } + } + + /** + * @param rgb RBG byte + * @return rbg(0, 0, 0) + * @description 转换RBG rbg(0,0,0) + * @author zhouhang + * @date 2021/4/26 + */ + private static String dealWithRbg(byte[] rgb) { + if (Objects.isNull(rgb)) { + return "rgb(0, 0, 0)"; + } + short[] shorts = new short[] { rgb[0], rgb[1], rgb[2] }; + return getRbg(true, shorts[0], shorts[1], shorts[2]); + } + + /** + * @param dataModel 单元格内容 + * @param workbook workbook + * @param cell cell + * @description s设置字体样式 + * @author zhouhang + * @date 2021/4/21 + */ + private static void setFontStyle(JSONObject dataModel, Workbook workbook, Cell cell) { + CellStyle cellStyle = cell.getCellStyle(); + Font font = workbook.getFontAt(cellStyle.getFontIndexAsInt()); + JSONObject v = dataModel.getJSONObject("v"); + // ht 水平对齐 水平对齐方式(0=居中,1=左对齐,2=右对齐) excel:左:1 中:2 右:3 未设置:0 + v.put("ht", ExcelCenterStyleEnum.getExcelCenterStyleByExcelCenterCode(cellStyle.getAlignment().getCode()) + .getOnlineExcelCode()); + // bl 字体加粗设置 + v.put("bl", font.getBold() ? 1 : 0); + // lt 斜体 + v.put("it", font.getItalic() ? 1 : 0); + // ff 字体 + v.put("ff", font.getFontName()); + // fc 字体颜色 + if (font instanceof HSSFFont) { + HSSFFont hssfFont = (HSSFFont) font; + HSSFColor hssfColor = hssfFont.getHSSFColor((HSSFWorkbook) workbook); + if (Objects.nonNull(hssfColor)) { + v.put("fc", ColorUtil.convertRGBToHex(hssfColor.getTriplet()[0], hssfColor.getTriplet()[1], + hssfColor.getTriplet()[2])); + } + } + else { + XSSFFont xssfFont = (XSSFFont) font; + XSSFColor xssfColor = xssfFont.getXSSFColor(); + if (Objects.nonNull(xssfColor)) { + v.put("fc", "#" + xssfColor.getARGBHex().substring(2)); + } + } + // fs 字体大小 + v.put("fs", font.getFontHeightInPoints()); + // cl 删除线 + v.put("cl", font.getStrikeout() ? 1 : 0); + // ul 下划线 + v.put("un", font.getUnderline()); + // 背景色 + String fillColorHex = ColorUtil.getFillColorHex(cell); + if (Objects.nonNull(fillColorHex)) { + v.put("bg", fillColorHex); + } + } + + /** + * @param model sheet页信息 + * @param sheet sheet页 + * @description 设置单元格合并信息 + * @author zhouhang + * @date 2021/4/21 + */ + private static void dealWithExcelMerge(GridRecordDataModel model, Sheet sheet) { + if (CollectionUtils.isNotEmpty(sheet.getMergedRegions())) { + // {"color":"","list_id":"","column":60,"index":"1","jfgird_select_save":[],"rh_height":1790,"visibledatacolumn":[],"scrollTop":0,"block_id":"fblock","rowsplit":[],"visibledatarow":[],"jfgrid_selection_range":{},"name":"Sheet1","celldata":[],"ch_width":4748,"row":84,"scrollLeft":0,"id":364598,"chart":[],"config":{},"order":0,"status":1} + JSONObject jsonObject = model.getJson_data(); + JSONObject config = jsonObject.getJSONObject("config"); + JSONObject merge = new JSONObject(); + for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) { + JSONObject mergeBase = new JSONObject(); + mergeBase.put("r", mergedRegion.getFirstRow()); + mergeBase.put("c", mergedRegion.getFirstColumn()); + mergeBase.put("rs", mergedRegion.getLastRow() - mergedRegion.getFirstRow() + 1); + mergeBase.put("cs", mergedRegion.getLastColumn() - mergedRegion.getFirstColumn() + 1); + merge.put(mergedRegion.getFirstRow() + "_" + mergedRegion.getFirstColumn(), mergeBase); + } + config.put("merge", merge); + } + } - /** - * @param model sheet页信息 - * @param sheet sheet页 - * @description 设置单元格合并信息 - * @author zhouhang - * @date 2021/4/21 - */ - private static void dealWithExcelMerge(GridRecordDataModel model, Sheet sheet) { - if (CollectionUtils.isNotEmpty(sheet.getMergedRegions())) { - //{"color":"","list_id":"","column":60,"index":"1","jfgird_select_save":[],"rh_height":1790,"visibledatacolumn":[],"scrollTop":0,"block_id":"fblock","rowsplit":[],"visibledatarow":[],"jfgrid_selection_range":{},"name":"Sheet1","celldata":[],"ch_width":4748,"row":84,"scrollLeft":0,"id":364598,"chart":[],"config":{},"order":0,"status":1} - JSONObject jsonObject = model.getJson_data(); - JSONObject config = jsonObject.getJSONObject("config"); - JSONObject merge = new JSONObject(); - for (CellRangeAddress mergedRegion : sheet.getMergedRegions()) { - JSONObject mergeBase = new JSONObject(); - mergeBase.put("r", mergedRegion.getFirstRow()); - mergeBase.put("c", mergedRegion.getFirstColumn()); - mergeBase.put("rs", mergedRegion.getLastRow() - mergedRegion.getFirstRow() + 1); - mergeBase.put("cs", mergedRegion.getLastColumn() - mergedRegion.getFirstColumn() + 1); - merge.put(mergedRegion.getFirstRow() + "_" + mergedRegion.getFirstColumn(), mergeBase); - } - config.put("merge", merge); - } - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/ReportShareController.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/ReportShareController.java index 2d0304288..e74868c2a 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/ReportShareController.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/ReportShareController.java @@ -27,43 +27,42 @@ import org.springframework.web.bind.annotation.*; @Permission(code = "reportShareManage", name = "报表分享管理") public class ReportShareController extends GaeaBaseController { - @Autowired - private ReportShareService reportShareService; + @Autowired + private ReportShareService reportShareService; - @Override - public GaeaBaseService getService() { - return reportShareService; - } + @Override + public GaeaBaseService getService() { + return reportShareService; + } - @Override - public ReportShare getEntity() { - return new ReportShare(); - } + @Override + public ReportShare getEntity() { + return new ReportShare(); + } - @Override - public ReportShareDto getDTO() { - return new ReportShareDto(); - } + @Override + public ReportShareDto getDTO() { + return new ReportShareDto(); + } + @GetMapping({ "/{id}" }) + @AccessKey + @Override + @Permission(code = "detail", name = "明细") + public ResponseBean detail(@PathVariable("id") Long id) { + this.logger.info("{}根据ID查询服务开始,id为:{}", this.getClass().getSimpleName(), id); + ReportShare result = reportShareService.getDetail(id); + ReportShareDto dto = this.getDTO(); + GaeaBeanUtils.copyAndFormatter(result, dto); + ResponseBean responseBean = this.responseSuccessWithData(this.resultDtoHandle(dto)); + this.logger.info("{}根据ID查询结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean)); + return responseBean; + } - @GetMapping({"/{id}"}) - @AccessKey - @Override - @Permission(code = "detail", name = "明细") - public ResponseBean detail(@PathVariable("id") Long id) { - this.logger.info("{}根据ID查询服务开始,id为:{}", this.getClass().getSimpleName(), id); - ReportShare result = reportShareService.getDetail(id); - ReportShareDto dto = this.getDTO(); - GaeaBeanUtils.copyAndFormatter(result, dto); - ResponseBean responseBean = this.responseSuccessWithData(this.resultDtoHandle(dto)); - this.logger.info("{}根据ID查询结束,结果:{}", this.getClass().getSimpleName(), GaeaUtils.toJSONString(responseBean)); - return responseBean; - } - - @GetMapping({"/detailByCode"}) - @Permission(code = "detail", name = "明细") - public ResponseBean detailByCode(@RequestParam("shareCode") String shareCode) { - return ResponseBean.builder().data(reportShareService.detailByCode(shareCode)).build(); - } + @GetMapping({ "/detailByCode" }) + @Permission(code = "detail", name = "明细") + public ResponseBean detailByCode(@RequestParam("shareCode") String shareCode) { + return ResponseBean.builder().data(reportShareService.detailByCode(shareCode)).build(); + } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/dto/ReportShareDto.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/dto/ReportShareDto.java index 14690975a..8fe1e16b2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/dto/ReportShareDto.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/dto/ReportShareDto.java @@ -1,61 +1,61 @@ package com.anjiplus.template.gaea.business.modules.reportshare.controller.dto; -import java.io.Serializable; 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.Date; /** -* -* @description 报表分享 dto -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ + * @description 报表分享 dto + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ @Data public class ReportShareDto extends GaeaBaseDTO implements Serializable { - /** 分享编码,系统生成,默认UUID */ - @ApiModelProperty(value = "分享编码,系统生成,默认UUID") - private String shareCode; - /** 分享有效期类型,DIC_NAME=SHARE_VAILD */ - @ApiModelProperty(value = "分享有效期类型,DIC_NAME=SHARE_VAILD") - @NotNull(message = "6002") - private Integer shareValidType; + /** 分享编码,系统生成,默认UUID */ + @ApiModelProperty(value = "分享编码,系统生成,默认UUID") + private String shareCode; - /** 分享有效期 */ - @ApiModelProperty(value = "分享有效期") - private Date shareValidTime; + /** 分享有效期类型,DIC_NAME=SHARE_VAILD */ + @ApiModelProperty(value = "分享有效期类型,DIC_NAME=SHARE_VAILD") + @NotNull(message = "6002") + private Integer shareValidType; - /** 分享token */ - @ApiModelProperty(value = "分享token") - private String shareToken; + /** 分享有效期 */ + @ApiModelProperty(value = "分享有效期") + private Date shareValidTime; - /** 分享url */ - @ApiModelProperty(value = "分享url") - @NotEmpty(message = "6002") - private String shareUrl; + /** 分享token */ + @ApiModelProperty(value = "分享token") + private String shareToken; - /** 报表编码 */ - @ApiModelProperty(value = "报表编码") - @NotEmpty(message = "6002") - private String reportCode; + /** 分享url */ + @ApiModelProperty(value = "分享url") + @NotEmpty(message = "6002") + private String shareUrl; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") - private Integer enableFlag; + /** 报表编码 */ + @ApiModelProperty(value = "报表编码") + @NotEmpty(message = "6002") + private String reportCode; - /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ - @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + @ApiModelProperty(value = "0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG") + private Integer enableFlag; - /** 分享码 */ - private String sharePassword; + /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ + @ApiModelProperty(value = "0--未删除 1--已删除 DIC_NAME=DELETE_FLAG") + private Integer deleteFlag; - private boolean sharePasswordFlag = false; + /** 分享码 */ + private String sharePassword; + + private boolean sharePasswordFlag = false; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/param/ReportShareParam.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/param/ReportShareParam.java index 293f8b020..12b0f604d 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/param/ReportShareParam.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/controller/param/ReportShareParam.java @@ -7,10 +7,11 @@ import lombok.Data; import java.io.Serializable; /** -* @desc ReportShare 报表分享查询输入类 -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ + * @desc ReportShare 报表分享查询输入类 + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ @Data -public class ReportShareParam extends PageParam implements Serializable{ +public class ReportShareParam extends PageParam implements Serializable { + } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/ReportShareMapper.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/ReportShareMapper.java index 852490fe7..c820d90d0 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/ReportShareMapper.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/ReportShareMapper.java @@ -3,13 +3,14 @@ package com.anjiplus.template.gaea.business.modules.reportshare.dao; import com.anji.plus.gaea.curd.mapper.GaeaBaseMapper; import com.anjiplus.template.gaea.business.modules.reportshare.dao.entity.ReportShare; import org.apache.ibatis.annotations.Mapper; + /** -* ReportShare Mapper -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ + * ReportShare Mapper + * + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ @Mapper public interface ReportShareMapper extends GaeaBaseMapper { - } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/entity/ReportShare.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/entity/ReportShare.java index 88b4d748b..a26f319f2 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/entity/ReportShare.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/dao/entity/ReportShare.java @@ -7,44 +7,45 @@ import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.util.Date; + /** -* @description 报表分享 entity -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ -@TableName(keepGlobalPrefix=true, value="gaea_report_share") + * @description 报表分享 entity + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ +@TableName(keepGlobalPrefix = true, value = "gaea_report_share") @Data public class ReportShare extends GaeaBaseEntity { - /** 分享编码,系统生成,默认UUID */ - private String shareCode; - /** 分享有效期类型,DIC_NAME=SHARE_VAILD */ - private Integer shareValidType; + /** 分享编码,系统生成,默认UUID */ + private String shareCode; - /** 分享有效期 */ - private Date shareValidTime; + /** 分享有效期类型,DIC_NAME=SHARE_VAILD */ + private Integer shareValidType; - /** 分享token */ - private String shareToken; + /** 分享有效期 */ + private Date shareValidTime; - /** 分享url */ - private String shareUrl; + /** 分享token */ + private String shareToken; - /** 报表编码 */ - private String reportCode; + /** 分享url */ + private String shareUrl; - /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ - private Integer enableFlag; + /** 报表编码 */ + private String reportCode; - /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ - private Integer deleteFlag; + /** 0--已禁用 1--已启用 DIC_NAME=ENABLE_FLAG */ + private Integer enableFlag; - /** 分享码 */ - @TableField(exist = false) - private String sharePassword; + /** 0--未删除 1--已删除 DIC_NAME=DELETE_FLAG */ + private Integer deleteFlag; - @TableField(exist = false) - private boolean sharePasswordFlag; + /** 分享码 */ + @TableField(exist = false) + private String sharePassword; + @TableField(exist = false) + private boolean sharePasswordFlag; } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/ReportShareService.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/ReportShareService.java index e3613cbad..1cff83ad3 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/ReportShareService.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/ReportShareService.java @@ -7,21 +7,21 @@ import com.anjiplus.template.gaea.business.modules.reportshare.controller.param. import com.anjiplus.template.gaea.business.modules.reportshare.dao.entity.ReportShare; /** -* @desc ReportShare 报表分享服务接口 -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ + * @desc ReportShare 报表分享服务接口 + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ public interface ReportShareService extends GaeaBaseService { - /*** - * 查询详情 - * - * @param id - * @return - */ - ReportShare getDetail(Long id); + /*** + * 查询详情 + * @param id + * @return + */ + ReportShare getDetail(Long id); - ReportShareDto insertShare(ReportShareDto dto); + ReportShareDto insertShare(ReportShareDto dto); + + ReportShare detailByCode(String shareCode); - ReportShare detailByCode(String shareCode); } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/impl/ReportShareServiceImpl.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/impl/ReportShareServiceImpl.java index 5a1b98194..2c049c130 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/impl/ReportShareServiceImpl.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/modules/reportshare/service/impl/ReportShareServiceImpl.java @@ -23,100 +23,104 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** -* @desc ReportShare 报表分享服务实现 -* @author Raod -* @date 2021-08-18 13:37:26.663 -**/ + * @desc ReportShare 报表分享服务实现 + * @author Raod + * @date 2021-08-18 13:37:26.663 + **/ @Service public class ReportShareServiceImpl implements ReportShareService { - /** - * 默认跳转路由为aj的页面 - */ - private static final String SHARE_FLAG = "#/aj/"; + /** + * 默认跳转路由为aj的页面 + */ + private static final String SHARE_FLAG = "#/aj/"; - private static final String SHARE_URL = "#"; + private static final String SHARE_URL = "#"; - @Autowired - private ReportShareMapper reportShareMapper; + @Autowired + private ReportShareMapper reportShareMapper; - @Override - public GaeaBaseMapper getMapper() { - return reportShareMapper; - } + @Override + public GaeaBaseMapper getMapper() { + return reportShareMapper; + } - @Override - public ReportShare getDetail(Long id) { - ReportShare reportShare = this.selectOne(id); - return reportShare; - } + @Override + public ReportShare getDetail(Long id) { + ReportShare reportShare = this.selectOne(id); + return reportShare; + } - @Override - public ReportShareDto insertShare(ReportShareDto dto) { - //设置分享码 - if (dto.isSharePasswordFlag()) { - dto.setSharePassword(UuidUtil.getRandomPwd(4)); - } + @Override + public ReportShareDto insertShare(ReportShareDto dto) { + // 设置分享码 + if (dto.isSharePasswordFlag()) { + dto.setSharePassword(UuidUtil.getRandomPwd(4)); + } - ReportShareDto reportShareDto = new ReportShareDto(); - ReportShare entity = new ReportShare(); - BeanUtils.copyProperties(dto, entity); - insert(entity); - //将分享链接返回 - reportShareDto.setShareUrl(entity.getShareUrl()); - reportShareDto.setSharePassword(dto.getSharePassword()); - return reportShareDto; - } + ReportShareDto reportShareDto = new ReportShareDto(); + ReportShare entity = new ReportShare(); + BeanUtils.copyProperties(dto, entity); + insert(entity); + // 将分享链接返回 + reportShareDto.setShareUrl(entity.getShareUrl()); + reportShareDto.setSharePassword(dto.getSharePassword()); + return reportShareDto; + } - @Override - public ReportShare detailByCode(String shareCode) { - LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); - wrapper.eq(ReportShare::getShareCode, shareCode); - wrapper.eq(ReportShare::getEnableFlag, EnableFlagEnum.ENABLE.getCodeValue()); - ReportShare reportShare = selectOne(wrapper); - if (null == reportShare) { - throw BusinessExceptionBuilder.build(ResponseCode.REPORT_SHARE_LINK_INVALID); - } - //解析jwt token,获取密码 - String password = JwtUtil.getPassword(reportShare.getShareToken()); - if (StringUtils.isNotBlank(password)) { - //md5加密返回 - reportShare.setSharePassword(MD5Util.encrypt(password)); - } - return reportShare; - } + @Override + public ReportShare detailByCode(String shareCode) { + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(); + wrapper.eq(ReportShare::getShareCode, shareCode); + wrapper.eq(ReportShare::getEnableFlag, EnableFlagEnum.ENABLE.getCodeValue()); + ReportShare reportShare = selectOne(wrapper); + if (null == reportShare) { + throw BusinessExceptionBuilder.build(ResponseCode.REPORT_SHARE_LINK_INVALID); + } + // 解析jwt token,获取密码 + String password = JwtUtil.getPassword(reportShare.getShareToken()); + if (StringUtils.isNotBlank(password)) { + // md5加密返回 + reportShare.setSharePassword(MD5Util.encrypt(password)); + } + return reportShare; + } - @Override - public void processBeforeOperation(ReportShare entity, BaseOperationEnum operationEnum) throws BusinessException { - switch (operationEnum) { - case INSERT: - init(entity); - break; - default: + @Override + public void processBeforeOperation(ReportShare entity, BaseOperationEnum operationEnum) throws BusinessException { + switch (operationEnum) { + case INSERT: + init(entity); + break; + default: - break; - } - } + break; + } + } - /** - * 新增初始化 - * @param entity - */ - private void init(ReportShare entity) { - //前端地址 window.location.href https://report.anji-plus.com/index.html#/report/bigscreen - //截取#之前的内容 - //http://localhost:9528/#/bigscreen/viewer?reportCode=bigScreen2 - //http://127.0.0.1:9095/reportDashboard/getData - String shareCode = UuidUtil.generateShortUuid(); - entity.setShareCode(shareCode); - if (entity.getShareUrl().contains(SHARE_URL)) { - String prefix = entity.getShareUrl().substring(0, entity.getShareUrl().indexOf("#")); - entity.setShareUrl(prefix + SHARE_FLAG + shareCode); - } else { - entity.setShareUrl(entity.getShareUrl() + SHARE_FLAG + shareCode); - } + /** + * 新增初始化 + * @param entity + */ + private void init(ReportShare entity) { + // 前端地址 window.location.href + // https://report.anji-plus.com/index.html#/report/bigscreen + // 截取#之前的内容 + // http://localhost:9528/#/bigscreen/viewer?reportCode=bigScreen2 + // http://127.0.0.1:9095/reportDashboard/getData + String shareCode = UuidUtil.generateShortUuid(); + entity.setShareCode(shareCode); + if (entity.getShareUrl().contains(SHARE_URL)) { + String prefix = entity.getShareUrl().substring(0, entity.getShareUrl().indexOf("#")); + entity.setShareUrl(prefix + SHARE_FLAG + shareCode); + } + else { + entity.setShareUrl(entity.getShareUrl() + SHARE_FLAG + shareCode); + } + + entity.setShareValidTime(DateUtil.getFutureDateTmdHms(entity.getShareValidType())); + entity.setShareToken(JwtUtil.createToken(entity.getReportCode(), shareCode, entity.getSharePassword(), + entity.getShareValidTime())); + } - entity.setShareValidTime(DateUtil.getFutureDateTmdHms(entity.getShareValidType())); - entity.setShareToken(JwtUtil.createToken(entity.getReportCode(), shareCode, entity.getSharePassword(), entity.getShareValidTime())); - } } diff --git a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/runner/ApplicationInitRunner.java b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/runner/ApplicationInitRunner.java index 6beecc711..17454791e 100644 --- a/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/runner/ApplicationInitRunner.java +++ b/pigx-visual/pigx-report-platform/src/main/java/com/anjiplus/template/gaea/business/runner/ApplicationInitRunner.java @@ -13,19 +13,20 @@ import org.springframework.boot.ApplicationRunner; **/ public class ApplicationInitRunner implements ApplicationRunner { - @Autowired - private GaeaDictService gaeaDictService; + @Autowired + private GaeaDictService gaeaDictService; - @Autowired - private AccessAuthorityService accessAuthorityService; + @Autowired + private AccessAuthorityService accessAuthorityService; - @Override - public void run(ApplicationArguments args) throws Exception { + @Override + public void run(ApplicationArguments args) throws Exception { - //1、数据字典刷新 - // gaeaDictService.refreshCache(null); + // 1、数据字典刷新 + // gaeaDictService.refreshCache(null); + + // 2. 建立url权限拦截体系 + accessAuthorityService.scanGaeaSecurityAuthorities(); + } - //2. 建立url权限拦截体系 - accessAuthorityService.scanGaeaSecurityAuthorities(); - } }